branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>xuchaoji/photoUtil<file_sep>/searchFile.sh
#!/bin/bash
src="./Private"
#源文件的父目录
dst="./timeLine3"
#目标目录
function read_dir(){
for file in `ls $1`;do #step1 遍历文件
echo "判断 " $file "文件类型中..."
if [ -d $1"/"$file ];then
echo $file "是目录,处理目录中的文件"
read_dir $1"/"$file $2
elif [ -f $1"/"$file ];then #step2 复制文件到目标目录
echo "复制" $file "到" $2
[[ `cp -f -v -p $1"/"$file $2` ]]
else echo ".."
fi
done
}
read_dir $src $dst
#递归查找src中的文件,复制到dst中 (暂不能处理重名文件)
echo "复制完毕"
<file_sep>/README.md
#searchFile
递归查找src目录中所有照片,然后复制到dst目录
#sort.py
将sort.py 复制到dst目录,python sort.py 读取照片exif信息,按照 年份.月份 创建目录整理照片
| 6dc07fd04d3dec5c58a36ff8f7ad5e29f546123d | [
"Markdown",
"Shell"
] | 2 | Shell | xuchaoji/photoUtil | fae63082befb4167c34f1dd51c793facf38a8e3e | e81834b91155a7c4d49edd9a40ab4ac45f369329 |
refs/heads/master | <repo_name>yoonjochoi/what-is-the-digital-IQ-blog-structure<file_sep>/js/script.js
$(function(){
var jarallax = new Jarallax();
jarallax.setDefault('#intro-page', {display:'none'});
jarallax.setDefault('#site,#site-main,#site-arrow-1,#site-arrow-2,#site-arrow-3', {display:'none'});
jarallax.setDefault('#digital-marketing,#digital-marketing-main,#digital-marketing-texture-1,#digital-marketing-texture-2', {display:'none'});
jarallax.setDefault('#mobile,#mobile-main,#mobile-rings', {display:'none'});
jarallax.setDefault('#social-media-main,#social-media-sub-1,#social-media-sub-2', {display:'none'});
jarallax.setDefault('#BI-bg1, #BI-bg2, #BI-bg3, #BI-bg4, #BI1, #BI2, #BI3, #BI4', {display:'none'});
jarallax.setDefault('#ranking-bg', {display:'none'});
jarallax.setDefault('#wrap-reports,#span-Reports', {display:'none'});
jarallax.setDefault('#R1,#R2,#R3,#R4,#R5', {display:'none'});
jarallax.setDefault('#ranking-reportcover1-1,#ranking-reportcover1-2,#ranking-reportcover1-3,#ranking-reportcover1-4', {display:'none'});
jarallax.setDefault('#ranking-reportcover2-1,#ranking-reportcover2-2,#ranking-reportcover2-3,#ranking-reportcover2-4', {display:'none'});
jarallax.setDefault('#ranking-reportcover3-1,#ranking-reportcover3-2,#ranking-reportcover3-3', {display:'none'});
jarallax.setDefault('#ranking-homepagelink', {display:'none'});
jarallax.addAnimation('#l2-logo',
[{progress:'0%', top: '18%', opacity: '1'},
{progress:'5%', top: '9%', opacity: '1'},
{progress:'10%', top: '3%', opacity: '0'},
{progress:'75%', top: '3%', opacity: '0'}]);
jarallax.addAnimation('h1',
[{progress:'0%', top: '35%', opacity: '1', fontSize:'55px', paddingLeft: '78px'},
{progress:'10%', top: '10%', opacity: '1', fontSize:'55px', paddingLeft: '78px'},
{progress:'15%', top: '2%', opacity: '0.5', fontSize:'39px', paddingLeft: '167px'},
{progress:'75%', top: '2%', opacity: '0.5', fontSize:'39px', paddingLeft: '167px'}]);
jarallax.addAnimation('#scrollDown',
[{progress:'0%', top: '0%'},
{progress:'5%', top: '0%'},
{progress:'10%', top: '-20%'},
{progress:'100%', top: '-20%'}]);
jarallax.addAnimation('#intro-page',
[{progress:'0%', top: '100%', opacity: '0.5', display:'block'},
{progress:'5%', top: '100%', opacity: '0.5', display:'block'},
{progress:'10%', top: '25%', opacity: '1', display:'block'},
{progress:'20%', top: '15%', opacity: '0.5', display:'block'},
{progress:'75%', top: '15%', opacity: '0.5', display:'block'},
{progress:'100%', top: '15%', opacity: '0.5', display:'block'}]);
jarallax.addAnimation('#elevator-statement',
[{progress:'0%', top: '100%', fontSize:'17px', paddingLeft: '98px'},
{progress:'10%', top: '50%', opacity: '1', fontSize:'17px', paddingLeft: '98px'},
{progress:'12%', top: '50%', opacity: '1', fontSize:'17px', paddingLeft: '98px'},
{progress:'14%', top: '50%', opacity: '0', fontSize:'17px', paddingLeft: '98px'},
{progress:'20%', top: '45%', opacity: '0', fontSize:'17px', paddingLeft: '98px'},
{progress:'75%', top: '45%', opacity: '0', fontSize:'17px', paddingLeft: '98px'}]);
jarallax.addAnimation('#brands-are',
[{progress:'0%', top: '100%', paddingLeft: '124px'},
{progress:'10%', top: '56%', opacity: '1', paddingLeft: '124px'},
{progress:'15%', top: '56%', opacity: '1', paddingLeft: '246px'},
{progress:'20%', top: '45%', opacity: '0.5', paddingLeft: '246px'},
{progress:'75%', top: '45%', opacity: '0.5', paddingLeft: '246px'}]);
jarallax.addAnimation('#intro-page-site',
[{progress:'0%', top: '55%', opacity: '1', width:'100px', marginLeft:'20px'},
{progress:'10%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'15%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'17%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'25%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'75%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'}]);
jarallax.addAnimation('#intro-page-digital-marketing',
[{progress:'0%', top: '55%', opacity: '1', width:'100px', marginLeft:'20px'},
{progress:'10%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'15%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'17%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'25%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'75%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'}]);
jarallax.addAnimation('#intro-page-mobile',
[{progress:'0%', top: '55%', opacity: '1', width:'100px', marginLeft:'20px'},
{progress:'10%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'15%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'17%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'25%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'75%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'}]);
jarallax.addAnimation('#intro-page-social-media',
[{progress:'0%', top: '55%', opacity: '1', width:'100px', marginLeft:'20px'},
{progress:'10%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'15%', top: '50%', opacity: '1', width:'150px', marginLeft:'0px'},
{progress:'17%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'25%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'},
{progress:'75%', top: '45%', opacity: '0', width:'150px', marginLeft:'0px'}]);
jarallax.addAnimation('#intro-page-text',
[{progress:'0%', top: '100%'},
{progress:'10%', top: '50%', opacity: '1'},
{progress:'15%', top: '50%', opacity: '1'},
{progress:'20%', top: '45%', opacity: '0'},
{progress:'75%', top: '45%', opacity: '0'}]);
//main site
jarallax.addAnimation('#top-background',
[{progress:'0%', top: '100%', opacity: '1'},
{progress:'30%', top: '100%', opacity: '1'},
{progress:'45%', top: '0%', opacity: '1'},
{progress:'55%', top: '0%', opacity: '1'},
{progress:'100%', top: '0%', opacity: '1'}]);
//SITE
jarallax.addAnimation('#site',
[{progress:'0%', top: '100%', opacity: '1', display:'block'},
{progress:'40%', top: '25%', opacity: '1', display:'block'},
{progress:'48%', top: '10%', opacity: '0', display:'block'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#site-main',
[{progress:'0%', top: '100%', left: '-150%', display:'block', opacity: '1'},
{progress:'20%', top: '100%', left: '-150%', display:'block', opacity: '1'},
{progress:'28%', top: '40%', left: '61%', display:'block', opacity: '1'},
{progress:'41%', top: '40%', left: '61%', display:'block', opacity: '1'},
{progress:'48%', top: '100%', left: '-150%', display:'block', opacity: '0'},
{progress:'100%', top: '100%', left: '-150%', display:'block', opacity: '0'}]);
jarallax.addAnimation('#site-arrow-1',
[{progress:'0%', top: '34%', left: '-150%'},
{progress:'21%', top: '34%', left: '-150%', display:'block', opacity: '1'},
{progress:'33%', top: '34%', left: '58%', display:'block', opacity: '1'},
{progress:'41%', top: '34%', left: '58%', display:'block', opacity: '1'},
{progress:'48%', top: '10%', left: '-150%', display:'block', opacity: '0'},
{progress:'100%', top: '10%', left: '-150%', display:'block', opacity: '0'}]);
jarallax.addAnimation('#site-arrow-2',
[{progress:'0%', top: '0%', left: '-150%'},
{progress:'21%', top: '0%', left: '58%', display:'block'},
{progress:'36%', top: '38%', left: '56%', display:'block'},
{progress:'41%', top: '38%', left: '56%', display:'block'},
{progress:'48%', top: '0%', left: '58%', display:'block'},
{progress:'100%', top: '0%', left: '-150%', display:'block'}]);
jarallax.addAnimation('#site-arrow-3',
[{progress:'0%', top: '37%', left: '150%'},
{progress:'21%', top: '37%', left: '150%', display:'block'},
{progress:'36%', top: '37%', left: '56%', display:'block'},
{progress:'41%', top: '37%', left: '56%', display:'block'},
{progress:'48%', top: '37%', left: '150%', display:'block'},
{progress:'100%', top: '37%', left: '150%', display:'block'}]);
// DIGITAL MARKETING
jarallax.addAnimation('#digitalMarketing',
[{progress:'0%', top: '100%', opacity: '1', marginLeft:'352px'},
{progress:'50%', top: '100%', opacity: '1', marginLeft:'352px'},
{progress:'53%', top: '46%', opacity: '1', marginLeft:'352px', display:'block'},
{progress:'64%', top: '10%', opacity: '0', marginLeft:'352px', display:'block'},
{progress:'100%', top: '0%', opacity: '0', marginLeft:'352px'}]);
jarallax.addAnimation('#digital-marketing-main',
[{progress:'0%', top: '0%', opacity: '0'},
{progress:'43%', top: '0%', marginLeft: '7%', display:'block', opacity: '0'},
{progress:'51%', top: '30%', marginLeft: '7%', display:'block', opacity: '1'},
{progress:'56%', top: '30%', marginLeft: '7%', display:'block', opacity: '1'},
{progress:'61%', top: '0%', marginLeft: '7%', display:'block', opacity: '0'},
{progress:'100%', top: '0%', marginLeft: '7%', display:'block', opacity: '0'}]);
jarallax.addAnimation('#digital-marketing-texture-1',
[{progress:'0%', top: '19%', marginLeft: '-150%', display:'block'},
{progress:'43%', top: '19%', marginLeft: '-150%', display:'block'},
{progress:'51%', top: '19%', marginLeft: '-6%', display:'block'},
{progress:'56%', top: '19%', marginLeft: '-6%', display:'block'},
{progress:'61%', top: '19%', marginLeft: '-150%', display:'block'},
{progress:'100%', top: '19%', marginLeft: '-150%', display:'block'}]);
jarallax.addAnimation('#digital-marketing-texture-2',
[{progress:'0%', top: '100%', marginLeft: '-6%', display:'block'},
{progress:'43%', top: '100%', marginLeft: '-6%', display:'block'},
{progress:'51%', top: '19%', marginLeft: '-6%', display:'block'},
{progress:'56%', top: '19%', marginLeft: '-6%', display:'block'},
{progress:'61%', top: '100%', marginLeft: '-6%', display:'block'},
{progress:'100%', top: '100%', marginLeft: '-6%', display:'block'}]);
//MOBILE
jarallax.addAnimation('#mobile',
[{progress:'0%', top: '100%', opacity: '1'},
{progress:'61%', top: '100%', opacity: '1', display:'block'},
{progress:'64%', top: '52%', opacity: '1', display:'block'},
{progress:'67%', top: '42%', opacity: '1', display:'block'},
{progress:'74%', top: '10%', opacity: '0', display:'block'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#mobile-main',
[{progress:'0%', top: '100%', marginLeft:'-150px', opacity: '0'},
{progress:'63%', top: '100%', marginLeft: '-150px', opacity: '1', display:'block'},
{progress:'66%', top: '39%', marginLeft:'551px', opacity: '1', display:'block'},
{progress:'69%', top: '27%', marginLeft:'551px', opacity: '1', display:'block'},
{progress:'76%', top: '10%', marginLeft:'551px', opacity: '0', display:'block'},
{progress:'100%', top: '0%', marginLeft: '-150', opacity: '0', display:'block'}]);
jarallax.addAnimation('#mobile-rings',
[{progress:'0%', top: '0%', opacity: '0'},
{progress:'57%', top: '0%', opacity: '1', display:'block'},
{progress:'59%', top: '10%', opacity: '1', display:'block'},
{progress:'74%', top: '15%', opacity: '0', display:'block'},
{progress:'100%', top: '100%', opacity: '0', display:'block'}]);
//SOCIAL MEDIA
jarallax.addAnimation('#socialMedia',
[{progress:'0%', top: '100%', opacity: '1'},
{progress:'66%', top: '100%', opacity: '1'},
{progress:'81%', top: '29%', opacity: '1'},
{progress:'86%', top: '29%', opacity: '1'},
{progress:'100%', top: '29%', opacity: '1'}]);
jarallax.addAnimation('#social-media-main',
[{progress:'0%', top: '100%', opacity: '1', marginLeft:'111px'},
{progress:'66%', top: '100%', opacity: '1', marginLeft:'111px', display:'block'},
{progress:'83%', top: '28%', opacity: '1', marginLeft:'111px', display:'block'},
{progress:'84%', top: '28%', opacity: '1', marginLeft:'111px', display:'block'},
{progress:'100%', top: '28%', opacity: '1', marginLeft:'111px', display:'block'}]);
jarallax.addAnimation('#social-media-sub-1',
[{progress:'0%', top: '100%', opacity: '1'},
{progress:'66%', top: '100%', opacity: '1', display:'block'},
{progress:'81%', top: '24%', opacity: '1', display:'block'},
{progress:'88%', top: '24%', opacity: '1', display:'block'},
{progress:'100%', top: '24%', opacity: '1', display:'block'}]);
jarallax.addAnimation('#social-media-sub-2',
[{progress:'0%', top: '100%', opacity: '1', marginLeft:'29px'},
{progress:'66%', top: '100%', opacity: '1', marginLeft:'29px', display:'block'},
{progress:'81%', top: '55%', opacity: '1', marginLeft:'29px', display:'block'},
{progress:'88%', top: '55%', opacity: '1', marginLeft:'29px', display:'block'},
{progress:'100%', top: '55%', opacity: '1', marginLeft:'29px', display:'block'}]);
//BOTTOM ICONS
jarallax.addAnimation('#wrap-bottom-icons',
[{progress:'0%', top: '100%'},
{progress:'20%', top: '100%'},
{progress:'25%', top: '85%'},
{progress:'100%', top: '85%'}]);
//icon glow
jarallax.addAnimation('#BI-bg1',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'20%', top: '100%', opacity: '0'},
{progress:'25%', top: '85%', opacity: '0', display:'block'},
{progress:'44%', top: '85%', opacity: '1', display:'block'},
{progress:'46%', top: '85%', opacity: '1', display:'block'},
{progress:'49%', top: '85%', opacity: '0', display:'block'},
{progress:'100%', top: '85%', opacity: '0'}]);
jarallax.addAnimation('#BI-bg2',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'20%', top: '100%', opacity: '0'},
{progress:'45%', top: '85%', opacity: '0', display:'block'},
{progress:'52%', top: '85%', opacity: '1', display:'block'},
{progress:'60%', top: '85%', opacity: '1', display:'block'},
{progress:'63%', top: '85%', opacity: '0', display:'block'},
{progress:'100%', top: '85%', opacity: '0'}]);
jarallax.addAnimation('#BI-bg3',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'20%', top: '100%', opacity: '0'},
{progress:'63%', top: '85%', opacity: '0', display:'block'},
{progress:'67%', top: '85%', opacity: '1', display:'block'},
{progress:'70%', top: '85%', opacity: '1', display:'block'},
{progress:'72%', top: '85%', opacity: '0', display:'block'},
{progress:'100%', top: '85%', opacity: '0'}]);
jarallax.addAnimation('#BI-bg4',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'20%', top: '100%', opacity: '0'},
{progress:'59%', top: '85%', opacity: '0'},
{progress:'66%', top: '85%', opacity: '0', display:'block'},
{progress:'72%', top: '85%', opacity: '1', display:'block'},
{progress:'86%', top: '85%', opacity: '1', display:'block'},
{progress:'88%', top: '85%', opacity: '0', display:'block'},
{progress:'100%', top: '85%', opacity: '0'}]);
//icon img
jarallax.addAnimation('#BI1',
[{progress:'0%', top: '85%', opacity: '0'},
{progress:'20%', top: '85%', opacity: '0.2', display:'block'},
{progress:'25%', top: '85%', opacity: '1', display:'block'},
{progress:'42%', top: '85%', opacity: '1', display:'block'},
{progress:'45%', top: '85%', opacity: '1', display:'block'},
{progress:'47%', top: '85%', opacity: '0.2', display:'block'},
{progress:'100%', top: '85%', opacity: '0.2'}]);
jarallax.addAnimation('#BI2',
[{progress:'0%', top: '85%', opacity: '0'},
{progress:'20%', top: '85%', opacity: '0.2', display:'block'},
{progress:'44%', top: '85%', opacity: '0.2', display:'block'},
{progress:'47%', top: '85%', opacity: '1', display:'block'},
{progress:'50%', top: '85%', opacity: '1', display:'block'},
{progress:'60%', top: '85%', opacity: '1', display:'block'},
{progress:'62%', top: '85%', opacity: '0.2', display:'block'},
{progress:'100%', top: '85%', opacity: '0.2'}]);
jarallax.addAnimation('#BI3',
[{progress:'0%', top: '85%', opacity: '0'},
{progress:'20%', top: '85%', opacity: '0.2', display:'block'},
{progress:'59%', top: '85%', opacity: '0.2', display:'block'},
{progress:'62%', top: '85%', opacity: '1', display:'block'},
{progress:'70%', top: '85%', opacity: '1', display:'block'},
{progress:'72%', top: '85%', opacity: '0.2', display:'block'},
{progress:'100%', top: '85%', opacity: '0.2'}]);
jarallax.addAnimation('#BI4',
[{progress:'0%', top: '85%', opacity: '0'},
{progress:'20%', top: '85%', opacity: '0.2', display:'block'},
{progress:'63%', top: '85%', opacity: '0.2', display:'block'},
{progress:'72%', top: '85%', opacity: '0.2', display:'block'},
{progress:'75%', top: '85%', opacity: '1', display:'block'},
{progress:'86%', top: '85%', opacity: '1', display:'block'},
{progress:'88%', top: '85%', opacity: '0.2', display:'block'},
{progress:'100%', top: '85%', opacity: '0.2'}]);
//RANKING PAGE
jarallax.addAnimation('#span-DigitalIQ',
[{progress:'0%', top: '100%'},
{progress:'85%', top: '100%', display:'block'},
{progress:'89%', top: '0%', display:'block'},
{progress:'100%', top: '0%'}]);
jarallax.addAnimation('#span-Ranking',
[{progress:'0%', top: '100%', opacity: '0', marginTop:'45px'},
{progress:'85%', top: '100%', opacity: '1', marginTop:'45px', display:'block'},
{progress:'89%', top: '0%', opacity: '1', marginTop:'45px', display:'block'},
{progress:'100%', top: '0%', opacity: '0', marginTop:'45px'}]);
//span that changes "Ranking" to Reports"
jarallax.addAnimation('#span-Reports',
[{progress:'0%', top: '100%'},
{progress:'94%', top: '100%', marginTop:'45px', display:'block', opacity: '0'},
{progress:'98%', top: '0%', marginTop:'45px', display:'block', opacity: '1'},
{progress:'100%', top: '0%', marginTop:'45px', display:'block', opacity: '1'}]);
jarallax.addAnimation('#ranking-bg',
[{progress:'0%', top: '100%'},
{progress:'85%', top: '100%', display:'block'},
{progress:'89%', top: '0%', display:'block'},
{progress:'100%', top: '0%'}]);
jarallax.addAnimation('#R1',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'85%', top: '100%', display:'block', opacity: '1'},
{progress:'89%', top: '32%', display:'block', opacity: '1'},
{progress:'92%', top: '32%', display:'block', opacity: '1'},
{progress:'93%', top: '32%', display:'block', opacity: '1'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#R2',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'85%', top: '100%', display:'block', opacity: '1'},
{progress:'89%', top: '42%', display:'block', opacity: '1'},
{progress:'92%', top: '42%', display:'block', opacity: '1'},
{progress:'93%', top: '36%', display:'block', opacity: '1'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#R3',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'85%', top: '100%', display:'block', opacity: '1'},
{progress:'89%', top: '52%', display:'block', opacity: '1'},
{progress:'92%', top: '52%', display:'block', opacity: '1'},
{progress:'93%', top: '40%', display:'block', opacity: '1'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#R4',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'85%', top: '100%', display:'block', opacity: '1'},
{progress:'89%', top: '62%', display:'block', opacity: '1'},
{progress:'92%', top: '62%', display:'block', opacity: '1'},
{progress:'93%', top: '44%', display:'block', opacity: '1'},
{progress:'100%', top: '0%', opacity: '0'}]);
jarallax.addAnimation('#R5',
[{progress:'0%', top: '100%', opacity: '0'},
{progress:'85%', top: '100%', display:'block', opacity: '1'},
{progress:'89%', top: '72%', display:'block', opacity: '1'},
{progress:'92%', top: '72%', display:'block', opacity: '1'},
{progress:'93%', top: '48%', display:'block', opacity: '1'},
{progress:'100%', top: '0%', opacity: '0'}]);
//REPORT PAGE
jarallax.addAnimation('#reports',
[{progress:'0%', top: '100%'},
{progress:'93%', top: '100%', display:'block'},
{progress:'100%', top: '19%', display:'block'}]);
jarallax.addAnimation('#wrap-reports',
[{progress:'0%', top: '100%'},
{progress:'93%', top: '100%', display:'block'},
{progress:'100%', top: '24%', display:'block'}]);
});
| a65e399ca7fffc1634da5746758cb936e49d61fa | [
"JavaScript"
] | 1 | JavaScript | yoonjochoi/what-is-the-digital-IQ-blog-structure | 637cdf6b2af16dce19f7343c7bf9e2ff99a3dbaa | 47171f6fb56d3eafbbdc21ca450d54398859a0b0 |
refs/heads/master | <file_sep>function checkInfo() {
//Js is Working
//Validating Gender
if (document.forms["infoForm"]["gender1"].checked==false &&
document.forms["infoForm"]["gender2"].checked==false ){
alert("Please select a gender");
return;
}
if (document.forms["infoForm"]["gender1"].checked==true &&
document.forms["infoForm"]["gender2"].checked==true ){
alert("Please only select one gender");
return;
}
//Validating Age
var age=document.forms["infoForm"]["age"].value;
if (age <18 || age > 110){
alert("Please enter a valid age that is 18 and over");
return;
}
else if (isNaN(age)) {
alert("Please enter a numeric value for your age");
return;
}
//Validating Weight
var weight=document.forms["infoForm"]["weight"].value;
if (weight <25 || weight >1400){
alert("Please enter a valid weight");
return;
}
else if (isNaN(weight)) {
alert("Please enter a numeric value for your weight");
return;
}
//Validating Height
var height=document.forms["infoForm"]["height"].value;
if (height <70 || height>240 || height == ""){
alert("Please enter a valid height");
return;
}
else if (isNaN(height)) {
alert("Please enter a numeric value for your height");
return;
}
//Validating Goal Weight (Optional)
var goal=document.forms["infoForm"]["goal"].value;
if(goal == "" || goal == null){
alert("Thank you for entering your information!");
return;
}
else if (isNaN(goal)) {
alert("Please enter a numeric value for your goal weight");
return;
}
alert("Thank you for enterting your information!");
}// End of CheckInfo() Function
| bf5d3a986764b3ae8ed1e7f638b14cec688942bc | [
"JavaScript"
] | 1 | JavaScript | sophiemoore00/WebAppsProject | 0eb040982ba067100ce649432ec84d68d8ebf3d0 | d21366241a8bdc756766dac28951e26b80be215a |
refs/heads/master | <file_sep>n = gets.to_i
#標準入力から要素の一致を確認
#一致する場合は既存要素を削除して配列の先頭に
#そうでなければ配列に加える
arrays = []
n.times do
word = gets.chomp
arrays << word
if arrays.include?(word)
arrays.delete(word)
arrays.unshift(word)
else
arrays.push(word)
end
end
puts arrays
<file_sep>def title
puts "----------------------------"
puts "こんにちは! 本日は2種類のコーヒーをご用意しています。"
puts "メニュー 1: コロンビア産 300円 2: ペルー産 500円"
puts "どちらになさいますか"
puts "1:コロンビア産 2: ペルー産"
puts "番号をお選びください"
puts "----------------------------"
end
title
x = gets.to_i
if x == 1
puts "コロンビア産ですね"
total = (300 * 1.1).floor
puts "お会計は消費税と合わせて#{total}円です"
elsif x == 2
puts "ペルー産ですね!これはなかなか出回っていないんですよ!"
total = (500 * 1.1).floor
puts "お会計は消費税と合わせて#{total}円です"
end
<file_sep># p,295 Array_Class練習問題
#(1)
a = (1..100).to_a
#(2)
a = (1..100).to_a
a2 = a.collect{|i| i * 100 }
a = a.collect!{|i| i * 100 }
#(3)
a = (1..100).to_a
a3 = a.reject {|i| i % 3 != 0 }
a.reject!{|i| i % 3 != 0 }
#(4) (1)の配列を引用 全て出力結果は同じ
a = (1..100).to_a
a2 = a.reverse
a2 = a.sort{|n1, n2| n2 <=> n1}
a2 = a.sort_by {|i| -i}
#(5) (1)内、整数の和
a = (1..100).to_a
total = 0
a.each do |i|
total += i
end
p total
a.inject(0) {|sum,num| sum += num}
#(6)
a = (1..100).to_a
arrays = []
10.times do |i|
arrays << a.slice!(0, 10) #(取り除きたい部分配列の先頭のインデックス番号,取り除きたい部分配列の要素数)
end #この部分配列を取り出す動作を10回繰り返して配列を10個作る
p arrays
#(7)
def sum_array(nums1, nums2)
result = []
nums1.zip(nums2) do |a, b| #a,bは今回2文字のアルファベット。配列(今回でいう引数の配列が3つの場合は、ブロック変数もa,b,cと3つになる
result << a + b
end
return result
end
p sum_array([1, 2, 3], [4, 6, 8]) #=> [5, 8, 11]
<file_sep>#p,262 練習問題
#(1) 華氏温度=摂氏温度 x 9 ÷ 5 + 32
def cels_to_fahr(cels)
return cels * 9.0 / 5.0 + 32
end
cels_to_fahr(30)
#(2) 華氏温度を摂氏温度に変換するメソッド
def fahr_to_cels(fahr)
return (fahr.to_f - 32) * 5.0 / 9.0
end
#(3) 摂取1度から100度まで一度刻みに華氏温度との対応を出力
1.upto(100) do |i|
print i, " ", cels_to_fahr(i)
end
#(4) サイコロを振ってでた目を返すメソッド
#パラメーターは0~5
def dice
Random.rand(6) + 1
end
#(5) 10個のサイコロを振って出た目の合計
def dice10
num = 0
10.times
num = Random.rand(6) + 1
return num += num
end
<file_sep>a = []
n = gets.to_i
n.times {a.push(gets.to_i)}
puts a
#1行に複数要素
array = []
array = Array.new
n = gets.to_i
n.times
array << gets.split(" ").map(&:to_i)
puts array
#同じこと {}だとエラー
array = []
n = gets.to_i
n.times
array.push [ gets.split(" ").map(&:to_i) ]
puts array
<file_sep>n = gets.to_i
count = 0
num = 1
numbers = gets.split(" ").map(&:to_i)
while num <= n
if numbers.any? {|i| i % 3 == 0}
count += 1
num += 1
else
num += 1
end
end
p count
<file_sep># flattenメソッドとsumメソッド
n = gets.to_i
array = []
n.times do
array << gets.split(" ").map(&:to_i)
end
p array.flatten.sum
<file_sep>n = gets.to_s
zero1 = "0"
zero2 = "00"
if n.length == 1
puts zero2 + n
elsif n.length == 2
puts zero1 + n
elsif n.length == 3
puts n
end
#出力結果は同じ
n = gets.to_s
def count_digits(n)
zero1 ="0"
zero2 ="00"
if n.to_s.length == 1
puts zero2 + n
elsif n.to_s.length == 2
puts zero1 + n
elsif n.to_s.length == 3
puts n
end
end
count_digits(n)
<file_sep>arrays = []
while array = gets
arrays << array.chomp.split(' ').map(&:to_i)
end
arrays.map.with_index do |x, i|
if arrays[0][1] <= x[0] - x[1]*5
puts i
end
end
<file_sep># chompを入れて取得しないと、末尾改行が要素数に含まれてしまうので注意
n = gets.chomp.split("").map(&:to_i)
num = n.uniq
if num.length < 4
puts "NG"
else
puts "OK"
end
<file_sep>#2進数から10進数へ 初回
n = gets.chomp.split("").map(&:to_i)
p n[0]*2**4 + n[1]*2**3 + n[2]*2**2 + n[3]*2**1 + n[4]*2**0
<file_sep>#ハッシュから置き換える要素を与える(文字列)
hash = {"1" => "A", "2" => "B", "0" =>"C"}
n = gets.to_s.chomp
puts n.gsub(/[012]/, hash)
#配列の各要素頭文字を取得し、新しい文字列を生成
words = gets.split(" ")
words.each do |i|
new = i.slice(0)
print new
end
#小数点までの割り算から四捨五入のround
scores = gets.split(" ").map(&:to_i)
sum = 0
scores.each do |i|
sum += i
end
average = sum / 7.to_f
puts average.round(1)
#整数で指定の桁から切り捨てたい場合(下二桁の切り捨て)
price = gets.to_i
puts price.floor(-2)
<file_sep>n = gets.to_i
array = []
n.times do |i|
array.push(gets.split(' '))
array[i][1] = array[i][1].to_i + 1
puts "#{array[i][0]} #{array[i][1]}"
end
#二次元配列でstirng,integerが混ざっているのでこのような取り出し方をする
<file_sep>puts "----------------------------"
puts "こんにちは! 本日は2種類のコーヒーをご用意しています。"
puts "メニュー 1: コロンビア産 300円 2: ペルー産 500円"
puts "どちらになさいますか"
puts "1:コロンビア産 2: ペルー産"
puts "番号をお選びください"
puts "----------------------------"
def order(x, tax)
if x == 1
puts "コロンビア産ですね"
total = (300 * tax).floor
puts "お会計は消費税と合わせて#{total}円です"
elsif x == 2
puts "ペルー産ですね!これはなかなか出回っていないんですよ!"
total = (500 * tax).floor
puts "お会計は消費税と合わせて#{total}円です"
end
@x = x
end
order(x = gets.to_i, 1.1)
puts "-----------------------"
puts "お砂糖、ミルクはそれぞれご利用ですか?"
puts "1: 砂糖のみ 2: ミルクのみ 3: 両方 4:要りません"
puts "番号をお選びください"
puts "-----------------------"
@num = gets.to_i
if @num == 1
puts "お砂糖ですね!"
elsif @num == 2
puts "ミルクですね!"
elsif @num == 3
puts "お砂糖、ミルク両方お付けしますね!"
elsif @num == 4
puts "ブラックコーヒーでよろしいのですね"
end
def greeting
puts "お待たせ致しました!"
if @x == 1
coffee = "コロンビア産のコーヒー"
elsif @x == 2
coffee = "ペルー産のコーヒー"
end
if @num == 1
custom = "お砂糖付きの"
elsif @num == 2
custom = "ミルク付きの"
elsif @num == 3
custom = "お砂糖とミルク付きの"
elsif @num == 4
custom = "ブラックでご用意致しました、"
end
puts "#{custom} #{coffee}です!"
puts "ありがとうございました!"
end
g = greeting
puts g
puts "またのご来店をお待ちしております"
<file_sep>#文字列内 要素数の検索
string = gets.split("+")
answer = 0
num1 = 0
num2 = 0
num3 = 0
string.each do |i|
num1 += i.scan('/').length * 1
num2 += i.scan('<').length * 10
num3 = num1 + num2
end
p answer = num3
<file_sep>#最後に出力される値の配列要素を出力する
# nextを使う
n = gets.to_i
array =[]
n.times do
array << gets.split(" ")
end
person = gets
array.each do |i|
if i[0] == person
puts i[1]
else
next
end
end
<file_sep>#標準入力から得た10進数の値を2進数に変換したあと、指定順に数値の出力
array = gets.split(" ").map(&:to_i)
binary_number = array[1].to_s(2)
nums = []
array[0].times do
nums << gets.to_i
end
nums.each do |i|
puts binary_number[-i]
end
<file_sep>#約数の和
n = gets.to_i
numbers = readlines.map(&:to_i)
numbers.each do |i|
result = 0
for n in (1..i) do
if i % n == 0
result += n
end
end
result2 = result - i
if result2 == i
puts "perfect"
elsif
result2 == i - 1 || result2 == i + 1
puts "nearly"
else
puts "neither"
end
end
<file_sep>puts "OXで数字を埋めましょう!"
print "どこを変えましょうか?"
numbers = "123\n456\n789\n"
puts numbers
9.times do |i|
ox = i % 2
mode = if ox == 0 then "o" else "x" end
print "現在は#{mode}入力モードです"
s = gets.strip
numbers.gsub!(/#{s}/, mode)
print numbers
end
puts "終了します"
<file_sep>array = gets.split(" ").map(&:to_i)
person = array[0]
allocation = 100 / array[1]
student = []
person.times do
student << gets.split(" ").map(&:to_i)
end
score = 0
total_score = 0
#複数条件からトータルスコアで判定する場合に、事前に条件定義
student.each do |i|
score = i[1] * allocation
if i[0] <= 0
total_score = score - 0
elsif i[0] >= 1 && i[0] <= 9
total_score = score * 0.8
elsif i[0] >= 10
total_score = score - score
end
if total_score >= 80
puts "A"
elsif total_score >= 70 && total_score <= 79
puts "B"
elsif total_score >= 60 && total_score <= 69
puts "C"
elsif total_score < 60
puts "D"
end
end
<file_sep>#文字列内の検索と小数点切り捨て
#大好きなポイントカード制度お得デーの算出
n = gets.to_i
date = []
point = 0
n.times do
date << gets.split(" ")
end
date.each do |i|
if i[0].include?("3")
point += (i[1].to_i * 0.03).floor
elsif i[0].include?("5")
point += (i[1].to_i * 0.05).floor
else point += (i[1].to_i * 0.01).floor
end
end
<file_sep>
num = gets.chomp!
num2 = num.reverse
num3 = num.to_i + num2.to_i
num4 = num3.to_s
numbers = num4.split("")
if numbers.first == numbers.last
p numbers.join.to_i
else
num5 = num3.to_s.reverse
p num3 + num5.to_i
end
<file_sep>#scanメソッド
#区切る文字列の長さを指定する
array = gets.split(" ").map(&:to_i)
words = []
array[0].times do
words << gets.chomp!
end
string = words.join
puts string.scan(/.{1,#{array[2]}}/)
<file_sep>n = gets.split(":").map(&:to_i)
if n[1] <= 29
minute = n[1]+30
puts format("%02d:%02d", n[0], minute)
elsif n[1] >= 30
hour = n[0]+1
minute = (n[1]+30) - 60
puts format("%02d:%02d", hour, minute)
end
n = gets.split(":").map(&:to_i)
hour = n[0]
result_minute = n[1] + 30
if result_minute < 60
puts format("%02d:%02d", hour, result_minute)
else
hour += 1
result_minute -= 60
puts format("%02d:%02d", hour, result_minute)
end
<file_sep>#二次元配列から指定のindex番号で最大値と最小値を求める
array = []
n.times do
array << gets.split(" ").map(&:to_i)
end
max_array = []
min_array = []
array.each do |i|
max_array << i[2]
min_array << i[3]
end
puts "#{array[0][0]} #{array[n-1][1]} #{max_array.max} #{min_array.min}"
| a21629b0cdfe2037681fa9ffbc23c0c2dd6422a6 | [
"Ruby"
] | 25 | Ruby | NU-Moriya/Ruby_learning | 22a682f6d9da0fca45a2369a8d5c2e609539a09a | d8df79bf76821900bf08039f27a0129b5baa8fec |
refs/heads/master | <file_sep>#!/bin/sh
testNothing() {
assertEquals "This file has CRLF end lines" 1 `file crlf.txt | grep -c "CRLF"`
assertEquals "This file has CR end lines" 1 `file cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file lf.txt | grep -c "terminators"`
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 1 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
#All of these does not work with GIT v1.7.1 on Linux
testGitAttributesLf() {
echo $'* text eol=lf\n*.txt text\n' > "${0%/*}/../.gitattributes"
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
if [[ `git --version | cut -d '.' -f -2` < 'git version 1.8' ]]; then
__shunit_skip=$SHUNIT_TRUE
fi
assertEquals "This file does not have CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
#All of these does not work with GIT v1.7.1 on Linux
testGitAttributesAuto() {
echo $'* text auto\n*.txt text\n' > "${0%/*}/../.gitattributes"
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
if [[ `git --version | cut -d '.' -f -2` < 'git version 1.8' ]]; then
__shunit_skip=$SHUNIT_TRUE
fi
assertEquals "This file does not have CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
testGitConfigEol() {
git config core.eol lf && \
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 1 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
testGitConfigInput() {
git config core.autocrlf input && \
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
testGitConfigTrue() {
git config core.autocrlf true && \
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
testGitConfigTrueAndSafe() {
git config core.autocrlf true && \
git config core.safeocrlf true && \
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
testGitConfigInputAndSafe() {
git config core.autocrlf input && \
git config core.safeocrlf true && \
git add -A && git commit -m 'test' &> /dev/null && git push origin test &> /dev/null && \
git clone $(git config remote.origin.url) tmprepo &> /dev/null && cd tmprepo && \
git checkout -b test origin/test &> /dev/null && cd ..
assertEquals "This file has CR end lines" 1 `file tmprepo/cr.txt | grep -c " CR "`
assertEquals "This file does not have other then LF end lines" 0 `file tmprepo/lf.txt | grep -c "terminators"`
assertEquals "This file has CRLF end lines" 0 `file tmprepo/crlf.txt | grep -c "CRLF"`
}
. "${0%/*}/base.sh" | 8f84a0cf963278eb610ea0c10bacc3f3e0e345fe | [
"Shell"
] | 1 | Shell | 66Ton99/git-autocrlf | 6e75bbd9a3c372379300b32a031a59101f75aa5f | e3a7a1f2a4af021b7ba5504eb3ca08708d96c118 |
refs/heads/master | <file_sep>django
django-adminlte2
pymongo
black
pylint
apscheduler
<file_sep>from django.conf import settings
from pymongo import MongoClient
def db_connect():
client = MongoClient(settings.MONGODB_HOST, settings.MONGODB_PORT)
client.admin.authenticate(settings.MONGODB_USERNAME, settings.MONGODB_PASSWORD)
db = client[settings.MONGODB_NAME]
# client = MongoClient('mongodb://localhost:27017/')
# db = client['mydatabase']
return db
def get_collection(collection):
db = db_connect()
return db[collection]
<file_sep>from apscheduler.schedulers.background import BackgroundScheduler
from utils.db_connect import get_collection
query = {
"$and": [
{"entry.changes.value.item": {"$in": ["status", "comment"]}},
{"sys_status": {"$exists": False}},
]
}
def user_exist(user_id, col_user):
for user in col_user.find():
if user["id"] == user_id:
return True
return False
def obj_id_exist(col, name_id, obj_id):
for obj in col.find():
if obj["entry"][0]["changes"][0]["value"][name_id] == obj_id:
return True
return False
def get_obj(col, name_id, obj_id):
if name_id == "post_id":
return col.find_one({"entry.changes.value.post_id": obj_id})
return col.find_one({"entry.changes.value.comment_id": obj_id})
def filter_data():
col_feed = get_collection("feeds")
col_user = get_collection("feeds_van_users")
for doc in col_feed.find(query).sort("entry.changes.value.created_time", -1):
# insert user
user_id = doc["entry"][0]["changes"][0]["value"]["from"]["id"]
if not user_exist(user_id, col_user):
col_user.insert_one(doc["entry"][0]["changes"][0]["value"]["from"])
q_ = {"id": doc["entry"][0]["changes"][0]["value"]["from"]["id"]}
col_user.update_one(q_, {"$set": {"sys_status": "unblock"}})
if doc["entry"][0]["changes"][0]["value"]["item"] == "status":
col = get_collection("feeds_van_posts")
name_id = "post_id"
else:
col = get_collection("feeds_van_cmts")
name_id = "comment_id"
obj_id = doc["entry"][0]["changes"][0]["value"][name_id]
if not obj_id_exist(col, name_id, obj_id):
col.insert_one(doc)
else:
verb = doc["entry"][0]["changes"][0]["value"]["verb"]
obj_col = get_obj(col, name_id, obj_id)
if verb in ["edited", "hide"]:
# compare created time feeds and col
if (
doc["entry"][0]["changes"][0]["value"]["created_time"]
> obj_col["entry"][0]["changes"][0]["value"]["created_time"]
):
col.delete_one(obj_col)
col.insert_one(doc)
elif verb == "remove":
try:
message = obj_col["entry"][0]["changes"][0]["value"]["message"]
except:
message = "Nội dung này không ở dạng text."
col.delete_one(obj_col)
col.insert_one(doc)
col.update_one(doc, {"$set": {"entry.0.changes.0.value.message": message}})
col_feed.update_many(query, {"$set": {"sys_status": True}})
def start():
scheduler = BackgroundScheduler()
scheduler.add_job(filter_data, "interval", minutes=0.1)
scheduler.start()
<file_sep>from django.contrib.auth import views as auth_views
from django.urls import path
from django.views.generic.base import RedirectView
from . import views
urlpatterns = [
path("register", views.register),
path("login", auth_views.LoginView.as_view(template_name="login.html"), name="login"),
path("logout", auth_views.LogoutView.as_view()),
path("", RedirectView.as_view(url="/posts"), name="home"),
path("posts", views.PostListView.as_view()),
path("posts/<str:post_id>", views.PostDetailView.as_view()),
path("users", views.UserListView.as_view()),
path("managers", views.AdminView.as_view()),
path("block-user", views.block_user),
]
<file_sep>Python3 Required
### Install package
```sh
$ pip install -r requirements.txt
```
### Migrations data
```sh
$ python manage.py migrate
```
### Run
```sh
$ python manage.py runserver
```
Go to http://127.0.0.1:8000
<file_sep>{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-xs-12 col-md-8"><h2>Danh sách thành viên</h2></div>
<div class="col-xs-12 col-md-4">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" style="float: right;">Thêm thành viên</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body table-responsive" style="min-height: 200px;">
<table id="post-table" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th>STT</th>
<th>Username</th>
<th>Active</th>
<th>Staff</th>
<th>Superuser</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.username }}</td>
<td>{{ user.is_active }}</td>
<td>{{ user.is_staff }}</td>
<td>{{ user.is_superuser }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Thêm thành viên</h3>
</div>
<div class="modal-body">
{% block login_form %}
<form class="form-horizontal" method="post">
{% csrf_token %}
{% if message %}
<p class="login-box-msg" style="color: red;">{{ message }}</p>
{% endif %}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
<div class="col-sm-5">
{{ field.label_tag }}
</div>
<div class="col-sm-7">
{{ field }}
</div>
{% if field.help_text %}
<div class="col-sm-12">
<small style="color: grey">{{ field.help_text }}</small>
</div>
{% endif %}
</div>
{% endfor %}
{{ form.non_field_errors }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
{% endblock login_form %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}<file_sep>from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from django.contrib.auth import get_user_model
from utils.db_connect import get_collection
User = get_user_model()
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/login")
else:
form = UserCreationForm
return render(request, "register.html", {"form": form})
"""
def sort_by_key(val):
return val["entry"][0]["changes"][0]["value"]["created_time"]
def queryset_last(queryset_find, type_of_object):
queryset = []
obj_id_list = []
rm_obj_list = []
queryset_find.sort(key=sort_by_key, reverse=True)
for doc in queryset_find:
obj_id = doc["entry"][0]["changes"][0]["value"][type_of_object]
verb = doc["entry"][0]["changes"][0]["value"]["verb"]
if verb == "remove":
rm_obj_list.append(obj_id)
else:
if obj_id not in obj_id_list:
if obj_id in rm_obj_list:
doc["entry"][0]["changes"][0]["value"]["verb"] = "remove"
rm_obj_list.remove(obj_id)
queryset.append(doc)
obj_id_list.append(obj_id)
return queryset
"""
class PostListView(LoginRequiredMixin, ListView):
context_object_name = "post_list"
template_name = "post_list.html"
col = get_collection("feeds_van_posts")
def get_queryset(self):
query = list(self.col.find().sort("_id", -1))
queryset = []
post_id_list = []
col_feeds = get_collection("feeds")
for doc in col_feeds.find(
{
"$and": [
{"entry.changes.value.item": {"$in": ["status", "comment"]}},
{"sys_status": {"$exists": True}},
]
}
).sort("_id", -1):
post_id = doc["entry"][0]["changes"][0]["value"]["post_id"]
if post_id not in post_id_list:
for i in query:
if i["entry"][0]["changes"][0]["value"]["post_id"] == post_id:
queryset.append(i)
post_id_list.append(post_id)
return queryset
class PostDetailView(LoginRequiredMixin, ListView):
context_object_name = "comment_list"
template_name = "post_detail.html"
def get_queryset(self):
col = get_collection("feeds_van_cmts")
queryset = col.find({"entry.changes.value.post_id": self.kwargs["post_id"]}).sort("_id", -1)
return list(queryset)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
col = get_collection("feeds_van_posts")
post = col.find_one({"entry.changes.value.post_id": self.kwargs["post_id"]})
context["post"] = post
return context
class UserListView(LoginRequiredMixin, ListView):
context_object_name = "user_list"
template_name = "user_list.html"
col = get_collection("feeds_van_users")
def get_queryset(self):
queryset = self.col.find().sort("name", 1)
return list(queryset)
class AdminView(LoginRequiredMixin, ListView):
model = User
context_object_name = "users"
template_name = "managers/index.html"
form_class = UserCreationForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = self.form_class
return context
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/managers")
def block_user(request):
user_id = request.GET["user_id"]
action = request.GET["action"]
col = get_collection("feeds_van_users")
user = col.find_one({"id": user_id})
if action == "block":
col.update_one(user, {"$set": {"sys_status": "block"}})
else:
col.update_one(user, {"$set": {"sys_status": "unblock"}})
return JsonResponse({"detail": "successful"}, status=200)
"""
class CommentListView(ListView):
context_object_name = "comments"
template_name = "comment-list.html"
def get_queryset(self):
col = get_collection("feeds_van")
queryset = col.find(
{
"$and": [
{"entry.changes.value.item": "comment"},
{"entry.changes.value.post_id": self.kwargs["post_id"]},
]
}
).sort("_id", -1)
return queryset
"""
<file_sep>from datetime import datetime
from django import template
register = template.Library()
def date_time(timestamp):
return datetime.fromtimestamp(timestamp).strftime("%d-%m-%Y, %H:%M:%S")
def verb(v):
switcher = {"add": "Thêm", "edited": "Sửa", "remove": "Xóa", "hide": "Ẩn"}
return switcher.get(v, "Unknown")
register.filter(date_time)
register.filter(verb)
<file_sep>from django.apps import AppConfig
from utils import filter_data
class GraphApiConfig(AppConfig):
name = "graph_api"
def ready(self):
filter_data.start()
| 8af2e8f7a07e1e79dae05df5b345c40b3c7ec75f | [
"Markdown",
"Python",
"Text",
"HTML"
] | 9 | Text | vannn1604/graph_api | 736ece48a657e6c5fe4770f9aed3e404a4f98001 | ec88ffe2a3b07e070dcfd3c6819fe35e835240ab |
refs/heads/master | <repo_name>raunak321321/Artificial-Intelligence-code<file_sep>/kMeansClustering.cpp
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#include <vector>
#include <utility>
#include <climits>
#include <map>
using namespace std;
int min(vector<float> vec)
{
float minimum = vec[0];
int index = 0;
for (int i = 0; i < vec.size(); i++)
{
if (minimum > vec[i])
{
minimum = vec[i];
index = i;
}
}
return index;
}
float distance(pair<float, float> p1, pair<float, float> p2)
{
float x1 = p1.first;
float y1 = p1.second;
float x2 = p2.first;
float y2 = p2.second;
float dis = (pow((x1 - x2), 2) + pow((y1 - y2), 2));
return dis;
}
pair<float, float> coOrdinates(vector<pair<float, float>> subKCluster)
{
float iq = 0;
float eq = 0;
for (int i = 0; i < subKCluster.size(); i++)
{
iq = iq + subKCluster[i].first;
eq = eq + subKCluster[i].second;
}
iq = iq / subKCluster.size();
eq = eq / subKCluster.size();
pair<float, float> p;
p = make_pair(iq, eq);
return p;
}
vector<pair<pair<float, float>, vector<pair<float, float>>>> kMeansClustering(int k, vector<pair<float, float>> vec)
{
vector<pair<pair<float, float>, vector<pair<float, float>>>> kCluster(k);
for (int i = 0; i < k; i++)
{
((kCluster[i]).second).push_back(vec[i]);
pair<float, float> p = coOrdinates((kCluster[i]).second);
(kCluster[i]).first = p;
((kCluster[i]).second).pop_back();
}
label:
for (int i = 0; i < vec.size(); i++)
{
vector<float> vec1(k);
for (int j = 0; j < k; j++)
{
float dis = distance((kCluster[j]).first, vec[i]);
vec1[j] = dis;
}
int index = min(vec1);
((kCluster[index]).second).push_back(vec[i]);
}
int h = 0;
for (int i = 0; i < k; i++)
{
pair<float, float> p = coOrdinates((kCluster[i]).second);
pair<float, float> p1 = (kCluster[i]).first;
if (p.first == p1.first && p.second == p1.second)
{
h++;
}
}
if (h != k)
{
for (int g = 0; g < k; g++)
{
pair<float, float> p = coOrdinates((kCluster[g]).second);
(kCluster[g]).first = p;
kCluster[g].second.clear();
}
goto label;
}
// else
// {
// for (int g = 0; g < k; g++)
// {
// pair<float, float> p = coOrdinates((kCluster[g]).second);
// (kCluster[g]).first = p;
// }
// }
return kCluster;
}
float overallSumOfDistace(vector<pair<pair<float, float>, vector<pair<float, float>>>> finalKMeansCluster)
{
float result = 0;
int k = finalKMeansCluster.size();
for (int i = 0; i < k; i++)
{
float x1 = finalKMeansCluster[i].first.first;
float y1 = finalKMeansCluster[i].first.second;
int a = finalKMeansCluster[i].second.size();
for (int j = 0; j < a; j++)
{
float x2 = finalKMeansCluster[i].second[j].first;
float y2 = finalKMeansCluster[i].second[j].second;
result = result + distance(make_pair(x1, y1), make_pair(x2, y2));
}
}
return result;
}
int main()
{
vector<pair<float, float>> vec(20);
vec[0] = make_pair(20, 22);
vec[1] = make_pair(23, 12);
vec[2] = make_pair(8, 5);
vec[3] = make_pair(3, 3);
vec[4] = make_pair(6, 25);
vec[5] = make_pair(24, 4);
vec[6] = make_pair(23, 14);
vec[7] = make_pair(45, 5);
vec[8] = make_pair(6, 7);
vec[9] = make_pair(2, 2);
vec[10] = make_pair(9, 10);
vec[11] = make_pair(11, 10);
vec[12] = make_pair(16, 16);
vec[13] = make_pair(5, 23);
vec[14] = make_pair(23, 2);
vec[15] = make_pair(22, 2);
vec[16] = make_pair(56, 7);
vec[17] = make_pair(9, 2);
vec[18] = make_pair(8, 2);
vec[19] = make_pair(5, 48);
int k;
ofstream myfile;
myfile.open("example1.txt");
for (k = 1; k < 10; k++)
{
vector<pair<pair<float, float>, vector<pair<float, float>>>> finalKMeansCluster = kMeansClustering(k, vec);
for (int i = 0; i < k; i++)
{
cout << ((finalKMeansCluster[i]).first).first << " " << ((finalKMeansCluster[i]).first).second;
cout << endl;
printf("This is the %dth cluster and below are its vector-pair-->\n", i + 1);
for (int j = 0; j < (finalKMeansCluster[i]).second.size(); j++)
{
cout << ((finalKMeansCluster[i]).second)[j].first << " " << ((finalKMeansCluster[i]).second)[j].second << endl;
}
cout << endl;
}
float dis = overallSumOfDistace(finalKMeansCluster);
cout << "The total distance that is the sum of each cluster with their corresponding data is: " << dis << endl;
myfile << dis << endl;
}
myfile.close();
return 0;
}<file_sep>/aa.py
import numpy as np
import matplotlib.pyplot as plt
fileObj = open("example1.txt", "r")
words = fileObj. read(). splitlines()
word1 = np.arange(1, 10, 1)
for i in range(0, len(words)):
words[i] = float(words[i])
plt.plot(word1, words, color = 'red', marker = "o")
plt.xlabel("X-No Of Cluster")
plt.ylabel("Y-Sum of squared errors")
plt.show()
fileObj. close() | 0aaeed7fb8c8d2bf9821e0bbb5e280760c293f26 | [
"Python",
"C++"
] | 2 | C++ | raunak321321/Artificial-Intelligence-code | 5afd7c38e0df3f86e260bbccdc41e9bf649039f9 | 5faa487e3140bb4e85c35864a207a6e4779f90a6 |
refs/heads/main | <repo_name>theNewDynamic/minjinlee.com<file_sep>/content/event/yale-club-of-new-york-city.md
---
title: Yale Club of New York City
date: 2017-05-18 18:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
A Conversation with author <NAME>.
> <div><p><NAME> has worked in publishing (currently with Macmillan); in new media (as founder of <a href="http://cookstr.com/">cookstr.com</a>), and as a journalist. His previous book, <em>The End Of Your Life Book Club</em>, spent twelve weeks on the <em>New York Times</em> bestseller list in hardcover and paperback. He is also the author with <NAME> of <em>Send: Why People Email So Badly and How to Do It Better</em>. His newest title, <em>Books for Living</em>, describes the role that books can play in our lives and shows how a few specific books that Schwalbe champions can help us live each day more fully and with more meaning. Wil graduated from Yale in 1984 with a B.A. in Classical Civilization. </p></div><file_sep>/content/news/2007-06-01-audrey_magazine.md
---
title: "Audrey Magazine"
date: 2007-06-01T23:16:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "<NAME>"
link_to_original: "http://www.audreymagazine.com/June2007/News01.asp"
description: ""
_slug: 2007-06-01-audrey_magazine
---
In her debut novel Free Food for Millionaires, author <NAME> tackles the rarely explored world of modern Asian America in novel form with familiar ...
<file_sep>/content/event/london-the-asia-house.md
---
title: 'London: Asia House Bagri Foundation Literature Festival'
date: 2017-05-23 18:45:00
show_time: true
venue:
name: Asia House
address: 63 New Cavendish Street
city: 'Marylebone, London'
state:
zip: W1G 7LP
link: 'http://asiahouse.org/events/reflections-east-asian-20th-century/'
---
A Conversation with <NAME> and <NAME>
"Reflections on the East Asian 20th Century"
“The winter following Japan’s invasion of Manchuria was a difficult one. Biting winds sheared through the small boarding house, and the women stuffed cotton in between the fabric layers of their garments. This thing called the Depression was found everywhere in the world, the lodgers said frequently during meals, repeating what they’d overheard from the men at the market who could read newspapers. Poor Americans were as hungry as the poor Russians and the poor Chinese. In the name of the Emperor, even ordinary Japanese went without. No doubt, the canny and the hardy survived that winter, but the shameful reports – of children going to bed and not waking up, girls selling their innocence for a bowl of wheat noodles, and the elderly stealing away quietly to die so the young could eat – were far too plentiful.”
An excerpt from Pachinko by <NAME>, published by Head of Zeus in 2017, p.12.
On Tuesday 23rd May, Reflections on the East Asian 20th Century will take us back in in time with <NAME> – bestselling author of Free Food for Millionaires – who will be presenting her new novel Pachinko for the first time in the UK.
Beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them, this epic tale – which has been in the making since 1989 when <NAME> was a junior in college – follows a Korean family through eight decades and four generations. Betrayed by her wealthy lover, Sunja finds unexpected salvation when a young tubercular minister offers to marry her and bring her to Japan to start a new life.
So begins a sweeping saga of exceptional people in exile from a homeland they never knew and caught in the indifferent arc of history. In Japan, Sunja’s family members endure harsh discrimination, catastrophes, and poverty, yet they also encounter great joy as they pursue their passions and rise to meet the challenges this new home presents. Through desperate struggles and hard-won triumphs, they are bound together by deep familial roots.
<NAME> will be in conversation with author, literary critic and former Man Booker Prize for Fiction judge <NAME> to reveal a profound story which delves into questions of faith, family and identity.
The talk will be followed by a book signing and drinks reception.
To book tickets for this event please click here
General: £10, Concessions: £8, Members: £5
Asia House Arts Members need to enter their unique membership number when booking online. This can be found on the back of your membership card. Please call 0207 307 5454 if you experience any issues booking tickets.<file_sep>/content/news/2017-12-06-usa-today-10-books-we-loved-reading-in-2017.md
---
title: 'USA Today: 10 Books We Loved Reading in 2017'
date: 2017-12-06 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: USA Today
link_to_original: >-
https://www.usatoday.com/story/life/books/2017/12/06/10-books-we-loved-reading-2017/921590001/
description:
---
By <NAME>
These 10 fiction and non-fiction titles rose to the top of the heap for USA TODAY's book reviewers this year.
1. <NAME> the Bardo by <NAME> (Random House, fiction)
Saunders’ brilliantly imagined novel, both heartbreaking and hilarious, takes place in a cemetery the night <NAME> buries his 11-year-old son, Willie, and is narrated by a chorus of voices — the dearly departed who aren’t quite ready to move on to the great beyond; winner of the Man Booker Prize.
1. <NAME> by <NAME> (Simon & Schuster, non-fiction)
Isaacson once again has leveraged his prodigious research and storytelling acumen to bring a dead genius back to life in a doorstopper-sized tome that nonetheless makes for quick reading as one marvels at how da Vinci, the gay, left-handed Renaissance wizard, influenced art, technology and the city of Florence.
'<NAME>' by <NAME> (Photo: Simon & Schuster)
1. Anything Is Possible by <NAME> (Random House, fiction)
In these nine linked stories set in small-town Amgash, Ill., Strout writes about the lives of people in the heartland — their big heartaches and small triumphs — with empathy and grace and delivers her best book since <NAME>.
1. We Were Eight Years In Power: An American Tragedy by Ta-Nehisi Coates (One World, non-fiction)
Coates, one of the most influential thinkers of our time, confronts the legacy of President <NAME>, the election of <NAME> and what each says about the intractability of race in our country.
'Uncommon Type' by <NAME> (Photo: Knopf)
1. Uncommon Type: Some Stories by <NAME> (Knopf, fiction)
Not only can the guy act, he can write, and you can hear Hanks’ instantly identifiable voice all through this appealing, accomplished collection of 17 stories, each inspired by a vintage typewriter.
1. Sticky Fingers by <NAME> (Knopf, non-fiction)
This wildly entertaining if unflattering biography of Rolling Stone magazine co-founder <NAME> pulsates with drugs, sex and rock ‘n’ roll and has just as much chutzpah as its subject, who was infuriated by his (hand-picked) biographer’s laser-beam reporting.
1. Pachinko by <NAME> (Grand Central, fiction)
Lee’s ambitious social novel, Dickensian in scope, follows multiple generations of one ethnically Korean family in 20th century Japan as they search for a comfortable place in the world; a National Book Award finalist.
'Sticky Fingers' by <NAME> (Photo: Knopf)
1. My Absolute Darling by <NAME> (Riverhead, fiction)
This powerful debut novel is a deep and moving story of family drama and survival, with a seriously brave little girl at its center who has to break from her abusive father’s hold to find her true self.
1. Manhattan Beach by <NAME> (Scribner, fiction)
Egan departs from her more experimental work in this historical novel, about <NAME>, the first female diver at the Brooklyn Navy Yard during World War II; it’s as immersive, eerie and sublime as Anna’s trips underwater.
'Manhattan Beach' by <NAME> (Photo: Scribner)
1. The Changeling by <NAME> (Spiegel & Grau, fiction)
Not only an engaging read but an important one, this modern fairy tale superbly tells the story of a man desperately trying to find the truth about his dead son while weaving in witches, trolls and Trump-era issues.
Contributing reviewers: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME><file_sep>/content/event/kacf_awgc.md
---
title: KACF/AWGC
date: 2008-01-22T23:20:00-05:00
venue:
name: Korean American Community Foundation and the Asian Women's Giving Circle, NEW YORK
link:
_slug: kacf_awgc
---
Korean American Community Foundation and the Asian Women’s Giving Circle sponsor:
A Public Conversation with <NAME> and <NAME> about FREE FOOD FOR MILLIONAIRES
Tuesday, 6.30PM-8.30PM
SHIN CHOI BOUTIQUE in SOHO
119 Mercer Street, between Spring and Prince
Seating is limited: Please RSVP to <NAME>
<EMAIL> or 201-670-1198
<file_sep>/content/event/brooklyn-public-library--whitman-circle.md
---
title: 'Brooklyn Public Library: Whitman Circle'
date: 2018-06-20 18:30:59 -0400
images: []
description: 'Fundraiser for Brooklyn Public Library '
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/review/new-york-times-ten-best-books-of-2017.md
---
title: 'New York Times Ten Best Books '
date: 2020-01-23T00:00:00-05:00
attribution: New York Times Ten Best Books - Editors of The New York Times Book Review.
book: book/pachinko.md
description: ''
featured: false
weight:
---
Lee’s stunning novel, her second, chronicles four generations of an ethnic Korean family, first in Japanese-occupied Korea in the early 20th century, then in Japan itself from the years before World War II to the late 1980s. Exploring central concerns of identity, homeland and belonging, the book announces its ambitions right from the opening sentence: “History has failed us, but no matter.” Lee suggests that behind the facades of wildly different people lie countless private desires, hopes and miseries, if we have the patience and compassion to look and listen.<file_sep>/content/event/south-carolina-fiction-addiction.md
---
title: 'South Carolina: Fiction Addiction'
date: 2018-02-05 12:00:00
show_time: true
venue:
name: Fiction Addiction
address: '1175 Woods Crossing Road, No. 5'
city: Greenville
state: SC
zip: '29607'
link: 'http://www.fiction-addiction.com'
---
12PM Korea Center of Greenville, SC: Lunch (ticketed event)
2176 E. Coleman Road, Greer, SC 29650
3PM Fiction Addiction: Reading & Signing (ticketed event)
1175 Woods Crossing Road, Greenville, SC
Events curated by Fiction Addiction owner, <NAME>
<file_sep>/content/event/vromans_bookstore_june_27th.md
---
title: Vroman’s Bookstore, June 27th
date: 2007-06-27T20:00:00-05:00
venue:
name: Vroman’s Bookstore, Pasadena, CA
link: www.vromansbookstore.com/NASApp/store/IndexJsp?s=storeevents&eventId=347376
_slug: vromans_bookstore_june_27th
---
<file_sep>/content/news/ny-post-the-10-best-books-to-read-to-beat-coronavirus-boredom.md
---
title: The Best Books to Read During The Coronavirus Pandemic, According to PEOPLE
Editors
date: 2020-04-02T00:50:11-04:00
link_to_original: https://people.com/books/best-books-to-read-during-the-coronavirus-pandemic-people-editors/
images: []
tags: []
categories: []
description: ''
---
> "Very rarely do I get to throw myself into a book that makes me feel so seen. Through protagonist <NAME>, <NAME> perfectly articulates what it feels like to find yourself battling between two cultures as you try to navigate young adult life in New York City. _Free Food for Millionaires_ is beautifully written and filled with characters you will love, hate and learn from." — _<NAME>, Features Editor_<file_sep>/content/event/odyssey_bookshop1.md
---
title: Odyssey Bookshop
date: 2007-08-15T07:00:00-05:00
venue:
name: Odyssey Bookshop, South Hadley, MA
link: www.odysseybks.com
_slug: odyssey_bookshop1
---
Reading and Q&A
7PM
<file_sep>/content/news/2017-02-01-amazons-best-books-of-the-month--best-fiction-and-literature-of-the-month.md
---
title: "Amazon's Best Books of the Month & Best Fiction and Literature of the Month"
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Business Insider
link_to_original: 'http://www.businessinsider.com/best-books-amazon-february-2017-2/#4-3-2-1-1'
description:
---
This epic and emotional novel follows several generations of one Korean family, and their fraught life in exile. But there is also much joy to be found in the ways in which this family overcomes obstacles in their adopted home.
PACHINKO is an Amazon's Best Books of the Month & a Best Fiction and Literature Book of the Month.
<file_sep>/content/event/yale-university--davenport-college-tea.md
---
title: 'Yale University: Davenport College Tea'
date: 2018-11-29 16:00:15 -0500
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2015-05-21-junot-diaz-and-min-jin-lee-in-conversation-at-asian-american-literary-festival-video.md
---
title: <NAME> and <NAME> in Conversation at Asian American Literary Festival (VIDEO)
date: 2015-05-21 12:00:00
categories: ["Media"]
tags:
- Video
attribution:
link_to_original:
description: 'Asian American Literary Festival at the Powerhouse Arena on October 29, 2011'
---
At the [Asian American Writers' Workshop](http://aaww.org/)
<iframe width="560" height="315" src="https://www.youtube.com/embed/DuXGDE6tolY" frameborder="0" allowfullscreen=""></iframe><file_sep>/content/news/2017-10-04-pachinko-is-a-national-book-awards-finalist-for-fiction.md
---
title: Pachinko is a National Book Awards Finalist for Fiction
date: 2017-10-04 12:00:00
categories: ["News"]
tags:
- News
attribution: NPR
link_to_original: >-
http://www.npr.org/sections/thetwo-way/2017/10/04/555536038/here-are-the-finalists-for-the-2017-national-book-awards
description:
---
By <NAME>
It began with more than 1,500 books.
With all the works submitted by publishers, the judges for this year's National Book Awards have had their hands (and bookshelves) full the past few months. But that daunting number of contenders winnowed further Wednesday, as the National Book Foundation announced the finalists for its literary prize — just five works each in four categories: fiction, nonfiction, poetry and young people's literature.
You can find those shortlists below, paired with links to NPR's previous coverage for readers to get to know those nominees better.
For now, at least, there are two winners whose names we won't have to wait on: <NAME>, who has already won a National Book Award for The Shipping News, will be honored this year with the Medal for Distinguished Contribution to American Letters, the NBF's version of a lifetime achievement award. And <NAME>, president and CEO of Scholastic, will be receiving the Literarian Award for Outstanding Service to the American Literary Community.
The rest of this year's winners will be announced on Nov. 15 in New York City.
Fiction
<NAME>: Dark at the Crossing<br><NAME>: The Leavers<br><NAME>: Pachinko<br><NAME>: Her Body and Other Parties: Stories<br><NAME>: Sing, Unburied, Sing
Nonfiction
<NAME>: Never Caught: The Washingtons' Relentless Pursuit of Their Runaway Slave, Ona Judge<br><NAME>: The Evangelicals: The Struggle to Shape America<br><NAME>: The Future Is History: How Totalitarianism Reclaimed Russia<br><NAME>: Killers of the Flower Moon: The Osage Murders and the Birth of the FBI<br><NAME>: Democracy in Chains: The Deep History of the Radical Right's Stealth Plan for America
Poetry
<NAME>: Half-light: Collected Poems 1965-2016<br><NAME>: The Book of Endings<br>Layli Long Soldier: WHEREAS<br><NAME>: In the Language of My Captor<br><NAME>: Don't Call Us Dead: Poems
Young People's Literature
<NAME>: What Girls Are Made Of<br><NAME>: Far from the Tree<br><NAME>: I Am Not Your Perfect Mexican Daughter<br><NAME>: Clayton Byrd Goes Underground<br><NAME>: American Street<file_sep>/content/news/2017-06-14-village-voice-nycs-best-independent-booksellers-share-their-picks-for-summer-reading.md
---
title: "Village Voice: NYC's Best Independent Booksellers Share their Picks for Summer Reading"
date: 2017-06-14 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Village Voice
link_to_original: 'https://www.villagevoice.com/2017/06/14/nycs-best-independent-booksellers-share-their-picks-for-summer-reading/'
description:
---
By <NAME>
With its legendary eighteen miles of books, the Strand is a good first stop to find the summer’s ideal beach read. <NAME>, the Strand’s director of communications, recommends French wunderkind <NAME>’s The End of Eddy, a portrait of the poor, violent northern manufacturing town in which the author grew up. She also loves <NAME>’s One Day We’ll All Be Dead and None of This Will Matter, a book of essays about being raised the daughter of Indian immigrants in the U.S.; Janet Mock’s upcoming Surpassing Certainty; and <NAME>’s Spaceman of Bohemia. She likes these books because they offer a look at someone else’s reality: “These books are all stories of different experiences, perspectives, challenges, and successes,” she says.
<NAME>, a book buyer at bookbook in the West Village who focuses specifically on cookbooks, says he’d “100 percent recommend” <NAME>’s Salad for President. “Some of the recipes are really easy,” he says. “Watermelon wedges with fennel, olive oil, and sea salt. Things you can get at the market quickly.” His colleague <NAME> is a big fan of <NAME> Pachinko, a multigenerational saga of a Korean family in exile in Japan; Lewis Mason, who also works there, will be reading <NAME>’s diaries.
For the rest of the article, please click the link below.<file_sep>/content/about.md
---
title: About
images:
- "/uploads/minjinlee.jpg"
description: ''
type: page
menu:
main:
weight: 8
---
<NAME> is a recipient of fellowships in Fiction from the Guggenheim Foundation (2018), the Radcliffe Institute of Advanced Study at Harvard (2018-2019), and the New York Foundation for the Arts (2000). Her novel _Pachinko_ (2017) was a finalist for the National Book Award for Fiction, a runner-up for the Dayton Literary Peace Prize, winner of the Medici Book Club Prize, and a _New York Times_ 10 Best Books of 2017. A _New York Times_ Bestseller, _Pachinko_ was also a Top 10 Books of the Year for BBC, Canadian Broadcasting Corporation, and the New York Public Library. _Pachinko_ was a selection for "Now Read This," the joint book club of PBS NewsHour and The New York Times. It was on over 75 best books of the year lists, including NPR, PBS, and CNN. _Pachinko_ will be translated into 30 languages. President <NAME> selected _Pachinko_ for his recommended reading list, calling it, "a powerful story about resilience and compassion." Lee's debut novel _Free Food for Millionaires_ (2007) was a Top 10 Books of the Year for _The Times of London_, NPR’s _Fresh Air_, _USA Today_, and a national bestseller. In 2019, _Free Food for Millionaires_ was a finalist for One Book, One New York, a city-wide reading program. Her writings have appeared in _The New Yorker_, NPR’s _Selected Shorts_, _One Story_, _The New York Review of Books, The New York Times Magazine_, _The New York Times Book Review_, _The Times Literary Supplement_, _The_ _Guardian_, _Conde Nast Traveler_, _The Times of London_, _and Wall Street Journal_. She served three consecutive seasons as a Morning Forum columnist of the _Chosun Ilbo_ of South Korea. In 2018, Lee was named as an _Adweek_ Creative 100 for being one of the "10 Writers and Editors Who are Changing the National Conversation" and a Frederick Douglass 200. In 2019, Lee was inducted in the New York Foundation for the Arts Hall of Fame. She received an honorary degree of Doctor of Humane Letters from Monmouth College. She will be a Writer-in-Residence at Amherst College from 2019-2022. She serves as a trustee of PEN America, a director of the Authors Guild and on the National Advisory Board of the Immigration Initiative at Harvard.
Extended Bio:
<NAME>'s _Pachinko_ (2017) was a finalist for the National Book Award for Fiction, a runner-up for the Dayton Literary Peace Prize, winner of the Medici Book Club Prize, a _New York Times_ 10 Best Books of 2017, a _USA Today_ Top 10 Books of 2017, an American Library Association Notable Book, and an American Booksellers Association's Indie Next Great Reads. It is a _New York Times_ Bestseller. _Pachinko_ was also a Top 10 Books of the Year for BBC, Canadian Broadcasting Corporation, _San Francisco Chronicle_, the New York Public Library, _Seattle Post-Intelligencer_, and the Chicago Public Library. _Pachinko_ was a selection for "Now Read This," the joint book club of PBS NewsHour and The New York Times. It was on over 75 best books of the year lists, including NPR, PBS, CNN, _Vox_, History Channel, _Esquire_, _Financial Times_, _Amazon_, _The Boston Globe_, _Minnesota Public Radio_, _Literary Hub_, _New Statesman_, _BuzzFeed_, _South China Morning Post_, _The Millions_, _Goodreads_, _BookPage_, _The Rumpus_, _Southern Living_, _Town & Country_, _Book Riot_, _Bustle_, _Financial Review_, _Interpreter_, _Refinery29_, _Chicago Tribune_, _Publishers Weekly_, _Kirkus Reviews_, _Electric Literature_, _WBUR On Point_, _The Brooklyn Rail_, _Read It Forward_, _Whitcoulls Top 100_, _Entropy_, _Irish Independent_, _RTE_, and _The Irish Times_. _Pachinko_ will be translated into 30 languages.
Lee's debut novel _Free Food for Millionaires_ (2007) was a Top 10 Books of the Year for _The Times of London_, NPR’s _Fresh Air_ and _USA Today_. It was a No. 1 Book Sense Pick, a _New York Times_ Editor’s Choice, a _Wall Street Journal_ Juggle Book Club selection, and a national bestseller. In 2019, _Free Food for Millionaires_ was selected as a finalist for One Book, One New York, a city-wide reading program and the largest bookclub in the world.
She is a recipient of fellowships in Fiction from the <NAME> Foundation and the Radcliffe Institute for Advanced Study at Harvard University. In 2000, she received a fiction fellowship from the New York Foundation for the Arts, and in 2019, she was inducted into its Hall of Fame. She was awarded an honorary degree of Doctor of Humane Letters from Monmouth College. The Frederick Douglass Family Initiatives and the Antiracist Research and Policy Center at American University named her a Frederick Douglass 200 for her work as a writer. In 2018, Lee was named as an Adweek Creative 100 for being one of the "10 Writers and Editors Who are Changing the National Conversation." Lee received the Peden Prize from _The Missouri Review_ for Best Story, the _Narrative_ Prize for New and Emerging Writer, and the Reading Women Award.
Her fiction has been featured on NPR’s _Selected Shorts_ and _One Story_. Her writings about culture, politics, books, travel and food have appeared in _The New Yorker_, _The New York Review of Books, The New York Times Magazine_, _The New York Times Book Review_, _The Times Literary Supplement_, _The_ _Guardian_, _Conde Nast Traveler_, _The Times of London_, _Vogue_, _Travel + Leisure_, _Literary Hub_, _Wall Street Journal_ and _Food & Wine_. Her personal essays have been anthologized in _To Be Real_, _Breeder_, _The Mark Twain Anthology: Great Writers on His Life and Works_, _One Big Happy Family_, _Sugar in My Bowl_, and _Global and the Intimate: Feminism in Our Time_. She served three consecutive seasons as a Morning Forum columnist of the _Chosun Ilbo_ of South Korea.
Lee has spoken about writing, politics, film and literature at various institutions and organizations, including Columbia University, French Institute Alliance Francaise, Amherst College, University of Michigan MFA, M.I.T., Radcliffe Institute for Advanced Study, The Center for Fiction, Tufts, Loyola Marymount University, Stanford, Johns Hopkins, Johns Hopkins SAIS, University of Connecticut, Wellesley College, Boston College, Hamilton College, Hunter College of New York, Harvard University, Harvard Law School, Yale University, Ewha University, Waseda University, the American School in Japan, World Women’s Forum, Korean American Community Foundation, Korean Community Center (NJ), the Hay Literary Festival (UK), Hong Kong International Literary Festival, Melbourne Writers Festival, Sydney Writers Festival, the Tokyo American Center of the U.S. Embassy, the Asia House (UK), and the Asia Society in New York, San Francisco and Hong Kong. In 2017, she won the Literary Death Match (Brooklyn/Episode 8), and she is a proud alumna of Women of Letters (Public Theater).
On July 10, 2018, she had the unique honor of being a Double Jeopardy clue in the "Literary Types" category for $1200 on the game show _Jeopardy_: "Korean-born Min Jin Lee wrote a 2017 book with this Japanese pinball game as its title," to which the contestant Becky answered correctly in the interrogative, "What is Pachinko?"
She was born in Seoul, South Korea and immigrated to Queens, New York with her family in 1976 when she was seven years old. Lee is a graduate of the Bronx High School of Science and was inducted into the Bronx Science Hall of Fame. At Yale College, she majored in History and was awarded the Henry Wright Prize for Nonfiction and the James Ashmun Veech Prize for Fiction. She attended law school at Georgetown University and worked as a lawyer for several years in New York prior to writing full time.
From 2007 to 2011, Lee lived in Tokyo where she researched and wrote _Pachinko_. As of the fall of 2019, she will be based in New York City, where she will be working on _American Hagwon_, the third diaspora novel of "The Koreans" trilogy and _Name Recognition_, a work of non-fiction. From 2019-2022, she will be a Writer-in-Residence at Amherst College. She serves as a trustee of PEN America, as a director of the Authors Guild and on the National Advisory Board of the Immigration Initiative at Harvard.<file_sep>/content/news/2007-03-29-washington_post.md
---
title: "Washington Post"
date: 2007-03-29T23:00:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Washington Post"
link_to_original: "http://www.washingtonpost.com/wp-srv/artsandliving/books/features/2007/spring-books/index.html"
description: ""
_slug: 2007-03-29-washington_post
---
When a 22-year-old Princeton grad takes too long to find a job, her dad sends her packing. ...
<file_sep>/content/news/2007-04-25-usa_today.md
---
title: "USA Today"
date: 2007-04-25T21:59:11-05:00
categories: ["News"]
tags:
- Reviews
attribution: "USA Today"
link_to_original: "http://www.usatoday.com/life/books/reviews/2007-04-25-food-for-millionaires_N.htm"
description: ""
_slug: 2007-04-25-usa_today
---
Free Food for Millionaires by <NAME> may be the right book at the right time. It’s a first novel that, through sheer coincidence, opens a door onto the ...
<file_sep>/content/event/bronx-high-school-of-science-commencement-keynote-speaker-class-of-2019.md
---
title: 'Bronx High School of Science: Commencement Keynote Speaker, Class of 2019'
date: 2019-06-26 12:00:00 -0400
show_time: true
venue:
name: United Palace Theater
address: Bronx High School of Science
city: ''
state: ''
zip:
link: ''
---
<file_sep>/content/event/cuyahoga-public-library-foundation-writers-center-stage.md
+++
date = 2021-11-09T05:00:00Z
description = "Cuyahoga County Public Library Foundation: Writers Center Stage Series"
images = []
link = "https://case.edu/maltzcenter/WCS3"
show_time = false
title = "Cuyahoga Public Library Foundation: Writers Center Stage"
[venue]
address = "1855 Ansel Rd"
city = "Cleveland"
name = "Maltz Performing Arts Center, Case Western Reserve University"
state = "Ohio"
zip = "44106"
+++
<file_sep>/content/event/on-reading-shirley-hazzard-s-the-transit-of-venus.md
---
show_time: true
title: 'On Reading: Shirley Hazzard’s The Transit of Venus'
date: 2021-03-24T19:30:00-04:00
description: 'Join us to celebrate a new edition of Shirley Hazzard’s classic literary
masterpiece The Transit of Venus. We have an all-star panel of Hazzard fans for
the occasion. Our moderator is award-winning and bestselling author <NAME>
(Fates and Furies, Florida) who wrote the introduction to the new edition. Groff
will lead a conversation with Pulitzer-prize winning biographer <NAME> (Cleopatra:
A Life; The Witches: Salem, 1692), writer <NAME> (Small Fry: A Memoir),
best-selling author <NAME> (The Interestings), National Book Award finalist
<NAME> (Pachinko), and award-winning English writer <NAME> (Out of Sheer
Rage) on the lasting legacy of The Transit of Venus and Hazzard herself.'
venue:
address: Virtual
city: ''
name: ''
state: ''
zip: ''
link: https://centerforfiction.org/event/on-reading-shirley-hazzards-the-transit-of-venus/
images: []
---
<file_sep>/content/event/catapult--don-t-write-alone.md
---
title: 'Catapult: Don''t Write Alone'
date: 2018-07-28 17:30:00 -0400
images: []
description: 'Catapult''s "Don''t Write Alone Weekend": A Conversation with <NAME> and <NAME> '
link: https://catapult.co/classes/don-t-write-alone-weekend-2018-07-27
show_time: true
venue:
address: 58 W 10th Street
city: New York
name: <NAME> Creative Writers House NYU
state: NY
zip: 10003
---
<file_sep>/content/news/2017-02-25-financial-times-book-review.md
---
title: Financial Times (Book Review)
date: 2017-02-25 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Financial Times by <NAME>
link_to_original: 'https://www.ft.com/content/01c1e6cc-f75e-11e6-bd4e-68d53499ed71'
description:
---
<br>By <NAME>
<br>It took the Korean-American writer <NAME> almost 30 years to bring Pachinko to life. The idea to write about the Korean immigrant experience in Japan first came to her in 1989. Lee did her research, and even completed a draft, before turning instead to the experience of Korean immigrants in America in her celebrated debut, Free Food for Millionaires (2007). She returned to the project over the years but, as she says in the book’s acknowledgments, “it did not feel right”. Sample the FT’s top stories for a week You select the topic, we deliver the news. Select topic Enter email addressInvalid email Sign up By signing up you confirm that you have read and agree to the terms and conditions, cookie policy and privacy policy. After such a long gestation, the finished product — a doorstop historical saga that spans four generations of one family — wears its labours lightly. The story begins with, and always returns to, the life of Sunja, the adored only daughter of a Korean couple from a fishing village. We follow her from an early failed love affair to her marriage to Isak, a Christian pastor, and their journey from occupied Korea to Osaka, Japan, where they meet the full force of colonial prejudice. As one character tells Isak: “No one will rent to the Koreans. As pastor, you’ll get a chance to see how the Koreans live here. You can’t imagine: a dozen in a room that should be for two, men and families sleeping in shifts. Pigs and chickens inside homes. No running water. No heat. The Japanese think Koreans are filthy . . . ” The story that follows is a deeply wrenching one of migration, circling around themes of in-between identities, belonging and acceptance. The latter is never granted for Sunja’s family: the Korean in Japan remains a perpetual outsider in Pachinko. Personal stories coalesce with national histories. We are shown the effects of Japan’s occupation of Korea (which began in 1910) through Sunja’s experiences, and the after-effects of the bombing of Nagasaki in 1945 via her brother-in-law’s horrifying injuries, and so on until 1989. We never feel history being spoon-fed to us: it is wholly absorbed into character and story, which is no mean feat for a novel covering almost a century of history. Family members endure homelessness, poverty, disease, suicide, sudden death and imprisonment without trial, among other ordeals. Their suffering marks them indelibly but their status as victims is mitigated by a resourceful, everyday heroism. Lee’s exploration of the immigrant experience highlights different kinds of trauma, including that which is passed down the generations — from Sunja to her sons, Noa and Mozasu, and grandson, Solomon. While Mozasu rebels against the expectation to be a pliant, obedient “good Korean”, Noa lives behind a carefully composed façade of “Japaneseness” to survive in his hostile environment. Solomon, meanwhile, is distanced from anti-Korean prejudice by his father’s wealth and an American education, but despite his privilege he must still negotiate questions of identity. Lee’s portrait of an immigrant who begins with nothing but thrives against all the odds is at once particular and universal. The arc of Sunja’s journey is not unlike that traced by Sunjeev Sahota in his Man Booker-nominated The Year of the Runaways (2015), which tells the story of Indian immigrants to Britain who survive abject beginnings to eventually live in relative comfort. When Sunja looks back at her life, she is almost unable to draw a line from her early poverty to her eventual wealth (both her sons make their fortunes through running the titular “pachinko”, a type of Japanese pinball bar). Pachinko tells many people’s stories and deftly brings its large ensemble of characters alive. Occasionally the plot is jarred by too-neat twists, such as the convenient return of Sunja’s lover, announced on the same page as the death of her husband. The biggest off-note, though, is Lee’s treatment of Noa, who is abruptly discarded in a sudden death, his children’s stories left dangling. His is one of many untimely deaths of fathers and mothers: there is no nuclear family in Lee’s world, and a recurrence of dead spouses and single parents. It seems as if the novelist is showing us how migration can fracture a family far beyond a single generation. Despite the many tragedies, romance and love still flourish in Pachinko, and surrogate parents are found in aunts, uncles and grandparents. The final image is a vivid one of Sunja as an elderly woman. She is standing over her husband’s grave, reflecting on her losses but still standing, Lee seems to be saying, like a true survivor.
Pachinko, by <NAME>, Apollo, RRP£18.99/Grand Central Publishing, RRP$27, 496 pages<file_sep>/content/event/pen-pals--friends-of-the-hennepin-county-library.md
---
title: 'Pen Pals: Friends of the Hennepin County Library I (Evening)'
date: 2018-10-25 19:30:25 -0400
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: https://www.supporthclib.org/min-jin-lee
description: ''
link: https://www.supporthclib.org/min-jin-lee
---
<file_sep>/content/news/2016-10-24-the-book-report-network-hachette-book-club-brunch-2016.md
---
title: 'The Book Report Network: Hachette Book Club Brunch 2016'
date: 2016-10-24 12:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original: 'http://www.readinggroupguides.com/blog/2016/10/24/hachettes-2016-book-club-brunch'
description:
---
On Saturday, October 22nd, almost 300 book lovers joined authors and publishing professionals for Hachette’s annual Book Club Brunch — now in its fifth year. Boasting a variety of authors, books and snacks, this event is highly anticipated by readers and sells out nearly every year. The Book Report Network staffers were unable to make it, but we had seven generous readers share their experiences with us, including which authors they connected to most, which books they can’t wait to read, and how the discussion of <NAME>’s PACHINKO — which readers were given the opportunity to read before the event — played out in such a large group.
The Book Report Network: Who did you attend the event with?
<NAME> (Secaucus, NJ): I attended the event with my friend, co-worker and book club member, Marilyn.
<NAME> (Rockville, MD): A group of seven readers — made up of family and friends.
<NAME> (Urbana, OH): My cousin and a fellow Booktopian.
<NAME> (Jeffersonville, PA): My sister-in-law, <NAME>.
<NAME> (Long Island, NY): I attended the event with my friend Lily, who is an avid reader (she reads three to four books a WEEK!), but who had never attended the brunch before.She truly enjoyed the day!
<NAME> (Readington, NJ): <NAME>.
<NAME> (Whitehouse Station, NJ): <NAME>.
<br>
TBRN: How many Hachette Book Club Brunches have you attended?
Valerie: I have been to four out of five events. I have seen the first HBGB event grow from 70 book lovers attending to the fifth event, where almost 300 eager book lovers attend. Hachette provides a very nice brunch for us book enthusiasts, but we come to admire what book lovers might call the souls behind the words we love so much.
Denise: This is the third for me and my husband! The first for two in the group, and the second for the other three. (We are all already planning for next year.)
Linda: Two.
Marcia: This was my fourth.
Melanie: This was my third time attending the brunch.
Anne: This was my first time.
Kathleen: This is my second.
<br>
TBRN: Was there one particular author, or maybe two or three, that you were most looked forward to seeing? If so, what was that experience like?
Valerie: Hachette never disappoints us book enthusiasts; their panels are always interesting, their authors real, eager, bright and sometimes funny. <NAME> and <NAME> were of interest to me only because I have read their books before. Hicks writes historical fiction, which is my favorite genre.
Denise: I LOVED the book TRUEVINE and couldn't wait to hear <NAME> speak. The premise of her fascinating nonfiction book seems so improbable: She documents the story of two albino African-American brothers, who became freaks in circus shows. Were they taken? Were they stolen? What was their story? She lived up to my high expectations:smart, engaging, a fantastic story teller. She spoke about how hard it was to get one particular critical source to speak to her. In order to get that source’s cooperation, she made a bargain that Macy will deliver her eulogy! That is how persuasive Macy is, and how determined she was to get her story.
Linda: I wasn't anticipating any of the authors.
Marcia: Two authors, <NAME> and <NAME>. I've wondered about <NAME> ever since her first book — THE SNOW CHILD. I was intrigued by her photo! Her sense of magic appeals to me. I also enjoyed her discussion of the challenge of writing only in the first person, and using letters and journals. I was unfamiliar with <NAME>. I love her book and was looking forward to meeting the woman who wrote it. She didn't disappoint. She was warm, empathetic and fun. She also spoke very clearly from her own experience about being Korean/Japanese. And her parents came to hear her!
Melanie: I most looked forward to hearing <NAME> discuss PACHINKO, since it was the only book I had read by the presenting panelists.
Anne: I particularly looked forward to seeing <NAME>, since I enjoy her work so much. She was amazing — very animated, funny and interesting.
Kathleen: I most looked forward to seeing <NAME> — and it was a good experience.
<br>
TBRN: Which panel of the day was your favorite?
Valerie: Fiction is my preferred genre, so I favored the fiction panel. <NAME>, <NAME> and <NAME> were all interesting and enjoyable. Love when they share their lives. Hachette’s nonfiction authors — <NAME>, <NAME> and <NAME> — had everyone’s attention, with not one head dipping forward in sleep mode. I was inspired to purchase D. Watkins’ book, THE COOK UP.
Denise: It would almost feel like a betrayal to answer that question, like choosing your favorite child. I loved both panels, and have different "favorite" things about each. So many great moments in each — authors and panel moderators alike were connected and on their game. The first panel, on narrative nonfiction, all discussed critical deaths as prompts for their writing.The second panel authors, on fiction, all discussed writing about places at times of challenge and change.
Linda: Tough to answer since they were all excellent. I guess I'll say the Literary Fiction panel because we found out what a kook <NAME> is, and <NAME> tugged at all of our hearts when he broke up telling us about his dog of 17 years that he had to put down two days before.
Marcia: The Narrative Nonfiction panel, featuring <NAME>, <NAME>, <NAME>. Their discussion of turning life into memoir was inspiring. All three authors were very generous in sharing their lives, beginning with the event that started each of them writing — the death of a brother, mother and father. They covered many topics and the one that resonated the most with me was about the importance of using their memoirs as a way of claiming their own authenticity. I think I was most taken with <NAME>. He's led an amazing life — and a difficult one — from his days into drugs on the streets of Baltimore to his life as a writer and literacy advocate. For him to go through what he had to and come out on the other side with a clear vision and hope is inspiring. Great, great panel!
Melanie: I do not read nonfiction as frequently as fiction, but I have to say I enjoyed the Narrative Nonfiction panel the most. Initially, the panelists appeared to be quite a diverse group, but upon hearing all of their stories, all had the common thread of losing a loved one as the catalyst to begin writing their books. While they did indeed come from very different backgrounds, as they spoke about their work it became clear that they had many similarities in their human experiences. Their reasons for sharing their stories made the audience feel that we are all interconnected as we travel through the experience of being human. <NAME> did a wonderful job moderating and highlighting similarities among the panelists.
Anne: The first panel of the day (nonfiction). Since the authors wrote memoirs, they discussed their own personal experiences, which were incredibly varied and interesting.
Kathleen: <NAME>.
<br>
TBRN: Were there any authors who surprised you or shared something unexpected?
Valerie: <NAME> shared his feelings about his writing: “Writing is my therapy I get paid for.” For readers, it is our free therapy, so thank you D.
Denise: Again, hard to narrow down…but for me, <NAME> is the author who most connected. Watkins' brother's death prompted his book, THE COOK UP. Watkins spoke about growing up around poverty; he wasn't poor because his brother was a drug dealer. Watkins has always been a reader, and he wants books in children's hands (he is currently working on a YA book). He spoke about how reading develops critical and necessary thinking and communication skills. This is where he had me.He said, “In my community, if you can't think critically, the penalty can be death.” Of everything said, in a day full of ideas, that haunts me.
On a much lighter note, authors respectfully discussed including real people in their books, and the potential cost of that type of writing. What if your writing hurts others? Author <NAME> keeps in mind <NAME>'s guidance:If they didn't want to be written about, maybe they shouldn't have been such assholes.
Linda: <NAME> is from the town where I live, and when I asked her about that, I had a new best friend (and she'll be in Urbana at the end of next month).
Marcia: <NAME> demonstrating a library cart dance was totally surprising!
Melanie: <NAME>, who was not familiar to me before the brunch, shared how he felt compelled to write his story of the experience growing up in the “hood” so that other people could grow up reading about themselves and circumstances they might actually experience in their own lives, something he was not able to read about when he was growing up. This struck a chord with me because, surprisingly, growing up I did not like reading. I realize now this was because of the books that were chosen for us to read in school: THE SCARLET LETTER, THE CRUCIBLE and THE OLD MAN AND THE SEA are a few that come to mind that I didn’t like! I would have much rather read something more relevant to my life, and perhaps I would have found a love of reading earlier. Literacy as a way out of poverty was discussed, and by writing literature that young people in impoverished backgrounds can relate to he is trying to instill a love of reading in a population that literature is typically not written for. Very important work!
Anne: Yes! <NAME> jumped up and did a “Library Cart Drill” straight out of the pages of the book.
Kathleen: I didn't know anything about <NAME>, but his sincerity and emotion surprised me and made me want to check out his books.
<br>
TBRN: This year’s book club discussion book was PACHINKO by <NAME>. Were you able to get an advance copy and read it before the event? Did you participate in the discussion at the end of the event? What did you think of the book?
Valerie: <NAME>, our afternoon keynote speaker with her beautiful welcoming smile, took us all on her 19-year journey from the time PACHINKO was first born, when in college she was inspired by a young Korean boy who sadly took his life after being bullied. She also shared how her parents and the history of their home was important enough for her to research deeply and passionately to get it right and make it real. I’m disappointed in myself for not having had the time to read it before the event — you can be sure that tonight I will be reading PACHINKO past my bedtime, almost feeling like I already have a friend.
Denise: Hachette sent copies to attendees before the event — a lovely way to prepare for the day. I thought PACHINKO was wonderful, a sweeping saga. Such deep themes of love, loss, coping, identity, strength and belonging. Min Jin Lee was wonderfully engaging and open to audience questions. The audience discussion made the novel even more nuanced for me.
Linda: I am loving the book and cannot get enough time with it. <NAME> is such a precious human. I really appreciate the history and culture lessons that I am getting from the book.
Marcia: I did have a copy of the book but didn't get a chance to finish it. I am loving it. The discussion echoed my feelings. Everyone who spoke raved about the book. It was described as a "page turner," "a book I wanted to go on and on and never end" and “a book that totally spoke to me." I'll definitely be finishing this book!
Melanie: Yes, I read PACHINKO before attending the event, but I did not ask a question during the discussion. <NAME> was a really personable and humble interviewee. I thought the book was fascinating in that I did not know any Korean history, and therefore knew nothing about Koreans immigrating to Japan and how much they are discriminated against. Min shared that, even today, Koreans whose families have been in Japan for five generations are not allowed to become nurses or policemen! This is why many enter the pachinko industry, which is one of the biggest industries in Japan, where they are accepted. I thought the characters in the book were well created, and I really cared about them. I did feel that there was no true climax to the story, but many little ones that were moved on from quickly once revealed. I felt it was a bit too long and perhaps tried to cover a bit too much scope, but I am very glad I read the book and would recommend to those who enjoy multi-generational family sagas.
Interestingly, I had a pachinko machine at my house growing up. We had a traditional pin-ball machine and then my dad bought a pachinko machine, “Japanese pinball.” It was very pretty, but we never figured out quite how to play it; basically the ball just dropped down through the pins to the bottom of the machine. Definitely not as interactive as pinball! I guess if money is at stake it might make it more engaging!
Anne: Yes, I received an advance copy in the mail prior to the event. Unfortunately, I haven’t read it yet.
Kathleen: I did receive the book and read it before the event. It is not really possible to have a "discussion" with over 200 people in the room, but I did enjoy the questions posed by other participants and the author's response. The characters and events in the book really rang true to me, and I cared about each and every one of them.
<br>
TBRN: Which books did you most look forward to reading after the brunch?
Valerie: In order of my reading I will begin with PACHINKO, THE ORPHAN MOTHER and THE EXCELLENT LOMBARDS.
Denise: THE COOK UP by <NAME> is first on my list. I have been lucky enough to have already read most of the books featured. Every book featured was purchased by someone in our little group. And book sales all around were booming!
Linda: MY (UNDERGROUND) AMERICAN DREAM by <NAME>, who started as an illegal immigrant and is about to vote in her first U.S. election.
Marcia: PACHINKO, THE COOK UP, TO THE BRIGHT EDGE OF THE WORLD, MY (UNDERGROUND) AMERICAN DREAM, FACTORY MAN, STRANGERS TEND TO TELL ME THINGS and THE ORPHAN MOTHER.
Melanie: Every year after the brunch I want to read books by all the presenters! Somehow I never get to each and every book, but this year the book I want to read first is MY (UNDERGROUND) AMERICAN DREAM. As an undocumented Mexican immigrant who went to college and became a successful Wall St. executive, always being afraid of being “found out,” <NAME> definitely piqued my interested about her story! She shared that this would be the first presidential election she will be voting in, now that she is a citizen of the U.S., an interesting tidbit.
Anne: I am currently reading TRUEVINE by <NAME>.
Kathleen: TRUEVINE, which I purchased on the spot.
<br>
TBRN: Did you discover books that you would like to share with your book group for possible discussion? If so, which ones?
Valerie: I will be talking about and excitedly bringing back to my book club THE ORPHAN MOTHER, THE EXCELLENT LOMBARDS and PACHINKO in February 2017. I also was able to obtain some extra brochures to share with my book club for future book club picks.
Denise: PACHINKO is a natural book club choice. One haunting sentence about belonging and identity:"If he had an embarrassing wish, it would be this: he would be a European from a long time ago" could by itself serve as a prompt for a full book club discussion. Hearing the discussion of THE ORPHAN MOTHER made me want to read THE WIDOW OF THE SOUTH. Maybe our club will read the two as a pair? I thought each of the books discussed could serve as a great book club discussion — if ONLY the authors could participate in all of those discussions!
Linda: MY AMERICAN (UNDERGROUND) AMERICAN DREAM by <NAME>, THE COOK UPby <NAME>, TRUEVINE by <NAME> and PACHINKO.
Marcia: I think my group would enjoy PACHINKO and STRANGERS TEND TO TELL ME THINGS.
Melanie: TRUEVINE by <NAME> sounded as if it has some true-life mystery in it, possibly unsolved, and this might lend itself to a good group discussion.
Anne: So far, all of the books I’ve read from the event are ones that I would share.
Kathleen: Any of them would be good.
<br>
TBRN: Would you attend this event again in the future?
Valerie: I will always be interested in attending Hachette’s Book Club Brunch and next year will not hesitate to buy my ticket. I had to have a little faith in Hachette and sweat on the waitlist.
Denise: Yes! Can't wait to return to this spectacular event.
Linda: In a heartbeat.
Marcia: Definitely!
Melanie: Absolutely!
Anne: Yes, definitely.
Kathleen: Yes. I enjoyed this year even more than last year.
<br>
TBRN: Any additional thoughts?
Valerie: I would also like to thank the HBG Book Club Task Force for running such a friendly, smooth event, and <NAME>olas for running up and down the aisles with raffle gifts. Also <NAME>, for her effortlessly moderating and orchestrating this book lovers’ event. It was a fun time for us all; our day went by quickly.
Denise: Hachette’s Book Club Brunch is wonderful! <NAME> and her colleagues make the day so much fun. Karen is a human bundle of energy, leading the day in part as confidential guide, in part as cheerleader of all things reading. She can make a serious recommendation one moment and announce raffle winners the next. Nearly 300 in the audience — up from 70 for the first brunch. It was happiest group of people on a rainy day. So many people were return visitors. The day was carefully structured, and each panel fascinating. The $45 admission ticket included: great raffles, a tote bag full of great books, snacks and food the priceless opportunity to have an intimate day with authors and people who love books. It is a dream day for book clubs.
Marcia: This was the fifth anniversary of the Hachette brunch. Hard to believe that it started with only 70 participants. There were 290 happy readers participating on Saturday in spite of the rain. Congratulations to Karen Torres and her staff who have once again created a very satisfying experience for the many book lovers that attended.
Melanie: I look forward to the next Hachette Book Club Brunch!!
Anne: Some further consideration could be given to logistics, i.e., make sure there are enough chairs for everyone, move the bookselling tables to the basement cafeteria where there is more room. But these are minor quibbles; it was a great day and I would definitely go back.
Kathleen: The authors were all very prepared, entertaining and informative. I enjoyed it very much. To nitpick — the theater was lovely and comfortable, but the crowd crush for book sales and lunch (we ended up eating our lunch sitting on stairs) was annoying. I suspect that the facility imposed a lot of challenges for the elderly and disabled.<file_sep>/content/news/2017-12-24-the-new-york-times-best-sellers-december-24-2017.md
---
title: 'The New York Times Best Sellers: December 24, 2017'
date: 2017-12-24 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The New York Times
link_to_original: >-
https://www.nytimes.com/books/best-sellers/trade-fiction-paperback/?nytapp=true&_r=0
description:
---
Pachinko debuts the list at no. 10 for Paperback Trade Fiction.
Please click the link for the list. Thank you.
<file_sep>/content/event/asia_society_of_northern_california_and_green_apple_books.md
---
title: Asia Society of Northern California and Green Apple Books
date: 2007-06-21T05:30:00-05:00
venue:
name: Asia Society of Northern California and Green Apple Books
link: www.asiasociety.org
_slug: asia_society_of_northern_california_and_green_apple_books
---
Asia Society of Northern California and Green Apple Books: Meet the Author
Asia Society of Northern California
Conference Room
500 Washington St. (at Sansome)
San Francisco, CA
Registration: 5:30PM ($5 for Members and Students/$10 for Non-members: Sushi and Wine Reception to Follow)
Program: 6:00PM
For information: Please contact <NAME>, Assistant Director for Programs 415-421-8707
Books will be made available for sale by co-sponsor GREEN APPLE BOOKS
www.asiasociety.org/northerncalifornia
www.greenapplebooks.com
<file_sep>/content/event/new-yorker-festival-2022.md
+++
date = 2022-10-09T15:00:00Z
description = "The chef <NAME>, the filmmaker Lee <NAME>, the writer <NAME>, and the actor <NAME> on culture, representation, and creative expression. Moderated by <NAME>."
images = ["/uploads/asian-representation-panel-730x480.jpg"]
link = "https://festival.newyorker.com/tickets/identity-and-craft/"
show_time = true
title = "New Yorker Festival: \"Identity and Craft\""
[venue]
address = "333 West 23rd Street"
city = "New York"
name = "<NAME>"
state = "NY"
zip = "10011"
+++
<file_sep>/content/news/pbs-newshour-interview-with-jeff-brown.md
---
title: 'PBS NewsHour: Interview with <NAME> (Video I) '
date: 2018-07-30 18:13:23 -0400
link_to_original: https://www.pbs.org/newshour/show/pachinko-author-min-jin-lee-answers-your-questions
images: []
tags:
- 'Video '
- interview
- pbs newshour
- nyt
- book club
categories: []
description: 'An Interview with PBS NewsHour''s <NAME>. Part I. '
---
<file_sep>/content/writing/2008-04-27-sex_debt_and_revenge_balzacs_cousin_bette.md
---
title: "Sex, Debt, and Revenge: Balzac’s Cousin Bette"
date: 2008-04-27T22:27:40-05:00
categories:
tags: ["Essays"]
where_published: "Barnes & Noble Review"
link_to_original: "http://www.barnesandnoble.com/bn-review/note.asp?note=16288150"
link_to_pdf:
description:
_slug: 2008-04-27-sex_debt_and_revenge_balzacs_cousin_bette
---
Sex, Debt, and Revenge: Balzac’s Cousin BetteBy <NAME>. Not too long ago, my friend Harold told me that if he didn’t have to earn a living, ...
<file_sep>/content/event/world_womens_forum.md
---
title: World Women’s Forum
date: 2008-10-22T03:53:00-05:00
venue:
name: World Women's Forum, Seoul, South Korea
link: www.womanforum.org
_slug: world_womens_forum
---
October 22: 2PM-3.30PM
“Women’s Lives Mirrored in Literature”
Professor <NAME>, Moderator
Authors: <NAME>, <NAME> and <NAME>
<file_sep>/content/writing/a-review-of-toni-morrison-s-new-book-home-in-the-times-of-london.md
---
title: 'NYT: In Praise of bell hooks'
date: 2019-02-28T20:21:13.000+00:00
categories:
tags: []
where_published: New York Times
link_to_original: https://www.nytimes.com/2019/02/28/books/bell-hooks-min-jin-lee-aint-i-a-woman.html
link_to_pdf:
description:
_slug: '2019-02-28T05:00:00.000+00:00'
---
"For me, reading 'Ain’t I A Woman,' was as if someone had opened the door, the windows, and raised the roof in my mind. I am neither white nor black, but through her theories, I was able to understand that my body contained historical multitudes and any analysis without such a measured consideration was limited and deeply flawed."<file_sep>/content/event/sayers--doers.md
---
title: '<NAME>'
date: 2017-06-12 19:00:00
show_time: true
venue:
name: <NAME>
address: 46 West 116th Street
city: New York
state: NY
zip: '10026'
link: 'https://www.sayersanddoers.com'
---
Talks by Google's in-house entrepreneur <NAME>, business consultant and philosopher <NAME>, innovative journalist and robotics and human augmentation futurist <NAME>, and me. For tickets, please go to www.sayersanddoers.com<file_sep>/content/news/pbs-newshour-interview-with-jeff-brown-video-ii.md
---
title: 'PBS NewsHour: Interview with <NAME> (Video II)'
date: 2018-07-30 18:17:05 -0400
link_to_original: https://www.youtube.com/watch?v=P5HRArtdq-E
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/event/hay-literary-festival.md
---
title: Hay Festival
date: 2017-05-27 17:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Hay-On-Wye, Wales
In Conversation with <NAME>, author of THE LUCKY ONES. The conversation chaired by <NAME>, Culture Director of ELLE UK. <file_sep>/content/news/2009-04-05-wall_street_journal_asia_april_3_2009.md
---
title: "Wall Street Journal- Asia, April 3, 2009"
date: 2009-04-05T18:43:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Wall Street Journal Asia"
link_to_original: "http://online.wsj.com/article/SB123864135687881583.html"
description: ""
_slug: 2009-04-05-wall_street_journal_asia_april_3_2009
---
 When I was in Hong Kong for the Man Hong Kong International Literary Festival, I was interviewed by the journalist <NAME> who is also on the staff of the Far Eastern Economic Review.

<file_sep>/content/review/toronto-star-on-pachkinko.md
---
title: Toronto Star on Pachkinko
attribution: Toronto Star
date: 2017-03-11 17:53:37 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Top 10 Books of February of the Canadian Library Association's Loan Stars Program<file_sep>/content/news/2017-01-10-book-riot-most-anticipated-books-of-2017.md
---
title: 'Book Riot: Most Anticipated Books of 2017'
date: 2017-01-10 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: 'Book Riot: <NAME>'
link_to_original: 'https://bookriot.com/2017/01/10/most-anticipated-books-of-2017/'
description:
---
<NAME>’s sophomore novel opens during Imperial Japan’s occupation of Korea, and follows a family through five generations of self-discovery. The breadth and depth of challenges come through clearly, without sensationalization. The sporadic victories are oases of sweetness, without being saccharine. Lee makes it impossible not to develop tender feelings towards her characters—all of them, even the most morally compromised. Their multifaceted engagements with identity, family, vocation, racism, and class are guaranteed to provide your most affecting sobfest of the year.<file_sep>/content/event/savoy-bookshop-and-cafe-westerly-rhode-island.md
---
title: 'Savoy Bookshop and Cafe: Westerly, Rhode Island'
date: 2017-03-27 18:00:00
show_time: true
venue:
name: Savoy Bookshop and Cafe
address: 10 Canal Street
city: Westerly
state: RI
zip: 02891
link: 'http://www.banksquarebooks.com/westerly-store'
---
In Conversation with <NAME>-Fusaro of the Westerly Sun
(This event is the new rescheduled date after the Feb date was canceled due to a snow storm.)<file_sep>/content/event/nantucket-book-festival-2018.md
---
title: 'Nantucket Book Festival 2018: Opening Celebration '
date: 2018-06-15 19:00:00 -0400
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: https://nantucketbookfestival.org
description: ''
images: []
---
June 14-16, 2018
<file_sep>/content/event/center-for-marketing-intelligence-interpublic-group.md
---
title: 'Center for Marketing Intelligence: Interpublic Group'
date: 2017-05-15 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Asian Pacific American History Month
In Conversation with <NAME>, Co-Program Lead, Asian Heritage Group Advisory Board and Account Services Manager of IPG, Center for Marketing Intelligence
Private Event<file_sep>/content/news/2011-05-13-vogue-up-front-after-the-earthquake.md
---
title: 'VOGUE: Up Front "After the Earthquake"'
date: 2011-05-13 01:26:00
categories: ["News"]
tags:
- Essays
attribution: Vogue
link_to_original: 'http://www.vogue.com/culture/article/upfront-japan'
description:
_slug: 2011-05-12-up_front_after_the_earthquake
---
March 11, 2011, fell on a Friday, the day I run errands and go to the market. Until 2:46 p.m., about an hour before my thirteen-year-old son, Sam, would return home from his international school in Chofu, a suburb of Tokyo, it had been a good day. Once in a rare while in the life of a writer struggling on her sophomore novel, it’s possible to achieve a state of semi-contentedness by producing a few decent pages, and that morning was a halcyon interlude in my otherwise grumbling condition. After printing out my day’s work, I tidied the house, raced to the bank, paid my utility bills, then mulled over what to make for dinner for Sam and my husband, Christopher.
read the rest at [Vogue](http://www.vogue.com/culture/article/upfront-japan/)
---<file_sep>/content/news/2016-12-25-nylon-50-best-new-books-2017.md
---
title: 'NYLON: 50 Best New Books 2017'
date: 2016-12-25 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Nylon
link_to_original: 'http://www.nylon.com/articles/best-new-books-2017'
description:
---
<file_sep>/content/event/books_inc_san_francisco_ca.md
---
title: Books Inc. San Francisco, CA
date: 2007-06-22T20:00:00-05:00
venue:
name: Books Inc. San Francisco, CA in Opera Plaza
link: www.booksinc.net
_slug: books_inc_san_francisco_ca
---
Friday Fiction Series
Time: 7PM
Opera Plaza
601 Van Ness
San Francisco, CA
415-776-1111
<file_sep>/content/event/bronxville-public-library.md
---
title: Bronxville Public Library & Sommer Center at Concordia College
date: 2018-01-23 19:00:00
show_time: true
venue:
name: Sommer Center at Concordia College
address: 171 White Plains Road
city: Bronxville
state: NY
zip: '10708'
link: >-
https://www.eventbrite.com/e/pachinko-by-min-jin-lee-author-talk-tickets-40805054015
---
The Friends of the Bronxville Public Library (FOBPL) are encouraging book clubs to read <NAME>’s Pachinko, a finalist for the National Book Award, a national bestseller and a New York Times Editor’s Choice, in preparation for a special conversation with the author that will take place on the evening of Tuesday, January 23, 2018 at 7 PM at the Sommer Center for Worship and Performing Arts at Concordia College. <NAME> will be interviewed by Bronxville’s S<NAME>, Distinguished Lecturer and Director of the Journalism Program, Hunter College, and the audience will participate in a book discussion. Copies of Pachinko are available at Wormath's Book Shop in Bronxville and at the event.
THIS EVENT IS NOW CLOSED.
Please register for the event on the eventbrite link. <file_sep>/content/news/2017-02-07-npr-book-review-culture-clash-survival-and-hope-in-pachinko.md
---
title: 'NPR Book Review: Culture Clash, Survival and Hope in PACHINKO'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: NPR Book Reviews by <NAME>
link_to_original: 'http://www.npr.org/2017/02/07/512910187/culture-clash-survival-and-hope-in-pachinko'
description:
---
February 7, 20177:00 AM ET
<NAME>
In fiction we seek a paradox, the familiar in the foreign, new realities that only this one particular author can give us. Pachinko, the sophomore novel by the gifted Korean-born <NAME>, is the kind of book that can open your eyes and fill them with tears at the same time.
Pachinko, for those not in the know, is one of the national obsessions of Japan, a dizzying cross between pinball and a slot machine, wherein small metal balls drop randomly amid a maze of brass pins. There's a comic feel of Rube Goldberg to the device, but the final effect is oddly mesmerizing. The urge to play can quickly become an addiction, and of course the game is a perfect metaphor for the ricochet whims of fate. Owning pachinko parlors becomes a way for the clan depicted in the novel to climb out of poverty — but destiny cannot be manipulated so easily.
We are in Buddenbrooks territory here, tracing a family dynasty over a sprawl of seven decades, and comparing the brilliantly drawn Pachinko to <NAME>'s classic first novel is not hyperbole. Lee bangs and buffets and pinballs her characters through life, love and sorrow, somehow making her vast, ambitious narrative seem intimate.
"History has failed us, but no matter," she writes in the book's Tolstoyan opening sentence, hinting at the mix of tragic stoicism that is to come. During the second decade of the 20th century, as Korea falls under Japanese annexation, a young cleft-palated fisherman named Hoonie marries a local girl, Yangjin, "fifteen and mild and tender as a newborn calf." The couple has a daughter, Sunja, who grows to childhood as the cosseted pet of their rooming house by the sea in Yeong-do, a tiny islet near the Korean port city of Busan.
As a shy, vulnerable adolescent, Sunja is the prey of a formidable middle-aged gangster named <NAME>u. With features that make him look "somewhat Japanese," and elegant Western-style fashions such as "white patent leather shoes," Hansu embeds himself deeply into the remainder of Sunja's life. He's a Godfather, but also something of a fairy godmother. Most importantly, he provides a financial buffer when the family relocates to Osaka, Japan.
Lee deftly sketches a half-familiar, half-foreign but oftentimes harsh new world of a Korean immigrant in imperialist Japan. Sunja gives birth out of wedlock to Hansu's son, her shame erased at the last minute by marriage to a patrician, good-hearted pastor. The entwined destinies of the gangster's bastard and a second child, the son of a preacher man, become an engine that drives the story forward.
Amid the nightmare of war, the people of Osaka deal with privations. "City children were sent alone to the country by train to buy an egg or a potato in exchange for a grandmother's kimono." Sunja and her beloved sister-in-law Kyunghee have set themselves up in business making the flavorful national specialty of Korea, kimchi. Pickled cabbage serves as mode of survival, rising to symbolic importance alongside the pachinko game itself, organic and homey where the other is mechanical and sterile.
There are horrors in 'Pachinko' — a lengthy prison term is marked by gruesome torture — but the core message remains ultimately one of survival and hope.
The cultures, Korean and Japanese, clash. Sunja's son, Mozasu, who owns pachinko parlors, will level with his best friend over fried oysters and shishito peppers, in a passage that lies at the heart of these characters' dilemmas: "In Seoul, people like me get called Japanese bastard, and in Japan, I'm just another dirty Korean no matter how much money I make, or how nice I am."
Lee is at her best describing complex behaviors and emotions with unadorned, down-to-earth language. "Isak knew how to talk with people, to ask questions, and to hear the concerns in a person's voice; and she seemed to understand how to survive, and this was something he did not always know how to do." There are horrors in Pachinko— a lengthy prison term is marked by gruesome torture — but the core message remains ultimately one of survival and hope.
"Pachinko was a foolish game," Lee writes, "but life was not." The reader could be forgiven for thinking that the reverse might also be true. This is honest writing, fiction that looks squarely at what is, both terrible and wonderful and occasionally as bracing as a jar of Sunja's best kimchi.<file_sep>/content/event/johns_hopkins_sais_us_korea_institute.md
---
title: JOHNS HOPKINS-SAIS U.S.-Korea Institute
date: 2007-11-06T01:03:00-05:00
venue:
name: U.S. Korea Institute at SAIS-Johns Hopkins University, Washington, D.C.
link: www.uskoreainstitute.org
_slug: johns_hopkins_sais_us_korea_institute
---
Reading and Q&A with <NAME>, author of FREE FOOD FOR MILLIONAIRES
With <NAME>, Assistant Professor of English, George Mason University
Reception 5.30-6.30PM
Program: 6.30PM
U.S.-Korea Institute at SAIS
The <NAME> School of Advanced International Studies
The Johns Hopkins University
Co-sponsored by Korean-American Coalition of DC
<file_sep>/content/news/guggenheim-2018-fellows.md
---
title: Guggenheim 2018 Fellows
date: 2018-04-05 00:42:42 -0400
images: []
image_credit: ''
categories: []
where_published: Artforum
link_to_original: https://www.artforum.com/news/guggenheim-foundation-announces-2018-fellows-74905
description: ''
---
<file_sep>/content/event/an-unlikely-story-bookstore,-plainville,-ma.md
---
title: An Unlikely Story Bookstore, Plainville, MA
date: 2018-11-09 19:00:30 -0500
images: []
description: ''
link: https://www.anunlikelystory.com
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/stanford-bookstore.md
---
title: Stanford Bookstore
date: 2017-02-25 13:00:00
show_time: true
venue:
name: Stanford Bookstore
address: 519 Lasuen Mall
city: Stanford
state: CA
zip: '94305'
link: 'https://www.stanford.bkstr.com'
---
Stanford Parents' Weekend: In Conversation with Professor <NAME>, <NAME>. Atha Professor in the Humanities, Professor of English, Director of American Studies. Dr. Fishkin is the award winning author, editor or co-editor of over forty books. Her most recent book is WRITING AMERICA: LITERARY LANDMARKS FROM WALDEN PIND TO WOUNDED KNEE. She is the editor of the 29 volume Oxford Mark Twain (Oxford University Press).<file_sep>/content/news/2017-10-27-pbs-newshour-video-essay-in-my-humble-opinion.md
---
title: 'PBS NewsHour: Video Essay: "In My Humble Opinion"'
date: 2017-10-27 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
- Video
- Essays
- Audio
attribution: PBS NewsHour
link_to_original: >-
https://www.pbs.org/newshour/show/when-we-talk-about-north-korea-we-forget-whats-happening-to-its-people
description:
---
To see the video essay about my family in North Korea, please click the link. Thank you.<file_sep>/content/event/the-booksmith-san-francisco.md
---
title: 'The Booksmith, San Francisco'
date: 2017-02-15 19:30:00
show_time: true
venue:
name: The Booksmith
address: 1644 Haight Street
city: San Francisco
state: CA
zip: '94117'
link: 'http://www.booksmith.com'
---
In Conversation with <NAME>, the Managing Editor of *Zyzzyva* and Contributing Editor of *LitHub*. <NAME> is the former book editor of the *San Francisco Chronicle and* member of the board of directors of the National Book Critics Circle. His writings have appeared in the *Virginia Quarterly Review*, *The Believer* and his reviews have aired on KQED's *The California Report*.<file_sep>/content/event/morristown-festival-of-books.md
---
title: Morristown Festival of Books
date: 2017-10-14 12:20:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Panel with <NAME> (A Separation), <NAME> (Under the Idala Tree), and <NAME> (Pachinko), moderated by <NAME>, co-founder and president of Bookreporter.com and The Book Report Network.<file_sep>/content/review/american-booksellers-association.md
---
title: American Booksellers Association on Pachkinko
attribution: 'American Booksellers Association: INDIE NEXT Great Reads Feb 2017 (Jennifer
Steele, Boswell Book Company)'
date: 2017-03-11 17:52:37 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Through it all is a message about love, faith, and the deep-rooted bonds of family. <NAME> gives us a phenomenal story about one family's struggle that resonates with us today. It will take hold of you and not let go!<file_sep>/content/event/parnassus-bookstore-with-ann-patchett.md
---
title: 'Parnassus Books: Conversation with <NAME>'
date: 2018-03-21 19:00:00
show_time: true
venue:
name:
address: 3900 Hillsboro Pike Suite 14
city: Nashville
state: TN
zip: '37215'
link: 'http://www.parnassusbooks.net'
---
<file_sep>/content/news/2017-06-24-the-australian-book-review.md
---
title: The Australian (Book Review)
date: 2017-06-24 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Australian
link_to_original: 'http://www.theaustralian.com.au/arts/review/min-jin-lees-pachinko-exiles-existence-is-all-a-game-of-chance/news-story/c43c14c9f9ce400bf0d818e5f1f4cf7f'
description:
---
By <NAME>
In his 1970 book Empire of Signs Roland Barthes said of pachinko, the Japanese cousin of pinball, that the player’s fate is set in motion and sealed by the first, and only, movement: after perching the ball up, you’re helpless, and watch your destiny spelled out before you. With each machine, the odds change every day at the whims of the manager.
With its insistence on constant chance-taking against overwhelming and unknown odds, this scattershot game is a neat metaphor for diaspora. And so it is with the Korean family in Min Jin Lee’s Pachinko, a roiling immersive novel of generations coming to terms with their exile in Japan, caught between internal feelings of loss and the physical difficulty of exile.
Throughout this novel history is made. Or rather history happens. Where Seoul-born, New York-based Lee’s 2007 debut novel Free Food for Millionaires focused on a single life in Manhattan, Pachinko goes generations back to trace the Korean diaspora in Japan — the Zainichi — condemned to the margins of society. Lee was living in Tokyo when she wrote the novel.
“History had failed us, but no matter” are the opening words, and the successive separations in the novel work like a series of concussions: they are staggering and reverberate down the generations as intonations of doom.
We start in a small fishing village in North Korea in the early 20th century. A simple man with a cleft palate receives a wife in an arranged marriage. They run a boarding house. They have a daughter, Sunja, who is solid, stoic, but also fierce and full of life.
Sunja’s fate is set in train by Koh Hansu, a Korean yakuza with a double life who first saves her from the potential assault of Japanese boys, but then seduces her and creates the expectation of marriage. She dodges the disgrace of pregnancy by leaving for Japan with Isak, a young pastor who takes the child as his own.
Sunja is the patient heart of this novel, the metronome that measures the music of time. The beatific Isak walks in the light of the Lord, but his death is foretold. From there Sunja scrabbles for existence in the ruins of a wartime economy, eking out an existence for her two sons selling kimchi with her new sister-in-law, Kyunghee.
Those sons are where this novel cleaves, and there are shades of Fyodor Dostoevsky in the polarity between them. For the noble and studious older brother Noa, Hansu’s son, it is the high road or no road. For the younger Mozasu, Isak’s child, it’s climbing the rungs of the pachinko world, to hustle and scramble.
This is a Dickensian narrative stripped of verbal excess. There is an essential spareness to Lee’s prose: death doesn’t knock before it steals in and steals away, and the narrative climaxes have a breathtaking forthrightness, brisk as loss itself, with a harsh discord that mirrors the tenor of grief.
From this zoom-focus view of familial existence amid calamity, great things are heard only in whispers and factory gossip. The shadows of comfort women hover throughout. There are shadows, too, of nuclear bombs. Sunja learns early on that: “A woman’s life is endless work and suffering. It is better to expect it.”
Pachinko is such an elemental novel. It cuts hard at our feelings. Food is a constant theme, the empty bellies of wartime, the dire need to eat, the heat and reek of the streets. Humiliations abound: bullying, abuse (and worse), identity cards and the anaesthetic brutality of bureaucracy. Yet the characters keep playing the game of life undaunted, as people without power must, and people with great reserves of strength can.
Lee is a master of showing how when fate — or patience — can snap, and the bareness of its aftermath. The real moral question she wrestles with is the dichotomy honour and dishonour: when the world strips you of your very roots, how do you grow? The divergent fates of Sunja’s sons are piercing. Noa buries himself deep in imagining himself Japanese, in shedding every aspect of his dishonour, while Mozasu embraces what life he can, lowering his sights and pulling himself up. The upshot is thick with tragedy and compromise.
Far offstage, as North Korea becomes a hermit kingdom, those inevitable longings for home are never rendered simple or nostalgic. Those who go back are never heard from again. Those who move back and forth like the yakuza Kohsu are damaged by the burden and dislocation of bearing two cultures at once. There is escape, but never back into the world that was lost, the place where belonging was possible.
When Noa finds a new family, passing as Japanese, he feels that, “Though he valued his wife and children as a kind of second chance, in no way did he see his current life as a rebirth.”
In universalising a unique migrant experience into an essential and symbolic drama of persevering hurt, there is a huge ambition within this novel. Lee’s prose is cool and unobtrusive, every claim is made with weight and a depth of feeling.
The consequence is a vision less of despair than of a world where work and chance collide, where one kind of wit and savvy displaces another, where survival and coexistence is always the name of the game. “Pachinko was a foolish game, but life was not,” Mozasu’s wife reflects. And there is an insistent sense of reality behind the music of frustration and hope, a quiet credible resonance, as Mozasu puts it, “Adapt. Wasn’t it as simple as that?”
<NAME> is a writer and critic.
Pachinko
By <NAME>
Head of Zeus, 490pp, $32.99<file_sep>/content/writing/new-york-review-of-books--review-of-han-kang-s-human-acts.md
---
title: 'The New York Review of Books: "Korean Souls" A Review of Han Kang''s HUMAN
ACTS'
date: 2018-07-19 04:21:33 +0000
images: []
image_credit: ''
categories: []
where_published: The New York Review of Books
link_to_original: https://www.nybooks.com/articles/2018/07/19/han-kang-korean-souls/
description: '"<NAME>, the South Korean writer who won the Man Booker International
Prize in 2016 for her novel The Vegetarian, was nine years old in 1979 when a new
military regime came to power in South Korea after a coup. Her family had just sold
their house in Gwangju, where she had been born and raised, and moved to Seoul.
The family that purchased it had two sons. Han’s father, a teacher, knew the younger
of the two, a fifteen-year-old middle school student named Dong-ho." (To read, please
click the link.)'
---
<file_sep>/content/event/talks-google.md
---
show_time: false
title: 'Talks@Google '
date: 2020-05-27T12:00:00-04:00
description: ''
venue:
address: 76 Ninth Ave,
city: New York
name: Google New York Office Building
state: New York
zip: "10011"
link: ''
images: []
---
<file_sep>/content/news/2017-10-29-interview-on-writers--company-with-eleanor-wachtel-audio.md
---
title: Interview on Writers & Company with <NAME> (Audio)
date: 2017-10-29 12:00:00
categories: ["Media"]
tags:
- Audio
- News
- Interviews
attribution: 'CBC Radio: Writers & Company'
link_to_original: >-
http://www.cbc.ca/radio/writersandcompany/min-jin-lee-on-the-untold-story-of-koreans-in-japan-1.4371100
description:
---
Sunday October 29, 2017
<NAME> on the untold story of Koreans in Japan
Pachinko is Korean-American author <NAME>'s second novel. (<NAME>/minjinlee.com)
LISTEN TO FULL EPISODE 1:02:01
Pachinko is a cross between pinball and a slot machine. In Japan, the game is a $200-billion business. It's also the title of Korean-American writer <NAME>'s second novel, which was recently named a finalist for the National Book Award.
Following a single family over several generations, Pachinko explores the experience of Koreans in Japan, most of whom were born and grew up there, but are still classified as "resident aliens." The novel's critical acclaim follows the success of <NAME> Lee's previous book, Free Food for Millionaires — a sharp-sighted tale of Korean-American immigrants. It was a bestseller, a New York Times editors' choice and named one of the top 10 novels of the year by the Times of London.
<NAME> was born in Seoul, South Korea in 1968. Her family immigrated to the United States when she was seven. She grew up in a blue-collar neighbourhood in Queens, New York.
The failures of history
"One thing that struck me in my study of history is how people are excluded. I don't mean just racial minorities or women. Pretty much all poor people who don't have documents are excluded from history and its records. People who were illiterate usually didn't leave any primary documents. I was interested in how we think about people because the history that we have is limited to an elite body. In my experience of trying to interview people from all different backgrounds, especially the very, very poor and the illiterate, I notice that their attitude is, 'We know that we weren't included in the party. However, we are fine. We're still going to keep on going. It doesn't matter. We're just going to adapt.' That is the primary idea of this book. History has failed pretty much everybody. And yet no matter, we persist."
Exploring Korea's painful past
"In the 21st century and in the latter part of the 20th century, we think of South Korea and North Korea. But for 5,000 years, there was just Korea. When it was just Korea, it essentially became a colony of Japan. Japan, which is a wonderful country, has very few natural resources. So when Japan wanted to expand, Korea became its breadbasket. They took a lot of things from Korea and the experience of most Koreans of that era is one of general humiliation because they had their property, language and a lot of their authority taken away. The experience of the people who lived under the occupation was very difficult because they lost their national identity. A lot of people don't like to talk about it. It's a period of history that's very complicated for the modern Korean to tackle because it's one of humiliation."
Expanding Western education
"We have huge holes in our education in the West. I think that we have little knowledge of Asian history. If you ask a well-educated, modern Western person about World War II, most will think that the theatre of war was only in Europe. But it's known that the Pacific War was going on concurrently, and we don't know anything about it. The 20th century Cold War proxy wars all took place in Asia. Yet again, we know hardly anything about it. This is a failure of the educational system. But people decide what is worth studying. We are going to have to know much more about Asia and the Middle East than we want to, or think that we need to know in the West."
Recognizing the Korean Japanese experience
"If I force myself to wonder what made me think about and work on this book for almost 30 years, it's this sense that the Korean-Japanese experience was never my experience. I moved to Queens, New York when I was seven and a half. I went to middle school in a foreign country, but I had so many different kinds of Americans push me along and encourage me. I was very odd. I didn't talk very well, we were poor and we didn't have any connections, but people showed up and pushed me along. I knew that there was something wrong if a country not only rejected you, but also your parents and your grandparents. This is what happened to the Korean-Japanese. Even today, they're not considered citizens."
<NAME>'s comments have been edited and condensed.
Music to close the broadcast program: "Arirang," performed by <NAME>, <NAME> and <NAME>.
To listen to the full episode, please click the link.<file_sep>/content/news/2017-02-28-the-millions-pachinko-review.md
---
title: 'The Millions: Pachinko Review'
date: 2017-02-28 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Millions by <NAME>
link_to_original: 'http://www.themillions.com/2017/02/people-without-home-min-jin-lees-pachinko.html'
description:
---
By <NAME>
Last December, <NAME> introduced her new novel in a YouTube video. In the video, Lee recalls a university lecture she heard when she was 19 about the Korean population in Japan. The lecturer discussed Japan’s colonization of Korea, and told of a Korean-Japanese family he knew whose son had committed suicide by jumping off the roof of their apartment building. After his death, his parents found his middle school yearbook. In the video, Lee, fighting back tears, lists the things his classmates had written in it: “Go back to where you belong;” “You smell like garlic;” “Die, die, die.” It’s a story that has stayed with Lee for almost three decades. It was the beginning of her desire to write a historical novel about Koreans in Japan.
Fans of Lee’s debut, Free Food for Millionaires, will recall a novel centered on Korean-Americans in working class Queens. But the author’s shift into historical fiction does not mean that Pachinko is a departure for Lee. Free Food fans will recognize in Pachinko Lee’s nimble 19th-century style omniscient narration, as adept at illuminating the lives of our central characters as it is those of their acquaintances and lovers (and even the occasional shop girl or bartender). Here, too, is a story of class aspiration, of living and sacrificing for the next generation. Finally, like Free Food, Pachinko is a novel about a community, a Middlemarch-inspired web of characters.
We begin in Busan, Korea at the turn of the century with the birth of Hoonie, who, a few years after Japan’s annexation of Korea in 1910, marries Yangjin, with whom he fathers Sunja. As a teen, Sunja is seduced and impregnated by charismatic yakuza Koh Hansu, or as he’s known to most: Boss Koh. Hansu, Sunja learns, is married, and though he promises to always support Sunja and their child, he tells her her cannot leave his wife for reasons related to business. Enter Baek Isak, a profoundly kind minister who’s stopped at the family’s boarding house on his way to an appointment in Japan. Isak offers to marry her, bring her with him, and raise the child as his own. Sunja, not wanting to bring shame to herself and her family, accepts, and we’re off to Osaka.
But life in Japan is brutal for Koreans. Sunja and Isak move in with Isak’s brother Yoseb, and his wife, Kyunghee. Yoseb orders Isak — who he knows to be generous to a fault — not to give food or money to his new neighbors; to let it be known that you have the least bit extra is to invite robbery. Yoseb warns Isak: “We’re all hungry…Be extra careful around other Koreans. The bad ones know that the police won’t listen to our complaints.” The police are all Japanese. Judges, too. In Japan, Koreans face discrimination at every turn. How, Lee’s epic asks, does one survive in a society that considers you subhuman?
Well, there are few approaches. As the novel progress, Sunja gives birth to two sons: Noa, her child by Hansu — though, of course, that’s a secret — and Mozasu, her child with Isak. Noa excels in school, puts up with the other children calling him names, and is proud when teachers tell him that he is “a good Korean.” Mozasu on the other hand becomes a ferocious fighter, whooping anybody who disrespects him or his family. Noa dreams of becoming an educated man. But it’s Mozasu, ironically, who’s more like Hansu (who, by the way, we have not seen the last of), harboring no faith in the fairness of the system and choosing instead to work whatever angles he can: while still a child, Mozasu tells Noa: “I want to make a lot of money, then umma and Aunt Kyunghee wouldn’t have to work anymore.”
It’s these aspirations that lead Mozasu into pachinko, a game comparable to pinball (but played for money), and a business looked down upon by most. In pachinko, Mozasu sees a metaphor for life:
His Presbyterian minister father had believed in divine design, and Mozasu believed that life was like this game where the player could adjust the dials yet also expect the uncertainty of factors he couldn’t control. He understood why his customers wanted to play something that looked fixed, which also made room for randomness and hope.
Mozasu is a success in the pachinko business, coming to manage, then own, several parlors. Decades pass. The family grows.
But are they at home in Japan? Is there such thing as home for the Korean-Japanese? As Mozasu puts it: “In Seoul, people like me get called Japanese bastard, and in Japan, I’m just another dirty Korean no matter how much money I make, or how nice I am.” In this novel, the question of home dovetails nicely with the theme of fatherhood. To what extent can Japan, a society that despises Koreans, ever be these characters’ home? To what extent is Noa, who wants only to be educated and virtuous like Isak, the man who raised him, still Hansu’s son? What does it mean to be connected to another person? To a nation? Lee offers us no simple answers.
But we don’t read novels for simple answers, do we? We read novels to get a glimpse of the world through someone else’s eyes. Lee does that for us here, and she does it while maintaining a light touch. Lee is not an author interested in dazzling you with her prose or reinventing the novel form (Pachinko’s structure is most like that of 19th-century British novels), preferring instead to keep her story and characters front and center. But somehow, she’s there on every page, present but invisible. That YouTube video I mentioned? I didn’t see it until after I’d finished the book. But I didn’t need that video to tell me that this story is deeply important to Lee. I felt it in every line. And when I reached the end, I knew that, like Lee when she heard the lecture that would inspire this novel, I’d just heard a story that would stay with me for a long time.
<NAME> holds an MFA in fiction from Rutgers University-Newark and teaches writing and literature at St. John’s University and Queensborough Community College. His work has appeared in The Lit Pub and The Common Online. He grew up on Long Island.<file_sep>/content/event/sedge_thomsons_west_coast_live.md
---
title: <NAME>’s WEST COAST LIVE
date: 2007-06-23T10:00:00-05:00
venue:
name: WEST COAST LIVE, Ferry Building, San Francisco, CA
link: www.wcl.org
_slug: sedge_thomsons_west_coast_live
---
<NAME>’s West Coast Live: San Francisco’s Live Radio Show to the World.
<NAME>, Eat Well Farms, with his rooster; <NAME>, “I’ll Sleep When I’m Dead; <NAME>; and <NAME>: FREE FOOD FOR MILLIONAIRES.
Please note that this is a ticketed event. For tickets: 415-664-9500 or Ticketweb.
<file_sep>/content/event/the-cosmopolitan-club.md
---
title: The Cosmopolitan Club
date: 2017-05-16 18:30:00
show_time: true
venue:
name: The Cosmopolitan Club
address: 122 East 66th Street
city: New York
state: NY
zip: '10065'
link: 'https://www.cosclub.com'
---
In Conversation with <NAME>, writer, food stylist, developer and Owner of Bottom Food Works<file_sep>/content/news/2017-01-24-pen-ten-interview.md
---
title: PEN TEN Interview
date: 2017-01-24 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: Pen Ten Interview with <NAME>
link_to_original: 'http://pen.org/pen-ten-min-jin-lee/'
description:
---
THE PEN TEN WITH MIN JIN LEE
By: <NAME> January 24, 2017
In this week’s PEN Ten, <NAME>, co-founder of the PEN Ten interview, speaks with <NAME>.
When did being a writer begin to inform your sense of identity?
I wrote and published essays in The Korea Times when I was in high school. Many years later, I quit being a lawyer to write full-time. However, neither early publication nor quitting a career made me feel like a writer. I began to feel like a real writer when I started taking evening writing classes at the 92nd Street Y in my late 20s and early 30s, because I met other adults who were serious about craft and were willing to disrupt their lives to learn it.
Whose work would you like to steal without attribution or consequences?
I’d steal themes from <NAME>, <NAME>, <NAME>, and <NAME>; plot from <NAME>, <NAME> and <NAME>; and sentences from <NAME> and <NAME>.
Obsessions are influences—what are yours?
I’m obsessed with faith, inequity, lost love, and history.
What’s the most daring thing you’ve ever put into words?
In college, I wrote and published essays about feminism, educational reform, and identity politics. I recall taking some flak for my views. However, later in life, I found it much tougher and riskier to write about my illnesses and failures.
Have you ever been arrested? Care to discuss?
Not yet.
When, if ever, is censorship acceptable?
I think it is advisable to censor oneself from harming others unnecessarily. Not everything should be said or written. I don’t mind if you disagree, but I find meanness untenable. That said, I do not believe that governments should censor the press—the bulwark of a true democracy. Lately, what I find alarming is that rather than just censoring information or ideas (limiting/blocking), oppressive governments are disseminating false ideology and lies through purportedly legitimate news channels, creating a nearly impossible environment for individuals to discern the truth and to behave appropriately.
What is the responsibility of the writer?
For me, it is to observe carefully and to think deeply about what I see, then and only then to record my impressions fairly and accurately. Whether in fiction or nonfiction, I want to be a fair and emotionally truthful writer. Also, I think I should tell a story worth the reader’s time and attention.
While the notion of the public intellectual has fallen out of fashion, do you believe writers have a collective purpose?
More than ever, we need public intellectuals. The essays of <NAME>, <NAME>, bell hooks, <NAME>, <NAME>, and <NAME> changed my life and gave me courage to persevere. More recently, smart writers like <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> are leading new ways of thinking in their respective fields.
What book would you send to the leader of a government that imprisons writers? or What book would you like to see on the incoming administration’s reading list?
For what it’s worth, I would send leaders of repressive regimes The Drama of the Gifted Childand For Your Own Good by psychoanalyst <NAME>, and gosh, maybe some good texts by pediatrician and psychoanalyst <NAME>. If I could, I’d send along a talented therapist.
Where is the line between observation and surveillance?
All of us need the powers and tools of observation. As writers, observation is our way to study, reflect, shape, and express. As writers, we fear and fight surveillance because surveillance is when those who are in power use the tools of observation against the observed and use the information gained in surveillance against the observed when the behaviors of the observed are inconvenient to those who are in power.
<NAME>’s debut novel Free Food for Millionaires was a No. 1 Book Sense Pick, a New York Times Editor’s Choice, a Wall Street Journal Juggle Book Club selection, and a national best seller; it was one of the Top 10 Novels of the Year for The Times of London, NPR’s Fresh Air, and USA Today. She has received the NYFA Fellowship for Fiction, the Peden Prize from The Missouri Review for Best Story, and the Narrative Prize for New and Emerging Writer. Her fiction has been featured on NPR’s Selected Shorts and has appeared most recently in One Story. <NAME> went to Yale College where she was awarded both the Henry Wright Prize for Nonfiction and the James Ashmun Veech Prize for Fiction. She attended law school at Georgetown University and worked as a lawyer for several years in New York prior to writing full-time. From 2007 to 2011, <NAME> lived in Tokyo, Japan where she wrote Pachinko (February 7, 2017). She lives in New York City with her family.<file_sep>/content/event/bookbar.md
---
title: BookBar
date: 2017-02-14 19:00:00
show_time: true
venue:
name: 4280 Tennyson Street
address:
city: Denver
state: CO
zip: '80212'
link: 'http://www.bookbardenver.com'
---
<file_sep>/content/news/2017-03-26-michigan-daily.md
---
title: Michigan Daily
date: 2017-03-26 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Michigan Daily
link_to_original: 'https://www.michigandaily.com/section/arts/pachinko-book-review'
description:
---
'Pachinko' is an intimate yet expansive immigrant story
<NAME>
Daily Arts Writer
Sunday, March 26, 2017
<NAME>’s second novel is a sprawling saga about a Korean family during the Japanese occupation of Korea. Spanning four generations, “Pachinko” explores questions of immigration, discrimination, political unrest and national identity. The family’s mindset is introduced in the opening line: “History has failed us, but no matter.” Their resilience is woven through the rest of the novel, a tale of an ordinary family that tumbles and endures.
Lee’s straightforward yet fluid prose contextualizes personal stories within the wider scope of political history. The novel spans from 1910 to 1989, and first introduces readers to Hoonie, a poor countryside boy in Korea. His wife, Yangjin, takes charge of their humble boarding house, toiling long hours to put food on the table of the unofficial family of boarders and maids packed in the small quarters.
When Yangjin’s daughter, Sunja, gets pregnant out of wedlock, she enters a marriage of convenience with a visiting Korean minister. The couple migrates to Osaka, where Koreans are treated as second-class citizens. They struggle to make Japan their home, since the Korea they know as “home” eventually splits into North and South Korea, and their family and friends scatter.
Their children Noa and Mozasu, as second-generation immigrants, face a different set of struggles. Born in Japan, but ethnically Korean, they embody an in-between state between cultures that makes them question their identity. They grew up attending Japanese schools and assimilating to the culture, yet they are never fully accepted by Japanese classmates and employers. On the other hand, they are removed from the experience of growing up in Korea, so they lack a strong emotional tie to a single nation.
Meanwhile, political unrest continues, changing lives for both the Koreans and Japanese in the story. Japan is rumbled by its involvement in World War II, changing the socioeconomic landscape of the family’s story once again.
These political events transpire in the backdrop. They appear indirectly, in the way they impact characters’ daily lives, relationships and decision-making. What makes Lee’s novel so rich is the use of national politics as a foundation upon which a set of fully developed characters is built, molding a unique family identity that blends culture with the personal.
The novel’s title, “Pachinko,” which refers to a Japanese gambling machine, is a fitting descriptor of the immigrant experience. It’s the family’s gamble of moving to another country, the questions and confusions that come with the unknown. It’s a gamble with the odds stacked against them, forcing immense sacrifice, pain and loss.
Yet at the same time, working at a pachinko parlor is the occupation that eventually helps the family establish themselves. It’s a gamble that holds the beaming hope that through hard work and resilience, families can win the opportunity to etch their story permanently into the history and community of a new country.
“Pachinko” is a novel that winds through lifetimes, cycling through new worlds as the political climate evolves. But whether the world involves Korean countrysides, tightly sealed bottles of kimchi, urban ghettos, police visits or university schooling, one force remains present throughout: The fierce loyalty the characters have to protect the people they love. Through the web of family, four generations ultimately find home.<file_sep>/content/event/amherst-college-3.md
---
title: Midwest Literary Walk
date: 2019-04-27 13:00:00 -0400
show_time: true
venue:
name: Chelsea First Congregational Church
address: 121 E. Middle Street
city: Chelsea
state: MI
zip: 48118
link: http://midwestliterarywalk.org/min-jin-lee/
description: ''
images:
- "/uploads/MWLW_logo_Title_H2.png"
---
<file_sep>/content/news/2017-12-28-history-channel-best-books-of-2017.md
---
title: 'History Channel: Best Books of 2017'
date: 2017-12-28 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: History
link_to_original: >-
http://www.history.com/news/the-best-books-shows-films-and-podcasts-of-2017-for-history-lovers
description:
---
The Best Books, Shows, Films and Podcasts of 2017 for History Lovers
FICTION
The year’s best historically inflected fiction offered reflections on wars and family ties across generations.
In a year when the Syrian refugee crisis loomed large, Pulitzer Prize–winner Viet Nguyen gathered short stories of people linked by the experience of the Vietnam War and its legacy in the collection The Refugees (Grove Press). Against the backdrop of the Civil War, <NAME>’s young son Willie entered the liminal realm of ghosts in Lincoln in the Bardo (Random House) in the latest from Man Booker Prize–winner George Saunders. In her second novel, Pachinko (Grand Central Publishing), <NAME> traced the story of one Korean family through the 20th century, from Japanese-occupied Korea to 1980s Japan. <NAME> reworks the ancient story of Antigone in Home Fire (Riverhead Books), a family tale set in the time of ISIS. An Irish-Catholic enclave in Brooklyn became the setting for <NAME>’s The Ninth Hour (Farrar, Straus and Giroux), a story centered on a widow, her daughter and a convent of nuns. <NAME> explores the intertwined lives of a Ukrainian town in the days after the German invasion of 1941 in A Boy in Winter (Pantheon).
For the complete list, please click the link.<file_sep>/content/news/2007-07-22-sun_sentinel.md
---
title: "Sun-Sentinel"
date: 2007-07-22T23:06:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: ""
link_to_original: ""
description: ""
_slug: 2007-07-22-sun_sentinel
---
Here’s what we know about <NAME>, the heroine of <NAME>’s sprawling first novel: She’s the daughter of…
<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-5.md
---
title: 'NY Post: The 10 best books to read to beat coronavirus boredom'
date: 2020-03-18T00:50:11-04:00
link_to_original: https://nypost.com/2020/03/18/the-10-best-books-to-read-to-beat-coronavirus-boredom/
images: []
tags: []
categories: []
description: ''
---
> _Free Food for Millionaires_, <NAME> (fiction, Grand Central Publishing)
>
> "<NAME> is the Queens-bred daughter of Korean immigrants, back in the city after graduating from Princeton and realizing her expensive degree is no match for the credit card debt she’s racked up. As she navigates the city, trying to figure out where she fits in this privileged world, she questions what will truly make her happy."<file_sep>/content/event/petes-reading-series.md
---
title: "Pete's Candy Store: Pete's Reading Series"
date: 2017-04-06 19:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Curated and hosted by <NAME> and <NAME>. Featuring <NAME>, <NAME>, and <NAME>. With WORD Bookshop.<file_sep>/content/event/onondaga-central-library-an-evening-with-min-jin-lee.md
---
show_time: false
title: Onondaga Central Library - An Evening with <NAME>
date: 2021-02-23T19:30:00-05:00
description: Virtual
venue:
address: '411 Montgomery St. '
city: Syracuse
name: The Oncenter Crouse Hinds Theater
state: NY
zip: ''
link: https://www.foclsyracuse.org/events-calendar/
images: []
---
<file_sep>/content/event/yale_university.md
---
title: Yale University
date: 2007-10-25T13:25:00-05:00
venue:
name: Yale University, New Haven, CT
link:
_slug: yale_university
---
October 25 and 26th
Reading and Q&A and the American Studies Salon
Professor <NAME>, Ph.D., Chairman of the American Studies Department
<file_sep>/content/event/junior_league_of_richmond.md
---
title: Junior League of Richmond
date: 2008-05-06T04:22:00-05:00
venue:
name: 63rd Book & Author Dinner of the Junior League of Richmond
link: www.jlrichmond.org
_slug: junior_league_of_richmond
---
7PM Greater Richmond Convention Center
<NAME>, PREDICTABLY IRRATIONAL: The Hidden Forces That Shape Our Decisions
<NAME>, THE PRINCE OF FROGTOWN
<NAME>, THE GIRL WITH NO SHADOW
<NAME>, THE FOOD YOU CRAVE: Luscious Recipes for a Healthy Life
<NAME>, FREE FOOD FOR MILLIONAIRES
<NAME>, LADIES OF LIBERTY: The Women Who Shaped Our Nation
This is a TICKETED event.
<file_sep>/content/event/amherst-college-21.md
---
title: 'Authors to the Pointe: <NAME> & <NAME>'
date: 2019-10-19T07:00:00-04:00
show_time: true
venue:
name: Grosse Pointe War Memorial
address: 32 Lake Shore Dr
city: Grosse Pointe Farms
state: MI
zip: "48236"
link: https://grossepointelibrary.org/news/authors-to-the-pointe-tickets-on-sale
description: ''
images: []
---
<file_sep>/content/news/the-huntington-news-author-min-jin-lee-speaks-with-students-as-part-of-the-visiting-distinguished-writer-series.md
---
title: 'The Huntington News: "Author <NAME> speaks with students as part of the
Visiting Distinguished Writer series"'
date: 2018-11-14 18:30:10 -0500
link_to_original: https://www.huntnewsnu.com/2018/11/author-min-jin-lee-speaks-with-students-as-part-of-the-visiting-distinguished-writer-series/
images:
- "/uploads/20181107-Min-Jin-Lee-HN-Dylan-Shen-1-1024x732.jpg"
tags: []
categories: []
description: ''
---
<file_sep>/content/event/jonny-sun-with-min-jin-lee-goodbye-again-essays-reflections-and-illustrations.md
---
show_time: true
title: '<NAME> with <NAME> / Goodbye, Again: Essays, Reflections, and Illustrations'
date: 2021-05-04T21:00:00-04:00
description: 'Booksmith is thrilled to host <NAME> for his new book Goodbye, Again:
Essays, Reflections, and Illustrations. He''ll be in conversation with the one and
only <NAME> (Pachinko)!'
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.booksmith.com/event/jonny-sun
images: []
---
<file_sep>/content/event/richmond-va-tuckahoe-woman-s-club.md
---
title: 'The Denver Post: Pen & Podium - Postponed '
date: 2020-03-16T23:30:00.000+00:00
show_time: true
venue:
name: Newman Center for the Performing Arts
address: University of Denver
city: Denver
state: CO
zip: "80210"
link: https://www.penandpodium.com/authors/min-jin-lee
description: ''
images:
- "/uploads/PenandPodium-logo-1.png"
---
<file_sep>/content/news/announcing-2018-2019-radcliffe-institute-fellows.md
---
title: Announcing 2018-2019 Radcliffe Institute Fellows
date: 2018-05-08 00:41:04 -0400
images: []
image_credit: ''
categories: []
where_published: Radcliffe Institute for Advanced Study at Harvard University
link_to_original: https://www.radcliffe.harvard.edu/news/press-releases/announcing-2018-2019-radcliffe-institute-fellows
description: ''
---
<file_sep>/content/writing/nyt-a-lifetime-of-reading-taught-min-jin-lee-how-to-write-about-her-immigrant-world.md
---
categories:
- Essays
date: 2021-04-07T06:00:13.000Z
description:
images: []
link_to_original: 'https://www.nytimes.com/2021/04/07/books/review/min-jin-lee-writer.html'
tags: []
link_to_pdf:
title: >-
NYT: A Lifetime of Reading Taught <NAME> How to Write About Her Immigrant
World
where_published: The New York Times
---
"As I walked home from the train station, it occurred to me that I had to write about the disgraced, the poor and the earnest strivers of Queens, and I would be able to tell their stories not because I was a writer but because I was a reader."<file_sep>/content/news/2017-05-24-times-literary-supplement-book-review-of-books-by-bandi-j-m--lee-mun-yol-yi-and-jieun-baek.md
---
title: 'Times Literary Supplement: Book Review of books by Bandi, <NAME>, <NAME>, and <NAME>'
date: 2017-05-24 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Times Literary Supplement by <NAME>
link_to_original: 'http://www.the-tls.co.uk/articles/private/north-korea/'
description:
---
Fictions of North Korea
By <NAME>
In December 1950 my grandmother sent my father, who was then sixteen, from the northern Korean port city of Wonsan to Busan in the south, to keep him safe from the communist army. He never saw his mother, brothers and sisters again. If my uncles, aunts and cousins have survived, I wonder to what extent they resemble my grandmother, whose peaceful face I have stared at countless times in the worn photograph my father has carried with him since their final meeting. Today, less than seventy years since the formation of the two Korean republics in 1948, most inhabitants of the peninsula cannot even remember living as one nation, and to South Koreans the North has become a mystery.
Three works of fiction by Korean writers now available in translation address the significant question of life in North Korea. The Accusation by Bandi, a collection of seven stories depicting…
Please consider a digital subscription to the TLS.<file_sep>/content/news/2008-05-14-central-fallout-podcast-interview.md
---
title: "Fallout Central Podcast"
date: 2008-05-14 12:00:00
categories:
- Media
tags:
- Video
- Interviews
attribution:
link_to_original:
description:
---
<iframe width="560" height="315" src="https://www.youtube.com/embed/_wNtnmInv4Y" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/5kNPLJTn0Po" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/s6YDGxQ0waQ" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/cxZIo1V70xU" frameborder="0" allowfullscreen></iframe>
<file_sep>/content/event/pen-world-literature-festival.md
---
title: 'PEN WORLD LITERATURE FESTIVAL: GENDER & POWER'
date: 2017-05-03 19:00:00
show_time: true
venue:
name: The Tenement Museum
address: 103 Orchard Street
city: New York
state: NY
zip: '10002'
link: 'http://worldvoices.pen.org/schedule/'
---
Literary Quest: Tenement Museum Edition: Festival audiences are invited to readings in the apartments of the Lower East Side Tenement Museum, with <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and Mariposa who draw inspiration from the historic family dwellings. (Lower East Side Tenement Museum; Wednesday, May 3)
This is a ticketed event for $25. The event is free for members of the Tenement Museum.<file_sep>/content/review/jens-book-reviews-on-free-food-for-millionaires.md
---
title: Jen's Book Reviews on Free Food for Millionaires
attribution: Jen's Book Reviews
date: 2007-03-11 18:04:36 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Leave your world behind and explore this story set against an interesting cultural backdrop. This is a book I thought about often at work, and could not wait to get home and dive into the story …<file_sep>/content/review/new-york-times-pachinko-review.md
---
title: New York Times Pachinko Review
date: 2020-01-15T00:00:00-05:00
attribution: <NAME> for the New York Times
book: book/pachinko.md
description: ''
featured: false
weight:
---
<NAME>’s stunning novel “Pachinko” — her second, after “Free Food for Millionaires” (2007) — announces its ambitions right from the opening sentence: “History has failed us, but no matter.”<file_sep>/content/event/amherst-college-23.md
---
title: 'Thalia Book Club: The Age of Innocence Turns 100'
date: 2020-01-21T19:30:00-05:00
show_time: true
venue:
name: <NAME>
address: Symphony Space
city: New York
state: NY
zip: "10025"
link: https://www.symphonyspace.org/events/thalia-book-club-edith-wharton-the-age-of-innocence
description: '"Edith Wharton’s Pulitzer Prize-winning portrait of Gilded Age New York
City turns 100 in 2020, and we’re celebrating with writers and admirers, including
<NAME> (THE IDIOT), <NAME> (THE CHELSEA GIRLS, THE MASTERPIECE), Min
<NAME> (PACHINKO), and <NAME> (BROOKLYN)."'
images:
- "/uploads/age-of-innocence_showname-Main-Image-1-symphony-space.jpg"
---
<file_sep>/content/review/asia-pacific-arts-on-free-food-for-millionaires.md
---
title: Asia Pacific Arts on Free Food for Millionaires
attribution: Asia Pacific Arts
date: 2007-03-11 18:06:42 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Then comes <NAME> and her acclaimed new novel Free Food for Millionaires, which takes a Jane Austen-type look at love, education…<file_sep>/content/news/2019-demott-lecture-at-amherst-college-video.md
---
title: 'Radcliffe Magazine: How to Write What You Don''t Know'
date: 2019-09-18T00:50:11-04:00
link_to_original: https://www.radcliffe.harvard.edu/news/radcliffe-magazine/how-to-write-what-you-dont-know
images:
- "/uploads/lee-greenidge-groff_305px.jpg"
tags:
- Media
- news
categories: []
description: In the stories of <NAME>, <NAME>, and <NAME>, research
is a recurring theme.
---
[https://www.radcliffe.harvard.edu/news/radcliffe-magazine/how-to-write-what-you-dont-know](https://www.radcliffe.harvard.edu/news/radcliffe-magazine/how-to-write-what-you-dont-know "https://www.radcliffe.harvard.edu/news/radcliffe-magazine/how-to-write-what-you-dont-know")<file_sep>/content/writing/literary-hub-.md
---
title: 'Literary Hub: Love in the New World '
date: 2017-11-15 00:35:08 -0500
images: []
image_credit: ''
categories: []
where_published: Literary Hub
link_to_original: https://lithub.com/min-jin-lee-love-in-the-new-world/
description: ''
---
<file_sep>/content/writing/lithub-on-selling-your-first-novel-after-11-years.md
---
title: 'Literary Hub: On Selling Your First Novel After 11 Years'
date: 2017-01-10 03:39:00 +0000
categories: []
tags:
- Publishing
where_published: LitHub
link_to_original: https://lithub.com/on-selling-your-first-novel-after-11-years/
link_to_pdf:
description: On the 10th Anniversary Edition Publication of FREE FOOD FOR MILLIONAIRES
_slug: 2007-03-01 00:00:00 +0000
images: []
image_credit: ''
---
I had already failed at two novel manuscripts. Publishers had rejected my first manuscript, and I rejected the second, because it was not good enough to send out. I was 32 years old and beginning my third novel.
I had been trying to get a novel published since 1995, the year I quit being a lawyer. Since high school, I’d had a chronic liver disease, and I couldn’t work the hours of a Manhattan law firm without getting ill, so I thought I’d write fiction. My husband Christopher had a steady job with health insurance, but we had gotten our apartment and mortgage with two incomes in mind. Money was tight. After a miscarriage and a difficult pregnancy, our son Sam was born, and that same year, we learned that beloved family members, who could no longer support themselves, were awash in catastrophic debt, and suddenly, we were responsible for another household.
It is never a financially prudent idea to be a fiction writer, but I had not anticipated running through my savings in a year, being unable to earn even a modest living, not being able to afford part-time childcare to write, having a debilitating liver disease, and taking on the debts of people I love.
I was ashamed. After six years, I had not yet written a published novel, and I was broke from the choices I had made. I wondered how we’d pay all these bills, send Sam to college, and save for retirement. When my friends asked me to lunch, I made excuses because I could not afford the luxury of eating out. I could not answer when they asked kindly when my book would be available to purchase. I hid my failure by staying home.
From the moment I quit lawyering, I tried to learn how to write good fiction. I had written and published personal essays in high school. I was a history major in college, but for pleasure, I’d taken three writing classes in the English department. To my surprise, in my junior and senior years, I won top writing prizes for nonfiction and fiction, respectively. It’s possible that the college prizes misled me to believe that I could publish a novel immediately after quitting the law. However, the more I studied fiction, the more I realized that writing novels required rigorous discipline and mastery, no different than the study of engineering or classical sculpture. I wanted to get formal training. Nevertheless, after having paid for law school, I could not hazard the cost of an MFA. So, I fumbled around and made up my own writing program.
Always a reader of the 19th-century greats, I read more widely. I read every fine novel and short story I could find, and I studied the ones that were truly exceptional. If I saw a beautifully wrought paragraph, say from <NAME>’s Three Junes, I would transcribe it in a marble notebook. Then, I would sit and read her elegant sentences, seemingly pinned to my flimsy notebook like a rare butterfly on cheap muslin. Craft strengthened the feelings and thoughts of the writer. When I read and reread Junot Díaz’s stories in Drown, I was struck by his courage and genius. His perfect narrative voice matched the intricacy and greatness of his plot architecture. Great fiction required not just lovely words or fine feelings, it demanded emotion, structure, ideals, and bravery. Fine works of fiction made me feel glad, the way I feel glad when I see a painting by a master, an ocean at dusk, or the face of a child.
In New York, it is possible to study with great writers for very little money. If one can afford to live here, there is a shock of riches in culture, so much so that artists work for almost nothing. Once a week, when Christopher could watch Sam after work, I took a turkey sandwich in a baggie or a carton of hummus and went to my writing classes or met with my writers’ group. For less than $200, I was able to study for several weeks with <NAME>, <NAME>, and <NAME> at the Asian American Writers’ Workshop early on in their careers. I took a class at the Gotham Writers Workshop with <NAME>. For about the same amount and for a season’s length of classes, I studied with <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> at the 92nd Street Y. The Y runs a famous preschool, and in the evenings, grown men and women sat in these preschool classrooms, smelling of tempera paints and box apple juice, anxious to know if their stories made any sense. Teachers generously encouraged me to continue, but privately, I wondered if I should quit. I was getting older, and I was afraid that I could not return to a steady profession.
The year after Sam was born, impulsively, I applied for a spot at the Sewanee Writers’ Conference and was accepted. The tuition was more money than we could spare, something like $1,000. However, I knew it was difficult to get a spot at all, and I felt I had to go. I had nursed Sam for a year, and I thought this might be a good reward for having given up my body—or so it seemed to me—for the pregnancies, the illnesses, and the breastfeeding. Christopher took time off from work and stayed with Sam, and I went to Tennessee. For nine days, I studied fiction with <NAME> and <NAME>. Each day, after my class, I would go back to my dorm room and cry because I missed my baby.
At Sewanee, it felt like everyone had gone to prestigious MFA writing programs like Iowa and had book contracts. Back then, conference attendees wore name tags, and mine read just my name, indicating that I had not received any scholarship money to defray the cost of the conference tuition. One day, during lunch, I met a young woman whose name tag stated her name plus the name of her fellowship. She hadn’t paid any tuition because her publications had merited her a scholarship. There was a group of us at the table, most of whom had scholarships, and the young woman casually mocked the housewives who had paid full freight to attend the conference. I didn’t realize at first, but she was talking about me. That summer, I was 30 years old, a new mother, and I learned that a talented young woman artist held housewife writers in contempt. I couldn’t eat so I returned to my room. I avoided her for the rest of the conference, because I sensed she was right. It had been a mistake to come all this way to take a class. Then at the end of the conference, <NAME> nominated my workshop story for an anthology called Best New American Voices 2000, and though the editors didn’t take my piece, I thought that maybe I could keep trying.
Then something else good happened a few months later. I got an Artist Fellowship from the New York Foundation for the Arts in the category of fiction. It was for $7,000. I used some of that money to pay for a five-day writing class in California with the famous editor and writer <NAME> and the novelist <NAME>. To improve my understanding of the sentence, I began to read poetry. I took a class at the Y with <NAME> to learn prosody, and it changed the way I looked at every word. Whenever the poetry critic <NAME> came to the Y to give one of her seminars, I did whatever I could to attend.
There was so much to learn and practice, but I began to see the prose in verse and the verse in prose. Patterns surfaced in poems, stories, and plays. There was music in sentences and paragraphs. I could hear the silences in a sentence. All this schooling was like getting x-ray vision and animal-like hearing. I had no way to prove objectively the things I was learning, and I can’t tell you why I thought my self-curated education correct, but I followed the steps I could afford to take and somehow trusted that I would learn how to write something fine.
When I ran out of money for classes, I went to readings and bought hardcover books I could not afford. At the bookstore or library, I’d sit all the way in the back. If there was a Q&A, I would have half a dozen questions forming a lump in my throat, but I wouldn’t voice a word. I went to the readings of <NAME>, <NAME>, <NAME>íaz, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and many more. I wanted to know: How did you do that? How did you send me into this whole other world of your creation? How did you make me feel these new and old feelings? How did you keep trusting that it was all worthwhile? And yet, I could barely form an audible sentence around them, but I suppose I didn’t have to, because I had their work, and their work spoke to me and stayed with me in a private way without me having to prove anything to them or them to me.
As a habit, I read on the subway. One day, I was finishing V.S. Naipaul’s A House for Mr. Biswas on the 2 train, and I burst into tears, amazed at the magnificence of Naipaul’s literary achievement. I knew of his politically controversial attitudes (e.g., he thought women writers were unimportant), and yet I understood that in this work, this man had done something extraordinary with fiction. Through characterization and sympathy, Naipaul had made me care deeply for a humble and curious character, who so clumsily yet so vitally struggled for his wishes. Later, I learned that Arwacas, the fictional setting of the novel, was based on Chaguanas, an immigrant town where East Indian-Trinidadians live and where Naipaul had grown up. Naipaul gave me permission to write about Elmhurst, my town in Queens.
After the classes, the readings, the discarded drafts, I started to research my novel like I was a journalist. When I wanted to learn more about my character <NAME>, the investment banker, I interviewed several men who went to Harvard Business School. One of them told me that I should pretend to apply, because one had to see a school like that to believe it. So I did. I logged into the website, and I filled out a visitor’s form, and I was able to come in for a day.
I sat in on a class. There were maybe 25 students, and each person had a name card in front of him or her. It was impossible to hide in that room; however, what was clear to me was that no one was hiding. It wasn’t like any class I had ever attended in high school, college, or even law school. I don’t know if everyone in that room had done his homework or if she understood the lecture and the complicated spreadsheet on the whiteboard, but I learned something about these attractive young people. I surmise that what distinguishes a Harvard Business School student is his confidence in his abilities. I have never been in a building so filled with young people who look like they can do anything and want to solve very difficult problems. After a few hours, I started thinking that maybe I should apply for business school because the energy was so buoyant. If anyone was depressed or anxious or doubtful, I think he or she must have stayed home that day. No, I did not apply to HBS, but that day changed me, because I started to value research, not for the details or the velvet scraps of dialogue, but for the feelings that new information made me have. I felt confident just by being with other highly energetic people. I wondered what it would be like to have two years of that atmosphere when even I, an applicant pretender and a writer with no book, felt that positive after mere hours. So I took that feeling and gave it to Ted, a man who believes that he is right even when he is troubled or afraid. Ted’s convictions propel him to great economic success. However, even his convictions are weakened in the presence of sexual desire and a secret yearning for a kindred person. Ted is not good, but research allowed me to recognize his vulnerability, which allowed me to love Ted in his totality.
Then something wonderful happened. The Missouri Review published a story I’d rewritten 17 or 18 times. I had a Bankers Box filled with just drafts of that one story. Maybe that’s what it took.
Not much after that, my wrists began to hurt. I had trouble lifting a coffee cup. My son was in preschool then, and to drop him off and pick him up, I had to walk a few blocks, but it was painful. My ankles were swollen and holding hands with my son to cross the street was hard. I couldn’t turn round doorknobs or walk up stairs with ease. After several misdiagnoses, I was sent to a rheumatologist who guessed correctly that my liver disease was making me ill. I had developed liver cirrhosis, and I had never had a drop of wine.
There were a lot of doctors, and they wrote about my case to each other. A gastroenterologist wanted me to try a course of treatment with Interferon, because I was so young, and liver transplants were not so easy to be had. For three months, I gave myself a shot of this medicine in my thigh each day. My hair fell out in clumps in the shower. When I bent down to sweep the floor, blood vessels would break in my face to make bruises. I could not leave the house sometimes because I had diarrhea or because I could not stop vomiting. Each day, I had a few hours of energy, and I would store them up for Sam, my three-year-old. I wanted him to think that I was well.
When the treatment ended, my liver function tests improved markedly. My doctor was cautious, so he took more tests. I continued to work on Free Food for Millionaires, compelled to finish a first draft. A year after the treatment, the doctor told me that I was cured of my chronic liver disease. One in a million, he marveled. I went home that afternoon, and I lay down on my bed with my good news. This life was unexpected. I told myself that I could not be so afraid of judgment that I would hold back. And so I did not.
When I sold the manuscript in the summer of 2006, I counted 11 years as my apprenticeship. I was 37 years old.<file_sep>/content/event/powells-city-of-books.md
---
title: Powell's City of Books
date: 2018-02-14 19:30:00
show_time: true
venue:
name: Powell's City of Books
address: 1005 W Burnside Street
city: Portland
state: OR
zip: '97209'
link: 'http://www.powells.com'
---
<file_sep>/content/event/paul-weiss-washington-d-c-.md
---
title: '<NAME>, Washington, D.C.'
date: 2017-06-20 12:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
In Conversation with <NAME>, Esq.
Private Event<file_sep>/content/news/2017-03-01-other-ppl-with-brad-listi-podcast.md
---
title: Other Ppl with Brad Listi (PODCAST)
date: 2017-03-01 12:00:00
categories: ["News"]
tags:
- Reviews
- Audio
- Interviews
attribution: Otherppl With Brad Listi
link_to_original: 'http://otherppl.com/min-jin-lee-interview/'
description:
---
<NAME> speaks with novelist and host Brad Listi of the Other People Podcast. Pachinko is the official February selection of THE NERVOUS BREAKDOWN BOOK CLUB.
Episode 455.<file_sep>/content/event/wyndham-campbell-festival.md
---
title: Windham-Campbell Festival
date: 2017-09-15 12:00:00
show_time: true
venue:
name: New Haven Free Public Library
address:
city:
state:
zip:
link: www.windhamcampbell.org
---
Ancestors: Where Do We Come From and Why Do We Care
I will be moderating a panel featuring <NAME>, <NAME>, <NAME>, and <NAME>. <file_sep>/content/news/2007-06-03-oc_register.md
---
title: "OC Register"
date: 2007-06-03T23:09:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "OC Register"
link_to_original: "http://www.ocregister.com/ocregister/entertainment/books/article_1715830.php"
description: ""
_slug: 2007-06-03-oc_register
---
The real lessons come after college is over
OCRegister - Jun 3, 2007
The first novel by <NAME> ‚ a Korean immigrant who went to Yale University, looks at the precarious time after college graduation when dreams may not ...
<file_sep>/content/event/pratt-institute.md
---
title: Writer's Forum at Pratt Institute
date: 2018-04-19 17:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/review/south-china-morning-post-on-pachkinko.md
---
title: South China Morning Post on Pachkinko
attribution: South China Morning Post by <NAME>
date: 2017-03-11 17:51:13 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
PACHINKO is about paying dues to a forgotten history; to the complex and fraught Japan-Korea relationship that endured well into the 90s and lingers to this day. But it doesn't wear its heart—or historical truths—on its sleeve. What drives this novel is the magisterial force of Lee's characterization; her ability to ground the narrative deeply and intimately in the details of daily life. Also threaded through it are questions of home, identity, nationhood and tradition—including the belief of its female protagonists that 'a woman's lot is to suffer.'<file_sep>/content/news/ny-post-the-10-best-books-to-read-to-beat-coronavirus-boredom-1.md
---
title: 'Esquire: The Best Books for Distancing Yourself From Reality Right Now'
date: 2020-03-25T00:50:11-04:00
link_to_original: https://www.esquire.com/entertainment/books/g31813146/books-to-read-while-social-distancing-quarantine-coronavirus/
images: []
tags: []
categories: []
description: ''
---
> _Packinko_, <NAME>
>
> "With the epic sweep of Zola or Dickens, Lee chronicles four storied generations of a Korean immigrant family, beginning with a pregnant young woman’s decision to enter a marriage of convenience that ferries her to a new beginning in Japan. Her decision to leave home echoes across generations, all of it playing out against the rich tapestry of an ever-changing 20th-century Japan. The sheer bigness of this novel is majestic, as are its themes of joy, sacrifice, and heartbreak."<file_sep>/content/review/st.-louis-dispatch-on-free-food-for-millionaires.md
---
title: St. Louis Dispatch on Free Food for Millionaires
attribution: St. Louis Dispatch
date: 2007-03-11 18:00:41 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Novelist Min <NAME> offers us the chance to see this entire culture, up close, personal and far more sympathetically. The book focuses on the emotional and…<file_sep>/content/event/brisbane-writers-festival.md
---
title: 'Brisbane Writers Festival: Friday Panel'
date: 2017-09-08 14:30:00
show_time: true
venue:
name: Auditorium 1
address:
city:
state:
zip:
link: 'http://uplit.com.au/festival/brisbane-writers-festival-2017/program/pains-of-the-past'
---
How does the past impact the future? Find out how fiction can explore the impact of intergenerational trauma, and how writing about it may be cathartic.
With <NAME>, Dr. <NAME>, <NAME>, and <NAME>.<file_sep>/content/review/new-york-times.md
---
title: New York Times
attribution: "*New York Times*"
date: 2007-03-11 18:17:00 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
This accomplished first novel, the coming-of-age story of a Princeton-educated Korean-American woman making her way in New York City in the 1990s, recalls the Victorian novels its heroine devours. Our reviewer, <NAME>, described it as ‘packed with tales of flouted parental expectations, fluctuating female friendships and rivalries,…romantic hopes and losses, and high-stakes career gambles.’<file_sep>/content/news/2008-04-27-new_york_daily_news.md
---
title: "New York Daily News"
date: 2008-04-27T23:02:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "New York Daily News"
link_to_original: ""
description: ""
_slug: 2008-04-27-new_york_daily_news
---
A first novel tells a sexy story of young Korean…
<file_sep>/content/event/center-for-fiction-fiction--personal-themes-a-writing-seminar.md
---
title: 'Center for Fiction: A Writing Seminar'
date: 2017-10-07 10:00:00
show_time: true
venue:
name: Center for Fiction
address: 17 East 47th Street
city: New York
state: NY
zip: '10017'
link: www.centerforfiction.org
---
I'll be teaching a one-day writing seminar on "Fiction & Personal Themes." For more information: www.centerforfiction.org<file_sep>/content/event/senator-mazie-hirono-min-jin-lee-heart-of-fire-discussion.md
---
show_time: true
title: 'Senator <NAME> + <NAME>: Heart of Fire Discussion'
date: 2021-05-03T19:00:00-04:00
description: 'Join Senator <NAME> as she presents her newest book Heart of Fire:
An Immigrant Daughter''s Story. Joining the senator in conversation is multiple
fellowship recipient and New York Times bestselling author <NAME>. This event
will be held on Crowdcast.io and will be live streamed to The Strand''s Facebook
Page.'
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.strandbooks.com/events/event193?title=senator_mazie_hirono__min_jin_lee_heart_of_fire_an_immigrant_daughters_story
images: []
---
<file_sep>/content/news/2017-08-01-new-york-times-match-book-recommends-pachinko.md
---
title: 'New York Times: Match Book Recommends Pachinko'
date: 2017-08-01 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The New York Times
link_to_original: 'https://www.nytimes.com/2017/08/01/books/review/match-book-fictional-family-sagas.html'
description:
---
By <NAME>
Dear Match Book,
I am spending two weeks this summer by a lake in New Hampshire and I plan to sit on the dock and get immersed in a few good books. I love reading family sagas — the longer the better — that are wrapped around historical events. My favorite books of this type have been “A Suitable Boy,” by <NAME>; “Angle of Repose,” by <NAME>; “The Forsyte Saga,” by <NAME>; and <NAME>’s Neapolitan novels. I have read “War and Peace,” by <NAME>, which I consider the ultimate family saga wrapped around history, but I found that there was too much war and not enough peace for my taste.
Do you have any suggestions for both divinely engrossing and beautifully written family sagas?
<NAME>
<br>BOSTON
…
Finally I suggest an urgent, satisfying saga from 2017 to add to your vacation reading stack: “Pachinko” by <NAME>. The careful, unadorned language of Lee’s second novel, the story of four generations of a Korean family living under Japanese forced occupation, is revealing and stealthily seductive. The story begins in earnest in 1932 with Sunja, a 16-year-old girl from a small village whose unexpected pregnancy changes the course of her life. Layers of history and politics build as the scope and sweep of the narrative widen. Yet even as the story stretches more than 50 years, Lee’s portraits of her characters — proud and tender — remain intimate.
Yours truly,
<br>Match Book
For the complete article, please click the link:
Do you need book recommendations? Write to <EMAIL>.<file_sep>/content/news/nypl-notes-from-a-reading-life-a-conversation-with-tim-gunn-and-min-jin-lee-video.md
---
title: 'NYPL: Notes from the Reading Life – A Conversation with <NAME> and <NAME>
Lee (Video)'
date: 2018-06-08 18:00:25 -0400
link_to_original: http://media.nypl.org/video/2018-06-08_NotesFromTheReadingLife_TimGunn_MinJinLee_NBF.mp4
images:
- "/uploads/maxresdefault.jpg"
tags: []
categories: []
description: ''
---
<file_sep>/content/news/a-new-essay-appears-in-the-new-yorker.md
---
title: 'New York Times: "Breaking My Own Silence'
date: 2019-05-20T07:00:00-04:00
categories:
- Media
tags:
- Essays
attribution:
link_to_original: https://www.nytimes.com/2019/05/20/opinion/confidence-public-speaking.html
description: |-
"I am 50 years old, and after more than four decades of living in the West, I realize that like writing, talking is painful because we expose our ideas for evaluation; however, like writing, talking is powerful because our ideas may, in fact, have value and require expression.
As a girl, I did not know this power, yet this is my power now."
---
> [https://www.nytimes.com/2019/05/20/opinion/confidence-public-speaking.html](https://www.nytimes.com/2019/05/20/opinion/confidence-public-speaking.html "https://www.nytimes.com/2019/05/20/opinion/confidence-public-speaking.html")<file_sep>/content/news/2017-07-30-vineyard-gazette-profile.md
---
title: 'Vineyard Gazette: Profile'
date: 2017-07-30 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: Vineyard Gazette
link_to_original: 'https://vineyardgazette.com/news/2017/07/30/when-odds-favor-house-its-still-important-feel-lucky'
description:
---
When the Odds Favor the House, It's Still Important to Feel Lucky
By Vivian Ewing
Sunday, July 30, 2017
Author <NAME> says she loves Martha’s Vine yard, and that she should be easy to spot at her favorite place, Morning Glory Farm. “If you can recognize a really tall Korean-American person eating a lot of pie, like even before she paid for it, that would be me,” she said.
Ms. Lee may love blueberry pie, but the Korean-Japanese characters in her novel Pachinko pull themselves up with kimchi. Pachinko is a nearly 500-page book that follows one family for seven tumultuous decades. Cultures clash and fates spiral. Wars are fought and babies are born. Like in the pinball-esque game of Pachinko, the pieces fall where they may.
In the early 1900s, young Sunja becomes pregnant with the child of a wealthy stranger. A baby born out of wedlock in 20th-century Korea is a societal death sentence, but a Christian minister offers to marry the young woman and bring her to Japan. Life goes from tough to torturous when the minister is thrown in jail for refusing to pledge allegiance to the Emperor. But Sunja and her sister in law Kyunghee manage to support themselves with their recipe for spicy pickled cabbage.
“Kimchi is something you can make,” Ms. Lee said of the womens’ vocation. “It’s something you can do to actually control your own destiny. You can sell this thing that has very low capital requirements and hopefully turn a profit and then reinvest in your business tomorrow.”
But even when Sunja and Kyunghee find a way to take their lives into their own hands, disaster still looms around every corner. “How about if the refrigerator breaks down and everything that we’ve made goes wrong?” Ms. Lee said of her characters’ fate. “There’s still so many things that we can’t control. We still have to wake up in the morning and try again.”
Over time, Sunja gives birth to her son, has several miscarriages and finally gives birth to another child. Although she escaped the indignity of raising her children without a husband, the hostility she faces in Japan at the beginning of World War II doesn’t amount to a better life. Prejudice against people who are Korean is vicious. Doctors refuse to pay visits and companies refuse to hire.
As the terror unfolds, Sunja’s sons fight the feeling that they don’t belong anywhere. Mozasu, her second-born, says, “In Seoul, people like me get called Japanese bastard, and in Japan I’m just another dirty Korean no matter how much money I make or how nice I am.”
Mozasu and his brother Noa both find work in one of the few avenues open to Koreans: Pachinko Parlors.
“Pachinko is absolutely a metaphor,” Ms. Lee said. “It’s a metaphor for the story because Pachinko, which is an adult gambling game, is like any other gambling game — stacked in favor of the house.”
People who play Pachinko know what they’re up against. “One of the things that we feel as we get older is that even though we keep trying, we feel like maybe sometimes the rules aren’t fair,” Ms. Lee said. “Maybe we need a little extra advantage and yet, we don’t give up because we know that we have to try. And I think that’s what life really is. There’s a part of you that has to have a sense of blind hope. Like, maybe we’ll get lucky. Maybe we’re going to make it.”
Sunja and her family do make it, although not without endless challenges.
“They were not blind to the fact that things were unfair,” <NAME> said. “They were actually very cognizant of it. At the same time they continued to be very tough and also very tender. And that’s really an amazing thing.”
<NAME> will speak on Saturday at 3 p.m. the Harbor View Hotel, and on Sunday at 11:45 a.m. at the Chilmark Community Center.<file_sep>/content/event/amherst-college-1.md
---
title: Renton, WA
date: 2019-05-03 08:00:00 -0400
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
---
<file_sep>/content/writing/2010-05-05-times_of_london_my_favorite_novel_of_2010.md
---
title: "Times of London: My Favorite Novel of 2010"
date: 2010-05-05T23:13:45-05:00
categories:
tags: ["Reviews"]
where_published: "Times of London"
link_to_original: "http://entertainment.timesonline.co.uk/tol/arts_and_entertainment/books/fiction/article7111534.ece"
link_to_pdf:
description: "
TONY & SUSAN by <NAME> is a masterful achievement in literature: [Times Online](http://entertainment.timesonline.co.uk/tol/arts_and_entertainment/books/fiction/article7111534.ece)"
_slug: 2010-05-05-times_of_london_my_favorite_novel_of_2010
---
My favorite novel of 2010 would have been my favorite novel of 1993 — if only I had known about it. At the time, Saul Bellow was not on Twitter but even his lavish quote for Tony & Susan, originally published that year, failed to sell enough copies of the book to keep it in print. So in an unusual eco-feat of arts recycling, Tony & Susan is being republished, giving it a much-deserved second life.
<file_sep>/content/news/2017-07-21-live-at-the-tenement-museum-pachinko-with-aawws-ken-chen-and-min-jin-lee-video.md
---
title: "Live at the Tenement Museum: Pachinko with AAWW's <NAME> and <NAME> (Video)"
date: 2017-07-21 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
attribution: AAWWTV
link_to_original: 'https://youtu.be/IuzT1tdCRZM'
description:
---
Introduced by my amazing sister, <NAME>, the Executive Director of Cities of Service.
<file_sep>/content/event/amherst-college-2.md
---
title: 'Richland Library: Meet the Author'
date: 2019-11-15T19:00:00-05:00
show_time: true
venue:
name: Richland Library Main
address: 1431 Assembly St.
city: Columbia
state: SC
zip: "29201"
link: https://www.richlandlibrary.com/event/2019-11-15/meet-author-min-jin-lee
description: ''
images: []
---
<file_sep>/content/news/boston-globe-an-exciting-chapter-for-min-jin-lee.md
---
title: 'Boston Globe: "An exciting chapter for Min Jin Lee"'
date: 2018-10-26 13:00:00 -0400
link_to_original: https://www.bostonglobe.com/lifestyle/2018/10/26/exciting-chapter-for-min-jee-lee/tGiFO1hRNrNRNvrtFadydL/story.html
images:
- "/uploads/DqsQNEmWkAghjFI.jpg"
tags: []
categories: []
description: Lee said she’d planned for Boston to be a setting in her new book even
before she moved here. “Boston is an epicenter of education,” she said. “People
around the world want to come here to this city to be educated. You can’t not include
Boston in this book.”
---
<file_sep>/content/news/2017-03-31-san-francisco-chronicle-book-review.md
---
title: San Francisco Chronicle (Book Review)
date: 2017-03-31 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: San Francisco Chronicle
link_to_original: 'http://www.sfchronicle.com/books/article/Pachinko-by-Min-Jin-Lee-11037390.php'
description:
---
By <NAME>
“History has failed us, but no matter.” So begins “Pachinko,” Min Jin Lee’s sweeping four-generation saga of a Korean family. The story starts shortly before Japan’s annexation of Korea in 1910 when a Korean fisherman and his wife decide to make extra money by taking in lodgers in the village of Yeong-do. This decision brings the couple a small degree of economic comfort as the rest of the country gets poorer.
The couple has only one surviving son, Hoonie. He has a cleft palate and a twisted foot, and they assume he will be unable to get married because of the belief that physical deformities persist over generations. However, a matchmaker intervenes. She’s trying to find a match for Yangjin, the fourth daughter of a tenant farmer who’s lost his lease under the colonial government. The farmer can’t offer a dowry, but Hoonie’s mother is excited about the previously inconceivable prospect of a grandson.
Tragically, Hoonie and Yangjin have three babies they lose to illness and disease. After Hoonie’s parents die, however, Yangjin gives birth to a daughter, Sunja. As an adult, Sunja starts a secret affair with <NAME>u, a wealthy, mysterious businessman who rescues her from some Japanese bullies at the marketplace. The earthiness of the affair (and Sunja’s daily life in the boarding house) is striking: “While he was moving inside her, doing this thing that she had witnessed pigs and horses doing, she was stunned by how sharp and bright the pain was and was grateful that the ache subsided.”
The novel is mostly about Sunja’s family after they move to Japan. Koh Hansu continues to affect and influence what happens to the family long after his initial sexual encounters with Sunja. The fortunes of her sons intersect with his.
“Pachinko” gets its title from a mechanical gambling device and recreational arcade game in Japan. Korean immigrants own a sizable percentage of the pachinko industry, which has a link to yakuza, Japan’s crime syndicates. Lee’s novel points out this is because Japanese employers in other industries often won’t hire them or terminate them for flimsy reasons. One mother thinks of the industry: “It was bad enough that her daughter worked in pachinko, but now, she had married a man who worked in the sordid business, cementing her caste in life.”
Like Lee’s debut novel, “Free Food for Millionaires,” “Pachinko” is interested in privilege, money and sex. “Free Food for Millionaires” chronicles the lives of several Korean American families in New York City. It especially focuses on how chance and folly shape the fortunes of Casey, a Korean American shopaholic. Just after she graduates from Princeton, she talks back to her physically abusive father, who throws her out of the house. He grew up in poverty in Korea and never lets his daughters forget it.
“Pachinko,” too, is concerned with the impact of chance and folly on the lives of poor or working-class immigrants. Like “Free Food for Millionaires,” it bears the influence of 19th century masters, whisking in and out of viewpoints, and (as if to underscore the influence) a main character finds respite in these classics. However, it deepens the themes of “Free Food for Millionaires” — it’s as if the author took Casey’s father and imagined in detail the impoverished and harrowing conditions that produced his rigid outlook.
“Pachinko” is uninterested in the mores of the rich, looking instead at the survival of the lower class. It is an extraordinary epic, both sturdily constructed and beautiful. Lee’s characters are tough, materialistic and determined not just to follow their ambitions despite challenging historical circumstances, but also to make a true home.
Lee never explicitly calls attention to parallels between the experiences of immigrants in Japan and immigrants in America. However, as an American reader, it is hard not to be struck by the similarities between anti-immigration sentiment and bigotry, no matter in what country they exist and no matter what image a country might project about its tolerance to the rest of the world.
Pachinko dramatizes the struggle to secure a place in an economy that is stacked against you and what that does to immigrant parents and their children. Although Lee is not interested in violent crime, preferring a stylistic register here closer to that of “War and Peace,” the subtler struggles of her characters echo some of the dynamics of Mario Puzo’s “The Godfather.”
Min Jin Lee captures something universal here with notable grace and exquisite craft. There’s a flintiness to the narration, but readers who appreciate British and Russian masters of times past will love this approach. As we struggle now against the indifferent vicissitudes of history, this novel is a timely reminder that many before us have managed to survive, if imperfectly, in a world hostile to them.
<NAME>’s writing has appeared in the Rumpus, Salon and the Los Angeles Review of Books. Email: <EMAIL>.<file_sep>/content/news/2017-05-26-irish-times-podcast-with-roisin-ingle.md
---
title: Irish Times (Podcast with Roisin Ingle)
date: 2017-05-26 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Audio
attribution: Irish Times
link_to_original: 'http://www.irishtimes.com/life-and-style/people/women-writers-have-to-take-humiliation-very-well-1.3097348'
description:
---
By <NAME>
“I think that if you’re a writer and a woman then you have to take humiliation very well,” says author <NAME>.
It took the Korean-American writer nearly 30 years to bring her latest novel Pachinko to life, coming ten years after her first book, Free Food For Millionaires, and having been in the works since 1989.
“I have accepted the fact that I don’t work very quickly, that I have been rejected a lot as a writer and that what I do is unusual, so I just have to accept the terms and that it’s going to take longer. It is what it is,” she tells Róisín Ingle, on the latest Róisín Meets podcast.
Pachinko is already a bestseller, a research-heavy saga spanning almost a century and covering four generations of a poor Korean immigrant family as they battle unrelenting prejudice.
The story moves from Korea at the beginning of the 20th century, to Osaka, Tokyo and Yokohama, telling the often ignored history of the ethnic-Korean community in Japan
Lee’s own family immigrated to America from Seoul when she was seven years old and she grew up in the Queens area of New York. She still lives in the city and says people there still haven’t quite gotten over the shock of Trump’s election.
“It’s all people talk about, our heads are still spinning, especially in New York… we’re all going, my god, how did we get it so wrong? We all got it wrong.”
Also in the podcast, Lee talks about why she is still grateful for her American citizenship “even now with Trump”, why immigrants suffer in advanced economies and how even Japanese people will tell you how difficult it is to be different in their culture.
To listen to the full conversation between <NAME> and <NAME>, go to iTunes, Soundcloud, or your preferred podcast app.
Please click on the link below to listen to the podcast of Roisin Meets.<file_sep>/content/news/2017-06-21-amazon-best-books-of-the-year-so-far-2017.md
---
title: Amazon Best Books of the Year So Far 2017
date: 2017-06-21 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Amazon Best Books of the Year So Far 2017
link_to_original: 'https://www.amazon.com/Best-Books-of-the-Year-So-Far/b/ref=amb_link_1?ie=UTF8&node=3003015011&pd_rd_r=PCXYC0T7S1DRXN1F90BC&pd_rd_w=k7UG4&pd_rd_wg=FrLxf&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=merchandised-search-leftnav&pf_rd_r=PCXYC0T7S1DRXN1F90BC&pf_rd_r=PCXYC0T7S1DRXN1F90BC&pf_rd_t=101&pf_rd_p=b2daeff6-5eba-4027-b868-06b9fa55345c&pf_rd_p=b2daeff6-5eba-4027-b868-06b9fa55345c&pf_rd_i=5522568011'
description:
---
Pachinko makes the Amazon list of BEST BOOKS OF THE YEAR SO FAR 2017 in the category of LITERATURE & FICTION.
For the complete list, please click the link below.<file_sep>/content/event/collegiate-authors-night.md
---
title: Collegiate Authors Night
date: 2017-10-24 18:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/yale-daily-news-min-jin-lee-90-discusses-her-book-immigration-at-college-tea.md
---
title: 'Yale Daily News: <NAME> ‘90 discusses her book, immigration at College
Tea'
date: 2018-11-30 12:54:20 -0500
link_to_original: https://yaledailynews.com/blog/2018/11/30/min-jin-lee-90-discusses-her-book-immigration-at-college-tea/
images:
- "/uploads/Screen Shot 2018-12-09 at 12.56.25 PM.png"
tags: []
categories: []
description: ''
---
<file_sep>/content/event/100th-anniversary-of-the-meeting-of-virginia-woolf-and-t.s.-eliot.md
---
title: 'New York Public Library: "Literary Friendships"—100th Anniversary of the Meeting
of Virginia Woolf & T.<NAME>: A Conversation with <NAME>, author of The
World Broke In Two'
date: 2018-11-15 18:30:54 -0500
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: ''
description: ''
show_time: false
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: ''
---
<file_sep>/content/review/mixed-race-america-on-free-food-for-millionaires.md
---
title: Mixed Race America on Free Food for Millionaires
attribution: ''
date: 2007-03-11 18:08:39 +0000
book: book/_index.md
description: ''
featured: false
weight: ''
---
<file_sep>/content/event/the-times-and-the-sunday-times-cheltenham-literature-festival-.md
---
title: 'UK: The Times and the Sunday Times Cheltenham Literature Festival '
date: 2018-10-06 18:00:07 -0400
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: https://www.cheltenhamfestivals.com/literature/whats-on/2018/divided-lands-family-ties/
description: '<NAME> hosts a unique conversation between two acclaimed Korean-
American writers: <NAME>’s Pachinko – one of The New York Times 10 Best Books
of 2017 – is an epic tale of family, identity, love, death and survival set between
Korea and Japan across eight decades and four generations. <NAME>’s White
Chrysanthemum is a heartbreaking story of the treatment of Korean women prostituted
by Japanese soldiers during WW2 and the redemptive bond of two sisters separated
by war.'
---
<file_sep>/content/event/irish-american-center-book-club.md
---
title: Irish American Center Book Club
date: 2017-12-04 18:30:00
show_time: true
venue:
name: Irish Arts Center
address: 553 West 51st Street
city: New York
state: NY
zip: '10019'
link: 'http://irishartscenter.org/event/iac-book-club-pachinko-by-min-jin-lee'
---
A discussion of PACHINKO with <NAME>, led by <NAME>. The event is free, but please reserve with the IAC.<file_sep>/content/news/2016-12-09-publishers-weekly-spring-2017-announcements-literary-fiction.md
---
title: 'Publishers Weekly Spring 2017 Announcements: Literary Fiction'
date: 2016-12-09 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Publishers Weekly by <NAME>
link_to_original: 'http://www.publishersweekly.com/pw/by-topic/new-titles/adult-announcements/article/72259-spring-2017-announcements-literary-fiction.html'
description:
---
Literary Fiction Listings
Akashic
Dance of the Jakaranda by <NAME> (Feb. 7, trade paper, $15.95, ISBN 978-1-61775-496-8). Firmly anchored in the African storytelling tradition, Kimani reimagines the rise and fall of colonialism in Africa by telling the story of the birth of Kenya’s railroad.
Algonquin
The Young Widower’s Handbook by <NAME> (Feb. 7, hardcover, $25.95, ISBN 978-1-61620-474-7). When <NAME>’s beloved wife dies, he heads west and takes her ashes with him. They had always meant to travel. Soon enough, he finds himself in encounters with characters even quirkier than he is: an overzealous Renaissance Faire worker; a raucous yet sympathetic troop of bachelorettes; a Chicago couple and their pet parrot, Elvis.
Archipelago
Wolf Hunt by <NAME>, trans. by <NAME> (Apr. 18, trade paper, $18, ISBN 978-0-914671-70-1). Published in 1986, Petrov’s novel centers on an ill-fated winter hunting expedition of six neighbors whose history together is long and interwoven. The shifting perspectives places the calamitous history of 20th-century Bulgaria into a human context of helplessness and desperation.
Atria
Beartown by <NAME> (May 2, hardcover, $26.99, ISBN 978-1-5011-6076-9). From the bestselling author of A Man Called Ove comes a novel about a forgotten town fractured by scandal, and the amateur hockey team that might just overcome that.
Ballantine
Ill Will by <NAME> (Mar. 7, hardcover, $28, ISBN 978-0-345-47604-3). A psychologist in suburban Cleveland, Dustin is drifting through his 40s when he hears the news: his adopted brother, Rusty, is being released from prison. Thanks in part to Dustin’s testimony, 30 years ago, Rusty received a life sentence for the massacre of Dustin’s parents, aunt, and uncle.
Catapult
Large Animals by <NAME> (May 16, trade paper, $15.95, ISBN 978-1-936787-48-7). Arndt’s debut collection confronts what it means to have a body. In “Jeff,” <NAME> confuses Jess for Jeff, instigating an identity crisis. In “Together,” a couple battles a mysterious and unnamed STD that slowly undoes their relationship, while outside a ferocious weed colonizes their urban garden.
Coffee House
Stephen Florida by <NAME> (June 13, hardcover, $25, ISBN 978-1-56689-464-7). A troubled college wrestler in North Dakota falls in love and becomes increasingly unhinged during his final season, when every practice, every match, is a step closer to greatness and a step further from sanity. 10,000-copy announced first printing.
Deep Vellum
The Golden Cockerel & Other Writings by <NAME>, trans. by <NAME> (May 16, trade paper, $16.95, ISBN 978-1-941920-58-9). This work presents Rulfo’s second novel in English for the first time, alongside several stories never translated at all. 10,000-copy announced first printing.
Dial
The Twelve Lives of <NAME>ley by <NAME> (Mar. 28, hardcover, $27, ISBN 978-0-8129-8988-5). Loo is 12 when she moves back to the New England fishing village of her early youth. Her father, Hawley, finds work on the docks. But lurking over Loo are mysteries, including the mother who died and the ghosts of Hawley’s past.
Ecco
The Hearts of Men by <NAME> (Mar. 7, hardcover, $26.99, ISBN 978-0-06-246968-7) is a novel of intertwining friendships and families set in the Northwoods of Wisconsin at a popular Boy Scout summer camp, from the author of Shotgun Lovesongs. 50,000-copy announced first printing.
Our Little Racket by <NAME> (June 20, hardcover, $26.99, ISBN 978-0-06-264131-1). A debut about wealth, envy, and secrets tells the story of five women whose lives are dramatically changed by the downfall of a financial titan. 100,000-copy announced first printing.
Europa
The Nakano Thrift Shop by <NAME>, trans. by <NAME> (June 6, trade paper, $16, ISBN 978-1-60945-399-2). Objects for sale at the Nakano Thrift Shop appear as commonplace as the staff and customers that handle them. But like those same customers and staff, they hold many secrets, and Hitomi, the inexperienced young woman who works the register, has fallen for her coworker, the oddly reserved Takeo.
Flatiron
The People We Hate at the Wedding by <NAME> (June 6, hardcover, $25.99, ISBN 978-1-250-09520-6). A fractured family from the Chicago suburbs gathers in London for the eldest daughter’s marriage to an upper-crust Englishman, proving that the harder we strain against the ties that bind, the tighter they hold us close.
Farrar, Straus and Giroux
The Answers by <NAME> (June 6, hardcover, $26, ISBN 978-0-374-10026-1). Mary scours Craigslist for fast-cash jobs and finds herself applying for the “Girlfriend Experiment,” the brainchild of an eccentric and narcissistic actor, <NAME>, who is determined to find the perfect relationship—even if that means paying different women to fulfill distinctive roles.
Universal Harvester by <NAME> (Feb. 7, hardcover, $25, ISBN 978-0-374-28210-3). Life in the small town of Nevada, Iowa, takes a dark turn when mysterious footage begins appearing on VHS cassettes at the local Video Hut.
FSG/Crichton
Lover by <NAME> (Mar. 7, hardcover, $26, ISBN 978-0-374-19365-2). Kate, a senior executive at a multinational hotel company, has devoted her life to her job and her family. Catering to the needs of others comes easily to her, but now, after 10 years of marriage and two children, Kate discovers e-mails from her husband to another woman.
Grand Central
Pachinko by <NAME> (Feb. 7, hardcover, $27, ISBN 978-1-4555-6393-7) follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them all.
Graywolf
Encircling by <NAME>, trans. by <NAME> (Feb. 21, trade paper, $16, ISBN 978-1-55597-762-7). David has lost his memory. When a newspaper ad asks his friends and family to share their memories of him, three respond: Jon, his closest friend; Silje, his teenage girlfriend; and Arvid, his estranged stepfather. This first book of a trilogy is a psychological portrait of a man by his friends.
So Much Blue by <NAME> (June 13, trade paper, $16, ISBN 978-1-55597-782-5). <NAME>, working on a painting that he won’t allow anyone to see, had an affair 10 years earlier with a young watercolorist in Paris. As the events of the past intersect with the present, Kevin struggles to justify the sacrifices he’s made for his art and the secrets he’s kept from his wife.
Grove
The Refugees by <NAME> (Feb. 7, hardcover, $25, ISBN 978-0-8021-2639-9). A collection of stories by Pulitzer-winner Nguyen explores questions of immigration, identity, love, and family—including a young Vietnamese refugee who suffers profound culture shock when he comes to live with two gay men in San Francisco, and a woman whose husband is suffering from dementia and starts to confuse her for a former lover.
Hachette/Twelve
Often I Am Happy by <NAME> (Apr. 11, hardcover, $23, ISBN 978-1-4555-7007-2). Ellinor is 70. Her husband, Georg, has just died, and Ellinor is struck with the need to confide in someone, picking Anna, her long-dead best friend, who was also Georg’s first wife. Ellinor divulges long-held secrets and burdens of her past. 30,000-copy announced first printing.
Harper
The Book of Joan by <NAME> (Apr. 18, hardcover, $26.99, ISBN 978-0-06-238327-3). In the near future, world wars have transformed the world into a battleground. <NAME>, a charismatic and bloodthirsty cult leader, turns the planet into a quasi-corporate police state. A group of rebels unite to dismantle his iron rule, galvanized by the heroic song of Joan, a child-warrior who possesses a mysterious force. 25,000-copy announced first printing.
Sycamore by <NAME> (May 2, hardcover, $27.99, ISBN 978-0-06-266109-8). Out for a hike one scorching afternoon in Sycamore, Ariz., a newcomer to town stumbles across what appear to be human remains. As news of the discovery makes its way around town, Sycamore’s longtime residents fear the bones may belong to <NAME>, the teenage girl who disappeared suddenly some 18 years earlier. 75,000-copy announced first printing.
Holt
Marlena by <NAME> (Apr. 4, hardcover, $26, ISBN 978-1-62779-764-1). Fifteen-year-old Cat’s new town in rural Michigan is lonely and off-kilter, until she meets her neighbor, the manic, beautiful, pill-popping Marlena. The story of two girls and the feral year that will cost one her life and define the other’s for decades.
<NAME>
All Grown Up by <NAME> (Mar. 7, hardcover, $25, ISBN 978-0-544-82424-9). Who is <NAME>? When her therapist asks the question, Andrea knows the right things to say: she’s a designer, a friend, a daughter, a sister. But it’s what she leaves unsaid—she’s alone, a drinker, a former artist, captain of the sinking ship that is her flesh—that feels the most true. 30,000-copy announced first printing.
Mother Land by <NAME> (May 9, hardcover, $28, ISBN 978-0-618-83932-2). To those in her Cape Cod town, Mother is an exemplar of piety, frugality, and hard work. To her husband and seven children, she is the selfish, petty tyrant of Mother Land. 50,000-copy announced first printing.
Kensington
Miramar Bay by <NAME> (Mar. 28, hardcover, $19.95, ISBN 978-1-4967-0829-8). When <NAME> boards a late night bus in downtown L.A., he’s not sure where he’s going. Putting his acting career—and his fiancée—on hold, he finds himself stepping into the sleepy seaside town of Miramar Bay—where one woman inspires him to rethink all of his choices.
Knopf
Men Without Women by Haruki Murakami, trans. by <NAME> and <NAME> (May 9, hardcover, $25.95, ISBN 978-0-451-49462-7). Across seven tales, Murakami focuses on the lives of men who, in their own ways, find themselves alone. Here are vanishing cats and smoky bars, lonely hearts and mysterious women, baseball and the Beatles.
White Tears by <NAME> (Mar. 14, hardcover, $26.95, ISBN 978-0-451-49369-9). Two ambitious young musicians are drawn into the dark underworld of blues record collecting, haunted by the ghosts of a repressive past, in a murder mystery, a meditation on race, and a love letter to all the forgotten geniuses of American music.
<NAME>
The Reminders by <NAME> (May 30, hardcover, $26, ISBN 978-0-316-31699-6). The Rosie Project meets Tell the Wolves I’m Home in this debut novel about what happens when a little girl who can’t forget befriends a man who’s desperate to remember. 50,000-copy announced first printing.
Spaceman of Bohemia by <NAME> (Mar. 7, hardcover, $26, ISBN 978-0-316-27343-5). <NAME> has risen from smalltime scientist to become the country’s first astronaut. When a dangerous solo mission to Venus offers him both the chance at heroism he’s dreamt of, and a way to atone for his father’s sins as a Communist informer, he ventures into the vast unknown.
McSweeney’s
Sorry to Disrupt the Peace by <NAME> (Mar. 14, hardcover, $24, ISBN 978-1-944211-30-1). <NAME> is 32 years old, single, childless, college-educated, and partially employed as a guardian of troubled young people in New York. She’s accepting a delivery from Ikea in her shared studio apartment when her uncle calls to break the news: Helen’s adoptive brother is dead.
Melville House
First Love by <NAME> (Mar. 21, trade paper, $16.99, ISBN 978-1-61219-626-8). Neve is beset by financial anxiety and isolation, but can’t quite manage to extricate herself from her volatile partner, Edwyn. At the peripheries, Neve’s stunted father and self-absorbed mother offer their own forms of cruelty toward their daughter. Neve is caught between withdrawal and self-assertion, depression and rage.
Mira
The Orphan’s Tale by <NAME> (Feb. 21, trade paper, $15.99, ISBN 978-0-7783-1981-8) is a novel of friendship set in a traveling circus during WWII, introducing two women and their stories of sacrifice and survival. 300,000-copy announced first printing.
New Directions
I Am the Brother of XX by <NAME>, trans. by <NAME> (July 25, trade paper, $14.95, ISBN 978-0-8112-2598-4). Whether these stories involve famous writers (Calvino, <NAME>, <NAME>) or baronesses, 13th-century visionaries or tormented siblings growing up in elite Swiss boarding schools, Jaeggy’s signature intensity and precision mark these tales.
Norton
The Underworld by <NAME> (Mar. 7, hardcover, $24.95, ISBN 978-0-393-29305-0) begins with a disastrous fire inspired by a true incident in an isolated silver mining town in Idaho in the 1970s. Everyone in town had a friend, a lover, a brother, a husband killed in the fire. The novel imagines the lives of a handful of fictional survivors and their loved ones.
NYRB Classics
Notes of a Crocodile by <NAME>, trans. by <NAME> (May 2, trade paper, $14.95, ISBN 978-1-68137-076-7) is set in the post–martial-law era of 1990s Taipei and depicts the coming-of-age of a group of queer misfits discovering love, friendship, and artistic affinity while hardly studying at Taiwan’s most prestigious university.
Open Letter
The Invented Part by <NAME>, trans. by <NAME> (May 16, trade paper, $18.95, ISBN 978-1-940953-56-4). An aging writer, disillusioned with the state of literary culture, attempts to disappear in the most cosmically dramatic manner: traveling to the Large Hadron Collider, merging with the God particle, and transforming into an omnipresent deity—a meta-writer—capable of rewriting reality.
Pantheon
Autumn by <NAME> (Feb. 7, hardcover, $24.95, ISBN 978-1-101-87073-0). The first installment in a quartet, Smith explores what time is, how we experience it, and the recurring markers in the shapes our lives take and in our ways with narrative.
The Woman on the Stairs by <NAME>, trans. by <NAME> and <NAME> (Mar. 14, hardcover, $25, ISBN 978-1-101-87071-6). A missing painting, a mysterious woman, her husband and her lover come together in a story about obsession, creativity, and love.
Penguin
Ghachar Ghochar by <NAME>, trans. by <NAME> (Feb. 7, trade paper, $15, ISBN 978-0-14-311168-9) is a novel about a young man’s close-knit family splintered by success in rapidly changing present-day Bangalore, India.
Penguin Press
The Idiot by <NAME> (Mar. 14, hardcover, $27, ISBN 978-1-59420-561-3). Selin, the daughter of Turkish immigrants, arrives for her freshman year at Harvard. She begins corresponding with Ivan, and with each email they exchange, the act of writing takes on new and increasingly mysterious meanings. At the end of the school year, Selin heads to the Hungarian countryside, to teach English.
The Night Ocean by <NAME> (Mar. 7, hardcover, $27, ISBN 978-1-101-98108-5). Marina’s husband, Charlie, has become obsessed with H.P. Lovecraft, in particular Lovecraft’s summer of 1934, when he lived for two months with a gay teenage fan named <NAME>. Were they friends—or something more? Just when Charlie thinks he’s solved the puzzle, a new scandal erupts, and he disappears.
Picador
The Woman Next Door by <NAME> (Feb. 7, trade paper, $16, ISBN 978-1-250-12457-9). Hortensia James and <NAME> are neighbors. One is black, the other white. Both have recently been widowed, and are living with questions, disappointments, and secrets that have brought them shame. And each has something that the woman next door deeply desires.
Quercus
Minds of Winter by <NAME> (Mar. 7, hardcover, $26.99, ISBN 978-1-68144-245-7). Sir <NAME>’s 1845 campaign in search of the Northwest Passage ended in tragedy. Nothing from the expedition was retrieved, but when one of the chronometers appears a century and a half later in London, crudely disguised as a Victorian carriage clock, new questions arise about what really happened on that expedition.
Random House
<NAME> the Bardo by <NAME> (Feb. 14, hardcover, $28, ISBN 978-0-8129-9534-3). On Feb. 22, 1862, two days after his death, <NAME> was laid to rest in a marble crypt in a Georgetown cemetery. That very night, shattered by grief, <NAME> arrives at the cemetery, alone, and visits the crypt to spend time with his son’s body.
Random/Hogarth
Woman No. 17 by <NAME> (May 9, hardcover, $26, ISBN 978-1-101-90425-1). When Lady decides to take a break from her husband, she hires a live-in nanny so she can finish her book—but also possibly to avoid her children. S, a young artist/student, arrives on her doorstep to interview for the job and instantly connects with both her sons. But she soon begins to act in a way that causes Lady to question her reason for being there.
Random/Spiegel & Grau
The Lucky Ones by <NAME> (Mar. 7, hardcover, $26, ISBN 978-0-399-58865-5) centers on a group of wealthy girls, their parents, teachers, the maids who serve them, and the guerrilla fighters who surround them, in a jigsaw puzzle of a debut novel set in Colombia during the continuing civil war.
Restless
Temporary People by <NAME> (Mar. 14, trade paper, $17.99, ISBN 978-1-63206-142-3). In the United Arab Emirates, foreign nationals constitute more than 80% of the population. Brought in to construct the towering monuments to wealth that punctuate the skylines of Abu Dhabi and Dubai, these workers have no rights of citizenship and endure miserable living conditions. Unnikrishnan delves into their histories, myths, struggles, and triumphs.
Riverhead
Exit West by <NAME> (Mar. 7, hardcover, $26, ISBN 978-0-7352-1217-6). In a country teetering on the brink of civil war, two young people meet—sensual, fiercely independent Nadia and gentle, restrained Saeed. They embark on a furtive love affair, and are soon cloistered in a premature intimacy by the unrest roiling their city.
Scribner
House of Names by <NAME> (May 9, hardcover, $26, ISBN 978-1-5011-4021-1). “I have been acquainted with the smell of death.” So begins Tóibín’s retelling of Clytemnestra’s tale. Clytemnestra rules Mycenae now, along with her new lover Aegisthus, and together they plot the bloody murder of Agamemnon on the day of his return after nine years at war.
Live from Cairo by <NAME> (July 11, hardcover, $26, ISBN 978-1-5011-4687-9) is a debut novel about an impulsive American attorney, a methodical Egyptian translator, and a disillusioned Iraqi-American resettlement officer trying to protect a refugee who finds herself trapped in Cairo during the turbulent aftermath of the revolution.
<NAME>
The Impossible Fortress by <NAME> (Feb. 7, hardcover, $26, ISBN 978-1-5011-4441-7). A debut novel set in 1987—at once a romance and a coming-of-age story—about what happens when a 14-year-old boy pretends to seduce a girl to steal a copy of Playboy, but then discovers she is his computer-loving soul mate.
Sourcebooks Landmark
Girl in Disguise by <NAME> (Mar. 21, hardcover, $25.99, ISBN 978-1-4926-3522-2). For the first female Pinkerton detective, respect is hard to come by. Danger, however, is not. In the tumultuous years of the Civil War, the streets of Chicago offer a woman mostly danger and ruin, unless that woman is <NAME>, the first female Pinkerton detective and a desperate widow with a knack for manipulation.
St. Martin’s
The Standard Grand by <NAME> (Apr. 25, hardcover, $26.99, ISBN 978-1-250-10894-4). When an Army trucker goes AWOL before her third deployment, she meets a Vietnam vet and widower who inherited a tumbledown borscht belt resort. Converted into a halfway house for homeless veterans, the Standard—and its 2,000 acres over the Marcellus shale formation—is coveted by a Houston-based multinational company. Three violent acts are at the center of this debut.
Viking
What We Lose by <NAME> (July 11, hardcover, $22, ISBN 978-0-7352-2171-0). Raised in Pennsylvania, Clemmons’s heroine, Thandi, views the world of her mother’s childhood in Johannesburg, South Africa, as both impossibly distant and ever present. She is an outsider wherever she goes, caught between being black and white, American and not. She tries to connect these dislocated pieces of her life, and as her mother succumbs to cancer, Thandi searches for an anchor—someone, or something, to love.<file_sep>/content/news/2017-07-21-book-riot-the-buzziest-books-of-2017-so-far-critical-linking.md
---
title: 'Book Riot: The Buzziest Books of 2017 So Far: Critical Linking'
date: 2017-07-21 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Book Riot
link_to_original: 'http://bookriot.com/2017/07/21/buzziest-books-2017-far-critical-linking-july-21-2017/'
description:
---
By <NAME>
Join your fellow book nerds at Book Riot Insiders and get a sweet store deal, exclusive content, the magical New Releases Index, and more!
2017 has been a great year for book lovers so far. From new releases by our favorite writers to wonderful breakout books and genre-bending novels, the list of popular books in 2017 keeps growing. We’ve compiled a list of books getting the most buzz so far this year, along with their publishers’ descriptions.
Pachinko by <NAME>
Profoundly moving and gracefully told, Pachinko follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them. Betrayed by her wealthy lover, Sunja finds unexpected salvation when a young tubercular minister offers to marry her and bring her to Japan to start a new life.
So begins a sweeping saga of exceptional people in exile from a homeland they never knew and caught in the indifferent arc of history. In Japan, Sunja’s family members endure harsh discrimination, catastrophes, and poverty, yet they also encounter great joy as they pursue their passions and rise to meet the challenges this new home presents. Through desperate struggles and hard-won triumphs, they are bound together by deep roots as their family faces enduring questions of faith, family, and identity.
To see the full list, please click the link. Thank you.<file_sep>/content/writing/2007-03-22-free_food_for_millionaires.md
---
title: "Free Food for Millionaires"
date: 2007-03-22T15:58:02-05:00
categories:
tags: ["Short Stories"]
where_published: "Narrative Magazine"
link_to_original: "http://www.narrativemagazine.com/"
link_to_pdf: "/uploads/MinJinLee_FreeFood.pdf"
description: "The novel _Free Food for Millionaires_ was released by Warner Books May 2007. "
_slug: 2007-03-22-free_food_for_millionaires
---
COMPETENCE CAN be a curse. As a capable young woman, <NAME> felt compelled to choose respectability and success. But it was glamour and insight that she craved. A Korean immigrant who'd grown up in a dim, blue-collar neighborhood in Queens, she'd hoped for a bright, glittering life beyond the workhorse struggles of her parents, who managed a Manhattan dry cleaner.
Casey was unusually tall for a Korean, nearly five feet eight, slender, and self-conscious about what she wore. She kept her black hair shoulder length, fastidiously powdered her nose, and wore wine-colored lipstick without variation. To save money, she wore her eyeglasses at home, but outside she wore contact lenses to correct her nearsightedness. She did not believe she was pretty but felt she had something-- some sort of workable sex appeal. She admired feminine modesty and looked down at women who tried to appear too sexy. For a girl of only twenty-two, Casey had numerous theories of beauty and sexuality, but the essence of her philosophy was that allure trumped flagrant display. She'd read that <NAME> advised a woman to dress like a column, and Casey never failed to follow that instruction.
Seated in the spacious linoleum-covered kitchen of her parents' rent-controlled two-bedroom in Elmhurst, Casey looked out of place in her white linen shirt and white cotton slacks--dressed as if she were about to have a gin and tonic brought to her on a silver tray. Next to her at the Formica-topped table, her father, <NAME>, could've easily passed for her grandfather. He filled his tumbler with ice for his first whiskey of the evening. An hour earlier, he'd returned from a Saturday of sorting laundry at the Sutton Place drop shop, which he ran for a wealthy Korean who owned a dozen dry cleaners. Casey's father did not speak to her, and she did not speak to him as they sat together. Her younger sister, Tina--a Bronx Science Westinghouse finalist, vice president of the M.I.T. Campus Christian Crusade, and a pre-med-- was their father's favorite. A classical Korean beauty, Tina was the picture of the girls' mother, Leah, in her youth.
Leah bustled about cooking their first family dinner in months, singing hymns while Tina chopped scallions. Not yet forty, Leah had prematurely gray hair that obscured her smooth, pale brow. At seventeen, she'd married Joseph, who was then thirty-six. On their wedding night, Casey was conceived, and two years later, Tina was born.
Now it was a Saturday night in June, a week after Casey's college graduation. Her four years at Princeton had given her a refined diction, an enviable golf handicap, wealthy friends, a popular white boyfriend, an agnostic's closeted passion for reading the Bible, and a magna cum laude degree in economics. But she had no job and a number of bad habits.
Virginia Craft, Casey's roommate of four years, had tried to convince her to give up the habit that preoccupied her considerably while she sat next to her brooding father. At the moment, Casey would've bartered her body for a cigarette. The promise of lighting one on the building roof after dinner was all that kept her seated in the kitchen--her bare foot tapping lightly on the floor. But the college graduate had other problems that were insoluble by a smoke. Since she had no job, she'd returned to her folks' two-bedroom on Van Kleeck Street.
Seventeen years earlier, in the year of the Bicentennial, the family of four had immigrated to America. And Leah's terror of change had kept them in the same apartment unit. It all seemed a bit pathetic. The smoking, among other things, was corroding Casey's sense of being an honest person. She prided herself on being forthright, though she often dodged her parents. Her biggest secret was <NAME>--her white American boyfriend. On the previous Sunday night after having some very nice sex, Jay had suggested, his elbow crooked over his pillow and head cradled in his hand, "Move in with me. Consider this, <NAME>: sexual congress on tap." Her parents also had no idea that she wasn't a virgin and that she'd been on the pill since she was fifteen. Being at home made Casey anxious. She continually felt like patting down her pockets for matches. Consequently, Casey found herself missing Princeton--even the starchy meals at Charter, her eating club. But nostalgia would do her no good. Casey needed a plan to escape Elmhurst.
Last spring, against Jay's advice, Casey had applied to only one investment banking program. She learned, after all the sign-up sheets were filled, that <NAME> was the bank that every Econ major wanted in 1993\. Yet, she reasoned, her grades were superior to Jay's, and she could sell anything. At the Kearn Davis interview, Casey greeted the pair of female interviewers wearing a yellow silk suit and cracked a Nancy Reagan joke, thinking it might make a feminist connection. The two women were wearing navy and charcoal wool, and they let Casey hang herself in fifteen minutes flat. Showing her out, they waved, not bothering to shake her hand.
There was always law school. She'd managed to get into Columbia. But her friends' fathers were beleaguered lawyers, their lives unappealing. Casey's lawyer customers at Sabine's, the department store where she'd worked weekends, advised her, "For money-- go to B school. To save lives, med." The unholy trinity of Law, Business, and Medicine seemed the only faith in town. It was arrogant, perhaps rash, for an immigrant girl from the boroughs to want to choose her own trade. Nevertheless, Casey wasn't ready to relinquish her dream, however vague, for a secure profession. Without telling her father, she wrote Columbia to defer a year.
Her mother was singing a hymn in her remarkable voice while she ladled scallion sauce over the roasted porgy. Leah's voice trilled at the close of the verse "waking or sleeping, thy presence my light," then with a quiet inhale, she began, "Be thou my wisdom, and thou my true word . . ." She'd left the store early that morning to shop and to cook her daughters' favorite dishes. Tina, her baby, had returned on Thursday night, and now both her girls were finally home. Her heart felt full, and she prayed for Joseph to be in a good mood. She eyeballed the whiskey level in the jug-sized bottle of Dewar's. It had not shifted much from the night before. In their twenty-two years of marriage, Leah had discovered that it was better when Joseph had a glass or two with his dinner than none. Her husband wasn't a drunk--the sort who went to bars, fooled around, or lost his salary envelope. He was a hard worker. But without his whiskey, Joseph couldn't fall asleep. One of her sisters-in-law had told her how to keep a man content: "Never deny a man his bop, sex, and sleep."
Leah carried the fish to the table, wearing a blue apron over her plum-colored housedress. At the sight of Casey pouring her second glass of water, Leah clamped her lips, giving her soft, oval face a severe appearance. Mr. Jun, the ancient choir director, had pointed out this anxiety tic to her before her solos, shouting, "Show us your joy! You are singing to God!"
Tina, of course, the one who noticed everything, thought Casey was just asking for it. Her own mind had been filled with the pleasant thoughts of her boyfriend, Chul, whom she'd promised to phone that night, but even so, she could feel Casey's restlessness. Maybe her sister would consider how much trouble their mother had gone through to make dinner.
It was the water drinking--this seemingly innocent thing. For always, Joseph believed that the girls should eat heartily at the table, grateful for the food and for the care given to it, but Casey habitually picked at her dinner, and he blamed Casey's not eating on her excessive water consumption. Casey denied this accusation, but her father was on the mark. Back in junior high school, Casey had read in a fashion magazine that if you drank three glasses of water before a meal, you'd eat less. It took great effort on Casey's part to wear a size six or smaller; after all, she was a girl with a large frame. Her weight also shifted by five pounds depending on how much she smoked. Her mother was thin from perpetual activity, and her younger sister, who was short like their father, had a normal build, and Tina disapproved of dieting. A brilliant student of both physics and philosophy, Tina had once scolded Casey when she was on Weight Watchers: "The world is awash in hunger. How could you cause your own?"
Casey's water drinking at the table was not lost on her father.
At five feet three, Joseph was compact, yet his rich, booming voice gave him the sound of a bigger man. He was bald except for a wisp of baby fuzz on the back of his head, and his baldness did not grieve him except in the winters when he had to wear a gray felt fedora to protect his head and large lobed ears. He was only fifty-eight but looked older, more like a vigorous man of seventy, especially beside his young wife. She was his second wife. His first, a girl his age whom he'd deeply loved, died of tuberculosis after a year of marriage and before she bore him any children. Joseph adored his second wife, perhaps more so because of his loss. He appreciated Leah's good health and her docile Christian nature, and he was still attracted to her pretty face and her delicate form, which belied her resilience. He made love to her every Friday evening. She had given him two daughters, though the elder looked nothing like her mother.
Casey drained her water glass and rested it on the table. Then she reached for the pitcher.
"I'm not Rockefeller, you know," Joseph said.
<file_sep>/content/event/book_passage_june_22.md
---
title: Book Passage, June 22nd
date: 2007-06-22T14:00:00-05:00
venue:
name: Book Passage, Corte Madera
link: www.bookpassage.com
_slug: book_passage_june_22
---
<file_sep>/content/news/nyt-a-lifetime-of-reading-taught-min-jin-lee-how-to-write-about-her-immigrant-world.md
+++
categories = []
date = 2021-04-07T04:50:11Z
description = ""
images = []
link_to_original = "https://www.nytimes.com/2021/04/07/books/review/min-jin-lee-writer.html"
tags = []
title = "NYT: A Lifetime of Reading Taught <NAME> How to Write About Her Immigrant World"
+++
"As I walked home from the train station, it occurred to me that I had to write about the disgraced, the poor and the earnest strivers of Queens, and I would be able to tell their stories not because I was a writer but because I was a reader."<file_sep>/content/review/darin-strauss-on-pachkinko.md
---
title: <NAME> on Pachkinko
attribution: <NAME>, National Book Critics Circle Award-winning author of *Half
a Life* and *Chang & Eng*
date: 2017-03-11 17:44:21 +0000
book: book/pachinko.md
description: ''
featured: false
---
Pachinko by <NAME> is a great book, a passionate story, a novel of magisterial sweep. It’s also fiendishly readable—the real deal. An instant classic, a quick page-turner, and probably the best book of the year.<file_sep>/layouts/partials/_global/footer.html
<footer class="footer font-sans" role="contentinfo">
<div class="flex justify-between items-center">
<div class="flex items-center">
<a class="hover:text-white no-underline px-3 color-inherit" href="{{ site.Home.RelPermalink }}" >
© {{ now.Format "2006" }} {{ site.Title }}
</a>
{{ partial "tnd-socials/follow.html" "w-4" }}
</div>
<a class="hover:text-gray no-underline color-inherit" href="https://www.thenewdynamic.com/?utm_source={{site.Title | urlize}}" >
site by the New Dynamic
</a>
</div>
</footer><file_sep>/content/writing/2008-04-27-why_im_a_democrat_ed._susan_mulcahy.md
---
title: "Why I’m A Democrat (ed. Susan Mulcahy)"
date: 2008-04-27T22:28:07-05:00
categories:
tags: ["Essays"]
where_published:
link_to_original:
link_to_pdf:
description:
_slug: 2008-04-27-why_im_a_democrat_ed._susan_mulcahy
---
<file_sep>/content/event/vromans.md
---
title: "Vroman's"
date: 2017-02-22 19:00:00
show_time: true
venue:
name: "Vroman's Bookstore"
address: 695 East Colorado Boulevard
city: Pasadena
state: CA
zip: '91101'
link: 'https://vromansbookstore.com'
---
In Conversation with <NAME>, author of novels *<NAME>* and the forthcoming *Memento Park*. Sarvas is also a literary critic and the creator of the highly acclaimed literary blog T*he Elegant Variation*.<file_sep>/content/event/sun-valley-writers-conference.md
---
title: Sun Valley Writers' Conference
date: 2019-07-20 19:01:06 -0400
images:
- "/uploads/sun_valley_writers_conference.jpg"
description: ''
link: https://svwc.com/svwc-2019/presenters
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2017-08-24-daily-mail-uk-review-of-10th-anniversary-edition-of-free-food-for-millionaires.md
---
title: >-
Daily Mail UK: Review of 10th Anniversary Edition of FREE FOOD FOR
MILLIONAIRES
date: 2017-08-24 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Daily Mail UK
link_to_original: 'http://www.dailymail.co.uk/home/books/article-4819830/LITERARY-FICTION.html'
description:
---
LITERARY FICTION
By <NAME> for the Daily Mail
| PUBLISHED: 17:21 EDT, 24 August 2017 | UPDATED: 17:21 EDT, 24 August 2017 |
FREE FOOD FOR MILLIONAIRES by <NAME> (Apollo, £14.99)
The heroine of this vivacious saga is <NAME>, an Ivy League Economics graduate seeking to make her way and find love in Nineties Manhattan.
However, Casey’s progress — like that of her sister Ella — is complicated by her heritage: born in Korea but raised in the U.S., she is estranged from her conservative, working-class parents in the novel’s opening scenes.
Casey is, among other things, a fan of 19th-century novels, and at 550 pages, Free Food For Millionaires boasts a Victorian classic’s bulk.
Yet with its focus on mores and money, it’s Jane Austen that Min Jin Lee’s debut most often brings to mind. Indeed, there are two memorable episodes in which an exchange of gifts reveals a gulf in regard and understanding that could have been penned by Austen herself, so well are they judged.
The sisters’ stories bowl absorbingly along, while their mother is also permitted a poignant starring role, receiving the same sympathetic treatment Min Jin Lee extends to almost all her characters.
<br><file_sep>/content/news/the-medici-book-club-prize--finalists-announced.md
---
title: 'The Medici Book Club Prize: Finalists Announced'
date: 2018-06-01 00:15:04 -0400
images: []
image_credit: ''
categories: []
where_published: Literary Affairs
link_to_original: http://literaryaffairs.net/the-medici-book-club-prize/
description: ''
---
<file_sep>/content/news/2017-01-23-bookish-best-book-club-picks-for-february-2017.md
---
title: 'Bookish: Best Book Club Picks for February 2017'
date: 2017-01-23 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Bookish by <NAME> and <NAME>
link_to_original: 'https://www.bookish.com/articles/best-book-club-picks-for-february-2017-neil-gaiman-george-saunders-and-more/'
description:
---
Pachinko
There’s something about generational sagas that we can’t get enough of. This novel by <NAME> explores the history of Korea and Japan during the early 1900s through the family of a pregnant girl. With her baby’s father out of the picture, Sunja decides to accept a marriage proposal from a pastor, even though it means traveling with him to Japan. The move is isolating and painful; Sunja and her Korean family are discriminated against because of their homeland. The novel follows the family through four generations as they search for belonging in a new land.<file_sep>/content/event/hong-kong-literary-festival-2017.md
---
title: Hong Kong Literary Festival 2017
date: 2017-11-09 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
November 9-12, 2017<file_sep>/content/event/helen-zell-writers-program-at-university-of-michigan-mfa.md
---
title: '<NAME> Writers'' Program at University of Michigan, MFA'
date: 2018-04-05 17:30:00
show_time: true
venue:
name: 'University of Michigan Museum of Art, Helmut Stern Auditorium'
address: 435 S. State Street
city: Ann Arbor
state: MI
zip: '48109'
link:
---
<file_sep>/content/news/2017-01-11-buzzfeed-32-most-exciting-books-of-2017.md
---
title: 'Buzzfeed: 32 Most Exciting Books of 2017'
date: 2017-01-11 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: 'Buzzfeed by <NAME>, Deputy Books Editor'
link_to_original: 'https://www.buzzfeed.com/jarrylee/the-most-exciting-books-coming-in-2017?utm_term=.vkO8mp8W1#.lnp6qK6Rn'
description:
---
<NAME>’s novel Pachinko is the portrait of one Korean family through multiple generations, from the early 1900s where prized daughter Sunja’s unexpected pregnancy threatens to bring shame to her poor family until a minister offers to marry her and start a new life together in Japan. Sunja’s descendants live in exile from their true homeland, and face (and rise above) all kinds of challenges, from poverty to discrimination, while establishing their identity and family in a new country.<file_sep>/content/news/2016-11-21-publishers-weekly-exquisite-meditation-on-the-generational-nature-of-truly-forging-a-home-.md
---
title: 'Publishers Weekly: "Exquisite meditation on the generational nature of truly forging a home."'
date: 2016-11-21 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Publishers Weekly
link_to_original: 'http://www.publishersweekly.com/978-1-4555-6393-7'
description:
---
Lee’s (Free Food for Millionaires) latest novel is a sprawling and immersive historical work that tells the tale of one Korean family’s search for belonging, exploring questions of history, legacy, and identity across four generations. In the Japanese-occupied Korea of the 1910s, young Sunja accidentally becomes pregnant, and a kind, tubercular pastor offers to marry her and act as the child’s father. Together, they move away from Busan and begin a new life in Japan. In Japan, Sunja and her Korean family suffer from seemingly endless discrimination, and yet they are also met with moments of great love and renewal. As Sunja’s children come of age, the novel reveals the complexities of family national history. What does it mean to live in someone else’s motherland? When is history a burden, and when does history lift a person up? This is a character-driven tale, but Lee also offers detailed histories that ground the story. Though the novel is long, the story itself is spare, at times brutally so. Sunja’s isolation and dislocation become palpable in Lee’s hands. Reckoning with one determined, wounded family’s place in history, Lee’s novel is an exquisite meditation on the generational nature of truly forging a home. (Feb.)<file_sep>/content/news/2017-04-05-washington-post-book-review-of-pachinko-audio.md
---
title: 'Washington Post: Book Review of Pachinko Audio'
date: 2017-04-05 12:00:00
categories: ["News"]
tags:
- Reviews
- Audio
- News
attribution: Washington Post by <NAME>
link_to_original: 'https://www.washingtonpost.com/entertainment/books/ingenious-new-audio-version-of-the-handmaids-tale-deepens-the-original/2017/04/05/e1df3cf6-1a17-11e7-bcc2-7d1a0973e7b2_story.html?utm_term=.fc4459ebefbc'
description:
---
PACHINKO
By <NAME>
Hachette Audio. Unabridged, 18 ¼ hours
Min Jin Lee’s second novel is a culturally rich, psychologically astute family saga. It begins in Korea in 1910, the year of Japanese annexation, and ends four generations later in Japan. Sunja is the only child of a Korean fisherman and his wife, who keeps a small boarding house. Hardworking and innocent, Sunja becomes pregnant at 16 by Hansu, a married businessman. She is saved from disgrace by a young Korean Presbyterian minister who marries her out of goodness. The couple immigrate to Japan, where Koreans are a despised underclass, and the story expands to follow Sunja and her husband, their children and others, including the Godfather-like Hansu, who operates behind the scenes with an eye on his natural son. Allison Hiroto reads this moving novel in a sweet, compassionate voice. Without changing register for male characters, she has a storyteller’s gift of distinguishing between speakers through modulations of tone and disposition. Further, her voice has great emotional range, capturing the fluctuations of joy, sorrow, anger, shame and hope in the hearts of these people as they wrestle with notions of home and the corrosive effects of bigotry.
<NAME> reviews audiobooks every month for The Washington Post.<file_sep>/content/news/2007-07-21-read_this_life_and_arts.md
---
title: "Read This (Life and Arts)"
date: 2007-07-21T22:55:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Seattle Post-Intelligencer"
link_to_original: ""
description: ""
_slug: 2007-07-21-read_this_life_and_arts
---
The first novel by <NAME> looks at the precarious time after college graduation when dreams may not be realized, carefully laid plans can collapse and ...
<file_sep>/content/news/2007-06-24-the_observer.md
---
title: "The Observer, Guardian"
date: 2007-06-24T23:13:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "The Observer"
link_to_original: "http://books.guardian.co.uk/reviews/roundupstory/0,,2109814,00.html"
description: ""
_slug: 2007-06-24-the_observer
---
When stalking is the only comfort
The Observer - Jun 24, 2007
<NAME> explores the most fundamental crisis of immigrants’ children: how to bridge a generation gap so wide it is measured in oceans, gaping between ...
<file_sep>/content/writing/tnd-test.md
+++
categories = []
date = 2021-08-04T04:00:00Z
description = ""
draft = true
image_credit = ""
images = []
link_to_original = "https://www.example.com"
title = "TND Test"
where_published = "Somewhere"
+++
<file_sep>/content/event/arnold--porter-kaye-scholer.md
---
title: 'Arnold & <NAME>'
date: 2017-07-19 18:00:00
show_time: true
venue:
name: 'Arnold & <NAME>'
address: 250 West 55th Street
city: New York
state: NY
zip: '10019'
link:
---
A Conversation with <NAME>, Esq.
Private Event<file_sep>/content/news/2017-02-06-nprs-morning-edition-interview-with-lynn-neary-podcast.md
---
title: "NPR's MORNING EDITION: Interview with <NAME> (Podcast)"
date: 2017-02-06 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Audio
attribution: "NPR's Morning Edition"
link_to_original: 'http://www.npr.org/2017/02/06/513304628/pachinko-is-a-family-saga-of-exile-discrimination-and-japanese-pinball'
description:
---
PACHINKO Is A Family Saga of Exile, Discrimination…And Japanese Pinball
Pinball is big business in Japan. Known as pachinko, the multibillion-dollar industry is dominated by Korean Japanese, an immigrant community that has been unwelcome and ill-treated for generations.
<NAME>'s new novel Pachinko is about much more than the game. It's about the story of one family's struggle to fit into a society that treats them with contempt.
Lee got the idea for her book when she was still a college student. It was 1989 and she went to a lecture by an American missionary who had been working with the Korean Japanese in Japan. He told a story about a 13-year-old boy who committed suicide. After his death the boy's parents found his school yearbook.
"And in this yearbook several of his classmates had written things like: Go back to your country," Lee says. "They had written the words: die, die, die. The parents were born in Japan, the boy was born in Japan. … That story just really could not be more fixed in my brain."
Lee, a Korean-American, was determined to tell the history of Koreans in Japan. She lived there for a while and interviewed many Korean Japanese to get a sense of what life was like for them. She decided to tell their history through a multigenerational family story.
"I was very interested in history but I also thought, you know, history is not that interesting sometimes and it can feel a bit medicinal," she says. "I wanted … to give these people flesh and blood in the same way that people that I know have contradictions and betrayals and deaths and marriages and the kind of texture of life."
The story begins in the early 20th century when Korea is already under Japanese rule. A young girl named Sunja is growing up in a small fishing village on a tiny Korean Island. She falls in love with a good looking, older man from the mainland.
Enlarge this image
A woman gambles in a Japanese pachinko parlor circa 1955.
Three Lions/Getty Images
When she becomes pregnant he tells her he is already married. Sunja is saved from disgrace by a Christian minister staying at her family's boarding house who offers to marry her and take her to Japan.
"She's a child, she's 16," Lee says. "When she goes to Japan she simply has no idea what's going to wait for her. And to be frank, most Koreans really didn't know that this was going to happen. They didn't know that the history would turn out this way."
The impoverished Koreans who left their occupied homeland didn't find life much easier in Japan. Sunja has two sons and her husband takes care of them both. But when he is arrested for preaching Christianity, her life becomes even more difficult. She and her children survive World War II but then the Korean War breaks out.
With the war and partition of Korea, it becomes almost impossible for Sunja to return to her homeland. Twenty years later she still yearns for what she has lost.
After the war the pachinko parlors start popping up all over in Japan. Both of Sunja's sons find work in the noisy pin ball dens which are often run by Korean Japanese.
"The Korean Japanese could not find legal employment for … seven or eight decades," Lee explains. "Even now they have great difficulty finding jobs in certain sectors. So, in pachinko they were able to find a kind of employment haven."
Though they may have found employment, and in many cases, financial success, that didn't necessarily translate into respect. Despite its popularity, the Japanese look down on pachinko parlors as gambling dens with connections to criminals. Even so, one of Sunja's sons thrives in the business. But her firstborn, Noa, never comes to terms with the circumstances of his life.
"Noa really is symbolic," Lee says. "He is an emblem of so many people that I met who wanted very desperately to just belong. And they would do everything they possibly could within legal channels to be considered a respectable human being."
As a naturalized American who feels she belongs in this country, Lee says it is hard for her to understand that generations of Koreans have never been fully accepted in Japan. But many of the Korean Japanese she interviewed dismissed her concerns. They have adapted to living in Japan even if their presence there is still not fully embraced.<file_sep>/content/news/pbs-books-at-the-associated-writing-programs-conference.md
---
title: PBS Books at the Associated Writing Programs Conference (Video)
date: 2018-03-09 18:30:49 -0500
link_to_original: https://www.pbs.org/video/min-jin-lee-awp-2018-d0ag09/
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/news/2017-02-17-publishers-weekly-radio-interview-with-rose-fox-and-mark-rotella-audio-episode-213.md
---
title: 'Publishers Weekly Radio: Interview with <NAME> and <NAME> (AUDIO) Episode 213'
date: 2017-02-17 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
- News
- Audio
attribution: Puiblishers Weekly Radio with <NAME> and <NAME>
link_to_original: 'http://www.publishersweekly.com/pw/podcasts/index.html?channel=8&podcast=687'
description:
---
An interview with PW Radio as PACHINKO hits No. 22 on the Publishers Weekly Hardcover Fiction Bestseller List.<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-1.md
---
title: 'Video: "Are Koreans Human?" at Radcliffe Institute for Advanced Study at Harvard
University'
date: 2019-03-01 00:50:11 -0500
link_to_original: https://www.radcliffe.harvard.edu/video/are-koreans-human-min-jin-lee
images:
- "/uploads/Screen Shot 2019-03-02 at 4.46.14 PM.png"
tags: []
categories: []
description: The author <NAME> RI '19 asks, "Who are the modern Koreans, and
what do they care about?" To answer this enormously complex question, Lee explores
the will of Koreans to survive and flourish as global citizens, their enduring faith
in education, and the costs of such a quest and what it may mean to the larger world
they seek to engage. She explains that when she's writing, she isn't just writing
about Koreans, education, or the diaspora—she's writing about humans.
---
<file_sep>/content/event/housing-works-what-the-dickens.md
---
title: 'Housing Works Bookstore Cafe: 8th Annual What the Dickens'
date: 2017-12-16 12:00:00
show_time: true
venue:
name: Housing Works Bookstore Cafe
address: 126 Crosby Street
city: New York
state: NY
zip:
link: 'http://housingworks.org'
---
Marathon reading of A CHRISTMAS CAROL by <NAME> with guest writers. <file_sep>/content/news/2017-02-07-newsweek-best-new-books-of-the-week.md
---
title: 'Newsweek: Best New Books of the Week'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Newsweek
link_to_original: 'http://www.newsweek.com/new-book-releases-february-7-2017-what-read-gaiman-darnielle-nguyen-mastri-553442?rx=us'
description:
---
<file_sep>/content/news/2017-01-23-origins-journal-interview.md
---
title: Origins Journal Interview
date: 2017-01-23 12:00:00
categories: ["News"]
tags:
- Interviews
- News
attribution: Origins Journal Interview with Editor-in-Chief <NAME>
link_to_original: 'http://www.originsjournal.com/more-interviews/2016/12/15/min-jin-lee-identity-love-and-exile'
description:
---
<NAME>: Identity, Love, and Exile
An Interview by <NAME>
<NAME> is no stranger to success. She has won several awards for her essays and short fiction, and her 2007 debut novel, Free Food for Millionaires, was a national bestseller recognized by the New York Times, Wall Street Journal, The Times of London, and NPR's Fresh Air, among others. Her new novel, Pachinko, forthcoming in February, is a gripping saga about a family whose origins begin in 1900s Korea. A series of events leads the family to Japan just prior to WWII where they live in exile for the next several decades, "bound together by deep roots as they face enduring questions of faith, family, and identity."
Critics are hailing Pachinko as one of the most anticipated books of 2017.
ORIGINS
Talk about your trajectory as a writer. I’m very interested in your decision to write versus practice law. I’m curious about the ways in which you’ve navigated or continue to manage these two identities: lawyer & writer.
LEE
I practiced law for two years (1993-1995) then quit to write full time. I had a liver illness diagnosed while I was in high school, and the illness made me vulnerable to sporadic fatigue and later to more serious issues. In my early thirties, I had liver cirrhosis, and thanks to Interferon B treatments, I have since been fully cured. I mention the illness, because more than being a lawyer or a writer, I have been a person with an illness for the formative years of my adult life, and being told repeatedly that I may get fatally worse from a young age made me think very hard about how to spend my time. In short, illness made me think about why I should write rather than practice law when I prefer writing and what I should write about rather than just any topic whatsoever. Though I no longer practice, I still feel like a lawyer—someone who can be thoughtful about what is most relevant in a problem and how a person should prioritize the issues at hand, and I am a writer, i.e., a person who observes carefully and puts her thoughts down on paper in a directed manner to create a shaped narrative.
ORIGINS
Can you tell us about pachinko and its significance not only in Korean culture but also in post-World War II Japan?
LEE
Pachinko is an adult gambling game, which became highly popular after World War II. It is also a multi-billion dollar industry with double the export revenues of the Japanese car industry. One out of eleven Japanese play pachinko regularly; however, it is also viewed with contempt and suspicion by middle class Japanese. As permanent residents, Korean-Japanese are foreigners even though they have been born in Japan for generations, and throughout the 20th century, Japanese companies and local governments would not hire them. Consequently, many had to find work in Korean-Japanese owned businesses such as pachinko parlors or yakiniku (Korean barbecue/galbi) restaurants. Nearly every Korean-Japanese person I encountered or researched had someone in his or her family with some distant or near connection to the pachinko industry—which includes machine manufacturers, pachinko balls, keihin (gifts) booths, bento makers, etc. Historically, the pachinko industry offered an employment refuge for poor people who could not find employment elsewhere.
Grand Central Publishing
ORIGINS
Identity is an overarching theme in Pachinko. The characters struggle with, mediate, deny, and, in some cases, redefine their identities. Often, identity plagues them. In what ways were you consciously dealing with identity in this book and what did the process of writing Pachinko reveal about your own identity, if anything?
LEE
Identity is central to this novel. The Korean-Japanese people are treated differently—legally, socially, culturally—by the majority because of their ethnic identity. The process of writing this book taught me a great deal about being an ethnic person who is distinct from the majority. All of us have so many aspects of our identities, and for me, the process of writing this book constantly reminded of my ethnic heritage as well as my American identity. Also, I felt aware of my gender, sexual orientation, marital status, parent status, religion, education, socio-economic status—many of which were so different from the Korean-Japanese people I met and interviewed. Also, I have never felt any close affiliation politically with either South Korea or North Korea, whereas, a Korean-Japanese who does not naturalize and is a permanent resident must choose one of the two governments for his or her passport, which must feel incredibly strange since most never set foot on either country.
ORIGINS
Origins matter to Sunja, the main character, and many of the other characters who often revere and defer to their elders. They uphold honor and tradition in spite of social, economic, and political pressures. Often Korea—both North and South—serves as a silent member of the cast. We think of origins as something static, but maybe our origins are as susceptible to evolution and perception as any other human reality. This seems evident in the ways in which several of the Korean characters who are born in Japan or in the United States, for example, think about themselves in relation to the “motherland.” What does this say about our affinity for cultural affiliations and/or our declarations about and definitions of ethnicity, race, nationality, etc.?
LEE
Your question is highly relevant to Americans and to all who identify as global citizens, especially because all of us are becoming increasingly transnational in our identities. Technology has broken down so many boundaries, and images and data are constantly exchanged, forging new hybrid identities, which are distinct from the values transmitted from our respective original communities. I think Sunja and women like her upheld values they didn’t necessarily create because their identities of origin compelled them to do so in a new, unwelcoming land. What I witnessed and learned from my research was that migrant and immigrant people held onto the values of their original communities because their adopted spaces were so often hostile to them. When communities welcome strangers and give them great latitude and tolerance, more strangers tend to assimilate faster because they feel safe and wish to increase their stakes.
ORIGINS
For some, there is a certain acceptance of one’s fate; Kyungee, Noa, Solomon, and Hana are different faces of this prism. Then there is Sunja, who seems to acclimate to new circumstances but also has an inner strength and courage to forge ahead in life. Mozasu, too. He recognizes his own strengths and weaknesses but overcomes his limitations—both individual and societal—and enjoys great success as a father and man. Talk about these juxtapositions and their significance to this family’s story.
LEE
In my interviews and research, I noticed that people tend to respond to change with either fatalism or a reliance on personal agency. Most people do a combination of both and add on other philosophical values; however, one value tends to dominate in most personalities. Highly successful people across cultures tend to adapt well and be versatile regardless of circumstances; I found this to be true in nearly all the places I researched. That said, adaptability requires great psychological resourcefulness and strong mental and spiritual foundations. What I found interesting was when social norms encouraged passivity and fatalism and viewed individual adaptability as threatening. Naturally, in those environments, it was dangerous to be independent and active.
ORIGINS
When Solomon turns 14, he is required to register with the Japanese government. When he goes to get his identification papers, he is fingerprinted and interviewed. He must confront the uncertainty of whether he will be allowed to stay in Japan—even though he was born there—or be deported to Korea, a country he has never visited (though he visits later) and where he has no living relatives. This storyline has obvious relevance for today, especially here in the United States where there’s talk of registering Muslims in the aftermath of our most recent presidential election. But it also speaks to the larger issue of how governments often regard and treat immigrants. Talk about this.
LEE
The fingerprinting issue was highly politicized for the Korean-Japanese because historically it was a conscious mode of surveillance for the government. Surveillance of those who are considered "other" and dangerous to the majority is a polarizing issue today across cultures and nations. America had internment camps for Japanese Americans during World War II, and those who were interned were American citizens. This was not even a hundred years ago. For all intents and purposes, The Korean-Japanese do not look very different from the Japanese, so it is fascinating and disturbing to witness the cultural obsession with bloodlines. Things have not changed very much. There are almost 65 million refugees in this world. Many of us appear to be afraid of whoever is the other and seek leaders who want to exclude newcomers. That said, I think progressive peoples everywhere need to reclaim painful dialogue in place of our echo chambers. I don’t think it is helpful to judge or categorically dismiss those who are excluding the minority. I think we may need to listen carefully to what is at stake for those who are making these divisive policies. That said, at any point in time, any one of us can be the other, and I think this is worth noting.
ORIGINS
Trauma and shame are threads that run through each character’s life in this book and in one of your interviews you talk about your interest in these themes. This reminds me of an article I read recently about how trauma can affect one’s genes, making it possible for subsequent generations to be affected—biologically, I suppose—by a grandparent’s or parent’s trauma. Whether or not trauma is passed down genetically, it certainly can affect not only its victim but also countless more. Why is it important to examine trauma and shame in a literary context?
LEE
I believe that trauma and shame are inherited, reinforced and reenacted in our respective families. Also, I believe that nations and cultures are larger families that replicate these dynamics. I am interested in exploring these painful legacies and also how they are healed actively and gradually. I believe history is a record of these psychological injuries and art can serve to repair, respond and heal.
ORIGINS
I thought your exploration of the immigrant experience was expert. Talk about the ways in which this perspective is depicted in the novel. e.g. the tension between Phoebe and Solomon or Kazu and Solomon; the different iterations of assimilation (Noa, Hansu Koh); the experience of the Korean immigrant experience in America, Japan, and Latin America.
LEE
Thank you. I am profoundly interested in the diaspora and what it means to be a Korean in the world. I have met and interviewed immigrants from all continents, and I am continually affected by how those who leave feel about those who stay and vice-a-versa. In South Korea, I have been looked upon as a curiosity because I am interested in the history that many South Koreans no longer care about, and I don’t mind this at all. I think it makes sense that since I am continually told that I am different and I am “something,” naturally, I want to know more about this something. When a person is a member of a dominant and mostly homogenous group, I think she or he does not have the same compulsion of discovery. All the characters you mention are outside their communities of origin either through physical movement or through a generational progression, and these evolutions and migrations affect them personally and interpersonally. I had the chance to interview Koreans from Brazil and Japanese from Colombia, and they were culturally Brazilian and Colombian, respectively, but they were so different from the majority, too. Lastly, I want to say that you noticed something really important to me: the different iterations of assimilation that you mention carved strong markers in the characters’ personalities and behaviors.
ORIGINS
The theme of exile is also alive and well in this book. Sanju leaves Korea, never to return. Yoseb, after suffering debilitating injuries, becomes a different man, relegated to his bed. Noa also exiles himself, both in life and in death. And so does Hana, come to think of it. There are also those who return home to North Korea, never to be heard from again. How do you think about exile and its impact on one’s identity and the collective identity of a given group of people?
LEE
As boundaries break down and people move more across the globe, we witness and experience a greater sense of literal or metaphorical exile, which includes feelings of loss, abandonment, rejection, and reclamation. I think this condition exists metaphysically and existentially, too. Many feel alien within their own families, and this may have nothing to do with race, class or other birth classifications. I find that there is a great deal of suffering that occurs because of this sense of exile and homelessness in the world.
ORIGINS
Religion, Christianity in particular, is a backdrop to this book. Can you talk about this and how it functions as a literary device?
LEE
Korean history can’t really be understood from the late 19th century to present day without understanding the significant role of Christianity in politics and education. Christians were very important to organizing political uprisings in early 20th century in Korea, and Christians of many stripes continue to play a significant role in the governance of South Korea today. Koreans around the world have strong feelings about Christianity, either for or against, and I wanted very much to express this in the lives of my characters. I find that religion occupies a very central space in the lives of believers, and I often find that intellectuals dismiss religion casually, and this is, I think, a missed opportunity in understanding how people behave. Also, this book, like my first, is written in a 19th century style of omniscient narration, and in my own fiction, I prefer the idea and believe in the assertions of an omniscient narrator written in the past tense.
ORIGINS
Throughout the book, we learn that women are born to suffer. They must endure. They must subjugate their own desires or be undone by them. I’m thinking of Hana and Etsuko—both of whom suffer mightily after acting on their sexual desires. Conversely, Kyunghee does not act on her desire to be with <NAME> and she suffers his loss. She sacrifices love. And now that I think of it, love between men and women feels elusive in this novel. It is strongest and always prevails in the context of family. Is that fair to say?
LEE
I was shocked by how many ethnically Korean women I interviewed discussed the necessity of suffering in a woman’s life. That said, I think the idea of not needing to suffer in life and choosing happiness is a fairly recent American notion. This idea of elective happiness and needlessness of suffering causes feelings of great anguish, resentment, and powerlessness to those who have unasked-for suffering. The reality is that terrible, unspeakably tragic things happen to so many people. How are we to make sense of this in a 21st century life paradigm of an all-consuming happiness-seeking quest, I wonder? I disagree with the idea of blaming those who suffer from depression, illness, difficult family members, addictions, etc., and as I get older, I think it is more compassionate to see that suffering is a part of life, and learning how to cope or persevere may be more helpful rather than to deny its inevitable arrival at one’s doorstep at different points in one’s life. As for love, I noticed often that ordinary women of regular means had to choose familial love over romantic love and had to view romantic love with great suspicion because a bad romantic choice could materially impact the quality of a woman's life. This idea is not that different than the idea that biology is destiny since women’s lives change with pregnancy and child-rearing more immediately and dramatically than in the lives of men.
ORIGINS
What surprised you about what you had written once you were done with Pachinko?
LEE
Gosh, I was very surprised that it took such a long time from the moment of inspiration (1989) to the final moment of publication (2017), and that I felt stubbornly compelled to carry this book with me for nearly three decades. Also, I have been surprised by the way this book has grown and taken a life outside of my vision. I am surprised by the interest this book has garnered.<file_sep>/content/event/brookline-library.md
---
title: Coolidge Corner Public Library in Brookline
date: 2018-03-03 14:00:00
show_time: true
venue:
name: Coolidge Corner Public Library in Brookline
address: 31 Pleasant Street
city: Brookline
state: MA
zip: '02446'
link: >-
https://www.brooklinebooksmith.com/events/2018-03/min-jin-lee---pachinko-br-kl-pereira---a-dream-between-two-rivers-br-in-conversation-with-katie-eelman/
---
Conversation with <NAME>, author of A DREAM BETWEEN TWO RIVERS: Stories of Liminality and <NAME>, author of PACHINKO, moderated by Co-founder and Editor-in-Chief <NAME> of Cutlass Press and Director of Media and Events at Papercuts, J.P.
This event will take place at the Coolidge Corner Public Library.
Books will be sold by Brookline Booksmith.
<file_sep>/content/review/book-riot-on-pachkinko.md
---
title: Book Riot on Pachkinko
attribution: 'Book Riot: Most Anticipated Books 2017'
date: 2017-03-11 17:48:33 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Lee makes it impossible not to develop tender feelings towards her characters—all of them, even the most morally compromised. Their multifaceted engagements with identity, family, vocation, racism, and class are guaranteed to provide your most affecting sobfest of the year. (<NAME>)<file_sep>/content/event/world-knowledge-forum-seoul.md
+++
date = 2021-09-15T04:00:00Z
description = "Conversation with Neda Ullaby of NPR in Seoul at the World Knowledge Forum"
images = []
link = "http://www.wkforum.org/WKF/2021/en/"
show_time = false
title = "World Knowledge Forum - Seoul "
[venue]
address = "249 Dongho-ro, Jung-gu"
city = "Seoul"
name = "<NAME>"
state = ""
zip = ""
+++
<file_sep>/content/news/2017-07-10-guardian-best-holiday-reads-2017-selected-by-writers.md
---
title: 'Guardian: Best Holiday Reads 2017 Selected by Writers'
date: 2017-07-10 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Guardian
link_to_original: 'https://www.theguardian.com/books/2017/jul/09/best-holiday-reads-summer-reading-2017-john-banville-jackie-kay-kirsty-wark-melvyn-bragg'
description:
---
By <NAME>
I’d recommend The End of Eddy (Harvill Secker £12.99), Édouard Louis’s sensational autobiographical novel set in northern France, and Pachinko (Head of Zeus £8.99), Min Jin Lee’s sprawling epic of Korean immigrant life in Japan. If you want to keep up with global affairs while sun-tanning, try Howard W French’s lively and illuminating Everything Under the Heavens: How the Past Helps Shape China’s Push for Global Power.
I’m heading to the east coast of Malaysia and have packed Qiu Miaojin’s Notes of a Crocodile (£9.99), recently published in translation by NYRB Classics; Svetlana Alexievich’s Second-Hand Time (Fitzcarraldo £14.99), and Zola’s L’Assommoir(Oxford World’s Classics £8.99).
For the complete list, please click the link below. Thank you.<file_sep>/content/event/amherst-college-14.md
---
title: 'Literary Lights: Associates of the Boston Public Library'
date: 2019-04-28 19:00:00 -0400
show_time: true
venue:
name: Boston Park Plaza
address: ''
city: ''
state: ''
zip: ''
link: https://www.associatesbpl.org/events-and-programs/literary-lights/#currentll-purchasetickets
description: The Associates of the Boston Public Library formally invites you to join
us for the 31st annual Literary Lights dinner on Sunday, April 28, 2019 at the Boston
Park Plaza. This annual black tie optional event is our opportunity to honor outstanding
writers from the Northeast and to celebrate their contributions to literature.
images: []
---
<file_sep>/content/news/2017-03-15-the-guardian-uk-book-review.md
---
title: The Guardian (UK) Book Review
date: 2017-03-15 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Guardian (UK)
link_to_original: 'https://www.theguardian.com/books/2017/mar/15/pachinko-min-jin-lee-review'
description:
---
By <NAME>
In the latter stages of Korean-American author <NAME>’s patient, sprawling story of a Korean family in Japan, Nobuo Ban, one of the novel’s principal characters, allows himself a moment of reflection. He is living a “small, invisible life” in Nagano, Japan, in 1969 – a modest but respectable middle-class existence, with a wife and four children and a job as a manager of a gambling joint where customers play the pachinko machines that lend the novel its title. But Nobuo’s unchanging routine and determinedly detached manner hide a terrible secret that plagues him daily: he is not, in fact, Japanese, but Korean – born Noa Baek, the son of poor immigrants despised by the rest of Japanese society. His failure to commit himself emotionally to his wife is at odds with the totality of his dedication to Japanese language, culture and manners, and betrays not just a deep-seated fear of being unmasked but an acceptance of the impossibility of equality or redemption. “Though he valued his wife and children as a kind of second chance, in no way did he see his current life as a rebirth.
Noa’s predicament is a terrifying embodiment of the anxieties of Koreans in Japan – he stands to lose his family and job if his true identity is revealed – and indeed of immigrants in general. His desire to assimilate is constantly tempered by the fear of rejection, a tension that works its way into virtually every scene in the novel.
Spanning nearly 100 years and moving from Korea at the start of the 20th century to pre- and postwar Osaka and, finally, Tokyo and Yokohama, the novel reads like a long, intimate hymn to the struggles of people in a foreign land. <NAME> meticulously reconstructs the relatively overlooked history of the large ethnic-Korean community in Japan, referred to as zainichi, whose perpetual status as outsiders obliges them, like Noa’s nephew Solomo in the novel, to renew their alien registration card every three years: a state of administrative limbo that mirrors their divided identities and condemns them to the role of the perpetual outsider.
The novel’s multi-generational narrative allows this rich history to unfold at a pace that is beguilingly peaceful, opening in a deceptively idyllic coastline setting in Korea, shortly after the Japanese annexing of Korea. Hoonie, the cleft-lipped, club-footed son of a fisherman, marries Yangjin, a 15-year-old “as mild and tender as a newborn calf”. Their first three babies die, but the fourth, Sunja, survives, and blossoms in adolescence. She soon falls for a sharp-suited man who wears white shoes and speaks fluent Japanese and Korean: a married yakuza, a polished gangster whose divided loyalties announce the end of Sunja’s innocence and the beginning of a life of hardship. Pregnant with Noa, her only salvation lies in marriage to an understanding pastor who arranges her escape to Japan, where she quickly becomes accustomed to the life of a Korean immigrant.
Shame and guilt underpin many of the finest scenes in the novel, with every character continually forced by their position as second-class citizens to make painful sacrifices, and, consequently, to consider the nature of those sacrifices. Sunja never fully comes to terms with falling pregnant by a married man, nor can she overcome her emotional and material debt to Isak, the man who saves her (his act of sacrifice for her and her family is not enough to provide her with any sense of salvation). Noa sacrifices his Korean identity in order to become Japanese, but fails to reconcile himself with either.
Much of the novel’s authority is derived from its research, which brings to life fishing villages and shabby townships
Although Noa and Hansu offer some of the most poignant emotional conflicts in the novel, the story is built upon the resilience of its female characters, who keep their families alive during their most difficult times, working long hours running boarding houses or making and selling kimchi in the most gruelling conditions in order to support the children. Elsewhere, minor characters such as Akiko and Phoebe probe the nuances in cultural difference in a way that Noa, Hansu or even Solomon are not able to.
Much of the novel’s authority is derived from its weight of research, which brings to life everything from the fishing village on the coast of the East Sea in early 20th-century Korea to the sights and smells of the shabby Korean township of Ikaino in Osaka – the intimate, humanising details of a people striving to carve out a place for themselves in the world. Vivid and immersive, Pachinko is a rich tribute to a people that history seems intent on erasing.
•Tash Aw’s Five Star Billionaire is published by 4th Estate. Pachinko by Min Jin Lee is published by Head of Zeus. To order a copy for £16.14 (RRP £18.99) go to bookshop.theguardian.com or call 0330 333 6846. Free UK p&p over £10, online orders only. Phone orders min p&p of £1.99.<file_sep>/content/event/frankfurt-the-other-half-asia-pacific—societies-in-diversity-and-change.-innovation,-religion,-gender-new-directions-in-challenging-times.md
---
title: 'Frankfurt: The Other Half: Asia Pacific—Societies in Diversity and Change.
Innovation, Religion, Gender: New Directions in Challenging Times'
date: 2018-10-11 13:00:24 -0400
images: []
description: 'Panel: <NAME> (USA), <NAME> (Singapore) and <NAME>
(New Zealand) Moderated by <NAME> '
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/politics_and_prose_july_2nd.md
---
title: Politics and Prose, July 2nd
date: 2007-07-02T20:00:00-05:00
venue:
name:
link: www.politics-prose.com
_slug: politics_and_prose_july_2nd
---
<file_sep>/content/event/the-women-conference-of-florida.md
+++
date = 2022-05-11T21:45:00Z
description = "Women’s Conference Of Florida hosts <NAME>, author of the New York Times Bestseller “Pachinko,\" on May 11 at the University of Tampa. "
images = []
link = "https://womensconferenceofflorida.com/"
show_time = true
title = "The Women's Conference of Florida"
[venue]
address = "401 W Kennedy Blvd, Tampa, FL "
city = "Tampa"
name = "University of Tampa Plant Hall , Historic Building"
state = "FL"
zip = "33606"
+++
<file_sep>/content/news/2017-07-10-best-books-of-2017-so-far-book-riot.md
---
title: 'Best Books of 2017 (So Far): Book Riot'
date: 2017-07-10 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Book Riot
link_to_original: 'http://bookriot.com/2017/07/11/best-books-2017-far/'
description:
---
PACHINKO
<br>by <NAME>
<br>FICTION
<br>Pachinko is an epic family saga that follows four generations of a Korean family from the early 1900s through the 1980s. The family immigrates to Japan early on in the story and Min Jin Lee simultaneously explores the changing family dynamics as well as the cultural tension and discrimination against Koreans living in Japan. The characters are complex, the story runs deep, and Min Jin Lee’s writing is descriptive without being overwritten. She pulls you into this family from page one and you never want to leave them.
* <NAME>
For the complete list, please click the link below. Thanks to the editors of Book Riot.<file_sep>/content/news/2017-12-13-the-brooklyn-rail-best-books-of-2017.md
---
title: 'The Brooklyn Rail: Best Books of 2017'
date: 2017-12-13 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Brooklyn Rail
link_to_original: 'https://brooklynrail.org/2017/12/books/Best-25-POETRY-Books-of-2017'
description:
---
By <NAME>, Books Editor
Best 25 FICTION books of 2017
THE POWER, <NAME>
THE HUNGER SAINT: A Novella, by <NAME>
SO MANY OLYMPIC EXERTIONS, <NAME>
AMERICAN WAR: A Novel, By <NAME>
FUTURE HOME OF THE LIVING GOD: A Novel, by <NAME>
THE GYPSY MOTH SUMMER: A Novel, by<NAME>
THE ILIAC CREST, by <NAME>
THE EPIPHANY MACHINE: A Novel, by <NAME>
THE GARGOYLE HUNTERS, by <NAME>
BAD DREAMS AND OTHER STORIES, by <NAME>
EXIT WEST, by <NAME>
A SEPARATION, by <NAME>
THE LEAVERS, by <NAME>
STRANGER, FATHER, BELOVED, by <NAME>
PACHINKO, by <NAME>
DEAR CYBORGS, by <NAME>
HER BODY AND OTHER PARTIES: Stories, by <NAME>
THE NINTH HOUR: A Novel, by <NAME>
MY HEART HEMMED IN, by <NAME>
LITTLE FIRES EVERYWHERE, by <NAME>
THE STANDARD GRAND, by <NAME>vo
HERITAGE OF SMOKE, by <NAME>
REFRIGERATED MUSIC FOR A GLEAMING WOMAN, by <NAME>
WAIT TILL YOU SEE ME DANCE, by <NAME>
SOUR HEART: Stories, by <NAME>
For the complete list, please click the link. Thank you.<file_sep>/content/event/brisbane-writers-festival-sunday.md
---
title: 'Brisbane Writers Festival: Sunday Panel'
date: 2017-09-10 13:00:00
show_time: true
venue:
name: Auditorium 1
address:
city:
state:
zip:
link: 'http://uplit.com.au/festival/brisbane-writers-festival-2017/program/from-across-the-sea'
---
From Across the Sea: <NAME>, <NAME> and <NAME> explore the experience of immigration across generations.<file_sep>/content/event/muse--marketplace-writing-conference.md
---
title: Muse & Marketplace Writing Conference
date: 2018-04-06 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
April 6-7th<file_sep>/content/news/2007-05-28-npr_talk_of_the_nation.md
---
title: "NPR Talk of the Nation"
date: 2007-05-28T23:32:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "NPR Talk of the Nation"
link_to_original: "http://www.npr.org/templates/story/story.php?storyId=10497458"
description: ""
_slug: 2007-05-28-npr_talk_of_the_nation
---
I am really interested in reading though I haven’t read them yet - <NAME>’s‚ Free Food for Millionaires.‚ It’s about the child of immigrant ...
<file_sep>/content/review/pattinase-on-free-food-for-millionaires.md
---
title: Pattinase on Free Food for Millionaires
attribution: Pattinase
date: 2007-03-11 18:02:37 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Summer Picks from The Boston Herald<file_sep>/content/news/ny-post-the-10-best-books-to-read-to-beat-coronavirus-boredom-3.md
---
title: 'Condé Nast Traveler: Best Books to Read if You''re Dreaming of Japan'
date: 2020-03-30T00:50:11-04:00
link_to_original: https://www.cntraveler.com/story/best-books-to-read-before-a-trip-to-japan
images: []
tags: []
categories: []
description: ''
---
> _Pachinko_ "offers a cross-generational look at 20th-century Japan through the eyes of impoverished Korean immigrants. The heartbreaking saga, set in the 1930s, begins when a young Korean woman, impregnated by a rich but married lover, enters a union of convenience with an ill minister. She follows him to Japan, effectively rebooting her life and everything she’s ever known. This is a stormy and powerful story about immigrant sacrifice, with undercurrents of compassion and steely female strength."<file_sep>/content/news/msnbc-the-last-word-with-lawrence-o-donnell.md
---
title: 'MSNBC: The Last Word with Lawrence O''Donnell'
date: 2021-03-17T00:50:11-04:00
link_to_original: ''
images: []
tags: []
categories: []
description: ''
draft: true
---
<file_sep>/content/event/2016-12-01-the-center-for-fiction.md
---
title: The Center for Fiction
date: 2016-12-01 19:00:00
show_time: true
venue:
name: The Center for Fiction
address: 17 East 47th Street
city: New York
state: NY
zip: 10017
link: 'http://www.centerforfiction.org'
---
The Modern Family: A panel discussion with <NAME>, <NAME>, <NAME>, and <NAME> about the importance of representing a broad spectrum of families in fiction.<file_sep>/content/event/london-uk-burley-fisher-bookstore.md
---
title: 'London, UK: Burley Fisher Books'
date: 2017-10-19 19:00:00
show_time: true
venue:
name: <NAME>
address: 400 Kingsland Road
city: London
state:
zip: E8 4AA
link: 'http://burleyfisherbooks.com'
---
<file_sep>/content/news/new-york-times-newsletter-australia-bureau-chief-damien-cave-recommends.md
---
title: 'New York Times Australia Letter: Australia Bureau Chief Damien Cave Recommends'
date: 2018-08-01 00:03:01 -0400
link_to_original: https://www.nytimes.com/2018/08/01/world/australia/joy-wonder-goop-good-news.html
images: []
tags: []
categories: []
description: This week, I’ve got a literary recommendation that lines up with our
joy and wonder theme, sort of. It’s “Pachinko,” the novel by <NAME>, which
chronicles four generations of an ethnic Korean family, first in Japanese-occupied
Korea in the early 20th century, then in Japan itself from the runup to World War
II and beyond. It doesn’t sound like fun, but our critics selected it as one of
best books of 2017 and there’s a humanity and warmth to the story, writing and characters
that makes it feel like a cozy warm blanket (as my very smart wife put it). I’m
not quite finished yet, but I agree. It’s a family saga more about human connections
than history, even as conflict and occupation intervene.
---
<file_sep>/content/news/2017-01-09-top-10-books-of-february-2017.md
---
title: 'Top 10 Books of February 2017:'
date: 2017-01-09 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Toronto Star
link_to_original: 'http://trueviralnews.com/librarians-pick-the-next-great-reads-toronto-star/'
description:
---
"Librarians pick the next great reads" The Canadian Library Association's Loan Stars Program<file_sep>/content/event/new-jersey-launch-at-barnes--noble.md
---
title: 'New Jersey Launch at Barnes & Noble'
date: 2017-03-04 14:00:00
show_time: true
venue:
name: 'Barnes & Noble'
address: 765 Route 17 South
city: Paramus
state: NJ
zip: '07652'
link: 'https://stores.barnesandnoble.com/store/2597'
---
A Conversation with <NAME>
<NAME> is an Assistant Editor at Town & Country, the oldest continually published magazine in America, where she covers the arts, culture, travel, weddings, and real estate.<file_sep>/content/event/award-winning-authors-of-pachinko-and-obit-join-ucm-and-national-book-foundation-for-april-20-program-in-hendricks-hall.md
+++
date = 2022-04-20T20:00:00Z
description = "An evening of readings and conversation with National Book Foundation Award-honored authors <NAME> (“OBIT”) and <NAME> (“Pachinko”)"
images = []
link = "https://www.ucmo.edu/news/university-news/posts/2022-03-31-award-winning-authors-of-pachinko-and-obit-join-ucm-and-national-book-foundation-for-april-20-program.php"
show_time = true
title = "Award-Winning Authors of ‘Pachinko’ and ‘OBIT’ Join UCM and National Book Foundation for April 20 Program in Hendricks Hall"
[venue]
address = "208 E South St"
city = "Warrensburg"
name = "<NAME> on the University of Central Missouri "
state = "MO"
zip = "64093"
+++
<file_sep>/content/event/2018-miami-writers-institute-1.md
---
title: Amherst College
date: 2019-09-11T20:00:00-04:00
show_time: true
venue:
name: Amherst Books
address: 8 Main Street
city: Amherst
state: MA
zip: '01002'
link: ''
description: ''
images:
- "/uploads/attachment 1.jpg"
---
<file_sep>/content/writing/new-yorker---after-the-pyeongchang-winter-olympics--healing-the-deepest-fracture-.md
---
title: 'The New Yorker: "After the Pyeongchang Winter Olympics, Healing the Deepest
Fracture"'
date: 2018-02-24 00:24:13 -0500
images: []
image_credit: ''
categories: []
where_published: The New Yorker
link_to_original: https://www.newyorker.com/culture/culture-desk/after-the-pyeongchang-winter-olympics-healing-the-deepest-fracture
description: ''
---
<file_sep>/content/event/amherst-college-17.md
---
title: 'New Castle County Reads '
date: 2021-10-22T23:00:00+00:00
show_time: false
venue:
name: Chase Center of the Riverfront
address: 815 Justison St.
city: Wilmington
state: DE
zip: "19801"
link: https://nccde.org/710/New-Castle-County-Reads
description: ''
images: []
---
<file_sep>/content/writing/2007-03-01-motherland.md
---
title: "Motherland"
date: 2007-03-01T22:39:00-05:00
categories:
tags: ["Short Stories"]
where_published: "The Missouri Review"
link_to_original: "http://www.missourireview.com/"
link_to_pdf: "/uploads/motherland_minjinlee.pdf"
description:
_slug: 2007-03-01-motherland
---
**Tokyo, 1979**
Etsuk<NAME>i loved all three of her children, but she did not love them all the same. Being a mother had taught her that this kind of emotional injustice was perhaps inevitable.
By midmorning, Etsuko had finished everything she had to get done for Solomon's party and was sitting in her office in the back of the airy, birch-paneled restaurant. She was forty-two years old, a native of Nagano who'd moved to Tokyo following her divorce six years before, and she had maintained a youthful prettiness that she felt was important to being a restaurant owner. She wore her jet-colored hair in a chignon style to set off her lively, egg-shaped face. From afar she could appear stem, but up close her face was animated, and her small, friendly eyes missed nothing. She applied her makeup expertly, having worn rouge and powder since middle school, and the red wool Saint Laurent suit that Solomon's father, Moses, had bought her hung well on her reedy figure.
Though Etsuko would normally have been pleased with herself for being so ahead of schedule, today she wasn't. She continued to stare at the phone message from her high school-aged daughter, Hana, with an unfamiliar Nagano number (maybe a coffee shop or a friend's house since Hana was rarely at home or at school). Calls with Hana could take five minutes or an hour, depending, and Moses was coming to pick her up soon. Her boyfriend of five years was a patient man about most things, but he liked her to be punctual. Etsuko dialed anyway, and Hana picked up on the first ring.
"I've been waiting." Hana's voice was reproving.
"I'm sorry," Etsuko said. "I got the message a few minutes ago. And I can't talk long." Even though Etsuko was afraid of her fifteen-yearold daughter, she had been trying to sound more firm, the way she was with her staff.
"Where are you?" she asked.
"I'm four months pregnant."
"_Nani?_"
Hana repeated herself, and this time Etsuko waited to speak. In her mind she could see her daughter's large, unblinking eyes. Hana resembled the girls in comic books, with her cute, lollipop head and small, girlish body. She dressed to get attention-short skirts, sheer blouses and high-heeled boots-and accordingly, she received that attention from all kinds of men. It occurred to Etsuko now that this was her _unmei_. Her ex-husband used to dismiss this idea of fate as a lazy explanation for the bad choices people made. But no matter; life had only confirmed her beliefs that there was indeed a pattern to it all. To Etsuko, this had to happen because as a girl she had been no different. When she was seventeen she had been pregnant with Tatsuo, Hana's oldest brother.
Etsuko and Hana remained silent on the line, but the poor phone reception crackled like a campfire.
"I want to come to Tokyo right away," Hana said.
"Why?"
"What do you think?"
Etsuko took a moment to breathe, for she had literally forgotten to take in air.
"Does your father know?"
"Are you stupid?"
"Hana—" Again she tried to sound authoritative, but it had no effect. Hana merely said that she'd take the next train to Tokyo. Then she hung up.
Two years after the divorce, when Hana was eleven, she'd asked if they could talk to each other like peers, and Etsuko had agreed because she was grateful that her daughter continued to talk to her at all. Also, she agreed because when she'd been a girl she had lied to her mother and father about everything. But Etsuko found that being detached as a mother had its own burdens. She wasn't allowed to ask any prying questions, and if she sounded too concerned (something Hana hated), her daughter hung up the phone and didn't call for weeks.
Etsuko had many regrets about her life in Nagano, but what she was most sorry about was what her reputation had done to her children. Her grown sons still refused to talk to her unless it was absolutely necessary. And she had only worsened things by continuing to see <NAME>, an ethnic Korean who owned pachinko parlors. Her sister Mari and her mother urged her to end it; they believed that his pinball business, however lucrative, was not respectable. But she couldn't. He had been a good friend to her; he had changed her life. And he was the only man she had never cheated on-something Etsuko had never believed could be possible for herself.
The spring before her thirty-sixth birthday, when she was still married and living in Nagano, Etsuko had seduced another one of her high school boyfriends. She had been having a series of affairs for almost three years with various men from her adolescence. What amazed her was how difficult it was the first time but how effortless it was to have all the others that followed. Married men wanted invitations from married women. It was no trouble to phone a man she had slept with twenty years ago and invite him to her house for lunch when her children were at school.
That spring, she began sleeping with an old boyfriend from her freshman year in high school. He'd grown up into a handsome, married playboy who still had the tendency to talk too much. One afternoon in her tiny Nagano living room, as the playboy was getting dressed to return to his office, he bemoaned the fact that she wouldn't leave her dull husband, who preferred the company of his work colleagues to hers. He laid his head between her small breasts and said, "But I can leave her. Tell me to do it." To this, she said nothing. Etsuko had no intention of leaving Nori and the children. Her complaint about her husband was not that he was boring or that he wasn't home enough. Nori was not a bad person. It was just that she didn't feel like she knew him in any clear sense after nineteen years of marriage, and she doubted that she ever would. Her husband didn't seem to need her except to be a wife in name and a mother to his children. For Nori, this was enough.
There was no acceptable excuse for her behavior. She knew that. But at night, when Nori sat at the kitchen table to eat the dinner that had gotten cold because he'd come home late once again from another company gathering, she waited for something to come, some insight, some feeling. As she watched him with his eyes locked to his rice bowl, she wanted to shake him because in all her life, she had never expected this kind of loneliness. Around that time, someone had handed her a pamphlet as she came out of the grocery store. On the flimsy cover, a middle-aged housewife was pictured as half skeleton and half flesh. On the bottom of the page it said, "Every day you are closer to your death. You are half dead already. Where does your identity come from?" She tossed the pamphlet away almost as soon as she got it, but the picture stayed with her for a long while.
The last time she saw the playboy, he gave her a sheaf of poems that he had written for her. As he left through the kitchen door, he confessed that he loved her only. His eyes pooled with tears as he told her that she was his heart. For the rest of the day, she ignored the housework and read and reread the maudlin and erotic poems. She couldn't say if they were good or not, but she was pleased by them (she marveled at the effort they must have taken) and reasoned that in his own showy way, he did love her. This one affair had given her what she had wanted from all the others—an assurance that what she had handed out in her youth had not died.
That night, when her family was sleeping, Etsuko soaked in the wooden tub and glowed in what felt to her like a victory. After her bath, she dressed in her blue-and-white _yukata_ and headed toward her bedroom, where her innocent husband was snoring gently. One thing seemed clear: If she needed all the men who had ever loved her to continue loving her, she would always be divided. She would always cheat, and she'd never be a good person. It dawned on her then that being a good person was something she had not given up on completely after all. In the morning, she told the playboy not to call anymore, and he didn't. He just moved on to the next pretty housewife in town.
But a few months later, Nori found the poems that she should have destroyed, and he beat her for the first time in their marriage. Her sons tried to stop him, and Hana, just nine years old then, screamed and screamed. That evening Nori threw her out, and she made her way to her sister's house. Later, the lawyer said it would be pointless for her to try to get custody of the children since she had no job and no skills. He coughed in what seemed like politeness or discomfort and said it would be pointless also because of what she had done. Etsuko nodded and decided to give up her children, thinking that she would not trouble them anymore. Then, following a want ad for a restaurant hostess, Etsuko moved to Tokyo, where she knew no one.
Etsuko wanted to believe that being with Moses was changing her. That she was sexually faithful to him she took as proof. She had once tried to explain this to her sister, and Mari had replied, "A snake that sheds its skin is still a snake." And her mother, on hearing that Moses wanted to marry her, said, "Haven't you done enough to your children?"
She came to believe that the penalties incurred for the mistakes you made had to be paid out in full to the members of your family. But she didn't believe that she could ever discharge these sums.
At noon, Moses came to get her. They were going to pick up Solomon at his school to take him to the Immigration Control Bureau. The government required all Koreans born in Japan after 1952 to report to the Bureau on their fourteenth birthday to request permission to stay in Japan for four more years. This practice was required every four years until the Korean died or left Japan for good. Moses had told her all of this a week before, and he had also asked her then to go with them.
As soon as she got in the car, Moses reminded her to put on her seat belt. Ever since his wife had been killed in a car accident when Solomon
was four years old, Moses had only bought fancy German cars with advanced safety features. His chauffeur, Yamamoto-san, was even a former driving instructor. His gray Mercedes was built like a truncated submarine; inside, the thick steel plate and tinted windows enveloped them, and it felt as if they were traveling beneath dark, quiet waters.
He asked if everything for the party was ready, and Etsuko said yes. She was still thinking about Hana. Before she'd left, she had phoned the doctor, and the procedure was scheduled for the morning after next.
Moses wasn't very good-looking, but his face had strength to it, and his gaze was direct. She had never been with anyone Korean before, and she hadn't known many Koreans before him, but she imagined that his squared-off facial features were traditionally Kankoku-his wide jawbone, straight white teeth, thick black hair and the shallowset, narrow, smiling eyes. He had a lean, slack body that reminded her of metal. When he made love to her, he was serious, almost as if he was angry, and she found that this gave her intense pleasure. His physical movements were deliberate and forceful, and she wanted to surrender to them. Whenever she read about something or someone Korean, she wondered what it would be like to go to North Korea, where his parents came from. Would people there be like him somehow?
She noticed that Moses was holding a wrapped present the size of a block of tofu. He handed it to her, and she tried to look happy. Beneath the silver foil paper was a box from the jewelry store where Moses bought all her gifts. Inside it was a gold-and-diamond watch nestled in dark red velvet.
"It's a mistress watch," he said. When she looked surprised, he said, "I bought it yesterday, and I showed it to Kuboda-san—" Kuboda was Moses' new manager at Hiro.
She frowned at him, still not understanding his meaning.
"He said these fancy watches are what you give to your mistress because they cost the same as a diamond ring, but you can't give a ring to your mistress since you're already married." He started to laugh.
For the first time since she'd gotten into the car, she checked to see if the glass partition separating them from the driver was closed all the way; it was. Her skin flushed with heat.
"Make him stop the car."
"What's the matter?" Moses took her hand, and she pulled it away. She wanted to say that she wasn't his mistress, but instead she burst into tears.
"Why are you crying? Every year for five years, I bring you a diamond ring. Each one bigger than the one before it, and you say no to me. And I go back to the jeweler, and he and I have to get drunk. Nothing has changed for me," he sighed. "You're the one who says no. Says no to the _Kankoku-jin_ gangster."
"You're not a gangster."
"I am _Kankoku_."
"You know that doesn't matter to me. It's my family."
Moses looked out the window, and when he spotted his son, he signaled to him with a quick wave.
Etsuko straightened her posture. The car stopped, and Solomon got in the front passenger seat. The glass partition opened, and he said hello. Etsuko reached over to straighten the rumpled collar of his white dress shirt, which he let her do. He said to her, "_Arigato_ very much," one of the jokes they made about mixing up words in different languages. Then he closed the partition so he could talk with Yamamoto-san about the previous night's Yokult Swallows game. They were loyal fans of the perennially losing baseball team.
Moses took her wrist and clasped the watch on it. "You're a funny woman. I bought you a gift. Just say thanks. I never meant that you were a—"
The bridge of her nose hurt, and she thought she would start crying again.
"Hana called. She's coming tonight."
"To the party?" He looked surprised; then he nodded like he understood. "Yes. To see Hiromi-san perform. She likes him?"
It had never crossed her mind to invite her daughter to Solomon's birthday party. Her daughter and Moses' son were only a year apart, but they'd never met one another. Etsuko went to Nagano twice yearly to see her children. They did not come to Tokyo.
"Uhtmn," she replied. Etsuko had no idea if Hana liked music. As a child, she had not been the kind who sang or danced. Etsuko stared at the back of the driver's gray-streaked head. He nodded slowly when Solomon talked, and their quiet gestures appeared intimate to her. She wished she had something like baseball that she could talk about with her daughter—a common subject they could visit without subtext or judgment.
Etsuko told Moses that Hana had an appointment with a doctor. When he asked if she was sick, Etsuko shook her head no.
What could she say? This was how life had turned out. Her oldest son, Tatsuo, was twenty-five years old, and it was taking him eight years to graduate from a fourth-rate college. Her second son, Taro, a withdrawn nineteen-year-old, having failed all his college entrance exams, had taken a position as a ticket collector at a movie theater. She had no right to expect her children to hold the aspirations of other middle-class people—to graduate from Tokyo University, to get a job at the Industrial Bank of Japan, to marry into a nice family. She had no right to expect them to make her proud.
Etsuko unclasped the watch and put it back in the red leather box. She laid the box in the space between herself and Moses on the white, starched doily covering the black leather seats. He handed it back to her.
"It's not a ring." His voice was firm. "Save me a trip to the jeweler. Do that for me."
Etsuko held the box in her hands and wondered how they'd stayed together five years, with him not giving up and her not giving in.
The Immigration Control Bureau was a giant gray box with an obscure sign. The first clerk they saw was a tall man with a narrow face and a shock of black hair buzzed off at the sides. He stared at Etsuko shamelessly, his eyes darting across her breasts, hips and jeweled fingers. She noticed then how overdressed she looked compared to Moses and Solomon, who wore button-down shirts, dark slacks and black dress shoes. They looked like the gentle Mormon missionaries who used to glide through Nagano on their bicycles when she was a girl.
"Your name . . ." The clerk squinted his eyes at the form Solomon was filling out. "Solomon. What kind of name is that?"
"It's from the Bible. My grandfather was a minister, and he named me. Solomon was a king in the Old Testament. A man of great wisdom." Solomon smiled at the clerk as if he was sharing a secret. He was proud of the things he remembered about his Korean grandparents, who had come to Japan as laborers from the north country before the war and then stayed on, since there was little for them to return to.
"Great wisdom? A king?" The clerk snorted. "Koreans don't have kings anymore."
"What did you say?" Etsuko asked. His snotty tone reminded her of all the temperamental cooks she had fired.
Quickly, Moses put his hand on her arm and pulled her back.
She looked at Moses. His temper was far worse than hers. Once, when a restaurant guest had tried to make her sit with him, Moses, who happened to be there that night, walked over, picked him up bodily and threw him outside the restaurant, breaking several of the mans { ribs. She expected no less of a reaction now, but Moses just glanced at the form.
"Sir," Moses said, "we're in a hurry to get back home." He paused and folded his hands behind him. "Thank you very much for understanding." There wasn't a trace of anger in Moses' voice or facial expression.
Solomon turned to Etsuko, and she flashed him a warning look.
The clerk pointed to the back of the room and told Moses and Etsuko to sit. In the long, rectangular room, shaped like a train car, with bankteller windows running parallel alongside the opposite walls, half a dozen people sat on benches, reading their newspapers or _manga_. Etsuko studied their faces, wondering if they were Korean or not. She couldn't be sure. From their seats, Etsuko and Moses could see Solomon talking to the clerk, but they couldn't hear anything.
Moses asked if she wanted a can of tea from the vending machine. She nodded yes; her neck felt stiff, and she still wanted to slap the clerk's face.
"You must have known—" She paused. "You must have warned him. I mean, you told him that today would not be so easy? Nee?" She didn't mean to be critical, but after the words came from her mouth, they sounded like criticism, and she was sorry.
"No." He opened and closed his fists rhythmically. "I came here once with my mother to fix my registration papers. When I was a boy. And there was a nice clerk. So I asked you to come. I thought—" He exhaled through his nostrils. "It was stupid. Stupid to wish for kindness."
"No. You couldn't have warned him. I shouldn't have said it like that."
"It is hopeless, _nee_? I cannot change his fate. He is my son, and he is Korean. He has to get those papers, and he has to follow all the steps of the law perfectly." He smiled, but the smile was unfamiliar to her, as if it were denying a bitter thing. "Once a clerk told me that I was merely a guest in this country."
"That's crazy. You and Solomon were born here."
"But the clerk was right. And this is something Solomon has to understand. We can always be deported. We have no motherland."
Slowly, Moses walked away in the direction of the vending machines. Etsuko lowered her shoulders and slouched in her seat. She didn't know what else to say.
Half an hour later, Solomon returned to them. Next he had his photograph taken, and after that he had to go to another room to get fingerprinted. Then they could go home. The last clerk was a woman; she was plump, and her light-green uniform shirt flattened her large breasts. She took Solomon's thumb and index finger and with gentleness dipped them into inkpots. Solomon depressed his fingers onto a white card as if he were a child painting. Moses looked away and sighed audibly. The clerk smiled at the boy and told him to pick up the registration card at the next room. Moses mumbled, "Let's get your dog tags."
Solomon turned to face his father. "Hmm?"
"It's what we dogs must have," Moses said.
The clerk looked furious. "Sir, the fingerprints and registration cards are necessary for the government's records. There's no need to feel insulted."
"But you don't make your children get fingerprinted on their birthday, do you?" Etsuko said.
The clerk's neck reddened. "My son is dead."
Etsuko tried not to feel anything for the woman. But she knew what it was like to lose your children-it was like you had failed, or worse, like you were cursed and didn't deserve any happiness.
"Koreans do lots of good for this country," Etsuko said.
The clerk nodded. "You Koreans always tell me that."
Solomon blurted out, "She's not Korean."
Etsuko touched his arm, and the three of them walked out of the room. She wanted to climb out of this gray box and see the light of outdoors again. She longed for the mountains of Nagano. And though she had never done so in her childhood, she wanted to walk in the cold, snowy forests, beneath the flanks of the dark trees. There was so much insult and injury in life, and she felt that she had no choice but to collect what was hers. But now she wished she could take Solomon's shame too and add it to her pile, even though she was already overwhelmed.
Hana was waiting for her at the restaurant. She was sitting at the table near the bar, sipping a Coke that one of the waitresses had gotten for her. Her hair was no longer permed. Instead it was straight and its natural color, a reddish black. It was cut in one even length and splayed across her thin shoulders. She wore a white cotton blouse, neatly ironed, a dark, pleated skirt coming to her knees, gray wool stockings and flat, schoolgirl shoes. She hadn't dressed this way since she was in primary school. Her stomach was flat, but her bud-like breasts looked fuller; otherwise, there was no way of knowing that she was pregnant.
The dining room was all set up for the party. White linen cloths covered a dozen round tables, and in the middle of each stood a tall floral arrangement. A busboy stood at the edge of the room, blowing up one blue balloon after another with a helium tank. He let them all float up to the ceiling.
Etsuko was happy to see her daughter appear so modest, and she nearly forgot the reason for her visit. She introduced Solomon to Hana, and they greeted each other politely. But their mutual curiosity was evident. Hana pointed to the balloons hiding the ceiling, and before Etsuko had a chance, Solomon replied quickly, "It's my birthday. Why don't you come to the party? There's going to be dinner here, and then we're going to a disco." Without even a glance toward her mother, Hana answered, "If you wish."
Etsuko wanted Solomon to go to his house. She hadn't wanted him to come here, but he had insisted on meeting her daughter. Etsuko needed to go to the bathroom, but she was reluctant to leave them alone together; she couldn't say why exactly. Later, when she returned from the bathroom, she saw them whispering like a pair of young lovers unconcerned with their dinner. Etsuko checked her watch and pushed Solomon to get home. On his way out he said, "Hey, I'll see you at the party." And Hana smiled like a courtesan and waved to himthe enticing gesture of a young woman who understood her moves.
"Why did you make him go?" Hana snapped. "I was having fun."
"Because he has to get dressed."
"I looked in them." Hana glanced at the bags near the entrance. A hundred party bags, three long rows, filled with tapes, new Sony Walkman cassette players, imported teen magazines and boxed chocolates, waited for Yamamoto-san to take them to the disco, where they'd be handed out after the party ended. "I wish my dad was a _yakuza_," Hana said.
"Hana—" Etsuko looked around to see if anyone could hear them.
"Your boyfriend's son doesn't seem like a brat. Yet." Hana smiled.
"He doesn't have it easy."
"Not easy? American private schools, millions in the bank, a chauffeur-driven Mercedes. Get some perspective, Mother."
"Today, on his birthday, he had to go to the Immigration Control Bureau to request permission to stay in Japan for another four years. If he's denied he could be deported."
"That's not going to happen." Hana looked certain of this.
"What do you know about it? He was born in this country too, and he had to be fingerprinted today like he was criminal. He's just a child."
"We're all criminals, Mother." Hana's carbon-colored eyes looked hard and ancient. "No one is innocent here."
Etsuko turned away. "Why must you be so hard-hearted?"
The steady line of Hana's lips crumpled. "How can you say that? I'm the only one who still talks to you."
"You're the only one who still needs to punish me. So go ahead. But I've said I'm sorry enough times." Etsuko tried to control her voice,
but she knew the waitresses heard everything. And suddenly it didn't matter anymore.
"Listen. I made the appointment," Etsuko said.
Hana looked up.
"The day after tomorrow we'll take care of your problem. And then we're even." Etsuko looked straight at her daughter's pale face. "You shouldn't be a mother. You have no idea how hard it is to have children. You're never forgiven for your mistakes."
Hana covered her _manga_ face with her hands and began to cry. A low moan grew into a shrill crying that was frightening to hear.
Etsuko moved toward her daughter. She didn't know if she should touch her or say something. It was possible that Hana might push her away. She put her hand on her daughter's head. Hana's brow felt warm, and her hair was satiny. At the touch, Hana winced, but Etsuko didn't immediately pull her hand back.
When Etsuko had lived in the cramped, three-bedroom house in Nagano, with its flat roof and leaky kitchen, certain labors had sustained her. At this moment, with a kind of pinprick pain, Etsuko recalled watching her sons devour paper-lined plates piled high with the shrimp that she had fried for dinner. In the middle of July it was worth it to stand in front of a hot tempura pan dropping battered shrimp into bubbling peanut oil, because to her sons, Etsuko's shrimp was better than candy. And it came to her like a tall and dark wave how much she'd loved combing Hana's freshly washed hair when her cheeks were still pink from the steamy bath water.
"I know you didn't want us. My brothers told me, and I told them they were wrong even though I knew they weren't. But I clung to you because I wasn't going to let you just leave what you started. How can you tell me how hard it is to have children? You haven't tried to be a mother. What right do you have? What makes you a mother?"
Etsuko stood silent, utterly transfixed by the realization that the absolute worst that she saw in herself was actually how her children saw her too.
"But ... how can you think that I didn't want the three of you?" Etsuko recollected all the letters she'd written, the gifts and money she'd sent, which the boys had returned. And worse, the phone calls to the house to check on them when her husband wouldn't say anything beyond _moshi-moshi_, then hand the phone to Hana because she was the only one who would take the receiver. Etsuko wanted to justify herself, her attempts, and to offer proof. Being a mother was what defined her more than any other thing—more than her roles of daughter, wife, divorced woman, girlfriend, restaurant owner. She hadn't done it well, but it was who she was, and it was what had changed her inside. From the moment Tatsuo was born, she had been filled with grief and selfdoubt because she was never good enough. Yet still it had been worthwhile, she believed, even though she had failed, because being a mother was something eternal; life wouldn't end with her death.
Etsuko blurted out, "But I didn't marry Moses. I don't even live with him. So I wouldn't make things worse for you and your brothers."
Hana tilted her head back slightly and chortled.
"Am I supposed to thank you for this great sacrifice? So you didn't marry a Korean gangster, and you want me to congratulate you for this? You didn't marry him because you don't want to suffer. You're the most selfish person I know. If you want to sleep with him and take his money to set up a fancy place like this and not marry him, that's your choice. Not mine." Hana dried her face with her shirtsleeve. "Mother, you don't want to be judged. That's why you haven't married him. That's why you left Nagano to hide out in the big city. You think you're such an outcast and a rebel, but you're not. You left because you're afraid, and you slept with all those men because you were weak. Don't tell me about sacrifices because I don't believe in such nonsense."
Hana started to cry again, as if saying all this hadn't given her any satisfaction.
Etsuko sat down in the nearest chair. What her daughter said was true. She was afraid of what the people in Nagano thought and what they continued to say. If she married someone like Moses, it would only prove to them that no decent Japanese man would touch a woman like her. She would be called a _yakuza_ wife. If she married him, she'd no longer be considered the tasteful owner of a successful restaurant in the best part of Tokyo—an image she only half believed in herself. She wondered what Moses thought of her. He must believe that she was a better person than she actually was. But her daughter wasn't fooled.
Etsuko picked up Hana's travel bag next to her chair and nudged her daughter to stand up so she could take her home.
Her apartment was in a luxury Homat building down the street. Halfway there, Hana had said she didn't want to go to the party anymore. She wanted to be left alone so she could sleep until the morning. Etsuko unlocked the deadbolt to her apartment and led Hana to her bedroom. She would sleep on the sofa that night.
Hana lay across the futon, and Etsuko pulled a light comforter over her thin young body and turned out the light. Hana curled herself into a C; her eyes were still open, and she said nothing. Etsuko didn't want to leave her. Despite everything, it struck her that what she was feeling was a kind of contentedness that they were together again. And in an awkward way, she had started to see that Hana had come to her for care. It made her feel thankful, like she was getting another turn. She sat down on the edge of the bed and stroked her daughter's hair again.
"You have this smell," Hana said, "I used to think it was your perfume. Joy, _nee_?"
"I still wear that."
"I know," Hana said, and Etsuko resisted the urge to sniff her own wrists.
"It's not just the perfume, though, it's all the other creams and things that you wear, and it makes up this smell. I used to walk around department stores wondering what it was. The smell of _Ma-ma_."
Etsuko wanted to say so many things, but above all that she would try not to make any more mistakes. "Hanako—"
"I want to go to sleep now. Go to the party. Leave me alone." Hana's voice was flat but more tender this time.
Etsuko offered to stay, but Hana waved her away. Etsuko mentioned then that her schedule was open the next day. Maybe they could go and buy a bed and a dresser. She kept talking, wanting to be interrupted. "Then you can always come back and visit me. I can make up a room for you," Etsuko said. Hana sighed, but her expression was blank. Etsuko couldn't tell what her daughter wanted. "I'm not saying you have to go. Especially after—" Etsuko put her fingertips across her lips, then quickly removed them. "You can stay. Start school here even."
Hana shifted her head on her pillow and inhaled, still saying nothing.
"I can call your father. To ask."
Hana pulled the blanket up to her chin. "If you want." Then she closed her eyes to sleep.
In the living room Etsuko sat on the sofa. When she had been a young mother of three little children, there used to be one time in her day when she'd felt a kind of peace, and that was always after her children went to bed for the night. She longed now to see her sons as they were back then: their legs chubby and white, their mushroom haircuts misshapen because they could never sit still at the barber. She wished she could take back the times she had scolded her children just because she was tired. She would let them stay in their bath a little longer, read them one more story before going to bed or fix them another plate of shrimp.
The children invited to Solomon's party were the sons and daughters of diplomats, bankers and other wealthy expatriates. Everyone spoke English rather than Japanese. Moses had chosen this prestigious international school in Tokyo because he liked Americans. He had specific ambitions for his son: Solomon should speak perfect English as well as perfect Japanese; he should grow up with other young upper-class people; and, ultimately, he should work for an American company in Tokyo or preferably New York, a city Moses had never been to but imagined as a place where everyone was given a fair shot. He used to say half jokingly that his son would be an "international man of the world."
A line of black limousines snaked along the street. As the children left, they stopped Moses and Etsuko to thank them for the fine dinner they'd eaten. Neither Moses nor Etsuko spoke very good English, so they nodded and smiled. Moses lined up the children in front of the restaurant. He ordered, "Ladies first," a saying he had picked up from American movies. The girls trooped into the cars in sixes and sped away. Then the boys followed. Solomon rode in the last car with his best friends: Nigel, the son of an English banker, and Mohandas, the son of an Indian ambassador.
The disco was dimly lit and glamorous. From the high ceiling twenty or so mirrored balls hung at different heights, so the large room was flooded with tiny panes of light that flashed and swayed with the movement of the balls. They had the effect of making anyone who walked across the floor shimmer like a fish underwater. After everyone sat down, the manager, a handsome Filipino man, stood on the stage behind the microphone. He had a beautiful, round voice.
"Welcome to Ringo's." He paused for the children's cheers. "For Solomon's birthday fiesta, Ringo's presents the hottest star in Japan—one day the world: <NAME>!"
The children didn't seem to believe him. The curtain rose to reveal the seven-piece rock band; then the singer emerged from the back. Hiromi looked utterly normal, almost disappointingly so. He dressed like a businessman who'd forgotten his necktie. He wore thick-framed eyeglasses just like the ones on his album cover, and his hair was neatly combed. He couldn't have been more than thirty.
Solomon kept shaking his head, looking more bewildered than anything. The band was loud, and the kids danced wildly. When the long set was over, Ichiro, the cook, wheeled an ice-cream cake shaped like a baseball diamond toward Solomon. A girl shouted, "Don't forget to make a wish, baby!"
In one huff, Solomon blew out the sparklers that topped the cake. Etsuko handed him the knife so he could cut the first slice. A spotlight shone on him as he poised the long, serrated blade over the cake. She asked him, "Do you want help?"
He put both hands on the handle. "I think—I got it," he said.
That's when she noticed the ink under his nails. He'd washed off most of it, but a shadow of the stain remained on his fingertips. "Oh," she said.
Solomon looked up from what he was doing;
Etsuko remained silent, and she guided his arm lightly to return him to his task. After the first slice, Solomon handed the knife to her. Waiters passed out the cake, and Hiromi, who was sitting by himself, accepted a piece. Seeing this, Moses pulled from his jacket a fat blue envelope filled with yen notes and told Solomon to give it to Hiromisan. The singer motioned to Solomon to sit down. In this light, Etsuko thought, no one would notice the ink.
The party was almost over, and Etsuko felt pleasantly exhausted— the way she did after the restaurant closed every night. She found Moses sitting in a booth drinking champagne by himself, and she sat down beside him. Moses refilled his glass and handed it to her; she drank it in two unladylike gulps. He told her that she had done a good job, and Etsuko shook her head. "_Ie_."
"I think she would have been pleased," Etsuko said without thinking.
Moses looked puzzled. A moment later, he nodded. "Yes. She would have been so happy for him."
"What was she like?" She shifted her body to see his face. Little squares of light danced across his sharp features.
"I've told you before. She was a nice lady. Like you." He had never said any more than that about his wife.
"No. Tell me something specific about her." She wanted to know how they were different, not how they were the same. What would be the point of her being there with him if she was the same as someone else?
"Why? She's dead." He looked hurt after saying this, as if it was new to him. Moses watched Solomon, who'd gotten up from Hiromi' s table and was now dancing with a tall Chinese girl. Solomon's forehead glistened with sweat as he followed the girl's elegant moves. Etsuko stared into her empty champagne glass.
"She wanted to name him Sejong," Moses said, "but it's tradition for the husband's father to name the grandson." He paused. "Se -jong. He was a king too. He invented the Korean alphabet." Moses laughed. "Maybe that's why my father picked a king from the Bible. To make her happy."
"Why are you laughing?" she asked.
"Because she was so proud of him. Her son. She wanted to give him the name of a king. She was like my father. So proud of everything-of being Korean, of my business and of her family. It was nice, I guess. But why?" He sounded wistful and full of wonder, neither bitter nor sad. "What do we have to be so proud of?"
"It's good to be proud of your children." She smoothed down her skirt. When her children had been born, what she had felt all three times was amazement at their physical perfection. All three times, she marveled at their miniature human form and their good health. But not once did she consider a name taken from history-the name of a king.
"One of those girls came up to me today and said Solomon looked like his mother." He pointed to a cluster of girls in the comer of the room. They wore bandeau tops and jersey skirts clinging to their thin hips.
"How could she know that?" she asked.
"She meant you."
"Oh," she nodded. "I wish I was his mother."
"No. You don't." Moses said this calmly, and she felt like she deserved that.
"You must think I'm no better than that woman clerk this afternoon," she said.
Moses shook his head as if she'd hurt him and put his hand over hers.
What had she been so proud of anyway? Her father had sold life insurance to isolated housewives, and Moses created places where grown men and women could play pinball and win tickets for diapers and soap. Both men had made money from chance and fear and loneliness.
Etsuko took off her watch and put it in front of him. "I want a ring." Moses nodded, but he didn't look at her. He patted her hand and said they should talk about it later. She had expected from him a great show of happiness, even though she knew that wasn't his way. This time, she decided, she would wait. Etsuko rose from the table and went to hand out the party bags. It was already midnight, and the children had to get home.
Solomon claimed that he was hungry. The three of them returned to her restaurant. The place was clean again and looked open for business. Etsuko asked Solomon what he wanted to eat. "A little bit of everything," he said. He looked so happy, and it pleased her to see him like this. She could count on him to be a happy person. Maybe that was what Solomon was for her and Moses.
At the edge of the dining room, Moses sat down at a table and opened his evening-edition newspaper. He looked like a middle-aged man waiting calmly for his train so he could get home. Etsuko headed for the kitchen, with Solomon following her.
She put down three plates on the prep counter. From the refrigerator, she pulled out the tray of fried chicken and the bowl of potato saladdishes that Ichiro had made following an American cookbook.
"Why didn't Hana come?" Solomon asked. "Is she sick?"
"No." It was the second time that someone had asked her this, and she didn't like to lie to a direct question.
"She's pretty, you know." He checked to see her reaction.
"Too pretty. That's her problem." Her own mother had once said this about her when a family friend had complimented Etsuko. She tried to change the subject. "Did you have fun tonight?"
"Yeah. I still cant believe it. Hiromi-san talked to me."
"What did he say?" She put two pieces of chicken on Moses' and Solomon's plates and one on hers.
"Not much. He said his best friends are Korean. And he told me to be good to my parents." Solomon looked away from her after he said this. He was trying to tell her that he hadn't denied her as his mother, and though this should have been a nice thing, it only made her feel more anxious.
"Your father said your mother was proud of you. From the moment you were born."
Solomon said nothing.
She didn't think that he needed a mother anymore; he was already grown up, and he was doing better than most kids she knew who had mothers who were alive. But he was staring at her, and she could see that he still wanted a mother, even though he was almost a young man.
"Come to the sink. Hold out your hands."
"A present?" he joked, then he opened his palms to her.
She put his hands over the sink and turned on the faucet. "There's still ink here."
The boy asked her, "Can they make me leave?"
"Everything went okay today," she replied and continued to scrub the pads of his fingers.
"Is she pregnant? She told me she came to Tokyo to get rid of her little problem."
Solomon seemed to sense that she wouldn't say anything more.
"Nigel got his girlfriend pregnant, and she had to get an abortion."
"Your friend?" She thought of the blond-haired boy who played Atari with him. He was only a year older than Solomon.
"My children hate me," she said. She had never admitted this to anyone for fear of sounding self-pitying.
"I hated my mother too. For dying." Solomon picked at the ink beneath his fingernails. "Your kids hate you because you're gone." Solomon's face grew serious and less boyish. "They cant help it."
Etsuko bit the inside of her lower lip. She could feel the small muscles inside her mouth, and she stopped herself from drawing blood. She was afraid to look at his face, and though she had tried to restrain herself, she burst into tears.
"Why? Why are you crying?"
Solomon's eyes filled up, and Etsuko looked at the boy in front of her. He had grown so much in these past five years. She looked below his chin and saw how supple and graceful his neck was, his Adam's apple only slightly protruding.
She inhaled to calm her breathing. "When Hana was born, the nurses put her footprints on a card. They washed the ink off, but not very well, so when I went home I had to get it off. I don't think she could see anything really, because she was just born, but I felt like she was looking at me because I was hurting her, and she just cried and cried—"
"Etsuko-_chan_, Hana will be okay. Nigel's girlfriend is fine. They might get married after college."
"No, no. It's not that. I'm just so sorry. That you might have thought that I didn't want to be your mother." She clutched her stomach, and again she tried to regulate her breath. "I've hurt so many people. And you are such a good boy, Solomon. I wish I could take credit for you."
His dark, straight hair clung to the sides of his face, and he didn't brush it away. He smiled at her, but his eyes were strained with worry.
"But I was born today, wasn't I? That's what a birthday's supposed to mean—not parties, not famous singers or dancing with pretty girls. I was born today, and isn't it funny how no one gets to remember that moment and who was there? It's all what's told to you. You're here now. You are mother to me."
Etsuko covered her mouth with her open palm and let his words go through her. Somewhere after being sorry there had to be another day, and after a trial there could even be some good in the judgment. At last, Etsuko shut off the water and put down the swollen, yellow sponge in the sink. The curved brass spout let go its last few drops, and the kitchen grew silent. Etsuko reached over to hold her child on his birthday.
<file_sep>/content/news/2017-02-01-bookpage-cover-story-interview-by-adam-morgan.md
---
title: 'BookPage Cover Story: Interview by <NAME>'
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: BookPage February 2017
link_to_original: 'https://bookpage.com/interviews/20934-min-jin-lee#.WJKPJ85OjE4'
description:
---
February 2017
Exploring the hidden history of Korean immigrants in Japan
BookPage interview by <NAME>
Reading Pachinko is like binge-watching every season of an HBO series. Instead of capturing a single time and place, <NAME>’s heartbreaking historical novel spans the entire 20th century through four generations, three wars and two countries with a troubled past. A moving and powerful account of one of the world’s most persecuted immigrant communities—Koreans living in Japan—it may be remembered as one of the best books of the year.
But here’s a secret: Lee almost abandoned Pachinko after the first draft.
Twenty years ago, she quit her job as a corporate lawyer to become a writer. It didn’t go well. “I wrote a dreadful manuscript with a pretentious title that was never inflicted upon innocent readers,” Lee says. Her second attempt didn’t go much better, but her third attempt at fiction, Free Food for Millionaires, was published to universal acclaim in 2007.
And yet, Lee couldn’t stop thinking about her abandoned second novel, the one that would eventually become Pachinko. While Free Food for Millionaires focused on Korean Americans in New York, she still wanted to write about the Korean diaspora in Japan. “The fascinating history of the Korean Japanese,” Lee says, “is one of the clearest manifestations of legal, social and cultural exclusion in a modern, well-educated and developed democratic nation.”
The first draft of Pachinko was set in Tokyo during the 1980s. But when Lee returned to the manuscript, she realized that she had to go back much further.
In 1910, Japan annexed Korea. With the stroke of a pen, every citizen of Korea became a subject of Imperial Japan, and would remain so until Japan’s defeat at the end of World War II. During those 35 years, thousands of Koreans immigrated across the sea to Japan, many of them farmers unable to prove they owned their land.
It is these Korean-Japanese immigrants and their descendants—the Zainichi—that Lee wanted to explore in the resurrected novel that became Pachinko.
The word Zainichi is Japanese for “staying in Japan temporarily,” which is misleading, since most Korean Japanese are permanent residents and naturalized Japanese citizens. Sadly, Zainichi have suffered decades of oppression in Japan. During World War II, Korean men were forced to fight for Japan while Korean women were kidnapped as sex slaves for Japanese soldiers. After the war and throughout the 20th century, Koreans were disenfranchised, excluded from Japanese society and denied equal rights. In fact, Japan didn’t stop fingerprinting Koreans during alien registration procedures until 1993.
“The Zainichi are by definition considered foreign, transient and ‘other’ by many Japanese people,” Lee says. “Moreover, some Korean Japanese, especially children who are traumatically bullied, are seen as other to themselves. I was profoundly disturbed by this idea of being seen as permanently ‘other’ at key stages of one’s psychological development.”
In 2007, just after the release of Free Food for Millionaires, Lee and her husband moved from New York to Tokyo.
“The move to Japan was a lucky coincidence for the book, but when I had to let go of the initial draft and start again—buddy, I was not a happy camper,” Lee says. “The field research forced me to throw out the initial manuscript and write a historical novel based primarily on one family.”
The result is Pachinko, a poignant, sprawling, multigenerational epic in the same vein as Yaa Gyasi’s Homegoing, full of births, deaths, marriages and betrayals. Written in light, fluid prose, it begins in the 1880s on the coast of Korea, where a boy with a cleft palate is born into a small fishing village. Shortly after Japan colonizes his homeland, he marries the daughter of a farmer with the help of a matchmaker. Their own daughter, Sunja, almost brings the family to ruin as a young adult, but a Protestant minister whisks her away to Japan in 1933, where she becomes the matriarch of an extended family.
In Osaka, Sunja and her children are subject to bigotry because of their Korean heritage. Through World War II and the fall of the Empire of Japan, Sunja raises two boys with the help of her sister-in-law. The firstborn studies European literature in college until he learns a shocking family secret. Heartbroken, he moves to Nagano and pretends to be Japanese, eventually joining his brother in the pachinko business, though not in the same parlor, or even the same city. Eventually, Sunja becomes the grandmother of a Tokyo banker who carries the story into the 1980s, a full century after the story began.
The novel was initially called Motherland, but Lee changed the title when she came to a realization: “Nearly every Korean-Japanese person I interviewed or researched was somehow related (either intimately or distantly) to the pachinko business, one of the very few businesses Koreans were allowed to work in or have an ownership interest.”
If you’ve ever watched “The Price Is Right,” you’re already familiar with pachinko. It’s essentially a vertical pinball machine, though it was stylized as “plinko” for the game show.
“The pachinko business—a multibillion-dollar industry with double the export revenues of the Japanese automobile industry—is often viewed with great suspicion and contempt by middle-class Japanese,” Lee says. “However, one out of every 11 Japanese adults plays pachinko regularly, and there is at least one pachinko parlor in every train station and shopping street in Japan. Pachinko is a game of chance and manipulation, and I was interested in this gambling business as a metaphor.”
Like a pachinko ball, Sunja careens through the 20th century as a daughter, a wife, a mother and finally a grandmother. “It took so much of my life to write this novel, and even though the work and the waiting was its own trial, I have to acknowledge that it was helpful to age along with the book because I had the opportunity to encounter and learn as many different perspectives as possible,” Lee says.
And while Pachinko takes place on the other side of the globe, it should be required reading for Americans in 2017.
“The recent presidential election has demonstrated a deeply divided nation, but what is even more troubling to me is how all the different groups cannot seem to comprehend the views of the others,” Lee says. “In an increasingly polarized world with great economic, educational and socio-cultural disparities, I want to believe that we can turn to narratives to empathize with all the parties who participate in both inclusion and exclusion.”
If you want a book that challenges and expands your perspective, turn to Pachinko. And don’t be intimidated by the page count or the grand scale of the story—in Lee’s deft hands, the pages pass as effortlessly as time.<file_sep>/content/review/psychiatric-services--a-journal-of-the-american-psychiatric-association.md
---
title: Psychiatric Services, A Journal of the American Psychiatric Association
attribution: Psychiatric Services, A Journal of the American Psychiatric Association
date: 2007-03-11 18:15:14 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
In her first novel, *Free Food for Millionaires*, <NAME> largely succeeds in unraveling the story of postcollege, Korean immigrant <NAME>, who is still challenged by her family traditions while striving for acceptance and personal fulfillment in the largely assimilated world of New York high finance. As the main character’s life unfolds, Lee masterfully reveals the fallible interpersonal relationships that define Han’s struggle. She also manages to tell the story from multiple perspectives, allowing the characters richness and authenticity that is often missing in the single point of view.<file_sep>/content/news/2017-02-07-newsday-review.md
---
title: 'Newsday: Review'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Newsday by <NAME>
link_to_original: 'http://www.newsday.com/entertainment/books/books-by-sheelah-kolhatkar-claude-mckay-and-min-jin-lee-1.13070653'
description:
---
PACHINKO, by <NAME>. This historical novel, by the author of “Free Food for Millionaires,” follows several generations of a Korean family in Japan during the 20th century, where they face poverty and intense discrimination but make a fortune running pachinko parlors, a pinball-like game. Lee has worked her own Asian variation on the immigrant saga. (Grand Central, $27)<file_sep>/content/event/pen-america-read-the-resistance-fb-live.md
---
title: 'PEN America: Read the Resistance FB Live'
date: 2018-03-27 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<NAME> will discuss the resistance book pick, SISTER OUTSIDER by <NAME> with readers on Facebook Live at 12pm EST. Event curated by <NAME> of PEN America.<file_sep>/content/event/institute-library.md
---
title: The Institute Library
date: 2017-03-08 19:00:00
show_time: true
venue:
name: Institute Library
address: 847 Chapel Street
city: New Haven
state: CT
zip: '06510'
link: 'http://institutelibrary.org'
---
In conversation with Cyd and <NAME>. Cyd is the host of Book Talk WNNH. Cyd has been an English teacher, education advocate, criminal defense attorney, and policy analyst. Mark is an award winning writer and scholar. He is a contributing opinion writer for *The Los Angeles Times* and has a weekly podcast *Unorthodox*, produced by Tablet magazine. He is the author of *Knocking on Heaven's Door* and *Thirteen and a Day*. His writings have appeared in *The Times Magazine, Harper's, The Atlantic, The Nation, The Believer, The Christian Century*and* Playboy*. Cyd and Mark have four daughters, two dogs and a cat.<file_sep>/content/event/lrei.md
---
title: Little Red Elizabeth Irwin Literary Evening
date: 2017-12-07 18:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/min-jin-lee-is-named-as-a-frederick-douglass-200.md
---
title: <NAME> 200 Announced
date: 2018-07-12 00:05:22 -0400
images: []
image_credit: ''
categories: ["Award"]
where_published: 'Guardian '
link_to_original: https://www.theguardian.com/commentisfree/ng-interactive/2018/jul/05/the-frederick-douglass-200
description: '"The <NAME> 200 is a project to honor the impact of 200
living individuals who best embody the work and spirit of Douglass across those
areas where he had such an impact - abolitionist, politician, writer, feminist,
educator, entrepreneur and diplomat."'
---
<file_sep>/content/news/2007-11-28-everydayiwritethebook.md
---
title: "EverydayIwritethebook"
date: 2007-11-28T22:05:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Everydayiwritethebook"
link_to_original: "http://everydayiwritethebook.typepad.com/books/2007/11/interview-with.html"
description: ""
_slug: 2007-11-28-everydayiwritethebook
---
I was fortunate enough to meet <NAME>, author of Free Food for Millionaires, at a reading here in DC a few months ago. She had read my first blog post about her book, and graciously signed my copy. A few months later, when I posted ...
<file_sep>/content/news/2017-12-20-bbc-the-10-best-books-of-2017.md
---
title: 'BBC: The 10 Best Books of 2017'
date: 2017-12-20 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: BBC
link_to_original: 'http://www.bbc.com/culture/story/20171213-the-10-best-books-of-2017'
description:
---
By <NAME>
Pachinko, a finalist for the National Book Award, follows four generations of a Korean family from 1910, when Japan annexed Korea, through most of the 20th Century. It begins with an aging fisherman and his wife, who run a boarding house in a village near the port city of Busan. Their son, who has a cleft palate and twisted foot, is married at last. When his teenage daughter Sunja becomes pregnant by a visiting businessman, a kind pastor marries her and takes her to Osaka. After he dies, Sunja’s grit keeps the family afloat during the tough war years. One son makes it into Waseda University. The youngest runs pachinko parlours, where gamblers play machines in a game similar to pinball. But their future is shadowed by past secrets and betrayals.
For the complete list, please click the link. Thank you.<file_sep>/content/event/monmouth-college.md
---
title: 'London, UK: European Bank for Reconstruction and Development'
date: 2017-10-19 13:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/npr-1a-live-great-gatsby.md
---
show_time: true
title: NPR 1A Live - Great Gatsby
date: 2021-01-19T11:00:00-05:00
description: ''
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://the1a.org/about/
images: []
---
<file_sep>/content/news/talks-at-google-musings-writings-asian-american-voices.md
---
title: 'Talks at Google: "Musings & Writings: Asian-American Voices" (video)'
date: 2020-06-19T00:50:11-04:00
link_to_original: https://www.youtube.com/watch?v=xKIA5w2Iflo
images: []
tags: []
categories: []
description: ''
---
"Bestselling author <NAME> provides a masterclass on writing. In addition, she speaks about representation in media, fiction, non-fiction and her views on the evolving Asian-American identity."
Moderated by <NAME>. <file_sep>/content/news/2017-03-24-the-times-literary-supplement-book-review.md
---
title: 'The Times Literary Supplement: Book Review'
date: 2017-03-24 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Times Literary Supplement
link_to_original: 'http://www.the-tls.co.uk/articles/private/shadow-of-the-stain/'
description:
---
Min Jin Lee’s Moving Saga of a Korean Family in Japan
By <NAME>
In one of many moving, subtly observed scenes in Min Jin Lee’s sprawling family saga—the story of four generations over eighty years—a fourteen-year-old boy celebrates his birthday at a fancy restaurant in Yokohama, Japan, in the late 1970s. A guest comments on how lucky he is: “American private schools, millions in the bank, and a chauffeur.” The attendees are the “sons and daughters of diplomats, bankers, and wealthy expatriates from America and Europe” and the country’s most famous pop star makes a surprise appearance. Yet as the birthday boy cuts his cake—“a spectacular ice cream cake shaped like a baseball diamond”—his stepmother is upset to notice ink under his fingernails.
The boy, <NAME>, is not American, or European, or straightforwardly Japanese, but a Zainichi, a Korean resident of Japan. Historically, Zainichis have been consigned to second-class status; some, like Solomon’s uncle Noa, attempted to conceal their Korean ancestry and were forced to live in fear of discovery. While the situation has much improved, even today the question of whether to blend in quietly, or to fight actively against discrimination, still divides families.
The Japanese word “Zainichi” is itself controversial because it literally means “existing in Japan”. For one, this obscures the colonial exploitation of Korea; some Zainichis are descendants of Koreans brought to Japan as forced labourers. The term also implies temporary residence, even though it is used for those, like Solomon, who are born in Japan. And indeed Solomon is forced to register for his alien registration card on his fourteenth birthday. If denied, he stands to be deported to a country he’s never lived in. Every three years, he must request permission to stay in Japan. This birthday scene comes after Solomon has been fingerprinted like a criminal; he has attempted to wash the ink off, but a “shadow of the stain remained on his fingertips”.
In the eyes of many of Pachinko’s Japanese characters, Koreans—even “good Koreans”—are a stained race. Solomon’s grandmother Sunja muses, “The Japanese said that Koreans had too much anger and heat in their blood. Seeds, blood. How could you fight such hopeless ideas?” Solomon’s birthday shows both how much and how little has changed in the family since Sunja’s meagre childhood in a village at the southern tip of Korea. The novels begins with her peasant parents’ marriage shortly after 1910, when Korea was annexed by Japan—a time when Koreans were forced to take Japanese names and consider themselves subjects of the emperor. Sunja’s entanglement with two men—Hansu, the married man who seduces her, and Isak, the gentle Christian pastor she marries—sets in motion generations of struggle. No matter how much her family succeeds, they will always be too Korean for Japan, and too Japanese for Korea, which always proves impossible to return to: first as a ravaged colony, then an impoverished nation, then a divided one.
Lee employs a straightforward prose and linear structure, relying for effect on the drama of her immigrant narrative; she sweeps us along, skipping nimbly over years and into the heads of her characters. Whether they are noble and long-suffering, like Sunja, or morally compromised, like Hansu, Lee provides richly textured, sympathetic portraits. She also illuminates the difficulties faced by various Japanese characters, such as a secretly gay policeman with a disabled brother, and a teenage prostitute with AIDS, suggesting (perhaps idealistically) that these individuals, marginalized by their own society, are the most sympathetic to the Korean community.
The heart of the novel lies with Sunja, who moves with Isak to a Korean ghetto in Osaka in the 1930s, a dangerous time. In the ensuing decades she survives the imprisonment of her husband, wartime deprivation and discrimination against her two sons, Noa and Mozasu, who as both Korean and Christian are doubly disenfranchised. Hansu, now a powerful member of the yakuza—the Japanese criminal underworld—intrudes periodically into their lives as both a saviour and threat. Sunja keeps from Noa the real identity of his father, fearing, with reason, that the secret will destroy him. Mozasu prospers, however. Barred, like most Zainichis, from jobs in government or with respectable companies, he makes a career out of a popular if seedy phenomenon which explodes in the post-war period: pachinko, which gives the novel its central metaphor as well as its title.
Pachinko, often described as vertical pinball, is a way of getting around the gambling ban that still exists in Japan (legislation passed in December 2016 may now lift this). Players at pachinko parlors sit transfixed at colourful machines, firing away with tiny metal balls, apparently oblivious to the incessant clamour. (The clinking of these metal balls—“pachin pachin”—gives the game its name.) If they get lucky (and this is largely a game of luck), they collect more balls, which they can trade for cash. For Mozasu, who becomes a millionaire setting up such parlours, “life was like this game where the player could adjust the dials yet also expect the uncertainty of factors he couldn’t control.” One such factor is that he, like other owners, tinkers with them every day to set the outcomes. As in life, Mozasu’s Japanese girlfriend muses, “there could only be a few winners and a lot of losers. And yet we played on, because we had hope that we might be the lucky ones.”
The Korean characters in this novel are especially conscious of the rigged system they are set up against. Sunja’s attempts to ensure a better life for Noa backfire because he internalizes the stigma of his birth; Mozasu’s marriage prospects are marred by his “dirty” business. Even “lucky” Solomon, his son, whom he sends to college in New York, later encounters job discrimination in 1980s Japan. Yet these depredations bring the community together. <NAME> has produced a beautifully realized saga of an immigrant family in a largely hostile land, trying to establish its own way of belonging.
Please consider a digital subscription to The Times Literary Supplement.<file_sep>/content/news/2017-02-08-elle-com-clay-walls.md
---
title: Elle.com CLAY WALLS
date: 2017-02-08 12:00:00
categories: ["News"]
tags:
- Essays
- Interviews
attribution: Elle.com by <NAME>
link_to_original: 'http://www.elle.com/culture/books/g29448/books-by-immigrant-authors/'
description:
---
I recommend CLAY WALLS by <NAME> wholeheartedly as a seminal work by an important immigrant author.<file_sep>/content/news/dayton-literary-peace-prize-finalist.md
---
title: Pachinko is named as a Dayton Literary Peace Prize Finalist
date: 2018-08-14 22:31:51 -0400
link_to_original: http://daytonliterarypeaceprize.org/2018-finalists-press_release.htm
images: []
tags: []
categories: []
description: RECOGNIZING THE POWER OF LITERATURE TO PROMOTE PEACE AND RECONCILIATION,
DAYTON LITERARY PEACE PRIZE ANNOUNCES 2018 FINALISTS IN FICTION & NONFICTION Shortlist
includes Sing, ,Unburied, Sing by <NAME>, Pachinko by <NAME>, We Were
Eight Years in Power by Ta-Nehisi Coates; Winners to be honored at gala ceremony
on October 28th Dayton, OH (August 14, 2018) – Recognizing the power of literature
to promote peace and reconciliation, the Dayton Literary Peace Prize Foundation
today announced the finalists for the 2018 Dayton Literary Peace Prize in fiction
and nonfiction. Inspired by the 1995 Dayton Peace Accords that ended the war in
Bosnia, The Dayton Literary Peace Prize is the only international literary peace
prize awarded in the United States. The Prize celebrates the power of literature
to promote peace, justice, and global understanding. This year's winners will be
honored at a gala ceremony in Dayton on October 28th.
---
<file_sep>/content/writing/new-york-review-of-books-the-imperfect-and-sublime-gatsby.md
---
title: 'New York Review of Books: The Imperfect and Sublime ‘Gatsby’'
date: 2021-01-21T02:00:13-05:00
categories:
tags: []
where_published: The New York Review of Books
link_to_original: https://www.nybooks.com/daily/2021/01/21/the-imperfect-and-sublime-gatsby/
link_to_pdf:
description:
_slug: '2019-06-03T06:00:00.000+00:00'
images: []
---
"Amid a life of disappointments, Fitzgerald’s novel was a crowning achievement. I turn to it because it gives me the sober wisdom to revise my own American dream."<file_sep>/content/writing/2012-04-07-times_of_london_book_review_cynthia_ozicks_foreign_bodies.md
---
title: "Times of London Book Review: Cynthia Ozick’s FOREIGN BODIES"
date: 2012-04-07T10:44:47-05:00
categories:
tags: ["Essays"]
where_published: "Times of London"
link_to_original: "http://thetim.es/rfsJXt"
link_to_pdf:
description:
_slug: 2012-04-07-times_of_london_book_review_cynthia_ozicks_foreign_bodies
---
<file_sep>/content/event/colony_club.md
---
title: Colony Club
date: 2008-01-24T14:58:00-05:00
venue:
name: Colony Club, New York
link:
_slug: colony_club
---
New Novelists Forum
Curated by <NAME> and moderated by <NAME>
<NAME>, Author of BEGINNER’S GREEK and <NAME>, Author of FREE FOOD FOR MILLIONAIRES
PRIVATE EVENT
<file_sep>/content/event/2018-miami-writers-institute.md
---
title: Columbia University APAHM Keynote
date: 2019-03-28 20:30:00 -0400
show_time: true
venue:
name: Roone Arledge Auditorium
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
---
<file_sep>/content/event/brooklyn-book-festival-2018--national-book-foundation-panel-.md
---
title: 'Brooklyn Book Festival 2018: National Book Foundation Panel '
date: 2018-09-16 11:00:29 -0400
images: []
image_credit: ''
tags:
- National Book Foundation Panel
where_published: ''
link_to_original: http://www.brooklynbookfestival.org
description: "2017 National Book Awards Showcase presented by the NBF.\nCome hear
from a stellar lineup of 2017 National Book Awards authors discussing their work,
craft, and why literature matters. The panel includes Nonfiction Winner <NAME>
(The Future Is History: How Totalitarianism Reclaimed Russia), Fiction Finalist
<NAME> (Pachinko), Poetry Finalist <NAME> (In The Language of My Captor),
and Young People’s Literature Finalist <NAME> (I Am Not Your Perfect Mexican
Daughter). Presented by the National Book Foundation. Moderated by poet and Executive
Director of AAWW <NAME>. "
categories: []
---
<file_sep>/content/news/2010-05-01-chosun_ilbo.md
---
title: "Chosun Ilbo"
date: 2010-05-01T09:52:00-05:00
categories: ["News"]
tags:
- Essays
attribution: "<NAME>"
link_to_original: ""
description: ""
_slug: 2010-05-01-chosun_ilbo
---
조선일보 아침논단
by <NAME>
[2010. 04. 14] [번역된 한국 문학 그 놀라운 힘](http://news.chosun.com/site/data/html_dir/2010/04/14/2010041402191.html)
[2010. 03. 04] [한국 브랜드엔 충성할 미국인 있나](http://news.chosun.com/site/data/html_dir/2010/03/04/2010030402051.html)
[2010. 01. 25] [‘좀 더 잘 실패해보는’ 새해를](http://news.chosun.com/site/data/html_dir/2010/01/25/2010012501613.html)
[2009. 12. 14] [승리하는 팀](http://news.chosun.com/site/data/html_dir/2009/12/13/2009121300696.html)
[2009. 11. 19] [왜 한국인은 자살률이 높은가](http://news.chosun.com/site/data/html_dir/2009/11/18/2009111801889.html)
[2009. 10. 20] “[사는 게 행복한가요?](http://news.chosun.com/site/data/html_dir/2009/10/19/2009101901827.html)”
[2009. 09. 16] [진짜 교육](http://news.chosun.com/site/data/html_dir/2009/09/16/2009091601945.html)
[2009. 08. 12] [파리의 마레 지구에서 생긴 일](http://news.chosun.com/site/data/html_dir/2009/08/12/2009081201598.html)
[2009. 07. 13] [아무도 말하지 않는 진짜 이유](http://news.chosun.com/site/data/html_dir/2009/07/13/2009071302341.html)
[2009. 06. 11] [126년 묵은 사랑의 빚 88달러](http://news.chosun.com/site/data/html_dir/2009/06/11/2009061101717.html)
[2009. 05. 13] [어버이날, 나는 어떤 부모인가 생각한다](http://news.chosun.com/site/data/html_dir/2009/05/07/2009050701758.html)
[2009. 04. 06] [100번이나 불합격 통지를 받은 당신에게](http://news.chosun.com/site/data/html_dir/2009/04/06/2009040601714.html)
[2009. 03. 22] [질투와 자부심](http://news.chosun.com/site/data/html_dir/2009/03/22/2009032200888.html)
[2009. 02. 10] [차라리 대한민국을 성형하라](http://news.chosun.com/site/data/html_dir/2009/02/09/2009020901779.html)
[2008. 11. 19] “[왜 변호사를 그만두셨어요?](http://news.chosun.com/site/data/html_dir/2008/11/19/2008111901770.html)”
<file_sep>/content/event/sharon.md
---
title: <NAME>mer Book Signing
date: 2017-08-04 18:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link: 'http://www.hotchkisslibrary.org/annual-book-signing/'
---
<file_sep>/content/event/papercuts-jp.md
---
title: 'Papercuts JP: Independent Bookstore Day (Parts 1 & 2)'
date: 2017-04-29 19:00:00
show_time: true
venue:
name: Papercuts JP
address: 5 Green Street
city: Boston
state: MA
zip:
link: www.papercutsjp.com
---
Part 1:
<NAME> will be a bookseller for a day at Papercuts JP to celebrate Independent Bookstore Day 2017. Drink, snag swag and hang out with Kate, Katie and Min (who may go by the name Kat that day so she can feel right at home). (From 10am-6pm)
Part 2:
In the evening, there will be a Papercuts JP Conversation & Book signing for PACHINKO.
<NAME> in conversation with very cool undergraduates, <NAME> and <NAME>.
7pm
La Rana Rossa
154 Green Street
Jamaica Plains (across from Green Street Station on the Orange Line)
<NAME> is a senior at Harvard studying Social Studies and English. He was born in Seoul, South Korea and moved to Sydney, Australia at the age of ten. He is currently editing a student anthology of Korean diasporic writing and art. Following graduation, he will study public policy in Beijing as a Schwarzman Scholar.
<br>
<br><NAME> is a senior at Harvard studying History. A Brooklyn girl at heart, she was admittedly born in Staten Island. Following graduation, Nancy will study Jewish and Middle Eastern history at Oxford as a Rhodes Scholar.<file_sep>/content/news/2010-09-15-free-food-for-millionaires-trailer.md
---
title: '*Free Food for Millionaires* Trailer'
date: 2010-09-15 12:00:00
categories: ["Media"]
tags:
- Video
attribution:
link_to_original:
description:
_slug: 2011-06-20-free_food_for_millionaires_is_junot_diazs_summer_reading_pick_at_the_new_yo
---
<iframe src="https://player.vimeo.com/video/15013406" width="640" height="424" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe><file_sep>/content/news/2017-02-01-exclusive-excerpt-on-literary-hub.md
---
title: Exclusive Excerpt on Literary Hub
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- News
attribution: Literary Hub
link_to_original: 'http://lithub.com/pachinko/'
description:
---
June 1932
At the very beginning of summer, less than six months before the young pastor arrived at the boardinghouse and fell ill, Sunja met the new fish broker, <NAME>.
There was a cool edge to the marine air on the morning Sunja went to the market to shop for the boardinghouse. Ever since she was an infant strapped to her mother’s back, she had gone to the open-air market in Nampo-dong; then later, as a little girl, she’d held her father’s hand as he shuffled there, taking almost an hour each way because of his crooked foot. The errand was more enjoyable with him than with her mother, because everyone in the village greeted her father along the way so warmly. Hoonie’s misshapen mouth and awkward steps seemingly vanished in the presence of the neighbors’ kind inquiries about the family, the boardinghouse, and the lodgers. Hoonie never said much, but it was obvious to his daughter, even then, that many sought his quiet approval—the thoughtful gaze from his honest eyes.
After Hoonie died, Sunja was put in charge of shopping for the boardinghouse. Her shopping route didn’t vary from what she had been taught by her mother and father: first, the fresh produce, next, the soup bones from the butcher, then a few items from the market ajummas squatting beside spice-filled basins, deep rows of glittering cutlass fish, or plump sea bream caught hours earlier—their wares arrayed attractively on turquoise and red waxed cloths spread on the ground. The vast market for seafood—one of the largest of its kind in Korea—stretched across the rocky beach carpeted with pebbles and broken bits of stone, and the ajummas hawked as loudly as they could, each from her square patch of tarp.
For the remainder of the excerpt, please click the link below.<file_sep>/content/event/philadelphia-free-library.md
---
title: Philadelphia Free Library
date: 2018-03-22 19:15:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<NAME> and <NAME><file_sep>/content/event/awp-2018.md
---
title: 'AWP 2018: PEN Center USA—Historical Fiction Panel'
date: 2018-03-08 12:00:00
show_time: true
venue:
name: 'Room 14, 1st floor of Tampa Convention'
address:
city:
state:
zip:
link:
---
<file_sep>/content/review/new-york-times-on-free-food-for-millionaires.md
---
title: "New York Times on Free Food for Millionaires"
attribution: "*New York Times*"
date: 2007-03-11T10:53:14-04:00
book: book/free-food-for-millionaires.md
description: ""
featured:
---
This accomplished first novel, the coming-of-age story of a Princeton-educated Korean-American woman making her way in New York City in the 1990s, recalls the Victorian novels its heroine devours. Our reviewer, <NAME>, described it as ‘packed with tales of flouted parental expectations, fluctuating female friendships and rivalries, … romantic hopes and losses, and high-stakes career gambles.
<file_sep>/content/event/happy_endings_may_16th.md
---
title: In the Flesh Reading Series, May 16th
date: 2007-05-16T21:00:00-05:00
venue:
name: In the Flesh Reading Series with <NAME>
link: www.inthefleshreadingseries.blogspot.com/
_slug: happy_endings_may_16th
---
In the Flesh Reading Series with <NAME> @[Happy Endings Lounge](http://www.happyendinglounge.com "Happy Endings Lounge")
302 Broome St. NYC
(B/D to Grand, J/M/Z to Bowery, F to Delancey)
<file_sep>/content/news/2017-02-05-nbcs-bill-goldstein-pachinko-is-magnificent.md
---
title: "NBC's <NAME>: Pachinko is \"Magnificent\""
date: 2017-02-05 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: "NBC New York: <NAME>"
link_to_original: 'http://www.nbcnewyork.com/on-air/as-seen-on/Bill_s-Books-for-Sunday_-Feb_-5_New-York-412693443.html'
description:
---
Literary Critic <NAME> selects PACHINKO for Bill's Books on NBC New York's Weekend Today in New York<file_sep>/content/news/2007-07-01-the_new_york_times.md
---
title: "The New York Times"
date: 2007-07-01T22:43:17-05:00
categories: ["News"]
tags:
- Reviews
attribution: "The New York Times Sunday Book Review"
link_to_original: "http://www.nytimes.com/2007/07/01/books/review/Schillinger-t.html?sq="
description: ""
_slug: 2007-07-01-the_new_york_times
---
In her accomplished and engrossing first novel, the Yale-and-Georgetown-law-educated writer <NAME> tells the story of an angry young ...
<file_sep>/content/news/pbs-newshour--interview-for--now-read-this-.md
---
title: 'PBS NewsHour: Interview for "Now Read This"'
date: 2018-07-06 00:48:38 -0400
images: []
image_credit: ''
categories: []
where_published: PBS NewsHour
link_to_original: https://www.pbs.org/newshour/arts/choose-the-important-over-the-urgent-and-more-writing-advice-from-min-jin-lee
description: ''
---
<file_sep>/content/news/2017-02-20-wnyc-the-leonard-lopate-show-audio.md
---
title: 'WNYC: The Leonard Lopate Show (AUDIO)'
date: 2017-02-20 12:00:00
categories: ["Media"]
tags:
- Reviews
- News
- Audio
- Interviews
attribution: 'WNYC: The Leonard Lopate Show'
link_to_original: 'http://www.wnyc.org/story/one-korean-family-four-generations-later'
description:
---
Published by
The Leonard Lopate Show
One Korean Family, Four Generations Later
Feb 20, 2017
<NAME> joins us to discuss her new novel Pachinko, which traces four generations of a Korean family. Lee recounts the origins of the Korean diaspora, beginning with Japan’s annexation of Korea in 1910. The story begins in the village in Busan with a fisherman and his wife and the birth of their son, and follows their descendants who live as ethnic Koreans in Japan.
Min Jin Lee will be in conversation with <NAME>, with a book signing to follow, at Barnes & Noble at 765 Route 17 South in Paramus, NJ on Saturday, March 4th at 2:00pm. For more information, click here.
Min Jin Lee will be in conversation with <NAME>, with a book signing to follow, on Wednesday, March 15th at the Lower East Side Tenement Museum at 103 Orchard St. at 6:30pm. For more information, click here.<file_sep>/content/news/2017-06-24-irish-independent-profile.md
---
title: Irish Independent (Profile)
date: 2017-06-24 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Essays
attribution:
link_to_original:
description:
---
I had the pleasure of meeting <NAME> of the Irish Independent. A profile of my work appears in the Review (Irish Independent) on June 24, 2017. Thank you. Link: http://bit.ly/2so7qQy<file_sep>/content/event/waseda_university.md
---
title: WASEDA UNIVERSITY
date: 2010-05-20T00:06:00-05:00
venue:
name: WASEDA UNIVERSITY, Tokyo, JAPAN
link:
_slug: waseda_university
---
MAY 19, 2010, WEDNESDAY
Lecture, <NAME>, author of FREE FOOD FOR MILLIONAIRES and columnist of THE CHOSUN ILBO
Hosted by Professor <NAME>
2.45pm
<file_sep>/content/news/2008-03-28-columbia_university_conference_fear_of_flying_can_a_feminist_classic_be_an.md
---
title: "Columbia University Conference “Fear of Flying” Can a Feminist Classic Be an American Classic?"
date: 2008-03-28T22:42:01-05:00
categories: ["Media"]
tags:
- Video
attribution: "Columbia University"
link_to_original: "http://www.columbia.edu/cu/irwag/events/main/jong/"
description: ""
_slug: 2008-03-28-columbia_university_conference_fear_of_flying_can_a_feminist_classic_be_an
---
<object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/0e8ot2c922g&hl=en"><param name="wmode" value="transparent"><embed src="http://www.youtube.com/v/0e8ot2c922g&hl=en" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></object>
<file_sep>/content/news/2017-04-13-asian-review-of-books-book-review.md
---
title: Asian Review of Books (Book Review)
date: 2017-04-13 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Asian Review of Books
link_to_original: 'http://asianreviewofbooks.com/content/pachinko-by-min-jin-lee/'
description:
---
By <NAME>
The burdens of immigrant life in Japan provide the meat of <NAME>’s new novel Pachinko. Spanning five generations, Pachinko is the arresting tale of a Korean family which emigrated to Japan and is a welcome and timely publication dealing with the fraughtness of colonial and immigrant experiences. Although such scope might make one think of a sprawling, Tolstoyean narrative, Lee maintains a taut, narrow focus, unraveling the uniqueness of her characters while providing a deeply satisfying attention to detail.
Pachinko begins in 1910, the year Japan annexed the peninsula. Korea had been at the center of Japan’s quest to challenge Western hegemony in East Asia. Throughout, Lee elides much discussion of historical contexts, which reflects in many ways her characters’ own predicaments, poor, often illiterate and at the whim of social forces over which they have little control.
The first chapter is an evocative vignette that compresses the span from 1910 to 1932 and it instantly draws the reader in. We first meet Hoonie, the only surviving son of a fisherman and his wife, who run a lodging house in Yeongdo, an island village a ferry ride from the port town of Busan:
Hoonie was born with a cleft palate and a twisted foot; he was, however, endowed with hefty shoulders, a squat build, and a golden complexion…. Like his parents, Hoonie was not a nimble talker and some made the mistake of thinking that because he could not speak quickly there was something wrong with his mind, but that was not true.
When Hoonie dies of tuberculosis, his wife, Yangjin and their daughter, Sunja, take over the lodging house. It is renowned as a sparse but comfortable place, equipped with a fine kitchen. Author Lee is a food and travel writer and her attention to those kinds of details pervade the prose, providing a sense of comfort and familiarity. There are rich descriptions of simple meals or visits to the market early on, and her style is constantly grounding the reader in setting:
stacks of rice and soup bowls rested on the well-built shelves and braids of white garlic and red chilies hung from the low kitchen rafters. In the corner near the washbasin there was an enormous woven basket heaped with freshly dug potatoes. The comforting aroma of barley and millet steaming in the black rice pot wafted through the small house.
When the teenage Sunja meets Koh Hansu, a successful fish dealer from Jeju at the fish market, who defends her from the violence of Japanese school boys, the two begin a courtship that leads to an affair. One of the few shortcomings of the novel is Koh’s character. He often seems a bit too knowledgable, and is often used to move the story along to deeper, darker places. Sunja discovers Koh is married to a Japanese woman in Osaka and has three daughters, but only after she becomes pregnant. Refusing to speak about it or reveal the father, Sunja is destined to be scorned and her child left nameless for lack of father.
This devastation is the springboard for Lee to propel her characters and the reader to new and unfamiliar places: Christianity and then Japan. <NAME>, a young, tubercular missionary from Pyongyang staying at the lodging house, is grateful for the care mother and daughter give him and he takes pity on Sunja’s predicament. Isak believes this is a test of God’s and marries Sunja in order to save her from disgrace. The price she must pay is leaving Korea for Osaka where Isak is to be the assistant pastor at a Korean church. She trades her hard but simple life for the often miserable life of an immigrant in a country that sees Koreans as at best second-class human beings and certainly not citizens.
Koreans who emigrated during the colonial period, or who were born in Japan during that time, were denied any hope of citizenship. Referred to in Japan as “Zainichi”, which means foreign visitor “staying in Japan”, these Koreans are in limbo, particularly because Korea became two countries after the war. Yet they divided themselves into the Chongryon and Mindan, reflecting the situation on the peninsula, despite few having formal citizenship from either country. Lee’s characters speak elliptically of the troubling situation in the North and simply scoff at the thought of returning to the South, which for most of the novel is one of the poorest countries on earth.
Sunja and her generation, which includes Isak’s brother Yoseb and his wife Kyunghee, remembers Korea, and they hold out hope of perhaps one day returning. In the meantime, she is prepared to do anything, bear all the racism and classism of Japan in hopes of a better life for her sons. The elder Noa and the younger Moazasu, however, have much more tortured lives in Osaka and this conflict over identity provides a vital underpinning to the narrative. Lee even doubles down on this by making the characters Christian, a group doubly at odds in Japan where there they are seen as a cult.
Most important, though, is the slippery conception of self the immigrants must face. Koreans are seen as hot-blooded criminals, prostitutes and drunks, good only for being yakuza or pachinko parlor owners, which in the Japanese estimation is the same thing. Noa, for example, is studious and takes after his adoptive father, Isak. But deep down he harbors deeply troubling feelings about wanting to be Japanese and leaving his Koreanness behind. The messages are so muddled for him as everyone around him wants for him to excel exactly to prove the Japanese wrong.
<NAME>’s recent blockbuster Get Out posits “the sunken place” a lovely visual metaphor of the double consciousness required to “fit in” among a largely homogenous and hegemonic group. In the case of Peele’s film it is the sacrifice of black identity required to fit into whiteness. Something similar is at work in Lee’s work as her characters wrestle with passing or not passing as Japanese and deep down the characters know that they will never be accepted.
For example, when Moazasu’s son Solomon turns 14, he, like all Koreans born in Japan after 1952, must get fingerprinted to receive an alien registration card. For readers in the anglophone world, where citizenship often rests on jus soli this may seem outrageous. It is a moving scene that fully encapsulates how it is not just individuals, but the State that heaps humiliation on immigrants. Even Moazasu in some way agrees, having given up any hope of changing Japanese minds:
Anyway, the clerk was not wrong. And this is something Solomon must understand. We can be deported. We have no motherland. Life is full of things he cannot control so he must adapt. My boy has to survive.
Deeper into the novel, as her characters go from eking out an existence to solid immigrant successes, Lee’s gaze rests longer on the trappings of comfort that come with such success. It is a good device for showing their desires to distinguish themselves in an adopted land that cares little for them:
Father and son sat down in the armchairs in the center of the large room. Baskets of fruits and bowls of nuts topped the glass and stainless-steel coffee table opposite the long low-backed sofa. A stack of today’s Korean and Japanese newspapers remained half-read.
Pachinko is a rich, well-crafted book as well as a page turner. Its greatest strength in this regard lies in Lee’s ability to shift suddenly between perspectives. We never linger too long with a single character, constantly refreshing our point of view, giving the narrative dimension and depth. Add to that her eye and the prose that captures setting so well, and it would not be surprising to see Pachinko on a great many summer reading lists.
<NAME> is a freelance writer based in Los Angeles. His criticism and poetry has appeared or is forthcoming in a number of publications. You can follow him on twitter @jwwz.
<file_sep>/content/book/free-food-for-millionaires.md
---
title: Free Food for Millionaires
date: 2007-05-07 00:00:00
publisher: Grand Central Publishing
tags: ["fun"]
subtitle:
genre:
- Fiction
description: "In her critically acclaimed debut, National Book Award finalist <NAME> introduces the indelible <NAME>: a strong-willed, Queens-bred daughter of Korean immigrants who is addicted to a glamorous Manhattan lifestyle she cannot afford. Fresh out of Princeton with an economics degree, no job, and a popular white boyfriend, Casey is determined to carve a space for herself in the glittering world she craves-but at what cost?"
_description: >-
“It would be remarkable if she had simply written a long novel that was as easy
to devour as a 19th-century romance — packed with tales of flouted parental
expectations, fluctuating female friendships and rivalries, ephemeral (and
longer-lasting) romantic hopes and losses, and high-stakes career gambles. But
Lee intensifies her drama by setting it against an unfamiliar backdrop: the
tightly knit social world of Korean immigrants, whose children strive to blend
into their American foreground without clashing with their distinctive
background. It’s a feat of coordination and contrast that could kill
a chameleon, but Lee pulls it off with conviction.”
<br>**– <NAME>, *New York Times Book Review***
editions:
- isbn: 9780446699853
binding: paperback
publisher:
description: Trade Paperback
date: 2007-05-07 00:00:00
cover_image: "/uploads/cover_fffm_hdbk.jpg"
- isbn: 9780641856150
binding: hardcover
publisher:
description: Hardcover
- isbn: 9780446504386
binding: ebook
asin: B000U0NSSQ
reviews:
- attribution: USA Today
copy_markdown: 'Critic’s pick: Free Food for Millionaires, by <NAME> (Grand Central, $13.99). USA TODAY’s Carol Memmott says this “vastly ambitious” and “stirring” …'
- attribution: '<NAME>, _Self_, Contributing Books Editor'
copy_markdown: '*Free Food for Millionaires* is the best novel I’ve read in a long time. I’m sad to be finished and I desperately miss <NAME> - a perfectly imperfect character whose loyalty, chutzpah and great hats make her someone I wish I knew in real life.'
- attribution: St. Louis Dispatch
copy_markdown: 'Novelist <NAME> offers us the chance to see this entire culture, up close, personal and far more sympathetically. The book focuses on the emotional and…'
- attribution: Beattiesbookblog
copy_markdown: 'This new title, published 1 July, by Korean American writer <NAME> is causing a stir…'
- attribution: The Missouri Review
copy_markdown: Five years ago we published a story called “Motherland” by an emerging author named <NAME>. We were unanimous in our admiration of what was later selected as the best fiction of that volume year. It’s the story of a Japanese woman…
- attribution: Pattinase
copy_markdown: Summer Picks from The Boston Herald
- attribution: 'Tina Jordan, Entertainment Weekly'
copy_markdown: '*Free Food for Millionaires* is different from any book I’ve ever read—a big, juicy, commercial Korean American coming-of-age novel, one that could spawn a satisfying miniseries, and one that definitely belongs in this summer’s beach bag.'
- attribution: Whatarewritersreading
copy_markdown: 'On the fiction front, I just read Free Food for Millionaires by <NAME>, in one fell swoop. It’s (a huge book) about Ivy League-educated Korean Americans in New York City. I stayed up until 4 am because it is a subtle page-turner…'
- attribution: "Jen's Book Reviews"
copy_markdown: 'Leave your world behind and explore this story set against an interesting cultural backdrop. This is a book I thought about often at work, and could not wait to get home and dive into the story …'
- attribution: Outofthewoods.com
copy_markdown: 'But <NAME> is unrelentingly fair to her characters, letting us into their heads …. <NAME> (posting over at Chekhov’s Mistress) on Middlemarch: …'
- attribution: Asia Pacific Arts
copy_markdown: 'Then comes <NAME> and her acclaimed new novel Free Food for Millionaires, which takes a Jane Austen-type look at love, education, …'
- attribution: "Olsson's Bookstore"
copy_markdown: '<NAME>, author of Free Food for Millionaires, one of my favorite books this year, will be appearing at US-Korea Institute of the Paul H. Nitze School of Advanced International Studies (SAIS) next week, and Olsson’s will be …'
- attribution: Mixed Race America
copy_markdown: 'For the last few days I’ve been engrossed in a novel by <NAME>, Free Food for Millionaires'
- attribution: Lonestarlibrarian
copy_markdown: 'The life and times of a Korean American girl from Queens who goes to Princeton, …'
- attribution: Eugeneweekly.com
copy_markdown: 'Casey, the fictional character at the heart of <NAME>’s Free Food for Millionaires, can’t quite figure out how to fit her upper-class tastes into the world of her parents, Korean immigrants who work for a dry cleaning chain.'
- attribution: Bookreporter.com
copy_markdown: '<NAME> gets into the heads of a dry cleaner operator and a Julliard alumnus, an aging bookstore owner and a stockbroker on Wall Street. …'
- attribution: Historywire.com
copy_markdown: 'As the face of America becomes stunningly diverse, the need for competent cultural translators grows apace…Now, in her first novel, Korean-American writer <NAME> helps us understand Koreans as they grapple to grab the first rung of the economic ladder.'
- attribution: Politics-Prose.com
copy_markdown: '… <NAME>, in her first novel, paints a vast New York landscape that brings to mind …'
- attribution: Northwestasianweekly.com
copy_markdown: 'Weighing in at a mammoth 560 pages, <NAME>‚Äôs Free Food for Millionaires is …'
- attribution: Brijit.com
copy_markdown: 'Brijit provides original min-jin-lee abstracts for busy, smart readers.'
- attribution: latestbooks.org
copy_markdown: Free Food for Millionaires by <NAME> gives us an insight into the lives … <NAME> Lee has received the 2004 Narrative prize for her short story ‚Axis …
- attribution: Angry Asian Man
copy_markdown: 'Here’s an interview with <NAME> from Newsweek: Forget the Comparisons. … And here’s <NAME> Lee on NPR’s Tell Me More: Author <NAME>: ‘Free Food …'
- attribution: Entertainment Weekly
copy_markdown: 'Free Food for Millionaires is different from any book I’ve ever read — a big, juicy, commercial Korean-American coming-of-age novel, one that could spawn a satisfying miniseries, and one that definitely belongs in this summer’s beach bag.'
- attribution: 'Psychiatric Services, A Journal of the American Psychiatric Association'
copy_markdown: 'In her first novel, *Free Food for Millionaires*, <NAME> largely succeeds in unraveling the story of postcollege, Korean immigrant <NAME>, who is still challenged by her family traditions while striving for acceptance and personal fulfillment in the largely assimilated world of New York high finance. As the main character’s life unfolds, Lee masterfully reveals the fallible interpersonal relationships that define Han’s struggle. She also manages to tell the story from multiple perspectives, allowing the characters richness and authenticity that is often missing in the single point of view.'
- attribution: San Francisco Chronicle
copy_markdown: The Five-Forty-Five to Cannes (Crown) by <NAME>; Free Food for Millionaires (Warner) by <NAME>; The Gathering (Black Cat/Grove) by Anne …
- attribution: New York Times
images:
- /uploads/cover_fffm_hdbk.jpg
---
<NAME>’s parents, who live in Queens, are Korean immigrants working in a dry cleaner, desperately trying to hold on to their culture and their identity. Their daughter, on the other hand, has entered into rarified American society via scholarships. Free Food for Millionaires offers up a fresh exploration of the complex layers we inhabit both in society and within ourselves and examines maintaining one’s identity within changing communities.
<file_sep>/content/event/u.c.-irvine-.md
---
title: 'U.C. Irvine '
date: 2018-10-18 21:49:08 -0400
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
draft: true
---
<file_sep>/content/review/review-summary.md
---
title: ''
date: 2020-01-24T00:00:00-05:00
attribution: ''
book: ''
description: ''
featured: true
weight:
---
National Book Award Finalist
_New York Times_ Top Ten Books of the Year
President Obama Recommendation<file_sep>/content/review/northwestasianweekly.com.md
---
title: Northwestasianweekly.com on Free Food for Millionaires
attribution: Northwestasianweekly.com
date: 2007-03-11 18:12:48 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Weighing in at a mammoth 560 pages, <NAME>'s _Free Food for Millionaires_ is…<file_sep>/content/event/lbb-presents-online-viet-thanh-nguyen-with-min-jin-lee-the-committed.md
---
show_time: true
title: 'LBB Presents ONLINE: <NAME>yen with <NAME> - The Committed'
date: 2021-03-09T20:00:00-05:00
description: <NAME>, who will discuss his new novel, The Committed, on
March 9, 2021 at 7pm CT in a private online event. Nguyen will be in conversation
with bestselling author <NAME>
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.left-bank.com/event/viet-thanh-nguyen-committed
images: []
---
<file_sep>/content/news/2017-01-03-daily-mail-uk-top-10-most-anticipated-books-of-2017.md
---
title: 'Daily Mail UK: Top 10 Most Anticipated Books of 2017'
date: 2017-01-03 12:00:00
categories: ["News"]
tags:
- News
attribution: Daily Mail UK
link_to_original: 'http://www.dailymail.co.uk/home/event/article-4075760/100-Reasons-s-going-WONDERful-2017-Event-s-list-films-TV-shows-essential-books-new-year.html'
description:
---
100 Reasons It's Going to Be a Wonderful 2017: Daily Mail UK Event's List of the Must See Films, TV Shows and Essential Books of the New Year:
PACHINKO made the Top 10 List of Anticipated Books of 2017<file_sep>/content/news/2017-03-24-ploughshares-book-review.md
---
title: 'Ploughshares: Book Review'
date: 2017-03-24 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Ploughshares
link_to_original: 'http://blog.pshares.org/index.php/review-pachinko-by-min-jin-lee/'
description:
---
Pachinko
<br><NAME>
<br>Grand Central Publishing, Feb 2017
<br>496 pp; $27
Reviewed by <NAME>
<NAME>’s sophomore novel Pachinko spans eight decades and four generations of a Korean family that emigrates to Japan during the era of Imperial Rule and struggles to make a home there as they weather the Great Depression, World War II and the Cold War proxy war that eventually divides their motherland. Sunja is the hardworking teenage daughter of boardinghouse managers who live on a small island town outside of Busan. An older businessman seduces her, and only after becoming pregnant does Sunja discover that he has a wife and three daughters in Japan. One of the boarders, a minister recovering from tuberculosis, offers to marry Sunja and raise the child as his own. They move to Osaka, and though they never return to Korea, as their lives adjust to the profound challenges of war and want, the question of home is rarely forgotten.
The book’s title comes from a game that’s been popular in Japan since the 1940s and that shares some similarities with both pinball and slot machines in the United States. Though gambling is illegal in Japan, pachinko is an exception and pachinko parlors abound throughout the country. It’s an industry worth billions of dollars, and not without its own complex political history and metaphorical meaning, which Lee mines expertly.
Lee’s lauded debut novel Free Food for Millionaires was published in 2007 and dealt with a Korean American family living in Queens in the 1990s. If her first novel is an excellent iteration of the Korean immigrant story in America, then Pachinko is the seminal English literary work of the Korean immigrant story in Japan. Sunja’s eldest son Noa develops a love for English literature, and Pachinko has the sweep of some of Noa’s favorite authors’ work, including Dickens. From the first of its nearly 500 pages, the novel moves swiftly. Somehow an epic about familial duty and honor in the face of unending daily indignities is nothing short of a page-turner, and the reader is propelled forward as the novel’s characters are swept through twentieth century history.
Lee’s sentences and the novel’s plotting feel seamless, so much so, that one wonders why we make such a fuss about writing at all. Her style is literary without calling attention to its lyricism. The story isn’t in the language, and yet language is vital to the story, particularly, in whether characters speak Korean, Japanese, and later, English, and in what they can and cannot bring themselves to say to one another and admit to themselves. The omniscient narrative follows several central characters intimately, women and men, Korean and Japanese, younger and older, all grappling with the tensions between their desires and what the world demands of them.
Pachinko is as much a story about money and prejudice as it about colonialism, war and globalization. Lee explores how politics effect the family unit, but more profoundly and perhaps perniciously, individuals’ sense of identity and self-worth that underpin their decisions. The novel is a poignant reminder to any American alarmed by the new administration that we are not the first and will not be the last to experience an existential alienation at the hands of our government and world affairs so beyond our control and inescapable, the mind reels at the scale of power and speed of change.
“Adapt. Wasn’t it as simple as that?” Sunja’s brother-in-law asks himself. “For every patriot fighting for a free Korea, or for any unlucky Korean bastard fighting on behalf of Japan, there were ten thousand compatriots on the ground and elsewhere who were just trying to eat. In the end, your belly was your emperor.”
Falling into and then embracing the pachinko business eventually allows the family to not only satisfy their bellies, finally, but moreover, build considerable wealth. It also ensures that they will never be able to overcome Japan’s entrenched stereotypes about Koreans, no matter how unjust. The tone of the final third of the book shifts as life changes for the family: they leave behind questions of survival to grapple with those of success in a country that does not recognize them as full citizens even though they have lived in Japan for generations.
“A woman’s lot is suffering,” serves as a refrain throughout the book, and yet Sunja, the steadfast daughter, mother, wife, sister-in-law, grandmother and entrepreneur at the heart of the story, imbues the novel with strength, grace and maybe even a cautious sense of hope that the joys and sorrows of life are worthy of our enduring. Lee first had the idea for the novel in 1989 when the story ends. The nearly thirty years of Pachinko’s gestation was well worth the wait.<file_sep>/content/writing/2007-06-19-largehearted_boy_book_notes_archives.md
---
title: 'Largehearted Boy: Book Notes Archives'
date: 2007-06-19T22:17:08.000-05:00
categories:
tags:
- Essays
where_published: 'Largehearted Boy: Book Notes Archives'
link_to_original: http://www.largeheartedboy.com/blog/archive/2007/06/book_notes_min.html
link_to_pdf:
description: When I was growing up in Korea, my dad was a marketing executive—whatever
that means.
_slug: 2007-06-19-largehearted_boy_book_notes_archives
---
When I was growing up in Korea, my dad was a marketing executive—whatever that means. The story went that he used to up and quit his jobs because of his temper. My mother was the local piano teacher, and she brought in the steady pay. She had a number of students. The piano lesson tuition was paid in cash, won notes tucked into small white envelopes. Every Christmas, my little sister Sang and I had to go to our uncle’s house and keep out of the way while our mother hosted the year-end party for her students. My older sister Myung got to go to the party with cake, ice cream and presents because well, she was older, and she was also a student. No, I’m not bitter. My family immigrated to Queens, New York in 1976 when I was almost eight. When I think back to our small house in Seoul, I recall that piano room with its thin door closed, a neighborhood kid plunking away at the keys and my mother’s gentle instructions. Even when there were no students to teach, there was always music playing in the house—Hayden, Chopin and Beethoven. I like all sorts of tunes, but the stuff that makes me well up are the sonatas.<file_sep>/content/news/2017-02-01-esquire-magazine-the-5-books-you-should-read-in-february.md
---
title: 'Esquire Magazine: The 5 Books You Should Read in February'
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Esquire
link_to_original: 'http://www.esquire.com/entertainment/books/a52733/best-books-of-2017/'
description:
---
By <NAME>, host of Lit Up, a podcast about books, writers, and all things literary
Thirty years in the making, Lee's sweeping, multi-generational novel is set in 1900s Asia and is informed by stories she heard about legal and social discrimination against Koreans in Japan, a history largely denied and erased. This story kicks off with an unplanned pregnancy and the promise of a less shameful life in Japan and evolves into addictive family saga packed with forbidden love, the search for belonging, and triumph against the odds.<file_sep>/content/event/dayton-literary-peace-prize-.md
---
title: 'Dayton Literary Peace Prize '
date: 2018-10-28 10:00:47 -0400
images: []
description: '10am: A Conversation with the 2018 Winners and 5pm: 2018 Award Ceremony'
link: http://daytonliterarypeaceprize.org
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/review/elisabeth-egan-on-free-food-for-millionaires.md
---
title: <NAME> on Free Food for Millionaires
attribution: <NAME>, _Self_, Contributing Books Editor
date: 2007-03-11 17:59:45 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
*Free Food for Millionaires* is the best novel I’ve read in a long time. I’m sad to be finished and I desperately miss <NAME> - a perfectly imperfect character whose loyalty, chutzpah and great hats make her someone I wish I knew in real life.<file_sep>/content/event/tattered-cover-authors.md
---
title: 'Tattered Cover Literary Feast: Writers Respond to Readers 2018'
date: 2018-02-03 08:45:00
show_time: true
venue:
name: The Hangar at Stanley
address: 2501 Dallas Street No. 135
city:
state:
zip:
link: >-
https://www.eventbrite.com/e/tattered-cover-literary-feast-writers-respond-to-readers-2018-tickets-39337345058
---
<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
8.45am-5.30pm
This is a ticketed event. Please click the link. <file_sep>/content/news/2008-07-02-forget_the_comparisons_shes_unique_newsweek.md
---
title: "“Forget the Comparisons, She’s Unique” - Newsweek"
date: 2008-07-02T10:28:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Newsweek"
link_to_original: "http://www.newsweek.com/id/33105"
description: ""
_slug: 2008-07-02-forget_the_comparisons_shes_unique_newsweek
---
From the interview:
**Newsweek: But there was so much adultery in the book! Everyone was sleeping around and breaking up with each other. It’s sort of a dim view of love.**
<NAME>: Love is an absolutely tantalizing, beautiful thing. And yet, it is profoundly disappointing, too. I think adultery is a wonderful metaphor of betrayal. Sex is this intimate act between two people. In its highest form, we believe that it’s to be held sacred between two people who love each other. And that’s the reason why adultery always wounds us so much. But, if you take that as a metaphor, you can have adultery in friendship, you can have adultery in any intimate relationship.
<file_sep>/content/news/2017-02-07-fusion-pachinko.md
---
title: 'Fusion: PACHINKO'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Fusion by <NAME>
link_to_original: 'http://fusion.net/story/385342/trump-immigration-refugee-muslim-ban-book-list/'
description:
---
These new books by writers of color shed much needed light on the darkness of Trump’s immigration ban
by <NAME>
As judges across the country have weighed in over the past few weeks on the legality of Trump’s immigration ban, the future of tens of thousands of immigrants and refugees now hangs in the balance of our nation’s court system. On Tuesday, a federal appeals court will hear arguments to overturn a temporary ban on the president’s order. It’s a strange time when words etched into the base of the Statue of Liberty (that most American of monuments)—“give me your poor, your tired, your huddled masses yearning to breathe free”—are up for debate, but here we are.
To help grasp what’s going on, and what’s at stake, we’re highlighting three books published within the last month—all written by people of color—that address the history, complexity, and heart of America’s immigration battle.
<NAME>, PACHINKO
Why you should read it:
The praise for Lee’s second novel, published today, has been resounding and effusive. “Pachinko is a book about outsiders, minorities and the politically disenfranchised,” writes The New York Times, “But it is so much more besides.” Lee, who is Korean American, writes an epic tale of a Korean family in Japan over seven generations, from the early 20th century to the present. Pachinko gives us a moving and detailed portrait about what it’s like to sit at the nexus of two cultures, and what it means to forge a home in a place that doesn’t always welcome you.
Quotables:
In Seoul, people like me get called Japanese bastard, and in Japan, I’m just another dirty Korean. —Pachinko
For people like us, home doesn’t exist. —Pachinko
<NAME>, AGE OF ANGER: A HISTORY OF THE PRESENT
Why you should read it:
At a time when alternative truths are distorting our political discourse, Indian essayist and novelist <NAME> offers up a welcome tonic: a detailed, historic view that connects the rise of white nationalism, ISIS, and other fundamentalist movements. Age of Anger, out in the U.S. today, offers a clear-eyed analysis of and context for these movements. Mishra’s book dispels various myths—that ISIS’s appeal is grounded in Islam or economic despair, for example—and traces the forgotten Western roots of today’s extremist groups. (Spoiler alert: We’ve been here before.) He recently covered some of these themes in an essay for The Guardian.
Quotables:
This vanity, luridly exemplified today by <NAME>’s Twitter account, often ends up nourishing in the soul a dislike of one’s own self while stoking impotent hatred of others; and it can quickly degenerate into an aggressive drive, whereby individuals feel acknowledged only by being preferred over others, and by rejoicing in their abjection. (As Gore Vidal pithily put it: ‘It is not enough to succeed. Others must fail.’) —“Welcome to the Age of Anger,” The Guardian
Rich and poor alike voting for a serial liar and tax dodger have confirmed yet again that human desires operate independently of the logic of self-interest–and may even be destructive of it. —“Welcome to the Age of Anger,” The Guardian
VIET THANH NGUYEN, THE REFUGEES
Why you should read it:
It’s easy to reduce the lives of refugees to a single, black and white narrative, but Nguyen, himself a Vietnamese American refugee, renders a life of displacement in vivid and haunting color. The Refugees, out today, is a short story collection that follows in the footsteps of his Pulitzer Prize-winning novel, The Sympathizer, and has been praised by The A.V. Club as “haunting,” and The Washington Post as “exquisite.” Loss and displacement are themes, but so is work—as Nguyen’s characters construct lives built on the sacrifices that came before.
Quotables:
The dead move on. But the living, we just stay here. —The Refugees
Stories are just things we fabricate, nothing more. We search for them in a world besides our own, then leave them here to be found, garments shed by ghosts. —The Refugees
So it was that we soaped ourselves in sadness and we rinsed ourselves with hope, and for all that we believed almost every rumor we heard, almost all of us refused to believe that our nation was dead. —The Sympathizer<file_sep>/content/event/behind-the-book.md
---
title: Behind the Book
date: 2017-04-13 19:00:00
show_time: true
venue:
name: KGB Bar
address: 85 East 4th Street
city: New York
state: NY
zip: '10003'
link: www.behindthebook.org
---
A Reading to support the literacy nonprofit Behind the Book.
Behind the Book is a small literacy nonprofit that gets kids excited about reading by connecting them with contemporary writers and illustrators. Working with low-income students in the 1st-12th grades, we bring authors and their books into individual classrooms in curriculum-based programs that incorporate direct and sustained interaction between students and authors. In workshop fashion, students do original writing; in elementary school, students create illustrated books. All students receive copies of authors’ books to keep as their own. Our goal is to build a new generation of readers and writers. Authors in the classroom have included <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Toure, <NAME>, <NAME>, and <NAME>, among scores of other acclaimed and prize-winning authors.<file_sep>/content/event/montclair-literary-festival.md
---
title: Montclair Literary Festival
date: 2018-03-17 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/pen-parentis.md
---
title: PEN PARENTIS
date: 2018-02-13 19:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2017-02-03-new-york-times-book-review-interview-with-editor-pamela-paul-podcast.md
---
title: New York Times Book Review Interview with Editor <NAME> (Podcast)
date: 2017-02-03 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Audio
attribution: New York Times Book Review
link_to_original: 'https://www.nytimes.com/2017/02/03/books/review/a-brave-look-at-depression.html?_r=0'
description:
---
The Pachinko Interview segment follows the interviews Editor <NAME> has with <NAME> and a report with <NAME>.<file_sep>/content/event/bn_july_11th.md
---
title: Barnes & Noble, July 11th
date: 2007-07-11T20:30:00-05:00
venue:
name: Barnes & Noble at Lincoln Center
link: www.bn.com
_slug: bn_july_11th
---
Conversation with <NAME>, the Tony-award winning playwright of M. BUTTERFLY and the OBIE-award winner for GOLDEN CHILD.
<file_sep>/content/news/2017-05-10-the-booklist-reader-12-titles-to-celebrate-asian-pacific-american-heritage-month.md
---
title: 'The Booklist Reader: 12 Titles to celebrate Asian Pacific American Heritage Month'
date: 2017-05-10 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Booklist Reader by <NAME>
link_to_original: 'http://www.booklistreader.com/2017/05/10/books-and-authors/celebrate-asian-pacific-american-heritage-month-with-12-new-titles/'
description:
---
By <NAME>
Pachinko, by <NAME>
Lee’s (Free Food for Millionaires) exquisite, haunting epic crosses almost a century, four generations, and three countries, depicting an ethnic Korean family that cannot even claim a single shared name because, as the opening line attests: “History has failed us.” In 1910, Japan annexes Korea, usurping the country and controlling identity. Amid the tragedies that follow, a fisherman and his wife survive through sheer tenacity. Their beloved daughter, married to a gentle minister while pregnant with another man’s child, initiates the migration to Japan to join her husband’s older brother and wife. Their extended family will always live as second-class immigrants and no level of achievement, integrity, or grit can change their status as reviled foreigners. Two Japanese-born sons choose diverging paths; one grandson hazards a further immigration to the other side of the world. Incisively titled (pachinko resemble slot machines with pinball characteristics), Lee’s profound novel of losses and gains explored through the social and cultural implications of pachinko-parlor owners and users is shaped by impeccable research, meticulous plotting, and empathic perception.
For the full article, please click the link. <file_sep>/content/news/2008-09-09-profile_in_j_select.md
---
title: "Profile in J-Select"
date: 2008-09-09T22:27:00-05:00
categories: ["Media"]
tags:
- News
attribution: "J-Select"
link_to_original: "http://www.jselect.net"
description: ""
_slug: 2008-09-09-profile_in_j_select
---
Profiles about my work appeared in J-Select this month:“The Reluctant Expatriate,” (Sept/Oct 2008) was written by <NAME>, author of the novel _Losing Kei_.
<file_sep>/content/news/2017-02-07-paste-magazine-review-by-christine-an.md
---
title: 'Paste Magazine: Review by <NAME>'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Paste Magazine
link_to_original: 'http://www.newsweek.com/new-book-releases-february-7-2017-what-read-gaiman-darnielle-nguyen-mastri-553442?rx=us'
description:
---
“History has failed us, but no matter,” begins <NAME>’s Pachinko.
In her much anticipated second novel, Lee traces a Korean family across four generations as they search for home. Pachinko draws inspiration from the experiences of Zainichi Koreans, the permanent, ethnic Korean residents in Japan who have ties to Korea’s colonial days. The Zainichihave faced second-class status and anti-Korean sentiment in Japan, and it’s common for individuals to hide their Korean ancestry to avoid discrimination. Historically barred from more mainstream professions, some Zainichi have achieved success by operating and owning pachinko parlors—potentially lucrative yet ignominious establishments.
Pachinko is an upright pinball game popular in Japan for both recreation and gambling. Through the curls of cigarette smoke, you’ll find rows of colorful machines in pachinko parlors, each with hundreds of glittering brass pins and a handful of payout cups that create random paths in the play field. Typically, a player rents a tray with thousands of small steel balls to load and launch into the machine. Considering its literal scattershot nature and insistence on constant betting, pachinko serves as an image for diaspora—a scattering of people from one common homeland.
The novel’s core narrative centers on its female protagonist, Sunja (meaning “pure child” or “obedient child”), who is born into a peasant family near the Korean port city of Busan after Japan’s annexation of Korea in 1910, which ushers 40 years of colonial rule. When Sunja’s father dies, her mother takes over the family business, a modest boarding house where Sunja comes of age and runs errands for her mother. Sunja then catches the eye of Koh Hansu, a businessman from Japan, and the two become lovers. An unplanned pregnancy sets Pachinko’s dramatic gears in motion.
The novel follows its cast through the early 1900s to the late 1980s across the globe, capturing the zeitgeist of major historical periods like Japanese colonial rule, World War II, the Korean War and the AIDS crisis by demonstrating how global events become personal struggles. In Pachinko, history serves as a backdrop for narratives of resilience and loss, and major historical disturbances are treated with understatement.
In the game of pachinko, one makes bets by launching steel balls. If you’re an immigrant, you take your chance at work. For Lee’s characters, sometimes work brings them a large payout and sometimes it takes them to a dead end. Pachinko suggests that in immigrant narratives, work can be a trap as well. Financial freedom might offer stability, but it does not protect from injustice, discrimination or violence.
Lee shines in highlighting the complexities of being an immigrant and striving for a better life when resigned to a second-class status. In particular, she explores the mechanisms of internalized oppression and the fraught position of being a “well-behaved” member of a maligned group.
When history has failed, and the game is rigged, what’s left?
Throughout Pachinko, it’s acts of kindness and love. The slow accumulation of those moments create a home to return to again and again, even in the worst of times.<file_sep>/content/news/2017-12-12-cnn-the-fiction-that-got-me-through-2017.md
---
title: 'CNN: The Fiction that Got Me Through 2017'
date: 2017-12-12 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: CNN.com
link_to_original: >-
http://www.cnn.com/2017/12/12/opinions/these-books-got-me-through-2017-mitra-kalita-opinion/index.html
description:
---
By <NAME>
Fiction is the closest I will ever get to feeling like someone else.
This year, this polarized year, this year of Trump tweets and #MeToo and hurricanes and Klan rallies and mass shootings, I really needed that.
So I made a list of the books that helped me better understand the news and newsmakers of 2017. Only one was actually published this year. The others are works I read in the past but whose lessons and characters lingered. I returned to them as if they were old friends and sought counsel on how we got here and where we're going. They helped me shift my perspective and, in the busiest news cycle of my 20 years in journalism, enabled a broader, longer view.
Here are some of this year's top news stories and the books that helped me get through them:
Book: "Freedom" by <NAME> (2010)
Confession: I hated this book when it first came out. The characters, liberal and conservative, are so incredibly selfish. When it came out and <NAME> made the cover of Time and President Obama read it on the beach, then Oprah's Book Club, too, I was appalled. Franzen's prose and pacing are masterful. But my main fear was that his storytelling, and the reception to it, redeemed his protagonists' pursuit of individualism instead of damning it.
After the election of 2016, I'm more comfortable celebrating Franzen's prescient portrait of the dysfunctional Berglund family and of ideology trumping community and compromise. That seems to reflect the state of American discourse, at least among power brokers and my friends on Facebook. The novel's initial reception included criticism that it was too obsessively political: Franzen's hatred of suburban sprawl, love of bicycles and the cerulean warbler. In hindsight, this is a seminal work connecting the political to the personal. The desire to be free, it turns out, comes at a steep price.
News: White nationalists march on Charlottesville, Virginia
Book: "My Name is <NAME>" by <NAME> (2016)
Why are they so angry?
This was my question during the unrest in Charlottesville. The violence happened to peak the summer weekend my brother got married: a jubilant interracial wedding punctuated by news alerts about tiki torches and a white nationalist ramming a woman to death with his car.
I came home from the wedding and reached (again) for "My Name is <NAME>" by <NAME>. Raised in Midwestern poverty, Lucy works to get out of what we now call the "white working class" and becomes a successful writer. I found the passage where Lucy, sitting on her New York stoop, watches a gay couple walking by and feels wistful. "I know it's terrible of me, but I'm almost jealous of them. Because they have each other, they're tied together in a real community." She goes on, "…in spite of my plenitude, I was lonely. Lonely was the first flavor I had tasted in my life, and it was always there."
Everybody needs a community, most of all the loneliest among us.
News: Las Vegas mass shooting
Book: "The Goldfinch" by <NAME> (2013)
It was the deadliest mass shooting in modern history. Most reporting focused on the "Strip," the section of Las Vegas we visit as tourists.
Killer <NAME> lived 80 miles away, in the exurb of Mesquite. Farmers there once grew grapes for raisins and raised dairy cows. Now there's a Walmart and eight golf courses and clubs.
I read profiles of Paddock – he gambled, dabbled in real estate, took Valium for his nerves and hated to be out in the sun – and instinctively felt I knew the place he called home. That's thanks to "The Goldfinch," where <NAME> takes us into the transitioning Las Vegas suburbs to understand "what tourists never see."
When her main character Theo leaves New York and moves in with his deadbeat dad, he is welcomed by a sea of shopping plazas and identical housing developments against a vast Nevada sky that nurtures restlessness. He meets his drug dealer of a stepmother and makes a sketchy best friend. Vegas' vice, it seems, has no borders.
News: #MeToo
Book: "An Obedient Father" by <NAME> (2000)
This is a sickening book. <NAME> works as a civil servant in New Delhi's notorious bureaucracy and lives with his daughter and granddaughter. He accepts bribes and carries a horrible family secret.
Ages ago, before embarking on an overseas assignment, I read this book to understand India. This year, I turned to it to understand two themes: Moral corruption and political corruption; moral depravity and political depravity. This book confirms my conviction that you cannot separate the two.
"An Obedient Father" evokes sympathy for a sexual predator in Karan, weak and flawed as he is. Despite his ugliness – and, arguably, that of the current lot of men behaving badly or exposed as having done so in the past – there is also triumph. They are simple victories for those around him, such as survival, love and the power of confrontation, but victories nonetheless. These days, I cling to them.
News: The growing threat of North Korea
Book: "Pachinko" by <NAME> (2017)
We glimpsed the cruelty of North Korea in the story of Otto Warmbier, the American student detained there, then repatriated while in a coma.
I knew why they sent him back home. Months earlier, I had read this passage:
"Sunja nodded, having told herself long ago to expect the worst. The elders in her church had warned her that the Korean prisoners were usually sent home just as they were about to die, so that they would not die in jail. The prisoners were beaten, starved, and made to go without clothing to weaken them."
Sunja is the Korean daughter we meet and grow to love in "Pachinko," my favorite book of the year. I never really knew the history of Koreans' migration to Japan, and the sheer discrimination and displacement they encountered. The characters contend with allegiances to country, family, religion – only to learn they might never quite belong. Min Jin Lee's rendering of one family's journey helps explain the history of both countries in such an accessible, intimate manner. I think of it with every tweetstorm, headline and "Little Rocket Man" reference on escalating tensions among the United States, North Korea and Japan, and the people and identities most affected by war.
The opening words to the novel portend the cyclical nature of cruelty: "History has failed us, but no matter." Thankfully, her words do not.
As this year in my life as a journalist, reader and citizen has shown me: We read, we report, we revisit — with hopes that maybe one day, we'll learn.<file_sep>/content/event/la_jolla.md
---
title: WARWICK’s
date: 2008-04-28T05:23:00-05:00
venue:
name: Warwick's, La Jolla, CA
link: www.warwicks.com
_slug: la_jolla
---
Reading and Q&A
7:30PM
7812 Girard Avenue
La Jolla, CA 92037
<EMAIL>
<file_sep>/content/event/amherst-college-16.md
---
title: 'Strand Books: <NAME> (with <NAME>)'
date: 2019-10-22T19:00:00-04:00
show_time: true
venue:
name: Strand Bookstore
address: 828 Broadway
city: New York
state: New York
zip: "10003"
link: https://www.strandbooks.com/event/nicole-chung
description: |-
"With warmth, candor, and startling insight, <NAME> tells of her search for the people who gave her up, which coincided with the birth of her own child. ALL YOU CAN EVER KNOW is a profound, moving chronicle of surprising connections and the repercussions of unearthing painful family secrets-vital reading for anyone who has ever struggled to figure out where they belong.
Join us in the Rare Book Room as Nicole discusses her new book with fellow author <NAME>!"
images:
- "/uploads/logo.png"
---
<file_sep>/content/news/2016-12-22-american-booksellers-association-feb-2017-indie-next-great-reads-pick.md
---
title: 'American Booksellers Association: Feb 2017 INDIE NEXT Great Reads Pick'
date: 2016-12-22 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: American Booksellers Association
link_to_original: 'http://www.bookweb.org/news/february-2017-indie-next-list-preview-35253'
description:
---
Pachinko: A Novel, by <NAME>
<br>(Grand Central Publishing, 9781455563937, $27)
<br>“A father’s gentle nature, a mother’s sacrifice, a daughter’s trust, and a son’s determination are the cornerstones of this grand, multilayered saga. Pachinko follows one family through an ever-changing cultural landscape, from 1910 Korea to 1989 Japan. As the bonds of family are put to the test in the harsh realities of their world, Sunja and those she holds dear manage to carve themselves a place to call home with hard work, self sacrifice, and a little kimchi. Through it all is a message about love, faith, and the deep-rooted bonds of family. Min Jin Lee gives us a phenomenal story about one family’s struggle that resonates with us today. It will take hold of you and not let go!” —<NAME>, Boswell Book Company, Milwaukee, WI<file_sep>/content/news/the-muse-the-marketplace-keynote-video.md
---
title: The Muse & the Marketplace Keynote (Video)
date: 2018-04-06 18:30:31 -0400
link_to_original: https://vimeo.com/268061051
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/writing/new-york-times-book-review---work-life-balance-suffers--even--in-victorian-england.md
---
title: 'New York Times Book Review: "Work-Life Balance Suffers (Even) in Victorian
England'
date: 2017-02-21 00:30:50 -0500
images: []
image_credit: ''
categories: []
where_published: The New York Times Book Review
link_to_original: https://www.nytimes.com/2017/04/21/books/review/signs-for-lost-children-sarah-moss.html
description: Review of Sarah Moss's SIGNS FOR LOST CHILDREN
---
<file_sep>/content/news/2017-11-30-the-10-best-books-of-2017-the-new-york-times.md
---
title: 'The 10 Best Books of 2017: The New York Times'
date: 2017-11-30 12:00:00
categories: ["News"]
tags:
- Reviews
- News
- Interviews
attribution: The New York Times
link_to_original: >-
https://www.nytimes.com/interactive/2017/books/review/10-best-books-2017.html?_r=0
description:
---
The year's best books, selected by the editors of The New York Times Book Review.
Fiction
Pachinko
By <NAME>
Lee’s stunning novel, her second, chronicles four generations of an ethnic Korean family, first in Japanese-occupied Korea in the early 20th century, then in Japan itself from the years before World War II to the late 1980s. Exploring central concerns of identity, homeland and belonging, the book announces its ambitions right from the opening sentence: “History has failed us, but no matter.” Lee suggests that behind the facades of wildly different people lie countless private desires, hopes and miseries, if we have the patience and compassion to look and listen.
For the full list, please click the link below.<file_sep>/content/writing/nyt-tales-of-racism-and-sexism-from-3-leading-asian-american-women.md
---
title: 'NYT: Tales of Racism and Sexism, From 3 Leading Asian-American Women'
date: 2021-03-19T02:00:13-04:00
categories:
tags: []
where_published: The New York Times
link_to_original: https://www.nytimes.com/2021/03/19/us/racism-sexism-asian-american-women.html
link_to_pdf:
description:
_slug: '2019-06-03T06:00:00.000+00:00'
images: []
---
"I really want to encourage everybody to see this as a political issue, a physical issue, an economic issue. It’s complicated, it’s intersectional. And we need to think about it in a complex way."<file_sep>/content/event/columbia-university-graduate-school-of-journalism.md
---
show_time: true
title: Columbia University Graduate School of Journalism
date: 2020-02-10T11:00:00-05:00
description: Conversation with Professor <NAME>
venue:
address: 2950 Broadway
city: New York
name: Columbia University Graduate School of Journalism
state: NY
zip: "10027"
link: ''
images: []
---
<file_sep>/content/event/national-book-festival-.md
---
title: 'National Book Festival: Library of Congress '
date: 2018-09-01 13:00:19 -0400
images: []
description: ''
link: https://www.loc.gov/item/prn-18-084/
show_time: true
venue:
address: ''
city: ''
name: 'National Book Festival: Fiction Stage of Walter E. Washington Convention
Center '
state: 'Washington, D.C. '
zip: ''
---
<file_sep>/content/event/trident-booksellers-and-cafe.md
---
title: Trident Booksellers and Cafe
date: 2018-01-18 19:00:00
show_time: true
venue:
name: Trident Booksellers and Cafe
address: 338 Newbury Street
city: Boston
state: MA
zip:
link: 'https://www.tridentbookscafe.com'
---
Live Interview at Trident with Boston's own Writer's Bone Co-hosts, <NAME> and <NAME>. Daniel is the author of SID SANFORD LIVES! and Sean is a screenwriter. For more about them and their amazing podcasts, please see www.writersbone.com
<file_sep>/content/news/mit-news-novelist-min-jin-lee-makes-the-case-for-understanding-through-fiction.md
---
title: 'MIT News: "Novelist <NAME> makes the case for understanding through fiction"'
date: 2018-11-01 23:00:17 -0400
link_to_original: http://news.mit.edu/2018/novelist-min-jin-lee-understanding-through-fiction-1101
images:
- "/uploads/DrAnr7HWkAQacFO.jpg"
tags: []
categories: []
description: ''
---
<file_sep>/assets/js/lazysizes.js
var lazysizes = require("lazysizes")
var noscript = require("lazysizes/plugins/noscript/ls.noscript.js")
var bgset = require("lazysizes/plugins/bgset/ls.bgset.js")<file_sep>/content/event/amherst-college-20.md
---
title: 'First Presbyterian: "<NAME>: Faith, Family & Identity"'
date: 2019-11-13T14:00:00-05:00
show_time: true
venue:
name: First Presbyterian Church of Brooklyn
address: 124 Henry Street
city: Brooklyn
state: NY
zip: "11201"
link: http://brooklynheightsblog.com/archives/89442
description: Join First Church Brooklyn for an evening with NY Times best selling
author <NAME> in conversation with Rev. <NAME>
images: []
---
<file_sep>/content/news/2017-12-01-ottawa-citizen-vancouver-public-librarians-book-lists.md
---
title: 'Ottawa Citizen: Vancouver Public Librarians Book Lists'
date: 2017-12-01 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Ottawa Citizen
link_to_original: >-
http://www.ottawacitizen.com/entertainment/vancouver+public+library+librarians+offer+books/16024062/story.html
description:
---
Pachinko
By <NAME>
Grand Central Publishing
For fans of family sagas. A National Book Award finalist, this novel follows a family over several generations and the experiences of being Korean and living in Japan. This vivid saga is filled with resilience and emotion.<file_sep>/content/news/_index.md
---
title: "News & Media"
menu:
main:
weight: 3
---
<file_sep>/content/event/kingswood-oxford-school.md
---
show_time: true
title: Kingswood Oxford School
date: 2021-01-08T00:00:00-05:00
description: Virtual
venue:
address: ''
city: West Hartford
name: ''
state: Connecticut
zip: ''
link: ''
images: []
---
<file_sep>/content/news/2007-05-30-san_francisco_chronicle1.md
---
title: "San Francisco Chronicle"
date: 2007-05-30T22:48:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "San Francisco Chronicle"
link_to_original: ""
description: ""
_slug: 2007-05-30-san_francisco_chronicle1
---
Novel Looks at Life’s Uncertainties
San Francisco Chronicle - May 30, 2007
The first novel by <NAME> — a Korean immigrant who went to Yale University — looks at the precarious time after college graduation when dreams may not ...
<file_sep>/content/news/2017-03-21-new-york-society-library-pachinko-conversation-with-jeannette-watson-sanger-and-min-jin-lee-video.md
---
title: 'New York Society Library: Pachinko Conversation with <NAME> and <NAME> (Video)'
date: 2017-03-21 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
- Video
attribution: The New York Society Library
link_to_original: 'https://youtu.be/be6AelFVh-c'
description:
---
<file_sep>/content/news/2017-05-06-minnesota-public-radio-the-threads-book-of-the-week.md
---
title: "Minnesota Public Radio: The Thread's Book of the Week"
date: 2017-05-06 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: 'Minnesota Public Radio: The Thread'
link_to_original: 'https://www.mprnews.org/story/2017/05/06/books-ask-a-bookseller-fargo'
description:
---
A novel that asks: How do we forgive the ones we love?
The THREAD
By <NAME> · May 6, 2017
LISTEN
Ask a bookseller: Zandbroz Variety in Fargo, N.D.
May 5, 2017
1min 58sec
Every week, The Thread checks in with booksellers around the country about their favorite books of the moment. This week, we spoke with <NAME>, a manager at Zandbroz Variety in Fargo, N.D.
<NAME> grew up in the bookstore — Zandbroz is a family business.
Lately, she's been recommending "Pachinko," a new novel by <NAME>.
It's a sweeping family saga set in Korea and Japan. The story spans nearly the entire 20th century, following four generations through colonial rule, war and dislocation. For Danz, who has read a lot of historical fiction, it offered a different perspective on events like World War II and the Korean War. Much of the fiction on the market tells those stories from a Western perspective.
It all begins with Sunja, a young girl in a Korean fishing village who falls in love with an older man. When she becomes pregnant, she learns he is already married.
To spare her from social disgrace, a visiting minister agrees to marry Sunja himself. Together, they move to Japan.
"I found this novel very relevant to today's world, just because it's about outsiders, familial roles and also the politically marginalized. For me, it drew a lot of questions of what makes a nation, what defines a home, how do we define family, and how do we define what loyalty is to family?" Danz said. "Also, how do we learn to forgive those we're closest to?"
"Anyone that wants to read a book about historical fiction or a family epic, but wants a different cast of characters with a different historical viewpoint, this is the book for them."<file_sep>/content/news/2017-12-04-financial-review-australia-best-books-of-2017.md
---
title: 'Financial Review (Australia): Best Books of 2017'
date: 2017-12-04 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: 'Financial Review: News Website of the Year'
link_to_original: >-
http://www.afr.com/brand/afr-magazine/the-18-best-books-of-2017-20171023-gz6h50
description:
---
By <NAME>
PACHINKO was selected as one of 7 Fiction titles of the FINANCIAL REVIEW (Australia), the news website of the year.
1. The Choke, <NAME>, Allen & Unwin
The perfect title for a book that seizes you by the throat from its opening pages and never lets go. Laguna won the 2015 Miles Franklin Literary Award for The Eye of the Sheep, her first adult novel, and this one is even better. Thirteen-year-old <NAME> has been abandoned by her parents and raised by her tough-as-nails grandfather. A visit from her criminal father wreaks havoc on her troubled life. As brave and memorable a heroine as any in Australian literature. Raw, real, heartbreaking.
1. Pachinko, <NAME>, Apollo
Pachinko is a popular Japanese game of chance – a metaphor for life itself, as American-Korean writer <NAME> suggests in her second novel, a sprawling family saga about Koreans living in Japan, set over eight decades. The central character, Sunja, falls pregnant as a teenager to a married man, with consequences that reverberate through the generations. Lee's depiction of the alienation and discrimination suffered by Koreans in Japan is symbolic of the migrant experience everywhere. Gripping.
1. A State of Freedom, <NAME>, Chatto & Windus
Calcutta-born Mukherjee writes unflinchingly and with deep compassion of India and its people – those trying to escape lives of grinding poverty and those who have done so, and who feel pangs of educated-liberal guilt when they return. This is the third book by Mukherjee – whose previous work, The Lives of Others, was short-listed for the Man Booker – and it deals powerfully with issues ranging from familial love to modern slavery, workplace safety and revolutionary politics. Quietly devastating.
1. The Golden House, <NAME>, <NAME>
Rushdie's brilliant latest novel has it all – love, betrayal, revenge, lust, politics and death. Set in modern Manhattan, it tells the tragi-comic story of <NAME>, a wealthy immigrant, and his three sons, and features a maniacal businessman – a "cackling cartoon narcissist" – who becomes president. Rich in allusions to Greek mythology, pop culture, ancient philosophy and literature, it tackles big issues such as the nature of good and evil. Audacious, angry and funny, this is vintage Rushdie.
1. Home Fire, <NAME>, Bloomsbury
This electrifying novel is a modern take on Sophocles' masterpiece Antigone. In this version Parvaiz, a young British Muslim, goes to fight with ISIS in Syria, leaving his two sisters, Isma and Aneeka, in London to deal with the fallout. His fate lies in the hands of the hardline British Home Secretary, whose son is Aneeka's lover. A page-turning story of a clash between the individual and the state, morality and law, and romantic love and familial duty. Fiendishly clever and very timely.
1. The Animators, <NAME>, Scribe
Not since Thelma and Louise has there been such a feisty couple of women friends. Sharon and Mel meet in college and share a passion for cartoons. Soon they are working together as animators and what follows is a roller-coaster ride as their work and personal lives become inextricably linked. There is heartbreak and tragedy, as well as razor-sharp wit, as Whitaker explores the dark side of creativity and obsession, and of friendship and love. Unforgettable.
1. <NAME>, <NAME>, Hachette Australia
The Tin Man in The Wizard of Oz was lacking a heart, but English author Winman's third book most definitely is not. Set in Oxford, London, and the south of France, it centres on the complex relationship between Michael and Ellis, friends since childhood. When Ellis marries Annie things change. A recurring motif is Van Gogh's Sunflowers and the optimism and hope that it symbolises. A jewel of a book about grief, regret, heartbreak and longing.<file_sep>/content/event/wellesley-college.md
---
title: 'Wellesley College '
date: 2018-09-27 02:47:33 -0400
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/miami-book-fair.md
---
title: Miami Book Fair
date: 2017-11-18 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
November 18-19, 2017
Times TBA<file_sep>/content/event/amherst-college-litfest.md
---
title: Amherst College LitFest
date: 2018-03-01 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Conversation with <NAME> and Parul Seghal of The New York Times<file_sep>/content/review/buzzfeed-on-pachkinko.md
---
title: Buzzfeed on Pachkinko
attribution: Buzzfeed.com
date: 2017-03-11 17:49:30 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Most Exciting Books Coming in 2017<file_sep>/content/review/san-francisco-chronicle.md
---
title: San Francisco Chronicle
attribution: San Francisco Chronicle
date: 2018-05-09T13:46:23.000+00:00
book: book/pachinko.md
description: ''
featured: true
weight:
---
Beautiful…Lee's sweeping four-generation saga of a Korean family is an extraordinary epic.<file_sep>/content/news/2017-12-01-financial-times-best-books-of-2017-critics-picks.md
---
title: 'Financial Times: Best Books of 2017: critics'' picks'
date: 2017-12-01 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Financial Times
link_to_original: 'https://www.ft.com/content/03025382-d638-11e7-8c9a-d9c0a5c8d5c9'
description:
---
Selected by <NAME>, FT Columnist:
"History has failed us, but no matter." PACHINKO, <NAME>'s massive, richly wrought second novel, follows Sunja and her children across four generations, from a village in Busan to a ghetto for Korean immigrants in Japan. Sunja weds a pastor to cleanse the stain of her love affair with a charismatic married man. Her second son makes a fortune with pachinko parlours, but a character notes: 'Living everyday in the presence of those who refuse to acknowledge your humanity takes great courage.' One of 2017's most rewarding novels.
For the complete list, please click the link.<file_sep>/content/event/clint-smith-with-min-jin-lee-how-the-word-is-passed-a-reckoning-with-the-history-of-slavery-across-america.md
+++
date = 2021-06-10T23:00:00Z
description = "Harvard Book Store's virtual event series welcomes acclaimed writer, poet, and scholar <NAME>—author of the award-winning Counting Descent: Poems—for a discussion of his latest book, How the Word Is Passed: A Reckoning with the History of Slavery Across America. He will be joined in conversation by <NAME>, author of the celebrated, bestselling novels Fast Food for Millionaires and Pachinko."
images = []
link = "https://www.harvard.com/event/virtual_event_clint_smith/"
show_time = true
title = "Clint Smith with <NAME> - How the Word Is Passed: A Reckoning with the History of Slavery Across America"
[venue]
address = "Virtual"
city = ""
name = ""
state = ""
zip = ""
+++
<file_sep>/content/news/2017-11-12-south-china-morning-post-profile.md
---
title: 'South China Morning Post: Profile'
date: 2017-11-12 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: South China Morning Post
link_to_original: >-
http://www.scmp.com/culture/books/article/2119611/min-jin-lee-hong-kong-talks-about-her-hit-novel-pachinko-learning-wise
description:
---
By <NAME>
<NAME> is having a good day in Hong Kong. It’s the Korean American writer’s birthday and she has just stepped off a flight from New York. She has the happy glow of someone who has been nominated for a top literary prize.
“The flight was 17 hours and I’ll be here less than 70 hours – half of them awake. I’m not even sure I’m awake now. I’m here to see my friends, attend the festival and eat egg tarts – they have the best egg tarts in Hong Kong,” Lee says on Saturday during a Hong Kong International Literary Festival event.
For the remainder of the article, please click the link.<file_sep>/content/event/amherst-college-4.md
---
title: Chosun Ilbo Asian Leadership Conference
date: 2019-05-15T10:00:00-04:00
show_time: true
venue:
name: Meeting Room 4 (Emerald)
address: ''
city: Seoul, South Korea
state: ''
zip: ''
link: http://alcchosun.com/eng/Contents.asp?LoadPage=Program&YearCode=2019&DayCodeCount=2
description: 'Meet the Bestselling Author: <NAME>'
images: []
---
<file_sep>/content/event/upstairs_at_the_square_barnes_nobles.md
---
title: UPSTAIRS AT THE SQUARE, Barnes & Nobles
date: 2008-04-10T23:23:00-05:00
venue:
name: UPSTAIRS AT THE SQUARE, BARNES & NOBLES, NEW YORK CITY
link: www.bn.com
_slug: upstairs_at_the_square_barnes_nobles
---
Upstairs at the Square
hosted by <NAME>
with musical guest, <NAME>
and <NAME>
7PM
Barnes & Nobles, Union Square, New York, New York
33 East 17th St.
<file_sep>/content/event/advance-virtual-screening-talkback-of-minari.md
---
show_time: true
title: Advance virtual screening & talkback of MINARI
date: 2021-01-13T20:00:00-05:00
description: ''
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://aaww.org/curation/advance-virtual-screening-talkback-of-minari/
images: []
---
<file_sep>/content/news/2010-01-31-wall_street_journal_my_korean_new_year.md
---
title: "Wall Street Journal—My Korean New Year:"
date: 2010-01-31T00:32:00-05:00
categories: ["Media"]
tags:
- Video
attribution: "Wall Street Journal"
link_to_original: "http://online.wsj.com/article/SB10001424052748704094304575030320508272654.html?mod=WSJ_latestheadlines#articleTabs_video"
description: ""
_slug: 2010-01-31-wall_street_journal_my_korean_new_year
---
[](/uploads/wsj_article_1-2010.pdf)
This essay and video appeared in the [WSJ WEEKEND JOURNAL—ASIA](http://online.wsj.com/article/SB10001424052748704094304575030320508272654.html?mod=WSJ_latestheadlines#articleTabs_video "WSJ WEEKEND JOURNAL—ASIA") on January 29, 2010.
Korean New Year will begin on February 14, 2010. Have a good one!
<object id="wsj_fp" width="512" height="363"><param name="movie" value="http://s.wsj.net/media/swf/main.swf"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><param name="flashvars" value="videoGUID={882941C0-0EBB-487D-89FC-71C7BF20C5DF}&playerid=1000&plyMediaEnabled=1&configURL=http://wsj.vo.llnwd.net/o28/players/&autoStart=false" base="http://s.wsj.net/media/swf/"><embed src="http://s.wsj.net/media/swf/main.swf" bgcolor="#FFFFFF" flashvars="videoGUID={882941C0-0EBB-487D-89FC-71C7BF20C5DF}&playerid=1000&plyMediaEnabled=1&configURL=http://wsj.vo.llnwd.net/o28/players/&autoStart=false" base="http://s.wsj.net/media/swf/" name="flashPlayer" width="512" height="363" seamlesstabbing="false" type="application/x-shockwave-flash" swliveconnect="true" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></object>
<file_sep>/content/event/university-of-california-irvine.md
---
title: University of California Irvine
date: 2018-10-18 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/sf_dinner.md
---
title: SF DINNER
date: 2008-04-30T05:26:00-05:00
venue:
name: SAN FRANCISCO, CA
link:
_slug: sf_dinner
---
<NAME> Invites You to
An Asian Fusion Feast with
Author <NAME>
April 30, 2008
6.30PM
PONZU RESTAURANT
415 775 7979
www.ponzurestaurant.com
401 Taylor Street
San Francisco
Cost:
$95 per person or $175 per couple
AIWF & Asia Society members receive a discounted rate of $90 per person or $170 per couple
(Includes tax, tip & autographed copy of FREE FOOD FOR MILLIONAIRES)
For tickets:
call BOOK PASSAGE: 415-927-0960 x 1
or <EMAIL>
<file_sep>/content/news/2008-04-27-asian_american_writers_workshop.md
---
title: "Asian American Writer’s Workshop"
date: 2008-04-27T22:00:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Asian American Writer's Workshop"
link_to_original: "http://www.aaww.org/events_interviews_lee.html "
description: ""
_slug: 2008-04-27-asian_american_writers_workshop
---
Min Jin Lee Min Jin Lee’s upcoming debut novel, Free Food for ... Min Jin Lee: A pre-sell tour is when a publisher sends an author out around the country to ...
<file_sep>/content/writing/2008-01-04-weighing_in.md
---
title: "Weighing In"
date: 2008-01-04T21:26:03-05:00
categories:
tags: ["Essays"]
where_published: "Vogue"
link_to_original: "http://www.accessmylibrary.com/coms2/summary_0286-34387551_ITM"
link_to_pdf:
description:
_slug: 2008-01-04-weighing_in
---
In a lifelong struggle with her shape that spans relationships, career changes, and now a move halfway around the world, <NAME> charts the seismic shifts in her life by the numbers on the scale.
<file_sep>/content/review/whatarewritersreading-on-free-food-for-millionaires.md
---
title: Whatarewritersreading on Free Food for Millionaires
attribution: Whatarewritersreading
date: 2007-03-11 18:03:45 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
On the fiction front, I just read _Free Food for Millionaires_ by <NAME>, in one fell swoop. It’s (a huge book) about Ivy League-educated Korean Americans in New York City. I stayed up until 4 am because it is a subtle page-turner…<file_sep>/content/news/2017-01-31-kirkus-12-excellent-reads.md
---
title: Kirkus 12 Excellent Reads
date: 2017-01-31 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Kirkus Reviews
link_to_original: 'https://www.kirkusreviews.com/lists/12-excellent-reads-february/pachinko/'
description:
---
Pachinko makes the Kirkus Reviews 12 Excellent Reads List for February 2017<file_sep>/content/event/jumpstart-fall-luncheon-.md
---
title: 'JumpStart Fall Luncheon '
date: 2018-11-13 17:00:34 +0000
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: ''
description: ''
---
<file_sep>/content/news/ny-post-the-10-best-books-to-read-to-beat-coronavirus-boredom-4.md
---
title: 'Business Insider: 12 must-read books for Asian Pacific American Heritage Month'
date: 2020-04-21T00:50:11-04:00
link_to_original: https://www.businessinsider.my/best-books-asian-pacific-american-heritage-authors-2020-4
images: []
tags: []
categories: []
description: ''
---
> “'War, displacement, and colonialism have been the story of millions of Asian immigrant families but seldom have those stories been told in the voices and about the sacrifices of the women who held it all together,' Sung Yeon Choimorrow said. 'In telling the story of a Korean woman’s family trying to survive among their colonizers, PACHINKO captures perfectly the melancholy and suffering so embedded in the Korean psyche.'
>
> <NAME> of APANO added, 'This incredible, epic novel is filled with a family throughout four generations of forbidden love, a search for belonging, and overcoming the odds.'"<file_sep>/content/event/the-red-ink.md
---
title: Red Ink
date: 2018-02-08 19:00:00
show_time: true
venue:
name: Powerhouse Arena
address: 28 Adams Street
city: Brooklyn
state: NY
zip: '11201'
link:
---
Curated and moderated by writer <NAME>. Panel on ENVY with <NAME>, <NAME>, <NAME>, and <NAME>. Co-sponsored by Literary Hub.
<EMAIL><file_sep>/content/event/olssons.md
---
title: Olsson’s
date: 2008-04-18T05:14:00-05:00
venue:
name: Olsson's, Washington, D.C.
link: www.olssons.com
---
A Conversation with <NAME> and <NAME>
about FREE FOOD FOR MILLIONAIRES.
Reading and Q&A
Curated by <NAME>
7PM
OLSSON’S BOOKS & RECORDS
1307 19th Street NW
Washington, DC 20036
<file_sep>/content/event/_index.md
---
title: "Events"
description: Readings and Appearances
menu:
main:
weight: 7
---
<file_sep>/content/event/erbd.md
---
title: 'European Bank for Reconstruction & Development'
date: 2017-05-24 17:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
A Conversation with <NAME>, Director of Communications of EBRD<file_sep>/content/event/shanghai_international_literary_festival.md
---
title: Shanghai International Literary Festival
date: 2009-03-22T06:00:00-05:00
venue:
name: SHANGHAI INTERNATIONAL LITERARY FESTIVAL
link: www.m-restaurantgroup.com
_slug: shanghai_international_literary_festival
---
Sunday, March 22nd
“Late Bloomer or Freedom From Failure”
<NAME>, author of FREE FOOD FOR MILLIONAIRES in conversation with writer <NAME>
2PM
M on the Bund
For Ticket Information: www.mypiao.com
For Information: www.m-restaurantgroup.com
<file_sep>/content/event/kacf-giving-summit.md
---
title: KACF Giving Summit
date: 2018-05-19 09:00:11 -0400
images: []
description: '9am: Women''s Breakfast with KACF & 11am: Opening Speech '
link: ''
show_time: true
venue:
address: '60 Washington Square South '
city: ''
name: 'NYU Kimmel Center '
state: ''
zip: ''
---
<file_sep>/content/event/2016-09-22-43rd-annual-new-england-independent-booksellers-association-fall-conference.md
---
title: 43rd Annual New England Independent Booksellers Association Fall Conference
date: 2016-09-22 08:30:00
venue:
name: Rhode Island Convention Center
address:
city:
state:
zip:
link: 'http://www.newenglandbooks.org'
---
NEIBA Author Breakfast
With authors <NAME>, <NAME>, <NAME> and <NAME><file_sep>/content/event/marthas-vineyard-book-festival.md
---
title: "Martha's Vineyard Book Festival (Saturday Fiction Panel)"
date: 2017-08-05 15:00:00
show_time: true
venue:
name: Harborview Hotel
address: 131 North Water Street
city: Edgartown
state: MA
zip:
link:
---
SATURDAY, AUGUST 5, 2017: 3:00PM-3:55PM
Panel Discussion: "Fitting In: Friendship and Identity"
With authors <NAME>, <NAME>, <NAME>, and <NAME><file_sep>/content/event/melbourne-writers-festival-panel.md
---
title: 'Melbourne Writers Festival 2017: Saturday—Panel'
date: 2017-09-02 13:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Living in Trump's America with <NAME>, <NAME> and <NAME><file_sep>/content/news/2007-07-19-55_secret_street.md
---
title: "55 Secret Street"
date: 2007-07-19T22:07:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "55 Secret Street"
link_to_original: " http://55secretstreet.typepad.com/55secretstreet/ - References"
description: ""
_slug: 2007-07-19-55_secret_street
---
<NAME> is the author of the fantastic, critically-acclaimed novel Free Food for Millionaires. You may remember it as one of my 55 Summer Favorites. Min went to Yale where she was awarded both the Henry Wright Prize for Nonfiction ...
<file_sep>/content/event/tokyo-foreign-correspondents-club-japan.md
---
title: "Tokyo: Foreign Correspondents' Club of Japan"
date: 2017-09-12 18:15:00
show_time: true
venue:
name: FCCJ
address: Yurakucho Denki North Building 20F
city: 'Yurakucho 1-7-1, Chiyoda-ku, Tokyo'
state:
zip: 100-0006
link: 'http://www.fccj.or.jp'
---
Book Break: PACHINKO
In Conversation with <NAME>, the Tokyo Bureau Chief of The New York Times.
For Book Break tickets (Conversation & Dinner), please go to: www.fccj.or.jp
Tel. +81-3-3211-3161<file_sep>/content/news/2017-01-31-pachinko-is-a-first-edition-selection-for-greenlight-bookstore.md
---
title: Pachinko is a First Edition Selection for Greenlight Bookstore
date: 2017-01-31 12:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original: 'http://www.greenlightbookstore.com/firsteditionsclub'
description:
---
The Greenlight Bookstore First Editions Club offers great new literature each month, for building a library or keeping up with what’s new.<file_sep>/content/news/2017-05-05-cuny-tv-asian-american-life-interview-video.md
---
title: 'CUNY TV: ASIAN AMERICAN LIFE INTERVIEW (Video)'
date: 2017-05-05 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Video
- Audio
attribution: Asian American Life
link_to_original: 'https://www.youtube.com/watch?v=bi2__A0BIro&feature=youtu.be'
description:
---
The interview with <NAME> begins on minute 10.15.
[https://www.youtube.com/watch?v=bi2__A0BIro&feature=youtu.be](https://www.youtube.com/watch?v=bi2__A0BIro&feature=youtu.be)<file_sep>/content/event/amherst-college-7.md
---
title: Australia
date: 2019-09-11 08:00:00 -0400
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
draft: true
---
<file_sep>/content/event/st--anns-school.md
---
title: Saint Ann's School
date: 2017-12-07 10:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2017-01-30-probooknerds-podcast.md
---
title: ProBookNerds Podcast
date: 2017-01-30 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Audio
- News
attribution: ProBookNerds
link_to_original: 'http://directory.libsyn.com/episode/index/id/5036708 …'
description:
---
A Conversation with <NAME> of ProBookNerds, sponsored by OverDrive Libraries. <NAME> and <NAME> discuss the writing of PACHINKO at the American Library Association Midwinter 2017.<file_sep>/content/event/columbia_university.md
---
title: "Columbia University: Institute for Research on Women & Gender"
date: 2008-03-28T07:09:00-05:00
venue:
name: "Columbia University: Institute for Research on Women & Gender"
link: www.columbia.edu/cu/irwag/events/maain/jong/
_slug: columbia_university
---
Friday, March 28, 2008
Social Hall at Union Theological Seminary
3041 Broadway at 121st St.
2:00PM-8PM
FEAR OF FLYING by <NAME>: A Retrospective Consideration
with <NAME>, Director of the Institute for Research on Women and Gender at Columbia University and <NAME>, Columbia University Libraries.
2.15-3.45PM
FEAR OF FLYING at 35
Moderated by <NAME>, Barnard Center for Research on Women
<NAME>, writer and critic, Harvard University
<NAME>, writer and critic, Standford University
<NAME>, novelist, CUNY Graduate Center
4:15PM-5:45PM
Can a Feminist Classic be an American Classic?
Moderated by <NAME>, journalist, Columbia University School of the Arts
<NAME>, novelist
<NAME>, writer and critic, CUNY Graduate Center
<NAME>, journalist, salon.com
6-7PM
<NAME> in conversation with <NAME>, Columbia University
RECEPTION
<file_sep>/content/news/2017-05-27-nikkei-asian-review-profile.md
---
title: 'Nikkei Asian Review: Profile'
date: 2017-05-27 12:00:00
categories: ["News"]
tags:
- Reviews
- News
- Interviews
attribution: Nikkei Asian Review
link_to_original: 'http://asia.nikkei.com/Life-Arts/Life/Giving-a-voice-to-America-s-ignored-Asian-immigrants'
description:
---
By <NAME>, Contributing Writer
Giving a voice to America's 'ignored' Asian immigrants
Acclaimed author of 'Pachinko' tracks a Korean family over generations and continents
NEW YORK – It seemed fitting that <NAME>, the South Korea born, Ivy League educated author of the recently published novel "Pachinko," would choose the curious tastes of Cuban-Chinese food for a chat over lunch in Manhattan. She knew exactly what she wanted from the menu, mixing aromatic Chinese dishes with Cuban fried plantain bananas.
Born in South Korea and now based in New York, Korean-American writer MJL, pictured here in central Tokyo, is equally at home in Asia and the West. (Photo by <NAME> for KEYSHOTS.COM)
Having moved to New York from Seoul with her family as a child, Lee has endeavored in her writing to provide a voice for Asian immigrants. "Pachinko," her second novel, follows four generations of Koreans as they leave their homeland in the Japanese occupied Korean Empire to settle in Japan in the early 1900s.
The story, which could be called a love letter to Korean women, describes the family's displacement, and its economic and emotional struggles to survive, in such authentic terms that it elicits deep empathy from the reader.
"Pachinko" begins with the line: "History has failed us, but no matter." In fact, it does matter to Lee. "Asians have not been good at talking about themselves," she said. "Especially women do not write about their history. My purpose in writing the book was to portray the endurance of Koreans who emigrated to Japan in the 20th century."
The epic tale spans eight decades, from 1910 to 1989. It begins in the dirt-poor fishing village of Yeongdo, in what is now South Korea, with an arranged marriage between Hoonie, a humble disabled man, and Yangin, the child of a struggling widower with only female offspring. Their daughter Sunja propels the story to a Korean ghetto in Japan.
There, after falling pregnant by her dashing and married lover Hansu, the naive teenager agrees to marry a frail minister bound for a church in Osaka. The subsequent births of children, the family's struggle with profound poverty, tragic death and brutal discrimination from ethnic Japanese form the basis of a story that remains heartening as its author finds light in the darkest of places.
"I wanted to look at the sacrifices and resilience in Korean women, and show that their kind of strength is in essence real beauty," Lee said of the novel. She writes of Sunja leaving Korea: "Sunja held her bundles close to her heart and belly to inhale the lingering scent of home on the fabric covering their possessions."
The things lost in migration concern Lee. "The cost of migration is painful because we know that we can't ever get our homes back," she said. "There are 65 million refugees in the world at this moment in search of home and rest, and I wanted to present what is always lost."
"First-generation women, the matriarchs who made the journey, who worked in the markets, who raised their kids and who endured hardships are largely invisible," said Lee. "The world doesn't see them, especially Asian women. They are minor characters in history. In the market, it doesn't matter how you look. I'm concerned that the time spent by Asian women on physical beauty today is awful.
"They feel that if you are beautiful you can bypass suffering. They don't see that history tells us that suffering is an inevitable part of life, and the women who came before them were beautiful. In Korea, and sometimes in Japan, the emphasis on beauty comes from a history of suffering, humiliation, oppression and degradation from being Korean. I wanted to sing a song for those girls. Not the beautiful girls, the 'OK girls'. The women who endured."
Rock star
Some time after that conversation, I attended a talk by Lee at the New York Public Library. She stepped on stage like a rock star and proudly introduced her parents and sister, who were in the audience, taking special care to acknowledge them publicly before she shared her family story.
The cover of the U.S. edition of "Pachinko"
Lee was just seven years old and did not speak a word of English when she arrived in New York in 1976. Instead of trying to join difficult conversations she cultivated an inner world and a unique sense of humor. Her family settled in the far reaches of New York's Elmhurst section, in the borough of Queens, and lived a modest life. Her father opened a newspaper and candy stand in Manhattan, and Lee enthusiastically accompanied her parents on weekends because she would be given most of the damaged candy as a reward.
Before a packed house at the library Lee recounted a time when she watched as a customer flung a few coins directly at her father in payment for a newspaper. She knew this would never happen in Korea, and suddenly realized how much her father had sacrificed to take care of his family.
He wore a suit to work every day, even after her parents began a wholesale jewelry business selling cheap items to jewelry peddlers. "He wore that suit because that was what he had done in Korea. He was a marketing executive at a cosmetics company. He didn't see himself as changed," Lee said wistfully.
Lee knows about grit and perseverance. Gaining entry to Yale University and then to Georgetown University was part of the American dream, but her aspiration to write remained secondary to the study of law. As a student she wrote several pieces and won awards in both non-fiction and fiction before she began practicing corporate law at a Manhattan firm.
Finally, a chronic childhood disease forced her to abandon law and brought her closer to considering the possibilities of a literary career. "After the birth of our son and accepting family monetary obligations I began to realize it was not a financially prudent idea to be a fiction writer," she wrote after her first novel, "Free Food for Millionaires," was published in 2007.
That book followed 12 years of self-doubt, and a serious struggle to overcome the feeling that she had become a 30-year-old housewife dabbling with writing ambitions. "Lost in a world that didn't need my work," as she described the years after practicing law.
The catalyst in turning her struggles around came in the form of an artist fellowship from the New York Foundation for the Arts. She became her own teacher and critic, transcending her recurring and debilitating liver disease, raising her son, reading voraciously and attending every bargain writing course she could find. In the summer of 2006, when she was 37, she sold her first manuscript.
"Feeling unseen"
"Free Food for Millionaires" was a critical and financial success. When asked if this affected her Lee replied: "I do not get involved in criticism or praise." She had written several drafts of "Pachinko" before her debut, and the discarded work continued to haunt her. "I wrote so many versions of 'Pachinko' that I was full of doubt for literally decades," Lee recalled. "After 'Free Food for Millionaires' I decided to throw away the map and start over again on 'Pachinko.' "You have to write about what calls to you."
"Feeling unseen in my own life inspired me to want my characters to be seen for who they are," she noted. When her Japanese-American husband gained a senior job at a Western investment bank in Japan, Lee was able to use the years 2007 to 2011 in Tokyo to interview Japanese-Koreans and collect the multitude of stories that ultimately became the narrative of her second novel. "When I finally finished 'Pachinko' I felt really free," said Lee. She chose the title "Pachinko" because it represents a thread she found amongst most Japanese-Koreans.
"I chose to name the book 'Pachinko' because it is a Japanese form of pinball, but it's a rigged game. The house is going to win and yet people still play. The multibillion-dollar pachinko business is often viewed with great suspicion and contempt by middle-class Japanese," Lee said.
"However, one out of every 11 Japanese adults plays pachinko regularly, and there is at least one pachinko parlor in every train station and shopping street in Japan. Nearly every Korean-Japanese person I met in Japan had some historical connection or social connection with the pachinko business. Pachinko is a game of chance and manipulation, and I was interested in this gambling business as a metaphor. The world is an unfair place, and yet we continue to play and we continue to show up. We have to."
When asked by a woman in the public library audience which character in her novel she most identifies with, the author answered quickly: "Hansu! Although he's morally ambiguous, which I'm not, he's a sexy guy who wants to make things happen. He's one of those people who do stuff." Clearly, Lee is also a "do stuff" person.
"Free Food for Millionaires," about Koreans in the U.S., and "Pachinko," about Koreans in Japan, will eventually form part of a trilogy. Lee's next book concerns the overvaluation of education among Korean communities around the world.
Underpinning her view of the vast Korean diaspora, meanwhile, are deep-seated concerns about migration and refugee flows."I hope that we can all respond compassionately to welcome refugees and to help their assimilation and integration into our respective economies. I think our hearts have to be open to those who seem different than we are, and perhaps open to those we may even fear. For this purpose – this purpose of opening hearts – I think art and drama are in a unique position and may help in a different way," she said.<file_sep>/content/event/hands_on_tokyo.md
---
title: HANDS ON TOKYO
date: 2008-11-06T23:38:00-05:00
venue:
name: HANDS ON TOKYO
link: www.handsontokyo.org
_slug: hands_on_tokyo
---
A LUNCHEON TO BENEFIT HANDS ON TOKYO
<NAME>, author of FREE FOOD FOR MILLIONAIRES
TICKETED EVENT
12:00PM
Voie Lactee, Tomo Museum
10,000 Yen, Three-course luncheon
RSVP: <EMAIL>
<file_sep>/content/event/burgundy_books_july_14th.md
---
title: Burgundy Books, July 14th
date: 2007-07-14T15:00:00-05:00
venue:
name: Burgundy Books, East Haddam, CT
link: www.burgundybooks.net
_slug: burgundy_books_july_14th
---
<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-4.md
---
title: President Obama Recommends PACHINKO
date: 2020-01-23T00:00:00-05:00
link_to_original: https://www.bookweb.org/news/btw-news-briefs-572187
images:
- "/uploads/image1.jpeg"
- "/uploads/image2.jpeg"
tags: []
categories: []
description: '"This is a captivating book I read at the suggestion of a young staffer
on my team –– a historical novel about the Korean immigrant experience in wartime
Japan. Min Jin Lee draws you in from the first line, ''History has failed us, but
no matter.'' The book is named after a popular game in Japan that''s a bit like
a pinball machine –– a game of chance where the player can set the speed or direction,
but once it''s in play a maze of obstacles determines the outcome. Staying true
to the nature of the game, Min Jin Lee''s novel takes us through four generations
and each character''s search for identity and success. It''s a powerful story about
resilience and compassion." - <NAME>'
---
<file_sep>/content/news/2017-02-23-vanity-fair-magazine-pachinko.md
---
title: 'Vanity Fair Magazine: Pachinko'
date: 2017-02-23 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Vanity Fair by <NAME>
link_to_original: 'http://www.vanityfair.com/style/2017/02/brooding-books-to-read-during-the-dark-days-of-winter'
description:
---
IN SHORT
<NAME>’s High Noon (Bloomsbury) puts Hollywood and Washington on the stand. <NAME> takes a tour through the radical beauty of Nollywood Portraits(Skira). Not all our children will be raised in <NAME>’s Perfect Little World(Ecco). Risible raconteur <NAME> imagines The World to Come (Knopf). An immigrant’s Civil War years blow through <NAME>’s carbine in Days Without End (Viking). <NAME> strings together a rosary of memories for her grandmother <NAME> (Scribner). Sabotage and subterfuge collide in G<NAME>’s Churchill’s Ministry of Ungentlemanly Warfare (Picador). <NAME> is smitten with Oliver Sacks and their Insomniac City (Bloomsbury). <NAME> is the good kind of sketchy for Dior (Rizzoli). <NAME> mounts The Brain Defense (Penguin Press). <NAME> locks up good cops gone bad in Blue on Blue (Scribner). The Kingdom of Happiness (Touchstone) is upon us in Aimee Groth’s Zappos zinger. <NAME>’s first season, Autumn (Pantheon), has arrived. <NAME> pas de bourrées around The Schooldays of Jesus (Viking). <NAME>’s Pachinko (Grand Central) plays with the destiny of one Korean family. <NAME>’s Homo Deus (Harper) knows what plagues us. The stars align for <NAME> in Waves Passing in the Night (Bloomsbury). <NAME>’s natty narrator finds himself in All Our Wrong Todays (Dutton).<NAME> returns with tales of The Refugees (Grove). <NAME>makes a power play for The Presidents’ Secrets (Yale). <NAME> satirizes suburbia On Turpentine Lane (<NAME>). <NAME> hedges his bets in Sheelah Kolhatkar’s Black Edge (Random House). <NAME> wrote A Book of American Martyrs (Ecco) in the time it took you to read this.<file_sep>/content/news/2017-05-07-the-washington-post-bestseller-may-7-2017.md
---
title: 'The Washington Post Bestseller: May 7, 2017'
date: 2017-05-07 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Washington Post
link_to_original: 'https://www.washingtonpost.com/opinions/2017/05/03/ea0efc3c-300a-11e7-a335-fa0ae1940305_story.html?utm_term=.15474d16e709'
description:
---
HARDCOVER FICTION
1. THE FIX
(Grand Central, $29). By <NAME>. <NAME> witnesses an execution-style killing. It may well be his most perplexing case yet. [2]
2. GOLDEN PREY
(Putnam, $29). By <NAME>. <NAME>, recently of the U.S. Marshals Service, pursues a brutal drug cartel. [1]
3. ANYTHING IS POSSIBLE
(Random House, $27). By <NAME>. <NAME> returns home after 17 years. [1]
4. A GENTLEMAN IN MOSCOW
(Viking, $27). By <NAME>. A Russian aristocrat is under house arrest in Moscow. [16]
5. THE UNDERGROUND RAILROAD
(Doubleday, $26.95). By <NAME>. A young slave makes a desperate bid for freedom. [32]6
6. THE BLACK BOOK
(<NAME>, $28). By <NAME> and <NAME>. A missing black book sends shock waves through Chicago’s elite. [5]
7. NORSE MYTHOLOGY
(Norton, $25.95). By <NAME>. The popular author retells the great northern tales of Odin, Thor and Loki. [12]
8. BEARTOWN
(Atria, $26.99). By <NAME>. A successful junior ice hockey team helps revive a failing town. [1]
9. ALL BY MYSELF, ALONE
(<NAME>, $26.99). By <NAME>. An English aristocrat is murdered on an ocean cruise and her priceless necklace has gone missing. [4]
10. PACHINKO
(Grand Central, $27). By <NAME>. A poor Korean family tries to make it in Japan. [1]<file_sep>/content/news/2017-02-01-chicago-review-of-books-top-ten-books-of-february-2017.md
---
title: 'Chicago Review of Books: Top Ten Books of February 2017'
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Chicago Review of Books
link_to_original: 'https://chireviewofbooks.com/2017/01/31/the-10-best-new-books-to-read-this-february/'
description:
---
Pachinko makes the Chicago Review of Books Top Ten Books of February 2017<file_sep>/content/news/2017-01-09-bookbub-22-most-anticipated-book-club-reads-2017.md
---
title: 'BookBub: 22 Most Anticipated Book Club Reads 2017'
date: 2017-01-09 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: BookBub
link_to_original: 'https://media.bookbub.com/blog/2017/01/09/biggest-book-club-books-coming-in-2017/'
description:
---
A new tour de force from the bestselling author of Free Food for Millionaires, for readers of A Fine Balance and Cutting for Stone.
Profoundly moving and gracefully told, Pachinko follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them. Betrayed by her wealthy lover, Sunja finds unexpected salvation when a young tubercular minister offers to marry her and bring her to Japan to start a new life.
So begins a sweeping saga of exceptional people in exile from a homeland they never knew and caught in the indifferent arc of history. In Japan, Sunja’s family members endure harsh discrimination, catastrophes, and poverty, yet they also encounter great joy as they pursue their passions and rise to meet the challenges this new home presents. Through desperate struggles and hard-won triumphs, they are bound together by deep roots as their family faces enduring questions of faith, family, and identity.<file_sep>/content/event/pittsburgh-arts-and-lectures.md
---
title: Pittsburgh Arts & Lectures
date: 2019-04-01 19:30:21 -0400
images: []
description: ''
link: https://pittsburghlectures.org/programs/ten-evenings/
show_time: true
venue:
address: ''
city: ''
name: Carnegie Music Hall in Oakland
state: ''
zip: ''
---
<file_sep>/content/news/2017-03-20-reading-women-podcast.md
---
title: Reading Women (Podcast)
date: 2017-03-20 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- Audio
attribution: Reading Women Podcast
link_to_original: 'https://www.blubrry.com/reading_women/21970581/interview-with-min-jin-lee/'
description:
---
I got to talk with the wonderful hosts <NAME> and Autumn Privett of Reading Women. Thank you, Kendra and Autumn.<file_sep>/content/news/2016-12-01-center-for-fiction-modern-families-video.md
---
title: 'Center for Fiction: Modern Families (VIDEO)'
date: 2016-12-01 19:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original:
description:
---
A Conversation about Modern Families with authors <NAME>, <NAME>, <NAME>, and <NAME>
[https://www.youtube.com/watch?v=ONS3Y7V2nrM](https://www.youtube.com/watch?v=ONS3Y7V2nrM)<file_sep>/content/news/2016-11-01-chicago-review-of-books-top-ten-books-of-february-2017.md
---
title: Chicago Review of Books Top Ten Books of February 2017
date: 2016-11-01 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Chicago Review of Books
link_to_original: 'https://chireviewofbooks.com/tag/february-2017-books/'
description:
---
Pachinko makes the The 10 Best New Books to Read for February 2017.<file_sep>/content/writing/2012-04-24-a_review_of_toni_morrisons_new_book_home_in_the_times_of_london.md
---
title: "A Review of <NAME>’s new book HOME in The TIMES of LONDON"
date: 2012-04-24T14:21:13-05:00
categories:
tags: ["Essays"]
where_published: "THE TIMES OF LONDON"
link_to_original: "http://www.thetimes.co.uk/tto/arts/books/fiction/article3386800.ece"
link_to_pdf:
description:
_slug: 2012-04-24-a_review_of_toni_morrisons_new_book_home_in_the_times_of_london
---
<file_sep>/content/news/dayton-literary-peace-prize-.md
---
title: Dayton Literary Peace Prize
date: 2018-09-17 00:19:40 -0400
link_to_original: http://daytonliterarypeaceprize.org/2018-winners-press_release.htm
images: []
tags: []
categories: []
description: 'The 2018 Dayton Literary Peace Prize Runner-Up in Fiction: In Pachinko
(Grand Central), <NAME> brings the historical sweep of Dickens and Tolstoy
to the saga of four generations of a poor Korean immigrant family who, exiled from
a homeland they never knew, fight to control their destinies in 20th-centuryJapan.
As they encounter both catastrophes and great joy, the novel''s exceptional protagonists
confront enduring questions of faith, family, and identity. Lee said: “The world
is broken because we do not love enough. War, peace, and art require at least three
elements: imagination, will, and action – and ironically, all three are enacted
because men and women feel love. This is the central paradox – we love – the other,
self, family, faith, or nation – and we use that love – of something, or someone,
for anything – to justify our violence, compromises, and creation. We know that
peace is far more difficult than war or art, because peace requires both forgiveness
and restraint; so somehow, we must learn to love peace far more than war. If literature
bears witness to true narrative and if it awakens compassion, reconciliation may
indeed be possible. Where men and women have failed to love, literature may inspire
greater love for all those we''d once thought we feared or hated. I write fiction
because I believe that our love can refine our worse nature. I am deeply honored
to join the Dayton Literary Peace Prize family of writers as we pursue our collective
call toward global peace."'
---
<file_sep>/content/review/eugeneweekly.com-on-free-food-for-millionaires.md
---
title: Eugeneweekly.com on Free Food for Millionaires
attribution: Eugeneweekly.com
date: 2007-03-11 18:10:02 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Casey, the fictional character at the heart of <NAME>’s Free Food for Millionaires, can’t quite figure out how to fit her upper-class tastes into the world of her parents, Korean immigrants who work for a dry cleaning chain.<file_sep>/content/writing/2007-11-01-crowning_glory.md
---
title: "Crowning Glory"
date: 2007-11-01T22:24:44-05:00
categories:
tags: ["Essays"]
where_published: "Vogue"
link_to_original:
link_to_pdf:
description:
_slug: 2007-11-01-crowning_glory
---
<file_sep>/content/news/2017-11-30-slate-magazine-podcast.md
---
title: 'Slate Magazine: (Podcast)'
date: 2017-11-30 12:00:00
categories: ["News"]
tags:
- Reviews
- Audio
- Interviews
- News
attribution: 'SLATE: The Gist with Mike Pesca'
link_to_original: >-
http://www.slate.com/articles/podcasts/gist/2017/11/min_jin_lee_s_novel_captures_the_pain_and_grace_of_the_korean_japanese.html
description:
---
An Interview on THE GIST: A Daily News and Culture Podcast with Mike Pesca
Episode 880 of Slate's THE GIST
For the podcast and article, please click the link below.<file_sep>/content/event/bookexpo_america.md
---
title: BookExpo America
date: 2007-05-31T10:00:00-05:00
venue:
name: BookExpo
link: www.bookexpoamerica.com
_slug: bookexpo_america
---
May 31-June 3
Saturday, June 2, Author Signing
11AM Tantor Audio Booth No. 2268
Sunday, June 3, Author Signing
11AM Grand Central Publishing/Hachette Book Group USA Booth
<file_sep>/content/writing/2007-04-14-will.md
---
title: "Will"
date: 2007-04-14T00:50:58-05:00
categories:
tags: ["Essays"]
where_published:
link_to_original:
link_to_pdf: "/uploads/will_by_min_jin_lee.pdf"
description: "Published in _Breeder - Real Life Stories from the New Generation of Mothers_"
---
My husband looked so happy. "That's great," he shouted, then reached over to hug me, but stopped when he saw my face. My sparsely filled eyebrows must have been furrowed again, giving me away. The skin around Christopher's brown eyes crinkled with worry. "What's wrong? Aren't you happy about it?" After all, it wasn't an accident. We'd been married for three years and we'd both agreed recently to start a family.
Christopher removed his suit jacket, having just returned from the office. After spending the entire day at home by myself, I'd pounced on him as soon as he'd opened the front door. Then I'd blurted out the news.
"I am." I glanced at my bare feet, then watched him slip off his brown oxfords. I didn't want to seem ambivalent- so ungrateful. "I just thought it would take longer." My husband put his arms around me, and I peered over his shoulder, my chin resting on the yoke of his white dress shirt. I stared at the hallways mirror hanging slightly askew on the whitewashed wall. I could smell the clean scent of starch, and I wondered what would become of my life now.
I'd heard a lot about how so many women in New York City were infertile, how difficult it was to conceive. It took us three weeks. I never bought a fertility kit, took my temperature or counted the days of my menstrual cycle. With a snap of the fingers, presto- we were going to have a baby I was surprised by the speed of it, but more than that, I felt a kind of dread- and this filled me with shame. Children were blessings, everyone knew that.
I would not describe myself as having been a happy child- more like morose and slightly goofy. Far too tall for a Korean girl, I wore my oversized eyeglasses slung low on my rounded nose, my black hair bobbed. My tiny oval eyes bore a pinched expression as if I had lost my way. I was the middle of three girls in an immigrant family. Our parents worked six days a week in their small wholesale jewelry store in midtown Manhattan while my sisters and I went to the local public school, did our homework and waited for them to return safely to our brown brick apartment building in Elmhurst, Queens.
Each night, we'd hear the jangle of keys opening our apartment door; then Mom and Dad would walk in, remove their coats and shoes and separate from one another. Mom marched straight to the kitchen to finish cooking the dinner that my oder sister had started preparing and Dad would go to the living room, collapse into the maroon sectional sofa from Seaman's and read the _shin-mun_. My younger sister would fetch him a clean ashtray form the kitchen counter, and he'd pat her head. The only sounds in our rented one-bedroom apartment were the clinks of pots and pans coming from the narrow galley kitchen and the rustle of Dad's newspapers. The metallic smell of Benson & Hedges filled the air as the three of us, heads down, did our homework and waited for dinner.
Our parents were always tired; my sisters and I felt sorry for them. Though they never said it, we felt like we were an enormous burden- needing lunch money, new sneakers and jeans, and handing them countless school forms having to be read and signed in English. I didn't think about it then, but I can imagine now how scared they must have been to move to a new country, start a small business they knew nothing about and raise three little girls- all with only a modest knowledge of the language.
In Korea, Dad was an account executive who moved from job to job because he fought with his bosses. Mom was a minister's daughter who taught piano to the neighborhood children. born to well-off families from the opposite sides of a small country, both Mom and Dad had been sheltered from roughness and poverty as children. The war changed everything for them. At age sixteen, Dad left his hometown in the North and never saw his mother again. Unable to shake his fear and hatred of that war, he insisted on bringing us to America- a country, to him, full of romance and possibilities.
I was seven when our family immigrated; my mother was only thirty-five. After just a few months in New York, her white and pink skin faded.l Her glossy chestnut hair began to gray. After her bath, I'd occasionally help her pluck the white hair form her head with a pair of old-fashioned eyebrow tweezers. In the following years when there were too many white hair to harvest, she turned to Loving Care hair dye from the drugstore.
From the moment she arrived home from work until the rest of us went to bed, Mom as in motion. Her childhood home in Pusan had been filled with servants, and in our home in Seoul, I remember the country girls who lived with us to help Mom with the housework while she earned money as a piano teacher. In America, she worked twelve- or thirteen hour days, cooked our meals and kept our house tidy. But in those long years in Queens before my parents used their savings to buy a big house in the New Jersey suburbs, I can't recall seeing my mother smile or tease or laugh at a joke, even on holidays. For Mom and Dad, life in America was somber- to succeed, you had to be vigilant, sacrifice pleasure and endure.
As a young girl, I decided that I didn't want to marry or have children. I didn't even like to be around babies or toddlers- they seemed so needy and useless. So I studied very hard, earned gold stars and, when I had spare time, wrote and published essays for a Korean newspaper. My teachers told me that in America you could do anything you wanted. I paid attention to successful people in books and magazines and on television. My favorite writer when I was fifteen was <NAME>. He had gone to Yale, so I applied and, amazingly, I got in. I formulated a plot for my life: I would be a single professional with money of my own, wear nice clothes and live in a beautiful apartment in Manhattan. I would invest my savings, retire early and write novels and plays. I would not take care of anyone else.
The only thing I never considered was love. I met Christopher when I was twenty-two. After I finished law school two years later, we married. He had come from enormous privilege, the only child of a regal Japanese mother and an American diplomat father. My husband didn't believe that life had to be an unrelenting struggle filled with difficulties and betrayals of history for which you prepared by sewing gold coins in the lining of your coat. There could be fun and comfort in this life. To me, such ideas were extravagant, exotic, utterly unfamiliar. From the outset, it was obvious to me that I believed in work and he believed in grace.
Right after our honeymoon, I started my job as a corporate lawyer. I was at the office eighty to ninety hours a week, easily billing sixty. Sometimes I worked forty to fifty hours straight through, without going home to shower or change my clothes. After a year of this, I started to fantasize about selling lipstick at the Bergdorf's counter. At least salesgirls went home when the store closed. I never knew when I could go home. The more work you did, the more work you were given. I was a newlywed- I wanted to go to the movies with my husband on Saturday nights and cook dinner for us now and then. On Sunday nights, I'd cry hopelessly because I'd have to begin another week of endless work, or so it seemed to me. Christopher asked me why. Why would I keep doing something for so many hours if I didn't like it? He said, Quit. We could live on a lot less.
I said no. I couldn't just quit. I'd spent three years in law school. My parents had sacrificed almost twenty years working in that tiny jewelry store to put me through college and law school. As a junior institutional salesman at a Wall Street firm, my husband earned less than I did. I wanted to be a writer, but that wasn't a real job. No one paid you while you wrote a novel, and one book could take years and years. I heard Tolstoy wrote _War and Peace_ eight times. I stayed at that firm for another year.
I wondered if I'd enjoy my job more somewhere else, so I changed law firms. The new place was worse: I had to prove myself again. I worked there for fifty days, and after billing my first three-hundred-hour month- a feat I'd once dismissed as urban lawyer myth- I quit. There wasn't enough money in New York for me to work that way, and even so, I didn't care about money enough; I would not endure it anymore. I had written and published in high school and college, but had stopped in law school and for the two years that I practiced. After I quit my job I bought a computer and a printer. I wrote a very rough draft of a novel. I found an agent. I still needed to learn a great deal about writing, but I felt hopeful- not just about my new career, but about my revised plans for my life. My husband and I talked about having a child.
Perhaps I could be a mother if someone like Christopher was my child's father. He didn't scream, get depressed or fall apart. Not like me. What would a child who was half-Christopher and half-me be like? In my marriage, I felt loved and cared for and attended to. This support made me think that perhaps I could love a child even though I hadn't felt loved as a child. My husband said we would have a wonderful life even if we never had children, but would he always feel this way? I now had doubts about the plot I'd hatched as a young girl. I hadn't planned to get married, yet my marriage had turned out well. Perhaps the same would occur with having a child. I went off he Pill. I primed my body for a baby. I gave up caffeine, exercised in moderation, took prenatal vitamins. We stopped using condoms. Three weeks.
I was pregnant, but I couldn't imagine _my_ life as a mother. All I could see was the image of my mother- the whirling dervish- with half a dozen arms spinning in the air, each hand performing a different task. So I tried to focus on the pregnancy itself- on the physical requirements of this life growing in my body. I tried to follow the guidelines of the pregnancy books, but I kept falling short. I could not swallow another glass of grayish skim milk. I never ate any yellow vegetables, and my favorite foods- refined sugar and fat were no-noes. I felt tired all the time, but I resented taking naps. I was so sleepy that I couldn't read anything serious or write anything good. I was angry- my writing schedule was becoming a joke. I knew it would only get worse when the baby came. I was a bad mother, and my baby wasn't even born yet. I go piercing migraines for the first time in my life. Extra Strength Tylenol did nothing for me. I lay across my sofa, wet washcloths on my forehead, and hoped the pain would pass.
During each checkup at the doctor's office, I noticed an increase in my weight. Having previously struggled with a weight problem and lost the extra pounds, I did not want to be fat again, _ever_. The idea of gaining forty pounds was devastating.
I could not admit these feelings which seemed, even to me, grossly superficial and selfish. I did not tell anyone I felt this way. I was too smart, too nice, too with-it, too spiritual to be this vain, this self-conscious, this ungrateful. Everyone was overjoyed that we were having a child. My parents and my in-laws were ecstatic. My sisters were ready to spend a fortune on toys and baby clothes for their future niece or nephew, I was no longer me, I was merely the silent medium for the next generation.
In spite of everyone else's happiness, I grew more terrified. I feared becoming one of those people who talk only about their children, never see films, have a rotten social life, never read history books and live in a toy- and diaper-littered apartment. I had quit being a lawyer, hoping to become a writer, not a mother. And how could I forget that when I was little, my mother never had any time for her piano, her books or for laughter?
Eleven weeks into my pregnancy, my doctor could not find the fetus's heartbeat using a stethoscope with a built-in microphone. She instructed me to get an ultrasound examination at a nearby clinic. There was a slight possibility that something could be wrong: Fibroids could be blocking the fetus's heartbeat, or the fetus could be in a strange position. But she said not to worry, she was explaining these things at length only because she would not be there; another physician, who I didn't know, would see me.
My husband and I went together for the ultrasound. I undressed and lay down on the examining table. The doctor proceeded to project an image of the inside of my uterus on a monitor. In the dim room I tried to be still while a latex-sheathed probe was inserted in: "Be a good girl and don't fidget." It was so quiet in that room, so quiet that I felt dizzy. Minutes later, the doctor mumbled something to his assistant, who turned on the overhead lights. He told me that the fetus had expired. He didn't know why.
After the doctor left the room, Christopher and I cried. He helped me to get dressed and said very little- that it would be all right, that he loved me very much. He was sad, too, but I didn't do much to comfort him. Once again, i felt silenced, not just by my guilt this time, but also by my grief. I wondered if it was possible to have ended a life merely by having doubts about its beginnings.
Christopher returned to the office, and I went home and phoned my best friend to tell her what had happened. Finally, I confided that I hadn't been happy about being pregnant and I wondered if such feelings could have contributed to losing the pregnancy. Next time, I told her, I'd push such negative thoughts from my mind.
What an arrogant thing to think, she said. She repeated it again, _arrogance_. I was stunned. She might as well have kicked me. My friend was usually a fountain of sympathy. She told me that my fears had nothing to do with it -- _I_ had nothing to do with it. It was nature, science, God-- it wasn't meant to be. Regardless, it wasn't my will that mattered. The truth of her statements wounded me. I told her that I was tired and got off the phone.
When I saw my obstetrician the next day, she said that I needed to have a D&C procedure to clean out my womb and see if everything was all right. Then I should wait at least three months before trying again. Chris said he would accompany me, but I told him no. I don't know why exactly; a part of me felt that I'd failed him somehow. I was ashamed of another test,another procedure, another required step in the process of one big disappointment. I asked my mother to come with me. The anesthesiologist told me to count backward. That is all I remember. After it was over, I woke up on a plastic-sheeted operating bed, blood pooling around my hips. My mother held my hand while I sobbed, and though I knew that it didn't make any sense, I felt that I was being punished for my arrogance- for believing that motherhood was elective, not selective.
As a girl, I had asked myself if I ever wanted to be a mother, and I had answered no. I'd assumed that I could be a mother and I could refuse that role because its burdens seemed so great. And I had to ask myself now, as a young, married writer who had just lost a pregnancy: Did I _never_ want to be a mother? And my answer was no.
My mother had seemed so sad to me when I was growing up. How can I say this without offense? I didn't want to be like her, and I didn't want her life. I didn't always want to be second or third or fifth. Mom was beyond reproach. She was giving, patient, kind, fair, reliable and extremely competent. I would never be so selfless.
This is even harder to say- I was disappointed with my good mother because she did everything she was supposed to do except to seem happy that I was born. Her sadness and fatigue due to the overwhelming demands on a working mother of three children in a foreign country were without question well justified. But I had needs as her daughter- including the need to see her happy. If my mother wasn't happy, I wondered, then how could I be happy? Nothing I did or could do would ever redeem her sacrifices- this much I was beginning to understand. No lives were equal. She and Dad were far happier now in their retirement, but I still sensed her unarticulated regrets. These were my fears: One day my child would feel the need to make my life whole through her accomplishments, or worse, as an adult, she would be unable to remember me ever smiling at her as a little girl.
Mom had given up so much- too much, I thought. But I knew that her strength and continued presence had given me the ability to create a better life for myself. Would a life without enough hope and happiness for another generation be a better life- or would it just be a simpler one?
I didn't want to adopt a new plan, hatch a new plot or invoke a new will for my life. Instead I was aware of a wish, a prayer, a hope: in time, to be a decent mother who was happy about being one.
Whether I could be a mother at all was uncertain, at that moment; it was simply out of my hands. I had to forget my plans, my fears, my schedule, and just wait and be open to the uncertainty. There was nothing for me to do. In a way, I was relieved.
<file_sep>/content/event/the-great-gatsby-greenlight-bookstore-event-in-conversation-with-jennifer-buehler.md
---
show_time: true
title: The Great Gatsby - Greenlight Bookstore Event - In conversation with <NAME>
date: 2021-01-14T19:30:00-05:00
description: Virtual
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.greenlightbookstore.com/event/great-gatsby-feat-min-jin-lee-jennifer-buehler
images: []
---
<file_sep>/content/event/hampton-library-summer-author-series.md
---
title: 'Hampton Library Summer Author Series: Fridays at Five '
date: 2018-08-24 17:00:53 -0400
images: []
description: 'Pachinko: <NAME> in Conversation with <NAME>'
link: http://www.hamptonlibrary.org/about-us/friends-of-the-library/156-fridays-at-five/1716-august-24-min-jin-lee-with-bill-mccuddy
show_time: true
venue:
address: 2478 Main Street
city: Bridgehampton
name: Hampton Library in Bridgehampton
state: 'NY '
zip: 11932
---
<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-2.md
---
title: 'Hollywood Reporter: ''Pachinko'' Picked Up to Series at Apple'
date: 2019-03-14 00:50:11 -0400
link_to_original: https://www.hollywoodreporter.com/live-feed/pachinko-picked-up-series-at-apple-1194524
images:
- "/uploads/soo_hugh__pachinko_cover_split.jpg"
tags: []
categories: []
description: '"Sources say the eight-episode drama — the third show from <NAME>''s
Media Res — is among the biggest budgeted productions the iPhone maker has in the
works."'
---
<file_sep>/content/event/m-i-t.md
---
title: M.I.T. Starr Forum Series
date: 2018-10-30 20:30:00 +0000
images: []
description: 'In Conversation with Dr. <NAME>. Sponsored by MIT Starr Forum,
Migration Seminar, Center for International Studies, Japan Program, Korea Program,
and Women''s Studies. '
link: https://calendar.mit.edu/event/starrforum_Pachinko?utm_campaign=widget&utm_medium=widget&utm_source=MIT+Events+#.W6_LqhNKgUF
show_time: true
venue:
address: 'MIT Building 10-250 '
city: 50 Vassar Street, Cambridge
name: 'M.I.T. Starr Forum '
state: MA
zip: ''
---
A book talk with <NAME> and <NAME>.<file_sep>/content/news/2017-12-13-chicago-tribune.md
---
title: Chicago Tribune
date: 2017-12-13 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Chicago Tribune
link_to_original: >-
http://www.chicagotribune.com/suburbs/burr-ridge/news/ct-dch-column-clarkson-tl-1221-20171213-story.html
description:
---
Books for Reading and Gifting, By <NAME>
"Pachinko" by <NAME> is a novel which starts early in the 20th century. A pregnant out-of-wedlock young Korean woman with no husband in sight agrees to marry a sickly minister who will go to Japan. There she must settle in without language, culture or the comfort of being among her own people. The long, absorbing story follows to great acclaim.
For the remainder of the article, please click the link.
<file_sep>/content/event/the_collegiate_school.md
---
title: The Collegiate School
date: 2007-10-23T06:00:00-05:00
venue:
name: The Collegiate School, New York
link: www.collegiateschool.org
_slug: the_collegiate_school
---
Private Event
<file_sep>/content/news/2017-06-05-esquire-magazine-best-books-of-2017-so-far.md
---
title: 'Esquire Magazine: Best Books of 2017 (So Far)'
date: 2017-06-05 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Esquire Magazine
link_to_original: 'http://www.esquire.com/entertainment/books/a52733/best-books-of-2017/'
description:
---
Pachinko made the list, edited by <NAME>.
For the full review, please click on the link below.<file_sep>/content/event/ridgewood-nj.md
---
title: Ridgewood, NJ
date: 2019-04-03 06:37:58 +0000
images: []
description: ''
link: https://www.ridgewoodlibrary.org/friends
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/proskauer.md
---
title: Proskauer
date: 2017-05-31 18:00:00
show_time: true
venue:
name: Proskauer
address: 11 Times Square
city:
state:
zip:
link:
---
Private Event<file_sep>/content/news/buzzfeed-26-books-that-make-you-want-to-book-a-trip-asap.md
---
title: 'Buzzfeed: 26 Books That Make You Want to Book A Trip ASAP'
date: 2018-08-01 18:22:34 -0400
link_to_original: https://www.buzzfeed.com/cieravelarde/book-me-a-trip-to-singapore?utm_term=.xrL8po57N#.svl2OeYDg
images: []
tags: []
categories: []
description: By <NAME>
---
<file_sep>/content/news/new-york-times-breaking-my-own-silence.md
---
title: 'The New Yorker: "Stonehenge"'
date: 2019-06-03T02:00:00-04:00
categories:
- Media
tags:
- Essays
attribution:
link_to_original: https://www.newyorker.com/magazine/2019/06/10/stonehenge
description: '"In their attractive, polished faces, I saw that Stonehenge was as familiar
to them as having a gun held to my face was to me." '
---
> [https://www.newyorker.com/magazine/2019/06/10/stonehenge](https://www.newyorker.com/magazine/2019/06/10/stonehenge "https://www.newyorker.com/magazine/2019/06/10/stonehenge")<file_sep>/content/news/2007-04-24-usa_today1.md
---
title: "USA Today"
date: 2007-04-24T23:16:00-05:00
categories: ["News"]
tags:
- Excerpts
attribution: "USA Today"
link_to_original: "http://www.usatoday.com/life/books/excerpts/2007-04-24-free-food_n.htm"
description: ""
_slug: 2007-04-24-usa_today1
---
As a capable young woman, <NAME> felt compelled to choose respectability and success. But it was glamour and insight that she craved. ...
<file_sep>/go.mod
module github.com/theNewDynamic/minjinlee.com
go 1.14
require (
github.com/theNewDynamic/hugo-component-tnd-blocks v0.0.0-20200618163712-a1fce85c0c7b // indirect
github.com/theNewDynamic/hugo-layout_module-base v0.0.0-20210503172815-58d023fa7345 // indirect
github.com/theNewDynamic/hugo-layout_module-books v0.0.0-20190815205753-3dfb6f6b9b30 // indirect
github.com/theNewDynamic/hugo-layout_module-events v0.0.0-20190603181923-82d7a9938c40 // indirect
github.com/theNewDynamic/hugo-module-tnd-addtocal v0.0.0-20210705134130-f2c26969ad03 // indirect
github.com/theNewDynamic/hugo-module-tnd-books v0.0.0-20210521150338-185a66c15d43 // indirect
github.com/theNewDynamic/hugo-module-tnd-env v0.0.0-20210512181247-90dd1a287016 // indirect
github.com/theNewDynamic/hugo-module-tnd-events v0.0.0-20220622184014-3c80033e6e9f // indirect
github.com/theNewDynamic/hugo-module-tnd-forms v0.0.0-20210529224822-8d04dbda8558 // indirect
github.com/theNewDynamic/hugo-module-tnd-func v0.0.0-20210316194241-a6d99cfae5a6 // indirect
github.com/theNewDynamic/hugo-module-tnd-headers v0.1.4 // indirect
github.com/theNewDynamic/hugo-module-tnd-icons v0.1.7 // indirect
github.com/theNewDynamic/hugo-module-tnd-imgix v0.2.2 // indirect
github.com/theNewDynamic/hugo-module-tnd-media v0.0.0-20220330175441-4aeb80c7e616 // indirect
github.com/theNewDynamic/hugo-module-tnd-menus v0.0.0-20210322205111-03cfde5da487 // indirect
github.com/theNewDynamic/hugo-module-tnd-netlifycms v0.1.80 // indirect
github.com/theNewDynamic/hugo-module-tnd-redirects v1.2.4 // indirect
github.com/theNewDynamic/hugo-module-tnd-scripts v0.0.0-20220225163825-dcd4d76a127f // indirect
github.com/theNewDynamic/hugo-module-tnd-seo v0.1.10 // indirect
github.com/theNewDynamic/hugo-module-tnd-socials v0.1.5 // indirect
github.com/theNewDynamic/hugo-module-tnd-styles v0.7.4 // indirect
github.com/theNewDynamic/hugo-module-tnd-tags v0.0.0-20210820151839-aaac3b65c97e // indirect
)
<file_sep>/content/news/2017-03-03-popmatters-an-interview-with-min-jin-lee.md
---
title: 'POPMATTERS: An Interview with <NAME>'
date: 2017-03-03 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: popmatters.com by <NAME>
link_to_original: 'http://www.popmatters.com/column/world-unfair-place-interview-min-jin-lee/'
description:
---
BY <NAME>
3 March 2017
<NAME>’S NOVEL PACHINKO IS A MULTI-GENERATIONAL LOOK AT THE LITTLE-KNOWN PLIGHT OF KOREANS LIVING IN JAPAN.
(GRAND CENTRAL PUBLISHING)
<br>US: FEB 2017
Anyone familiar with Japan will know that Pachinko—the title of a new novel by Korean American author <NAME>—is a type of adult gambling game, a unique cross between video lottery terminals and pinball. The garish, high-tech machines are ubiquitous throughout the country; as an industry it dwarfs the Japanese auto sector.
For Lee, it’s also a reflection of life.
“You really can’t walk down the street or enter a single train station or go anywhere in Japan without seeing a pachinko parlour,” she explains. “And yet the middle class view this adult gambling game with enormous suspicion and a kind of contempt. When I interviewed all these pachinko parlour owners about how they messed around with the pins every single day to affect the payout, it occurred to me that pachinko is a rigged game. It isn’t gambling, it’s rigged. The house is going to win. And yet people still play! I think—and this is my little cynicism—that the world is an unfair place and yet we continue to play, and we continue to show up. We have to.”
Life is rigged against some more than others, and Koreans living in Japan have historically faced daunting odds. Lee tackles the historical oppression of Koreans in Japan by chronicling the fictional history of one family from its struggles in Japanese-occupied Korea at the beginning of the 20th century, through to a poignant conclusion in 1989 Tokyo.
Lee first started thinking about the book in 1989, when she attended a college lecture by an American missionary who’d worked with Koreans in Japan. As a history major, she knew plenty about Japan’s colonization and occupation of Korea in the first half of the century, but she was shocked to discover how little she knew about the plight of Koreans living in Japan. From discrimination in employment to lack of civil and political rights, to institutionally-supported bullying and harassment, the experience of the roughly 600,000 Koreans living in Japan attains a degree of suffering many are unfamiliar with.
“The missionary mentioned a story… he said that he worked with this one family which had a little boy who was 13 years old, and he had gone to the top of a department building and he had jumped off to his death. Which was really shocking. His parents were obviously very very troubled by this, and they went through his things. They found his middle school yearbook, in which his classmates who were also 13-years-old had said things like ‘You smell like garlic and we hate you’ and they said the words ‘Die! Die! Die!’ That story just really stayed with me.”
The sad episode makes its way into Pachinko, where one of the characters—Haruki, a police officer—is the one who must grapple with the tragedy of a young boy’s suicide. But for Lee it also inspired a desire to learn more about the experience of Koreans living in Japan, and the difficulties they encountered.
“I mean there was no way to learn about this at the time. It wasn’t taught anywhere,” she explains. She graduated college and went to law school, going on to practice as an attorney for two years. “But I really couldn’t get that story out of my head, and so I started doing more research, and then I decided I would write a novel, about the Korean Japanese community.”
Shifting from a successful career as an attorney to a struggling career as a writer wasn’t easy. She began working on what would later become Pachinko, but eventually shifted her attention to another novel, which she completed but was unable to get published. In 2007 she finally published her first novel, Free Food for Millionaires, about the experience of Korean Americans.
But the story of the young boy’s tragic death in Japan continued to haunt her. “The idea that someone could hate you so much, and that the people who could hate you are children! And that hatred can become manifest in a wish to die if you internalize that hatred—that really stayed with me. That [feeling] I think is in this book in other ways.”
Discrimination Resonates
In the ensuing years, Lee expanded her research on the Korean Japanese experience. She lived in Japan from 2007 to 2011 and conducted dozens of interviews. Meeting Koreans in Japan, going to their homes and workplaces and hearing their family stories, proved an important complement to the research she had been doing.
“It was really, really eye-opening because I realized that all the academic work that I had done for research, all that was accurate, but it didn’t really have a sense of truth about how people live their lives when things go wrong in the world. I think that when you have bad governments or really difficult situations which are so completely out of your control, when your country’s divided [like Korea’s split into North and South]… if that kind of situation happens, what do you do? And most of the time, what I learned is that people just try to get water and shelter and food and take care of their families and maybe if they’re lucky they try to educate their children.”
What also struck Lee, as she struggled to educate herself on the experience of the Korean Japanese community, was how unfamiliar other Koreans were with the issue.
“Most Koreans I know who are Korean American are unfamiliar with it. I think people are constantly surprised by it.”
Yet the experience of discrimination among minority immigrant communities, she says, resonates with many Americans.
“At the same time I’ve been having a lot of responses from people who read Pachinko and they tell me ‘Oh you know this is how Jewish people feel, this is how black people feel, this is how people from Armenia feel.’ There are so many groups around the world that have felt excluded and marginalized because of their birth despite all their attempts to assimilate and be a proper whatever.”
Lee, who describes her husband as half-Japanese and her son as a quarter Japanese, emphasizes that the book is not anti-Japanese, but that it does aim to tackle the homogenizing force of what she describes as monoraciality.
“I really love Japan and I liked living there very much, and there are so many terrific things about Japan. However, I do think what’s amazing is that Japan really prides itself on being monoracial. It doesn’t have the same kind of idea as in the UK or Canada or the United States, in which the idea of diversity is a strength. It’s not a weakness. So even today there’s an enormous amount of political rhetoric by the current [Japanese] administration to make sure that foreigners—and Koreans, no matter how many generations [they lived in Japan], are considered foreigners—are not included in the discussions. There is, I think, almost no effort really to talk about what happened in the past. It’s considered something really shameful, and that’s true.”
“It’s tragic, because pretty much if you meet any Korean Japanese person, they’re trying so hard to assimilate and trying to be decent Japanese. They want very much to be proper Japanese people because essentially they have no contact with Korea. They don’t know how to speak Korean, some of them have never been to Korea, and [Japan is] all they know. Everything is tied to the land of Japan.”
Koreans in Japan face a double-edged form of discrimination, notes Lee—they experience discrimination from the Japanese and Korean state alike. She depicts this in the novel too when, after the end of the Second World War, Japanese Koreans struggle with the decision about whether to go back to Korea. Some do return to their ancestral homeland, but others are deterred by experiences of discrimination against those who had lived in Japan.
“[T]hey’ll kill you in the North, and they’ll starve you in the South,” Hansu, a Korean, warns his employee Kim who’s considering going back after the war. “They all hate Koreans who’ve been living in Japan.”
Lee’s characters aren’t exaggerating. After the war, Japanese authorities encouraged the American occupation forces to deport all the Koreans. Former South Korean dictator Park Chung-hee, meanwhile, told Koreans living there to stay in Japan and not to return. Lee observes that there’s a complex dimension to immigration politics whereby countries will often point to instances of discrimination by other countries while perpetuating the same attitudes within their own borders.
“[There’s a] hypocrisy that so many people commit when they complain about trying to get rights from the host country - the alleged host country - because their own country of origin often has terrible immigration or cultural policies against outsiders,” she says, observing that the sentiment expressed in her novel continues to this day. “So the Koreans in Korea right now are very hostile to Korean Japanese people. Sometimes even to Korean Americans!”
Storytelling Against Racism
Lee feels that at its core, racism boils down to a fear of the other, whether the other happens to be a different gender, nationality, or ethnicity. She feels that research and data are important tools in fighting the spread of racism and discrimination, but admits that a lot of people simply aren’t willing to accept the facts around the benefits of diversity, when those facts conflict with their deep-seated fears of the other.
It’s here that Lee believes the power of the storyteller comes in—the ability to touch readers on a deeper level and humanize the ‘other’ in a way that is needed in today’s world more than ever. For her, this is one of the most compelling aspects of literature.
“These problems are so big for all of us, and I guess each person approaches it from whatever he or she knows how to do. I think the humanization aspect of storytelling has been very persuasive for me. English is not my first language, so when I came to America and I started to read about <NAME> of Russia, Anna became human to me. If I had only had the experience of Vladimir Putin, that would be a different experience of what I would think about Russia! Or if I think about <NAME>… people in the West have become human to me because I was able to read this literature.
“Right now I live in Harlem, and when I read authors like <NAME>, it’s a very very different Harlem when I think about <NAME> and his Harlem, or <NAME> and his Harlem, versus the Harlem that I live in today. It’s almost like having a sixth sense because there’s a narrative in addition to the scientific information, that’s more palpable to us.”
In addition to the politics of race and nationalism, there’s a very strong gender dimension to Pachinko. Sunja, the character whose life spans the bulk of the book, is a woman whose varied struggles over the years reflect many of those faced by Korean women in Japan, from misogyny within the family and breadwinning husbands who resist their wives’ efforts to earn money, to sexual harassment and assault. One tragic young female character runs away from home, becomes a sex worker and eventually dies of HIV-related illness.
Lee identifies proudly as a feminist and admits she grappled with presenting a literary depiction of the Korean adage that women’s lot is to suffer.
“They’re either oppressed through poverty or they’re oppressed because of their race. We don’t have the history of poor men. What happens to your gender, or the idea of your gender, if you are an oppressed male? That’s very interesting to me… I think that when men are saying certain things, it’s a reflection of the fact that they might feel that their masculinity is being threatened. I mean today women cannot drive in Saudi Arabia. Even today! But then again there are women that I know in New York City who have five thousand times more rights than some men. So I do think that we have to have a global understanding of feminism.”
One of the most interesting characters in the novel is Haruki. He appears as a young boy who’s bullied in school and is taken under the wing of Mozasu, a hot-tempered Korean child who’s also bullied and who befriends the young Japanese boy. Haruki grows up to be a police officer… and a closeted gay man. Unlike the Koreans in the novel, he doesn’t have to grapple with his ethnic background. But he does find himself alienated and struggling because of his sexuality. What inspired Lee to include this compelling character?
“Because it was very important to me to be fair. I think that so many people in Japan suffer as a result of the harmony that they have in society… It’s an extraordinary thing in Japan to see the kind of harmony and thoughtfulness about the way society can work. However, it can be very very oppressive if you’re not the mode that is acceptable to the majority. If you are different, if you are LGBT, if you are disabled, if you are an ‘other’ from the majority, if you are a mother let’s say and you want to work, or if you’re infertile… there are so many different classes of people that are not accepted by the majority! And they live in shame and they live in exclusion. That was so sad.”
“So it was very important to me to include them in this book. Because it isn’t so binary, where you have ‘oh the Japanese are evil’ and ‘the Koreans are victims.”
“It’s not like everybody’s perfect just because you’re in an oppressed class.”
Writing Korean Japanese Lives
Lee has been surprised by the positive reaction the book has garnered. What surprises her, she says, is that people connect to it. She understands the political urgency of works that deal with refugees and immigration, but her surprise stems from the fact that the plight of the Korean Japanese has been deliberately downplayed and ignored for so long.
“I think that there’s only one book in fiction written by a Korean Japanese person that’s been translated into English, Gold Rush by Yu Miri. There’s an excerpt of a memoir—an excerpt, not the whole book—that’s been translated into English called Zainichi by Kang Sang-Jun. There are maybe forty to fifty volumes of academic work, which are just amazing, about the Korean Japanese. But it’s impossible to find fiction and memoirs! I thought to myself, it’s because nobody cares… So it’s amazing to see this response.”
Of all the characters in the book, her favourites are two of the men: Hansu and Noa. Hansu is a smooth-talking yakuza, or gangster, of Korean origin who has been adopted into his wife’s Japanese crime family. His morality is ambiguous, driving him to terrible acts of cruelty yet also generous support of other Korean immigrants. Noa is his illegitimate son, who grows up to reject and despise his Korean background, seeking to assimilate as a Japanese.
“I love Hansu because he’s so real. He has such vitality. He has such confidence. Even though he’s wrong, and he’s immoral, there’s an honesty about his wish to survive. I found that really telling. In the opposite way, I loved Noa too, because he was so principled, even though he was so inhumane in the end. I thought the thing that drove him to be acceptable and clean and pure and Japanese ultimately destroyed him. That was really interesting to me too, because I think all of us have that part of us that wishes to be accepted by being really really good at something.”
Struggling for Self-Worth as a Writer
Developing a writing career hasn’t been easy for Lee. She quit her law career in 1995 and didn’t succeed in publishing her first novel until 2007. Nor could she afford to pursue graduate work in creative writing, like some aspiring American writers do. Instead, she attended writers’ talks and took occasional inexpensive classes, cobbling together her own learning program, and struggling to get into print at the same time.
“It’s tough… I literally have a binder full of rejections from journals. The very very best journals in the world have rejected me. But you know everybody pays their dues. I didn’t have early success, but I don’t know. Maybe I’d be a jerk if I did.”
Lee’s strength has always been her perseverance, she says. Growing up, she says her two sisters were always quicker and sharper than her, and consistently beat her at games and other activities. Her father reassured her, telling her they were the rabbits or hares in the family, and she was the tortoise.
“I guess I still really see myself as this kind of tortoise,” she laughs. “I’m kind of plodding and I’m kind of slow but I’m very steady and I just keep going. I don’t see myself as this kind of quick person. But … I do finish what I start.”
The hardest part of those years of struggling to get into print, she says, was justifying herself to others, and the humiliation she felt in the face of her increasingly successful friends and peers.
“I wanted to be good at this, but writing a novel isn’t something that you can learn in a class. It’s something you just have to do. Writing manuscripts takes time. Writing manuscripts that are worth reading takes even more time. So for me, this is how long it took. The parts that were really difficult were having to explain why I didn’t have anything to show. Because people are very kind and they would ask ‘Oh, what do you do?’ And you kind of mumble, ‘I’m a writer.’ But are you a writer if you haven’t published? I would argue now vehemently—of course you are! You’re writing! You’re a writer if you’re writing. But I think that that’s really hard to say with a straight face to a lot of people, especially a lot of successful people in New York.”
“Sometimes I would go somewhere as a guest and somebody would say ‘Oh, what do you do?’ I would say, ‘Oh, well I’m working on a book…’ They’d go ‘Oh, okay.’ And they would literally turn around and talk to somebody else. Then you would just go to the bathroom and cry. I mean what else could you do?”
What inspired a successful lawyer to abandon her career and throw herself into the unpredictable pursuit of a writer’s life? One of the factors that forced Lee to review her priorities was a serious liver disease that she’d suffered from since high school. Although she’s now healthy thanks to treatment, the potentially fatal illness loomed large throughout her 20s and 30s.
“Illness is very clarifying,” she says. “When I was working as an attorney I was working these very unreasonable hours. I thought to myself, if I were to die in my twenties or thirties, if I can’t get a liver transplant, then how do I want to say I spent my time? I think it was very easy for me to say, I can live with a lot less.”
“I know people have said this before elsewhere, and I believe it so very much, which is that I think it’s important to choose the important over the urgent. So whenever I have any kind of trial, I just ask myself, what’s really important? What feels really urgent? Sometimes paying that bill feels really urgent. You should pay your bills! But there are also things that are really important. You could choose to live your life in a certain way which honours your values and sometimes that will affect the way that you spend your money or the way that you spend your time. Aas I get older, it’s really time that’s the most important thing. Spending my time in a way that aligns with my sense of values.”
Writing Is a Tough Road to Trvel
While she’s happy with her own choices, Lee is quick to point out the writing life is not for everyone, either.
<br>
<br>“I have to be honest about this, I wouldn’t tell a lot of kids to go and be writers. It’s a tough, tough business. It’s not a business. It’s more like a tough road. It’s a really tough road.”
It’s even tougher for Asian American writers, she notes.
“I think it’s not an accident that you don’t have that many Asian American women writers who are breaking out. I don’t think it’s an accident that you don’t have that many Asian American writers, either women or men. I don’t think that immigrants are encouraged to become artists. That’s very gendered and racialized and ethnicized. It’s not even just money, because in east Asia and southeast Asia and south Asia, our cultures aren’t encouraging women to speak about their stories. So it’s taken me a long time to say, ‘Okay, well this is what I’ve seen and I think it’s so worthwhile that I’m going to try to get it in print.’ I mean that’s an act of audacity, for somebody from my background!”
“I think what’s really sad is this idea of tokenization,” she says. “I’ve been very fortunate that I’ve been on a lot of lists in the US, for most anticipated novel or whatever, and I notice that very often there’s [only] one Asian. I know for a fact that there are three or four [novels by Asians] that month that came out that are pretty good. I wonder, was there some decision, like ‘Well we can have one, but we can’t have three’? Is that a media decision? Is that a publishing decision? I don’t know. Or is it even a reader decision? Maybe people don’t want that many. I think people have to consider it or at least have to start talking about it. But it makes everybody really uncomfortable.”
For those aspiring writers who do commit themselves, Lee offers a bit of advice: focus on telling a story that matters to you, not on marketing yourself.
“Always remember the work. When I meet young writers, very often they’ll ask me ‘How do I get an agent?’ and ‘How do I break into the business?’ I’ll say, ‘Well, are you reading? What are you reading? Who do you like? Who do you want to write like? What kind of stories do you want to have on your desk that you feel so compelled by that you return to it again and again even if it makes no sense?’”
“Very often I hear writers tell me ‘Oh, I’m going to work on this subject.’ It’s a subject that’s sexy and interesting, and I’ll say ‘Well, how does it relate to you?’ Very often there isn’t a connection. So in a way we’ve become a bit too oriented on crowd-sourcing, on being market-oriented. Maybe that works, but maybe it doesn’t. Because in order to make anything really good you have to rewrite it a few times. In order for you to continue with it, it must be something that resonates with you almost body and soul. Because it really makes no sense to suffer so much for any other reason.”
Lee intends to turn her work on the Korean experience into a trilogy. Her first book, Free Food for Millionaires, focused on the experience of Koreans in America, and her second book Pachinko focuses on Koreans in Japan. Her third, she says, will be titled American Hagwon.
“Hagwon is a Korean word for cram school… American Hagwon is about the role for Koreans in education around the world. It’s almost a toxic idol… Education is a beautiful, liberating thing, but I think that tying in education and status and the need to do well at every cost, is toxic.”
“That’ll be my trilogy of Korea, and then next I’m going to start writing about wizards or something,” she laughs.
<NAME> is a writer and editor based in Eastern Canada. He's a columnist, writer and opinions editor with the online news magazine TheIndependent.ca. His work has appeared in a range of other publications both print and online, from Briarpatch Magazine to Feral Feminisms. In addition to a background in radio-broadcasting, union organizing and archaeology, he's currently completing a PhD in Gender, Feminist & Women's Studies in Toronto. He can be reached by email at <EMAIL> or @hansnf on Twitter.<file_sep>/content/event/loyola_marymount_university.md
---
title: Loyola Marymount University
date: 2007-11-02T20:00:00-05:00
venue:
name: Loyola Marymount University, Los Angeles, CA
link:
_slug: loyola_marymount_university
---
Media Migrations: Gender, Representation and Cultural Movement(s)
Time: 3-4.30PM
Moderator and Discussant: <NAME>, Ph.D. Dept. of African American Studies
<NAME>, Ph.D. Dept. of English, USC
<NAME>, Doctoral Student, Department of American Studies and Ethncity, USC
<NAME>, Author of Free Food for Millionaires
<file_sep>/content/news/2017-02-01-book-of-the-month-club-selection.md
---
title: Book of the Month Club Selection
date: 2017-02-01 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Book of the Month
link_to_original: 'https://www.bookofthemonth.com/pachinko-203'
description:
---
Pachinko is the February Selection of the historic Book of the Month Club founded in 1926 . Serving as judge, author of *Queen of the Night* and *Edinburgh*, <NAME> writes:
Reading Pachinko was, in many ways, personal to me, at first. My own family is from one of these small fishing islands off the coast of Korea, and this novel’s beginning was like getting to spy on my grandparents’ early lives. It introduced me to their struggles in ways they would never have—and yet, let me be clear, this novel does much more than to break an intergenerational silence. It also makes their era’s history accessible to American readers in new and marvelous ways.
The writing is remarkable—the tone never wavers, the prose is flinty and clear. The first line: “History has failed us, but no matter.” What follows is this masterpiece Lee has written, a captivating family drama that is also a sweeping epic spanning the unknown (to most of us) history of the two countries for most of the twentieth century. It’s also the story of a woman fighting fiercely for her life and her children, in the midst of poverty, war, and unbearable odds.
Most of us do not know the story of Koreans in Japan; people who came to Japan with high hopes, but who find they are treated as second class citizens –unable by law to own property, subject to discrimination and mockery, a stateless minority. Pachinko sets its story there, beginning in the early 1900s with one Sunja Baek, who becomes pregnant after a short affair with a married man, the son of a rich family. Seeking a better life abroad in Japan she leaves Korea in the company of a sympathetic pastor, as his wife. Japan is a land of opportunity in the minds of Sunja and her Korean countrymen, and they don’t anticipate the hardships that await them in their new home.
The result is a big novel to lose yourself in or to find yourself anew—a saga of Koreans living in Japan, rejected by the country they call home, unable to return to Korea as wars and strife tear the region apart. The result is like a secret history of both countries burst open in one novel. I hope you love it like I did.
— <NAME><file_sep>/content/event/asia_society.md
---
title: Asia Society - May 22nd, 2007
date: 2007-05-22T19:30:01-05:00
venue:
name: Asia Society
link: www.asiasociety.org/events/calendar.pl
_slug: asia_society
---
Meet the Author : <NAME>: Free Food For Millionaires
Conversation with <NAME>, Executive Director of the National Book Foundation
Auditorium, Asia Society and Museum, 725 Park Ave, New York
Cost: $7 students w/ID/seniors; $10 members; $12 nonmembers
<file_sep>/content/event/south-main-book-company.md
---
title: South Main Book Company
date: 2018-02-06 18:00:00
show_time: true
venue:
name: South Main Book Company
address: 110 South Main St.
city: Salisbury
state: NC
zip: '28144'
link:
---
<file_sep>/content/news/2017-08-04-sydney-morning-herald.md
---
title: Sydney Morning Herald
date: 2017-08-04 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Sydney Morning Herald
link_to_original: >-
http://www.smh.com.au/entertainment/books/pachinko-review-min-jin-lees-saga-of-koreans-in-japan-is-hard-to-put-down-20170727-gxk6aw.html
description:
---
By <NAME>
"Pachinko is a book that has the amplitude of the technique that is resolutely social realist but encompasses peasant women and bright boys in New York arguing about George Eliot. But Lee's key to the whole sideshow is the Korean/Japanese relation. Pachinko insinuates itself as the Homer of this landscape, it arrogates to itself a right to present the life of the Korean who is dirt under Japanese feet, driven to the dark corners of dodginess in a context of ancient virtue and a diagrammatic simplicity of technique.
Pachinko is a massive attempt, full of subtlety and strategy, to universalise the Korean experience by showing it with its nose pressed to the glass of history. The novel it has most affinity with both in terms of deliberate populism and its very intelligent stab at a latter-day Tolstoyanism is Vikram Seth's A Suitable Boy. Both books slum their way towards the highest possible acclaim."
For the complete review, please click the link below.<file_sep>/content/event/new-american-festival.md
---
title: 'The New Yorker Festival: American Identity'
date: 2019-10-13T11:00:00-04:00
show_time: true
venue:
name: Directors Guild Theatre
address: 110 West 57th Street
city: New York
state: New York
zip: "10019"
link: https://festival.newyorker.com/tickets/my-american-identity/
description: With <NAME>, <NAME>, <NAME>, and Ocean Vuong. Moderated
by <NAME>.
images:
- "/uploads/Screen Shot 2019-09-05 at 1.43.30 PM.png"
---
<file_sep>/content/event/medici-prize-.md
---
title: 'Los Angeles—The Literary Affairs Medici Foundation: The Beverly Hills Literary
Escape '
date: 2018-11-02 12:30:58 +0000
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: http://literaryaffairs.net/donate
description: 'Attending authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Moderated by <NAME>. Tickets:
$500 Donation to the Medici Foundation, $450 of which is tax deductible. '
---
<file_sep>/content/event/amherst-college-22.md
---
title: One Book One Community
date: 2020-02-20T17:00:00.000+00:00
show_time: true
venue:
name: <NAME>son Prairie Center for the Arts
address: '201 Schaumburg Ct., '
city: Schaumburg
state: IL
zip: "60193"
link: ''
description: ''
images: []
---
<file_sep>/content/event/texas-book-festival.md
---
title: Texas Book Festival 2017
date: 2017-11-03 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Friday, Saturday & Sunday, November 3-5, 2017
Austin, Texas
Lit Crawl: Saturday
Panel: Sunday<file_sep>/content/event/nantucket-mitchells-book-corner.md
---
title: "Nantucket: Mitchell's Book Corner"
date: 2017-08-08 10:30:00
show_time: true
venue:
name: "Mitchell's Book Corner"
address: 54 Main Street
city: Nantucket
state: MA
zip: '02554'
link: 'http://www.mitchellsbookcorner.com'
---
Reading & Book Signing<file_sep>/content/event/new_canaan.md
---
title: New Canaan, Connecticut
date: 2008-04-16T05:28:01-05:00
venue:
name: New Canaan Library, Connecticut
link: www.newcanaanlibrary.org
_slug: new_canaan
---
ELM STREET BOOKS at THE NEW CANAAN LIBRARY
151 Main Street
7.30PM
Please note that both the date and venue have been changed.
<file_sep>/content/news/2018-02-01-a-new-essay-appears-in-the-guardian.md
---
title: A new essay appears in The Guardian
date: 2018-02-01 12:00:00
categories: ["Media"]
tags:
- Essays
attribution:
link_to_original: >-
https://www.theguardian.com/commentisfree/2018/feb/12/north-south-korea-koreans
description:
---
> With the Winter Olympics in full swing, the big story is the Koreans, in particular the presence in Pyeongchang of <NAME>-un’s younger sister. It is said that analysts have been scrutinising <NAME>’s hair, makeup, dress, cheekbones, everything in microcosm. But few know very much about any of us.
["North good, south bad? Time to shed the Korea stereotypes"](https://www.theguardian.com/commentisfree/2018/feb/12/north-south-korea-koreans) appeared in *The Guardian* on February 12th, 2018.<file_sep>/content/review/kirkus-on-pachkinko.md
---
title: Kirkus on Pachkinko
attribution: _Kirkus_ (Starred Review)
date: 2017-03-11 17:46:23 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Deeply compelling story. An old-fashioned epic whose simple, captivating storytelling delivers both wisdom and truth.<file_sep>/content/event/newtown-literary.md
---
title: 'Newtown Literary Alliance: Fiction Writing Class'
date: 2018-04-21 14:30:00
show_time: true
venue:
name: Lewis H. Latimer House Museum
address:
city:
state:
zip:
link: 'https://www.newtownliterary.org/writingclasses'
---
"Writing on Race & Immigration"
A free 1 day class for writers in Queens, sponsored by Newtown Literary Alliance and the NYC Department of Cultural Affairs.
Contact: <NAME>, Executive Director and Founding Editor
<file_sep>/content/news/2017-12-14-the-millions-a-year-in-reading-2017.md
---
title: 'The Millions: A Year In Reading 2017'
date: 2017-12-14 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Millions
link_to_original: 'https://themillions.com/2017/12/year-reading-vanessa-hua.html'
description:
---
By <NAME>
We live in a time when immigrants, people of color, refugees, women, disabled people, LGBT people, the poor, and others in the margins are denied their stories—and denied their humanity. Reading about lives different than our own is an act both of empathy and resistance. In my year of reading, I found the following books by women deeply moving and illuminating.
For the complete article, please click the link.<file_sep>/content/event/brooklyn-ny.md
---
title: 'BAM: Eat, Drink & Be Literary'
date: 2019-05-01 18:30:00 -0400
images:
- "/uploads/edbl-2019-613x463.jpg"
description: Moderated by <NAME>, Fiction Editor of The New Yorker
link: https://www.bam.org/programs/2019/eat-drink-and-be-literary
show_time: true
venue:
address: Lepercq Space / Peter Jay Sharp Building
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/video-are-koreans-human-at-radcliffe-institute-for-advanced-study-at-harvard-university.md
---
title: 2019 DeMott Lecture at Amherst College (VIDEO)
date: 2019-09-01T00:50:11-04:00
link_to_original: https://www.youtube.com/watch?time_continue=517&v=ch1FIKfFw7k
images:
- "/uploads/2019_0901_Orientation_JL_3416_820x547.jpg"
tags:
- Media
- news
- video
categories: []
description: ''
---
[https://www.amherst.edu/news/news_releases/2019/9-2019/to-all-the-other-new-kids-](https://www.amherst.edu/news/news_releases/2019/9-2019/to-all-the-other-new-kids- "https://www.amherst.edu/news/news_releases/2019/9-2019/to-all-the-other-new-kids-")<file_sep>/content/review/san-francisco-chronicle-on-free-food-for-millionaires.md
---
title: San Francisco Chronicle on Free Food for Millionaires
attribution: San Francisco Chronicle
date: 2007-03-11 18:16:24 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
The Five-Forty-Five to Cannes (Crown) by <NAME>; Free Food for Millionaires (Warner) by <NAME>; The Gathering (Black Cat/Grove) by Anne…<file_sep>/content/event/book-soup.md
---
title: Book Soup
date: 2018-01-31 19:00:00
show_time: true
venue:
name: Book Soup
address: 8818 Sunset Boulevard
city: West Hollywood
state: CA
zip: '90069'
link: 'http://www.booksoup.com'
---
<file_sep>/content/news/2017-12-27-read-it-forward-favorite-books-of-2017.md
---
title: 'Read It Forward: Favorite Books of 2017'
date: 2017-12-27 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Read It Forward
link_to_original: 'http://www.readitforward.com/monthly-favorites/rifs-favorite-books-of-2017/'
description:
---
By <NAME>
PACHINKO
After the turn of the last century, a Korean family finds itself in disgrace when their beloved daughter Sunja winds up pregnant by her deceitful, gangster lover. When Sunja gets a surprising marriage offer from a minister, she accepts, and travels with him to Japan to start over. But things aren’t much easier in Japan for Sunja and her family. Over the course of the century, we follow the family’s saga as they open pachinko parlors—a national obsession that became an addiction for many players, and made good money for the parlor owners. The family struggles with their Korean identity in Imperial Japan, but they experience moments of joy, too. A beautiful book that feels somewhat Tolstoyan—profound yet utterly sink-into-able. (Grand Central)
For the complete list, please click the link.<file_sep>/content/event/down-town-association.md
---
title: Down Town Association
date: 2017-05-09 18:30:00
show_time: true
venue:
name: Down Town Association
address: 60 Pine Street
city: New York
state: NY
zip: '10005'
link: 'http://www.thedta.com'
---
In Conversation with <NAME>.
<NAME> lived in Japan for 14 years, as a teacher of English at colleges and language schools. Her main passion is ikebana, having just received her Riji certification, the highest level in Sogetsu Ikebana, and the Sogetsu Overseas Akane Teshigahara Award. Her second current passion is genealogy in the DAR.<file_sep>/content/event/ragdale-novel-affair.md
---
title: 'Ragdale: Novel Affair'
date: 2018-04-27 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
April 27-28, 2017<file_sep>/content/news/2017-02-23-foyles-bookstore-interview-on-uk-publication-day-for-pachinko.md
---
title: 'Foyles Bookstore: Interview on UK Publication Day for PACHINKO'
date: 2017-02-23 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: Foyles UK
link_to_original: 'http://www.foyles.co.uk/Public/Biblio/AuthorDetails.aspx?authorId=85821'
description:
---
Where did you get the idea for the story?
In 1989, I was at university, and I read History. One day, I skipped class and attended a lecture featuring an American missionary who worked with the Korean-Japanese population in Japan. The missionary discussed the very troubled history of Koreans in Japan, which I’d known nothing about. He said that in the community that he served, there was a 13 year-old Korean-Japanese boy who had been bullied relentlessly because of his ethnic status. He climbed up to his apartment building roof and jumped to his death. The boy and his parents were born in Japan. I never forgot this story.
Why do you think there are not more books telling the stories of Koreans in Japan? Or perhaps there are and they have not been translated into English?
There is awkwardness, ambivalence, controversy, and or shame in discussing the Korean-Japanese history in Japan. Due to the discrimination that the Korean-Japanese continue to face today, many Korean-Japanese will not discuss their ethnic background openly. In Japan, it is considered rude to ask a direct question about one’s ethnicity. The comparison in the West would be like asking a person’s religion, socio-economic background or sexual orientation, especially if there is a history of or present-day discrimination against the group to which he or she belongs. There are films and books about the Korean-Japanese community in Japanese. However, they are virtually unknown in the West. I do not know of a single work of fiction devoted to the Korean-Japanese written originally in English. I know of one Korean-Japanese novelist (<NAME>) whose works are available in translation.
Why did you choose to call your book Pachinko? The game obviously plays an important role in the novel and to Koreans in Japan, but were you also making a more general statement about luck and perhaps fate?
Pachinko is an adult gambling game involving a vertical pinball machine. The game became very popular after World War II. As of 2014, pachinko generates annual revenues of about 19 trillion yen, which is about $190 billion U.S. at the current exchange rate, or about twice the export revenues of the Japanese car industry. About one out of every seven Japanese adults plays pachinko regularly. Although ethnic Japanese started the pachinko business, in its near-century presence in Japan, a great number of ethnic Koreans have operated pachinko parlors and have been involved in every aspect of the business. Despite the strict regulatory involvement of the police and government authorities in the past twenty-five plus years, the Japanese continue to view the pachinko industry and the people involved with suspicion and hostility. Nearly every Korean-Japanese person I met in Japan had some historical or social connection, however close or far, with the pachinko business — one of the very few businesses in which Koreans could find employment and have a stake. For me, the pachinko business and the game itself serve as metaphors for the history of Koreans in Japan — a people caught in seemingly random global conflicts — as they win, lose, and struggle for their place and for their lives.
Your characters are all-too-human and make all-too-human mistakes. How hard did you find it not to judge them?
When I research my novels, I interview my subjects extensively, much like the way a long-form journalist works, which allows me to spend time with people who are like my characters. With the passage of time and with greater personal intimacy, I find that I care deeply for my interview subjects, who stand in for some of my characters. In that way, I find that I am not objective like a journalist. Consequently, I find it impossible to judge my characters in a neutral way. However, I think my primary task as a fiction writer is to be very truthful about the emotional lives of people. Fiction can allow greater truth because the characters are not human, and therefore there is less need to hide. Readers are generous, and I think if readers get accurate context and motivation through plot, point of view and characterization, they accept and appreciate the narrative outcomes.
Did you identify more with any one character and if so, why?
Of all my characters, I found Hansu compelling in a way that surprised me. He is a gangster and a violent criminal, but he is also a philosopher who is determined to survive and win a very unfair game, and I found his behaviour and outlook fascinating. Hansu’s love and need for Sunja is foundational to this book. He loves her and needs her because he longs for home and for the person he once was. Love, stripped down to its essence, is like that, I think.
The Koreans’ sense of displacement extends for many generations. Would it have made a difference had they been more welcome in Japan?
Welcoming strangers and successful integration can make an extraordinary difference in the lives of individuals and communities. I doubt there’s a sociologist, anthropologist or psychologist who would disagree. Segregation, legal and social discrimination and economic disparity can impair normal human development. Factors like poverty, early childhood suffering, family breakdown and war can devastate anyone and any nation. That said, I was astonished by the people, who survived such conditions, and how they fared in the face of their persistent rejection. Above all, I was impressed by the quality of their love for their families, communities and the nation where they lived.
Your own family moved from South Korea to the US in 1976. Does it, will it ever, feel like home to you?
The United States is home to me. It is not perfect in the West, but the West is often more generous in their immigration and social policies than many home countries of immigrants. Very often, foreigners criticize the unfair policies of Western nations, but their nations of origin often have extraordinarily unwelcoming policies toward refugees from nearby countries. This is a vexing conundrum. I recognize that all things are not equal and there are myriad factors in each nation’s immigration policies; however, in my family’s experience, we have been welcomed in the United States, and we are naturalized American citizens.
Do you agree with Kazu that being ‘mediocre’ is the worst thing a person can be?
I disagree with Kazu. All of us are mediocre at some things and exceptional in others. Kazu stands for a kind of person who sees the world in a binary way, and for him, mediocrity is terrifying. Being binary can be helpful in making simple decisions, because you exclude other factors; however, being binary is basically delusional or short-sighted at best because real life cannot be explained as choice A or B. In addition, most everyone starts out at something being fairly awful then perhaps luckily arrives at mediocrity; after a decade or so, with great perseverance, he or she becomes rather good at something. Sometimes, I find that very successful people forget that they were born in a wonderful family or a stable nation or were born with the good luck of having desirable height, beauty or good memory. I think the idea of choice is very important, but I think it is cruel to think that one can choose every aspect of one’s destiny.
What research did you have to do for the book and how far did it determine the fate of your characters – or was the broad sweep of their lives already in place from the outset?
I started out reading the relevant works of anthropologists, historians, sociologists and legal scholars, then I wrote a manuscript. However, when I lived in Japan from 2007-2011, I was able to interview dozens of Korean-Japanese people. My interviews made me realize that my initial manuscript was flawed because I had focused on the facts rather than the stories of the people. I rewrote another full manuscript, and I know this book would not have been in existence unless I had interviewed and travelled so extensively in Japan.
I was struck by how many of the dilemmas your characters face as ‘aliens’ are still relevant today to many ethnic groups around the world: how far to preserve their manner of dress, what they eat, their style of speech, and so on, in order to be accepted by the host country. Does this make you feel pessimistic, or do you think there are still ways to achieve some kind of integration without severing ties with one’s roots?
I’m not a pessimistic person. That said, I think what you are pointing out is historically and factually correct. At present, there are 65 million refugees in the world. Although human beings now live in perhaps the best time in evolutionary history in terms of technological advances and life expectancy, most people in developed countries do not feel that it is the best of times. In a scientific sense, things are great; however, things are truly not great for all. Technology has caused great disruptions as well as great advances for society. We also live with increasing political and economic disparity. Economists and political scientists argue with strong evidence that foreigners can do great things for nations; however, integration, as we all know, is uncomfortable for everyone. As human beings, we like those who are like us and fear those who are not like us — this is evolutionary behaviour. Nevertheless, I believe that we are also curious, sentient, complex moral beings who have evolved beyond self-interest and tribalism. I know we’re not going to win over everyone on this point; however, I think more of us want to try to understand, imagine and share so all of us can flourish.<file_sep>/content/event/pen-pals--friends-of-the-hennepin-county-library-ii--morning-.md
---
title: 'Pen Pals: Friends of the Hennepin County Library II (Morning)'
date: 2018-10-26 15:00:58 +0000
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: https://www.supporthclib.org/min-jin-lee
description: ''
link: https://www.supporthclib.org/min-jin-lee
---
<file_sep>/content/news/2007-05-09-livingreadgirl.md
---
title: "Livingreadgirl"
date: 2007-05-09T22:08:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Livingreadgirl"
link_to_original: "http://livingreadgirl.blogspot.com/2007/05/on-shelf-with-min-jin-lee.html"
description: ""
_slug: 2007-05-09-livingreadgirl
---
My thanks to <NAME>,for giving me her time and thoughts for this interview. Free Food For Millionaires will be available everywhere and if you would like to know more about <NAME> and her work,please visit her official website by ...
<file_sep>/content/event/pen-america-series-at-the-strand.md
---
title: Pen America Series at the Strand
date: 2017-12-11 18:30:00
show_time: true
venue:
name: Strand Bookstore
address: 828 Broadway
city: New York
state: NY
zip:
link: 'http://www.strandbooks.com'
---
Feminist Retrospective of the Year Past: With <NAME>, <NAME> and <NAME><file_sep>/content/event/boston-university.md
---
title: Boston University
date: 2019-01-24 18:00:59 -0500
images: []
description: ''
link: ''
show_time: true
venue:
address: Kilachand Hall, Kilachand Commons
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/variety-netflix-alan-yang-developing-min-jin-lee-s-free-food-for-millionaires-for-tv.md
---
title: 'Variety: Netflix, Alan Yang Developing Min Jin Lee’s ‘Free Food for Millionaires’
for TV'
date: 2021-01-27T00:50:11-05:00
link_to_original: https://variety.com/2021/tv/news/min-jin-lee-free-food-millionaires-alan-yang-netflix-1234892665/
images: []
tags: []
categories: []
description: ''
---
> "'Tigertail' filmmaker and 'Master of None' co-creator [Alan Yang](https://variety.com/t/alan-yang/) is teaming up with author <NAME> to adapt her critically acclaimed 2007 novel '[Free Food for Millionaires](https://variety.com/t/free-food-for-millionaires/)' as a television series, _Variety_ has learned exclusively. Lee is penning the screen adaptation, with Yang serving as non-writing executive producer."<file_sep>/content/writing/new-york-times-breaking-my-own-silence.md
---
title: 'The New Yorker: Stonehenge'
date: 2019-06-03T06:00:13.000+00:00
categories:
tags: []
where_published: The New Yorker
link_to_original: https://www.newyorker.com/magazine/2019/06/10/stonehenge
link_to_pdf:
description:
_slug: '2019-06-03T06:00:00.000+00:00'
---
"In their attractive, polished faces, I saw that Stonehenge was as familiar to them as having a gun held to my face was to me."<file_sep>/content/news/2017-02-14-lithub-5-books-making-news-this-week.md
---
title: 'LITHUB: 5 Books Making News This Week'
date: 2017-02-14 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: LitHub by <NAME>
link_to_original: 'http://lithub.com/five-books-making-news-this-week-death-dystopia-and-depression/'
description:
---
By <NAME>
<NAME>’s second novel is a multigenerational saga of a Korean family that spans most of the 20th century. Critics compare her to <NAME> and Dickens.
<NAME> (NPR) writes, “We are in Buddenbrooks territory here, tracing a family dynasty over a sprawl of seven decades, and comparing the brilliantly drawn Pachinko to <NAME>’s classic first novel is not hyperbole. Lee bangs and buffets and pinballs her characters through life, love and sorrow, somehow making her vast, ambitious narrative seem intimate.”
“Lee is an obvious fan of classic English literature, and she uses omniscient narration and a large cast of characters to create a social novel in the Dickensian vein,” writes <NAME> (USA Today). “Her protagonists struggle with the whims of history, with survival and acceptance in a land that treats even native-born Koreans as foreigners . . . ”
“Pachinko is about outsiders, minorities and the politically disenfranchised,” notes <NAME> (New York Times Book Review). “But it is so much more besides. Each time the novel seems to find its locus—Japan’s colonization of Korea, World War II as experienced in East Asia, Christianity, family, love, the changing role of women—it becomes something else. It becomes even more than it was. Despite the compelling sweep of time and history, it is the characters and their tumultuous lives that propel the narrative.”<file_sep>/content/news/2017-05-25-the-times-literary-supplement-podcast.md
---
title: 'The Times Literary Supplement: Podcast'
date: 2017-05-25 12:00:00
categories: ["News"]
tags:
- Reviews
- Audio
- News
attribution: The Times Literary Supplement Podcast
link_to_original:
description:
---
I had the chance to speak with <NAME> and <NAME> about the books I reviewed for The Times Literary Supplement on its wonderful podcast. The segment on the literature about North Korea begins on 25.01.
Freedom, Books, Flowers & the Moon: May 25
With <NAME> and <NAME> – TLS Philosophy editor <NAME> grapples with the mind-body problem and “what it means to be the kind of creatures we are”, plus the year that brightened Nietzsche’s outlook, and Biscuit the dog’s self-consciousness; Korean American author <NAME> on how Korean literature approaches the difficult dream of reunification and what a new collection of stories, The Accusation by the pseudonymous author “Bandi”, “the first work of fiction written by a North Korean author presumed still to be alive and living in the country”, tells us about life in that deeply mysterious land; finally, the great Alasdair Gray, author of Lanark, reads “From Vers Doré by <NAME>”, a new work first published in this week’s TLS.
To listen to the podcast, please click on the link.<file_sep>/content/writing/2007-03-22-axis_of_happiness.md
---
title: "Axis of Happiness"
date: 2007-03-22T17:45:45-05:00
categories:
tags: ["Short Stories"]
where_published: "Narrative Magazine"
link_to_original: "http://www.narrativemagazine.com/shared/prize.php"
link_to_pdf: "/uploads/lee.pdf"
description: "Axis of Happiness won the 2004 Narrative Prize from Narrative Magazine."
_slug: 2007-03-22-axis_of_happiness
---
THE MORNING HENRY EVANS stoppedby my office to tell me to go to Chicago, I was in the middle of my chapter-a-day habit: still in the Book of Hosea, much to my dismay, still in the Old Testament after years of dogged reading.
This habit required skimming the day's chapter of the Bible (usually the length of one onion-skin page ) , then reading the extensive commentaries in the footnotes, then finally reading the chapter again - all of this took on average of forty - five minutes. I did this at work because it was where I lived - fourteen hours a day, often six days a week. I couldn't help knowing some of the Bible because I was a P.K. (preacher's kid), but I'd started reading this fat copy of the NIV Study Bible with its elephant-gray leather cover because my mot h e r left it for me along with her modest wedding jewelry when she died three years ago.
I hadn't always liked being around my mother while she was alive . For years she'd suffered from rheumatoid arthritis. The chronic pain had given her pale, square face a kind of pinched, sour expression. The parishioners at my father's church called my mother a saint, and I suppose she wa s. But as her daughter, I didn't feel like I knew her very well, because she was so busy serving others. When I was a girl - eldest of four, the only girl, and the only one born in Korea - while my mot her cooked our dinners, made meals for bedridden parishioners, and folded the endless loads of laundry my brothers and I generated, I talked on the phone with my friends and read piles of library books. She left me alone to do my schoolwork because I wa s a very good student - the hope of academic greatness in my family. When she was growing up in a small town outside of Seoul, she had to drop out ofhigh school to work; there wasn't even enough money for the oldest son to finish school, that's how bad it was.
But she was always studying, trying to improve herself. "Increase your talents," she'd say. In the States, she worked on her English by reading People magazine, listening to NPR on the kitchen radio, and practicing on us kids. But her l's still sounded like r's, her f's became p 's, and she routinely dropped her d's. In private, my brothers and I mimicked her, and it wa s divine justice that on occasion, when I was especially nervo u s, I caught myself saying things l i ke"ko-pi" for coffee, referring to fried chicken as "Ken-tucky," or forgetting a particle in a sentence. These slips happened to my American-born brothers too, and Ben, the younge st and the funny one, would scan the room, looking like a scout with his right hand shielding his eyes, and say, "Is mom here?" We made fun of her behind her back, but we never q u e stioned the clarity of her thinking. When I talked back to her, she'd snap at me, "Yo u think you're so smart from reading all those books, but how smart can you be if you've neve r e ven read the Bible from front to back?"
Of course, there was nothing I could say to this - to dismiss this type of argument, I'd have to read the book.
My mother and father based their lives on a single idea: Salvation comes from the Lord . My father's cousin, who was an artist, had written this in hangul with a calligraphy brush on a verticalrice-paper banner. When youwa l ked into my parents' living room, the fi r st thing you saw was that banner hung next to a framed needlepoint of Jesus' face.
I figured out early that I didn't want their life - it was a hard, thankless existence with few comforts. But I couldn't reject their religion either. By the time I was grown, I'd had Pascal's wager drummed into me: What if God did exist and I was wrong in assuming that He didn't? So I hedged my bets, as they say, and stayed out of trouble. Each Sunday, I went to church with my husband and our infant daughter, tithed our pre-tax income, paid our live-in nanny's social security and health benefits, and was scrupulous in all my dealings.
About Christianity: I felt certain that God existed, that the historical person Jesus Christ was His son, and that I'd be saved if I believed that God's son redeemed me through His death and resurrection. The logic of redemption was satisfying, and I was willing to make the necessary leap of faith. But how can I say this?
I didn't feel much for God, and I certainly didn't want to deal with Him. Sure, I would do what He said, but I didn't have to like Him.
He loved me - I had read this, and of course, had sung it, heard sermons to this effect, but I think I believed it too because it made rational sense to me; after all, I was part of His creation - you have to love your children.
But was He interested in me?
No. I didn't buy that.
My mother's neat block- style Korean letters crowded the margins of her English-language Bible. The Book of Hosea only has fourteen chapters, but her marginalia nearly matched its length. In her tiny handwriting, it was as if I could see her. Late at nights, she'd usually be seated at the kitchen table with her right hand holding a cheap ballpoint pen at the ready to underline or bracket a passa ge - and with her left hand, she'd be twirling her bifocals slowly to and fro as if keeping the meter of a fine piece of music. After she finished her reading, I would catch her mumbling her prayers in Korean - hushed and breathless words mingled with tears as she called out to God. She was so contrite - her head bent low, her hands folded in a tight fist. She appeared so penitent for her small sins, which I imagined to be innocent, like gossip or pride - none of the biggies like murder or adultery. At the end of the first chapter of Hosea, she had written, "How could He want so much, and how can I offer Him so little?" Of course I found her piety annoying.
Yet there I wa s, in my spacious office in Manhattan onthe thirty- fifth floor ofa glassy skyscraper, reading her Bible behind closed doors. (I never told anyone that I did this because I had these rules: never discuss religion and never proselytize. That was my father's j o b.) When I traveled on business, I carried her Bible in my enormous purse and read it in my hotel room. This daily reading had started out as a kind of intellectual discipline - no different than when I studied Greek and Latin at Harvard. But I ke pt reading because I sensed that something might come of it - nothing like a gold star from a Sunday school teacher, but something significant, like some new feeling or wisdom - and even if nothing came of it, if I ever saw my mother again, then I'd at least have the last word. So there. Each day, after I read my chapter, I'd close the book and wait for a few seconds for something to happen - a call to prayer or some burst of feeling. But nothing. I didn't feel anything new, and I found that I didn't have anything to say to God.
It was only ten o'clock. I'd just slogged through a tedious letter agreement, and for breakfast I'd bought some pretzels and my second diet Coke of the day from the vending machine. I hadn't slept much the night before, or for the past ten months, ever since my daughter, Leah, was born. I asked Karen to put my calls through voice mail. (My sixty one-year-old secretary who swam laps before work was forever on my case telling me to put my head down for half an hour: "You're going to kill yourself if you don't sleep and eat b ett e r," she'd say, then she'd order orange juice with my lunch instead of the iced coffee that I'd asked for). So there I wa s, reading about the prophet Hosea and his rotten luck. To illustrate His own suffering, the Almighty tells Hosea to marry a faithless slut, who proceeds to bet r ay him. I was absently following the allegorical meaning of the circumstance when I heard a boom.
<NAME>, the managing partner of <NAME>, and the New York god of corporate securities, a.k.a. <NAME>, had a funny knock. Boom. It was literally one knock. I shoved the hefty Bible into the secret space I'd made for it in my top desk drawer. I grabbed a pen and pretended to write something down, and I said, "Hi, Henry," without even glancing up. Only he could have gotten past Karen.
Henry took off his Malcolm X eyeglasses and pinched the bridge of his nose together with his thumb and forefinger - he did this when his eyes were tired. He put his glasses back on and looked at me with pity.
"What?" I said. He was taking in the full glory of what must 've been the worst I'd ever looked in the ten years we'd worked together.
"Never mind," he said, as if he'd thought better of it.
<file_sep>/content/news/babe-ruth-the-beastie-boys-e-mail-follies-and-romance-for-today-our-staffers-recommend-the-best-reads-of-2018.md
---
title: '<NAME>, the Beastie Boys, e-mail follies, and romance for today: Our staffers
recommend the best reads of 2018'
date: 2018-12-11 16:34:21 -0500
link_to_original: http://www2.philly.com/entertainment/best-books--20181211.html
images: []
tags: []
categories: []
description: '"<NAME> nominates this sprawling, emotional saga of a Korean
family over four generations, exquisitely written and almost universally admired."'
---
<file_sep>/content/event/little-city-books.md
---
title: Little City Books
date: 2018-03-14 19:00:00
show_time: true
venue:
name:
address: 100 Bloomfield Street
city: Hoboken
state: NJ
zip:
link: 'http://www.littlecitybooks.com'
---
In Conversation with <NAME><file_sep>/content/event/brisbane-writers-festival-pachinko-with-min-jin-lee.md
---
title: 'Brisbane Writers Festival: Saturday PACHINKO with author <NAME>'
date: 2017-09-09 13:00:00
show_time: true
venue:
name: Auditorium 1
address:
city:
state:
zip:
link: 'http://uplit.com.au/festival/brisbane-writers-festival-2017/program/pachinko'
---
<file_sep>/content/event/amherst-college-10.md
---
title: 'Seattle Arts & Lectures: <NAME> - Rescheduled'
date: 2020-03-17T23:30:00.000+00:00
show_time: true
venue:
name: <NAME>
address: 200 University St
city: Seattle
state: WA
zip: "98101"
link: https://lectures.org/event/min-jin-lee/
description: ''
images: []
---
<file_sep>/content/news/2017-03-25-winnipeg-free-press-book-review.md
---
title: Winnipeg Free Press (Book Review)
date: 2017-03-25 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Winnipeg Free Press
link_to_original: 'http://www.winnipegfreepress.com/arts-and-life/entertainment/books/emotional-roots-of-korean-familys-story-resonate-417078664.html'
description:
---
Koreans in Japan search for success in Lee's sumptuous sophomore novel
Reviewed by: <NAME>
<br>Posted: 03/25/2017
<NAME>’s Pachinko could be called a sweeping family drama. It effortlessly carries the reader through generations, outlining its changing historical context without sacrificing the juicy details.
The novel is the Korean-American author’s second, after 2007’s bestselling Free Food for Millionaires, which focused on the Korean immigrant experience in America. Some of Pachinko’s many Korean protagonists gesture at emigrating to the U.S., but none do: Pachinko stays anchored closer to home.
For readers unfamiliar with Korean history, Pachinko offers an enjoyable primer. The novel begins in 1910 in a small fishing village in the south where Sunja, the much-beloved only daughter of a local innkeeper, is seduced by an older man and (shamefully) becomes pregnant. Sunja is "rescued" by a tubercular, northern Korean missionary named Isak, who marries her and whisks her off to Osaka, Japan.
Most of the story’s subsequent action takes place in Japan through the difficult years of the Depression and the Second World War, and the beginnings of prosperity in the second half of the century.
Lee is enormously skilled at enfleshing the bones of history: Sunja’s family members and friends are each given life in a few strokes. Though the cast of characters is large, it does not feel overwhelming. Sensual details about food and homes, clothing and money, neighbourhoods and livelihoods are lavishly provided. The reader will quickly traverse Pachinko’s vast scope but feel unhurried on the journey.
At its core, Pachinko is a narrative about success. The novel’s name comes from a Japanese arcade game used for gambling, in which the player attempts to navigate a series of pins and capture little steel balls that can be exchanged for valuable prizes. In Lee’s novel the game isn’t used only as a metaphor: some of the Korean characters work in pachinko parlours. But for them, success is a haunting, elusive dream.
Following Japan’s annexation of Korea in 1910, Korean immigrants faced incredible difficulties in Japan due to racial discrimination. Even the wealthiest of migrants were forced to live in slums and denied health insurance and good jobs. All migrants — and their descendants, including those born and raised in Japan — were required to register as Korean residents in Japan.
But when Sunja and Isak arrive in Japan, they are hopeful: "Yes, life in Osaka would be difficult, but things would change for the better. They’d make a tasty broth from stones and bitterness. The Japanese could think what they wanted about them, but none of it would matter if they survived and succeeded."
There is strength in numbers, they reason: if the family can grow, it will ultimately thrive.
It does grow, but Sunja remains Pachinko’s heart. Some of the novel’s most compelling ideas emit not from its historical roots but its emotional ones; the notion of motherhood offers the story a complex mythos. Sunja’s connection to her children is primal, but rife with suffering, or "go-saeng," when misfortune befalls them:
"Go-saeng — the word made her sick. What else was there besides this?… Should she have taught her son to suffer the humiliation that she’d drunk like water?… Did mothers fail by not telling their sons that suffering would come?"
In many ways Pachinko’s women suffer more than its men: the latter might be tortured by discrimination, but the resulting suffering is theirs only. The women carry their own suffering as well as that of their children, in ever-expanding generational rings.
But readers won’t carry suffering too heavily, because Lee doesn’t — she lets it fall into context, then proceeds. Life is dynamic: in Pachinko, it carries on, rich and wondrous.
<NAME> is a Winnipeg writer.<file_sep>/content/event/brooklyn-launch.md
---
title: Brooklyn Launch at Greenlight Bookstore
date: 2017-02-08 19:30:00
show_time: true
venue:
name: Greenlight Bookstore
address: 686 Fulton Street
city: Brooklyn
state: NY
zip: '11217'
link: 'http://www.greenlightbookstore.com'
---
In Conversation with <NAME>. Harold is Franke Visiting Fellow at the Whitney Humanities Center of Yale University. For twelve years, he was Executive Director of the National Book Foundation, presenter of the National Book Awards. He has translated, among other works, <NAME>úñ<NAME>’s *Chronicle of the Narváez Expedition* and the Filipino novelist José Rizal’s *Noli Me Tangere* and *El Filibusterismo*. In 2012, the University of Texas Press published his co-translation (with Ilan Stavans) of *The Plain in Flames* by <NAME> and in 2013 Penguin Classics published his edition of the *Collected Poems of Marcel Proust*. He is currently carrying out a research project on the business of translation in the United States under a grant from the Andrew W. Mellon Foundation. In 2015, Concordia College in Moorhead, Minnesota awarded him the degree of Doctor of Humane Letters, *honoris causa*.<file_sep>/content/writing/the-times-literary-supplement---fictions-of-north-korea-.md
---
title: 'The Times Literary Supplement: "Fictions of North Korea"'
date: 2017-05-24 00:57:50 -0400
images: []
image_credit: ''
categories: []
where_published: The Times Literary Supplement
link_to_original: https://www.the-tls.co.uk/articles/private/north-korea/
description: ''
---
<file_sep>/content/event/ewha_university.md
---
title: EWHA UNIVERSITY
date: 2009-06-12T03:16:00-05:00
venue:
name: EWHA WOMANS UNIVERSITY, SEOUL, SOUTH KOREA
link: www.fsel.org
_slug: ewha_university
---
The Korean Association for Feminist Studies in English Literature (KAFSEL) and The Society for Multi-Ethnic Studies: Europe and the Americas (MESEA)
International Conference: WOMEN, DISPLACEMENT AND CULTURAL IDENTITY
June 12-13, 2009
EWHA WOMANS UNIVERSITY, Seoul, South Korea
Ewha Campus Complex (ECC), Room B142
June 12, 2009, Friday
Special Colloquy: 1:00-2:30PM
“Women Writing in/of Displacement”
Chair: <NAME>, (Ewha Womans University)
Professor, Department of English, Director of Ewha English Program Office and Editor-in-Chief, FEMINIST STUDIES IN ENGLISH LITERATURE
Discussant: Me-<NAME> (Ewha Womans University)
<NAME> (Poet) (SUNY Buffalo): “Diaspora, Gender and the Translingual Condition”
<NAME> (Novelist): “Reticence and Field Work: On Writing the Sexual Lives of Asian Women; or How I Learned to Tell the Truth Through Fiction”
<file_sep>/content/news/2017-05-29-bookpage-12-best-novels-of-immigrants-and-refugees.md
---
title: 'BookPage: 12 Best Novels of Immigrants and Refugees'
date: 2017-05-29 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: BookPage
link_to_original: 'https://bookpage.com/the-book-case/21418-trend-report-12-best-novels-immigrants-refugees#.WTNm_RTAeqQ'
description:
---
By Cat, the Deputy Editor of BookPage
In recent years, we’ve seen an uptick in stellar novels of the immigrant experience—from Behold the Dreamers to Americanah, from The Book of Unknown Americans to The Buddha in the Attic—and 2017 continues that trend, with an even greater emphasis on refugees’ tales. It seems every month so far this year has offered a handful of stories that give a voice to the displaced, the fishes out of water, the strangers in strange lands. These are 12 of our favorites.
Lucky Boy by <NAME>
Fans of The Light Between Oceans will enjoy the moral dilemmas and tremendous heart of Sekaran’s second novel, the story of one boy tangled up in two families. When Soli, an illegal Mexican immigrant, is put in immigration detention, her 1-year-old son, Ignacio, enters the foster care system. He is placed with Kavya and Rishi Reddy, successful Indian-American immigrants. But as much as they may love him, Ignacio is not their son. Read our review.
Pachinko by <NAME>
Already one of the best books of the year, this multigenerational epic from Lee (Free Food for Millionaires) is a powerful account of one of the world’s most persecuted immigrant communities—Koreans living in Japan. This heartbreaking historical novel spans the entire 20th century through four generations and three wars, as a Korean family struggles to find a sense of belonging in a culture that regards them as aliens. Read our interview with Lee.
American Street by <NAME>
Don’t mind the YA label: Adult readers should read Zoboi’s debut as well as teens. <NAME>, an American citizen by birth, is separated from her Haitian mother while going through Customs, and so she must travel by herself to Detroit, where her American cousins introduce her to a very new world. It’s an unforgettable story of what happens when cultures, nationalities, races and religions collide. Read our interview with Zoboi.
Waking Lions by <NAME>
The chilling and provocative debut from Israeli author Gundar-Goshen opens with a hit-and-run, when Israeli neurosurgeon Eitan Green accidentally kills an illegal Eritrean immigrant. The victim’s wife, the enigmatic Sirkit, blackmails Eitan into treating sick Eritreans in the desert. With ruminations on pain and medicine woven throughout, this is a superb exploration of how we see—or fail to see—each other. Read our review.
Exit West by <NAME>
Hamid adds a dash of gentle magic to his tale of refugees and matters of the heart. In a Middle Eastern country on the brink of civil war, Nadia and Saeed fall in love. But soon they must flee their ruined homeland, passing through a doorway that acts as a portal to another city. As they journey around the world, the bonds of love are both forged and tested by displacement and survival. A must-read for 2017. Read our review.
The Leavers by <NAME>
Ko’s timely, assured debut received major critical acclaim before it was even published, as <NAME> awarded it the 2016 PEN/Bellwether Prize for Fiction (given to a novel that addresses issues of social justice). It’s the coming-of-age tale of 11-year-old Deming, who is adopted by a pair of white professors after his mother, an undocumented Chinese immigrant, doesn’t return from work one day. Read our review.
No One Can Pronounce My Name by <NAME>
That wry title is only a glimmer of the wonderful sense of humor that permeates the second novel from Satyal. The lives of three Indian Americans living in Ohio unfold with compassionate comedy and a nuanced look at sexuality and gender identity. It’s hard to categorize a book that tackles so many things so well, and the result can only be described as the new American novel. Read our review, and don’t miss our Q&A with Satyal.
Salt Houses by <NAME>
Alyan’s debut is a sweeping family tale told through multiple perspectives, and it all begins with the Six-Day War in 1967, when the Yacoub family is uprooted and forced to scatter across the globe. Alyan’s own parents met in Kuwait City and, after <NAME>’s invasion, were forced to seek refuge in the United States. This spectacular novel, touching on questions of home and heritage, was our May Top Pick in Fiction. Read our review.
Live from Cairo by <NAME>
Bassingthwaighte tapped his own experiences as a legal aid worker to craft his debut, set in 2011 Cairo. Four characters are at the heart of this remarkable novel: an Iraqi refugee who is denied her request to join her husband in the U.S.; the Iraqi volunteer assigned to her case; a lawyer for the Refugee Relief Project; and his translator. There is so much to like about this book, from brilliant characterization to exceptional writing. Coming July 11.
Refuge by <NAME>
Nayeri moved to America when she was 10 years old, and the protagonist of her second novel makes a similar move, except she leaves her father behind. Over the course of 20 years, the daughter and father build a relationship through four visits, each in a different city. The more their lives diverge, the more they come to rely on each other—especially when the daughter becomes involved in the present-day refugee crisis. Coming July 11.
What We Lose by <NAME>
Perfect for fans of Americanah, the much-anticipated debut from Clemmons unfolds through poignant vignettes and centers on the daughter of an immigrant. Raised in Philadelphia, Thandi is the daughter of a South African mother and an American father. Her identity is split, and when her mother dies, Thandi begins a moving, multidimensional exploration of grief and loss. Coming July 11.
Home Fire by <NAME>
From acclaimed novelist Shamsie comes the story of two Muslim sisters: Isma, who has just left London to attend grad school in America; and the headstrong, politically inclined Aneeka, who stayed behind. Their brother, Parvaiz, is seeking his own dream in the shadow of his jihadist father. And then the son of a powerful political figure enters the girls’ lives, setting in motion a tale of complicated loyalty. Coming August 15.
Plus one more: It’s not a novel, but we have to mention <NAME>’s exceptional collection of short stories, The Refugees. The nine stories, set within California’s Vietnamese community or in Vietnam, are dedicated to “all refugees, everywhere.”<file_sep>/content/event/cosmopolitan_club_february_26.md
---
title: Cosmopolitan Club, February 26, 2008
date: 2008-02-26T12:00:00-05:00
venue:
name: Cosmopolitan Club, New York
link:
_slug: cosmopolitan_club_february_26
---
Private Event
<file_sep>/content/event/princeton-theological-seminary.md
---
title: Princeton Theological Seminary
date: 2018-04-08 18:00:00
show_time: true
venue:
name: McKay Campus Center Lecture Hall
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/book_club_new_york_city.md
---
title: Book Club, New York City
date: 2008-03-27T05:45:00-05:00
venue:
name: Book Club, New York City
link:
_slug: book_club_new_york_city
---
Book Club: FREE FOOD FOR MILLIONAIRES
Host: <NAME>
Private Event
<file_sep>/content/news/2007-05-01-people_magazine.md
---
title: "People Magazine"
date: 2007-05-01T22:54:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "People Magazine"
link_to_original: ""
description: ""
_slug: 2007-05-01-people_magazine
---
<file_sep>/content/event/cuny-citytech-conversation-with-dr-dionne-bennett.md
---
show_time: true
title: 'CUNY Citytech: Conversation with Dr. <NAME> - Rescheduled'
date: 2020-03-26T18:00:00-04:00
description: ''
venue:
address: 285 Jay Street
city: Brooklyn
name: CUNY Citytech Academic Complex
state: NY
zip: "11201"
link: ''
images: []
---
<file_sep>/content/news/2008-05-05-at_the_asia_society.md
---
title: "<NAME> at the Asia Society"
date: 2008-05-05T13:07:00-05:00
categories: ["Media"]
tags:
- Video
attribution: "Asia Society Video"
link_to_original: "http://video.google.com/googleplayer.swf?docid=6065302396975086085&hl=en"
description: ""
_slug: 2008-05-05-at_the_asia_society
---
The Author of "Free Food for Millionaires" talks to <NAME>
<embed id="VideoPlayback" style="width:400px;height:326px" flashvars="" src="http://video.google.com/googleplayer.swf?docid=6065302396975086085&hl=en" type="application/x-shockwave-flash">
<file_sep>/content/event/denis-johnson-reading.md
---
title: 'Denis Johnson Tribute Reading:'
date: 2018-01-17 18:30:00
show_time: true
venue:
name: Strand Bookstore
address:
city:
state:
zip:
link:
---
<NAME>, <NAME>, and <NAME> will read from Johnson's THE LARGESSE OF THE SEA MAIDEN (stories)<file_sep>/content/news/2017-12-20-san-francisco-chronicle-top-10-books-of-2017.md
---
title: 'San Francisco Chronicle: Top 10 Books of 2017'
date: 2017-12-20 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: San Francisco Chronicle
link_to_original: 'http://www.sfchronicle.com/books/article/Top-10-books-of-2017-12445398.php'
description:
---
Pachinko is one of the 5 fiction titles selected in Top 10 Books of 2017.
Pachinko, by <NAME> (Grand Central; 490 pages; $27). Lee’s sweeping four-generation saga of a Korean family is an extraordinary epic, both sturdily constructed and beautiful.
— <NAME>
For the complete list, please click the link. Thank you.<file_sep>/content/news/2007-07-31-radio_new_zealand.md
---
title: "Radio New Zealand"
date: 2007-07-31T23:35:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "Radio New Zealand"
link_to_original: "http://www.radionz.co.nz/popular/ books/ninetonoon/reviews/books_july_2007"
description: ""
_slug: 2007-07-31-radio_new_zealand
---
Nine To Noon ...
by <NAME> (Hutchinson, ISBN 9780091796181)
<file_sep>/content/news/vogue-korea-july-2021.md
+++
categories = []
date = 2021-06-26T04:50:11Z
description = ""
images = ["/uploads/style_60fa698e2fdd1.jpg"]
link_to_original = "https://www.vogue.co.kr/2021/07/26/%ED%95%9C%EA%B5%AD%EA%B3%84-%EC%86%8C%EC%84%A4%EA%B0%80-4%EC%9D%B8/"
tags = []
title = "Vogue Korea: July 2021"
+++
<file_sep>/content/news/2016-09-26-kirkus-reviews-starred-review.md
---
title: 'Kirkus Reviews: Starred Review'
date: 2016-09-26 21:17:00
categories: ["News"]
tags:
- Reviews
attribution: Kirkus Reviews
link_to_original: 'https://www.kirkusreviews.com/book-reviews/min-jin-lee/pachinko/'
description:
_slug: 2011-06-20-free_food_for_millionaires_is_junot_diazs_summer_reading_pick_at_the_new_yo
---
An absorbing saga of 20th-century Korean experience, seen through the fate of four generations.
Lee (Free Food for Millionaires, 2007) built her debut novel around families of Korean-Americans living in New York. In her second novel, she traces the Korean diaspora back to the time of Japan’s annexation of Korea in 1910. “History has failed us,” she writes in the opening line of the current epic, “but no matter.” She begins her tale in a village in Busan with an aging fisherman and his wife whose son is born with a cleft palate and a twisted foot. Nonetheless, he is matched with a fine wife, and the two of them run the boardinghouse he inherits from his parents. After many losses, the couple cherishes their smart, hardworking daughter, Sunja. When Sunja gets pregnant after a dalliance with a persistent, wealthy married man, one of their boarders—a sickly but handsome and deeply kind pastor—offers to marry her and take her away with him to Japan. There, she meets his brother and sister-in-law, a woman lovely in face and spirit, full of entrepreneurial ambition that she and Sunja will realize together as they support the family with kimchi and candy operations through war and hard times. Sunja’s first son becomes a brilliant scholar; her second ends up making a fortune running parlors for pachinko, a pinball-like game played for money. Meanwhile, her first son’s real father, the married rich guy, is never far from the scene, a source of both invaluable help and heartbreaking woe. As the destinies of Sunja’s children and grandchildren unfold, love, luck, and talent combine with cruelty and random misfortune in a deeply compelling story, with the troubles of ethnic Koreans living in Japan never far from view.
An old-fashioned epic whose simple, captivating storytelling delivers both wisdom and truth.<file_sep>/content/news/dayton-literary-peace-prize.md
---
title: Dayton Literary Peace Prize, 2018 Runner-Up in Fiction Acceptance Speech (Video)
date: 2018-10-28 19:00:37 -0400
link_to_original: http://www.daytonliterarypeaceprize.org/2018_files/videos/Fiction-runner-up.htm
images:
- "/uploads/Screen Shot 2018-11-21 at 6.24.06 PM.png"
tags: []
categories: []
description: ''
---
<file_sep>/content/news/npr-on-point-min-jin-lee-on-life-as-an-immigrant-at-elite-colleges-and-in-america-1.md
---
title: 'Paris Review: Staff Picks'
date: 2019-08-30T02:00:00-04:00
categories:
- Media
tags: []
attribution:
link_to_original: https://www.theparisreview.org/blog/2019/08/30/staff-picks-family-fleece-and-flamin-hot-cheetos/
description: '"Sometimes my therapist, bless her, mentions phobias I don’t have. ''You’re
not an agoraphobe,'' she offered on Wednesday. But nevertheless, I am skeptical
of crowded opinions. Books loved by enormous groups of people unnerve me. I skirted
WOLF HALL for ages, and the number of people who told me PACKINKO is a good book
is equal to the number of times I responded, ''Oh, I have to read that,'' and then
didn’t. I shouldn’t have hesitated. <NAME> began her career as a lawyer, and
her interest in research and justice shines through this compelling family narrative.
It is sweeping but specific. When my reading lamp putters out—the only way I can
close the book at night—words and images last: Sunja’s simplest chima, or the way
her mother cuts radishes in perfect cubes. Huge cultural questions also sweep past,
not unanswered but unanswerable: How do communities thrive on each other’s exclusion?
How can a people flourish when their equity is rejected? This book is so much about
the collective, its fragility and its dangers, paper-thin walls and the thickness
of blood." —<NAME>'
---
> [https://www.theparisreview.org/blog/2019/08/30/staff-picks-family-fleece-and-flamin-hot-cheetos/](https://www.theparisreview.org/blog/2019/08/30/staff-picks-family-fleece-and-flamin-hot-cheetos/ "https://www.theparisreview.org/blog/2019/08/30/staff-picks-family-fleece-and-flamin-hot-cheetos/")<file_sep>/content/writing/2012-04-07-new_york_times_magazine_low_tide.md
---
title: "New York Times Magazine: Low Tide"
date: 2012-04-07T10:47:34-05:00
categories:
tags: ["Essays"]
where_published: "New York Times Magazine"
link_to_original: "http://nyti.ms/wb9Uzr"
link_to_pdf:
description:
_slug: 2012-04-07-new_york_times_magazine_low_tide
---
<file_sep>/content/event/alabama.md
---
title: ALABAMA
date: 2008-04-22T05:20:01-05:00
venue:
name: Alabama Booksmith, Birmingham
link: www.alabamabooksmith.com
---
Reading and Q&A
6PM
ALABAMA BOOKSMITH
2626 19th Place
Homewood, AL 35209
<file_sep>/content/event/denison-university.md
---
title: Denison University
date: 2019-03-07 23:00:29 +0000
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: ''
description: ''
---
<file_sep>/content/event/boston-college.md
---
title: 'Calvin College '
date: 2022-03-24T00:00:00-04:00
show_time: true
venue:
name: Calvin College
address: 3201 Burton St. SE
city: Grand Rapids
state: MI
zip: "49546"
link: ''
description: ''
images: []
---
<file_sep>/content/news/2007-06-10-privilege_and_poverty_a_rebellious_young_korean_woman_gets_a_crash.md
---
title: "Privilege and Poverty - A Rebellious Young Korean Woman Gets a Crash…"
date: 2007-06-10T22:49:01-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Charlotte Observer"
link_to_original: ""
description: ""
_slug: 2007-06-10-privilege_and_poverty_a_rebellious_young_korean_woman_gets_a_crash
---
<NAME> has just graduated from Princeton on scholarship, when a visit to her parents’ apartment turns ...
<file_sep>/content/event/elliott-bay-book-company.md
---
title: Elliott Bay Book Company
date: 2017-03-02 19:00:00
show_time: true
venue:
name: Elliott Bay Book Company
address: 521 Tenth Avenue
city: Seattle
state: WA
zip: '98122'
link: 'https://elliottbaybook.com'
---
In Conversation with <NAME>, Co-founder of The Second Shift<file_sep>/content/news/2017-06-28-mckinsey--co--what-ceos-are-reading-in-2017.md
---
title: 'McKinsey & Co.: What CEOs are Reading in 2017'
date: 2017-06-28 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: McKinsey.com
link_to_original: 'http://www.mckinsey.com/global-themes/leadership/what-ceos-are-reading-in-2017'
description:
---
<NAME>, member of the Group of Thirty and former CEO, Westpac
Lab Girl—<NAME> (Vintage, February 2017; nonfiction)
Pachinko—<NAME> (Grand Central Publishing, February 2017; fiction)
The Boys in the Boat: Nine Americans and Their Epic Quest for Gold at the 1936 Berlin Olympics—<NAME> (Penguin Books, 2014; nonfiction)
For the full list, please click the link.<file_sep>/content/event/book-passage.md
---
title: Book Passage
date: 2017-02-16 19:00:00
show_time: true
venue:
name: Book Passage
address: 51 Tamal Vista Boulevard
city: Corte Madera
state: CA
zip: '94925'
link: 'http://www.bookpassage.com'
---
Conversation with <NAME>, co-founder and president of Book Passage<file_sep>/content/event/london-waterstones-piccadilly.md
---
title: 'London: Waterstones, Piccadilly '
date: 2018-10-08 18:30:51 -0400
images: []
description: 'In Conversation with <NAME>: Pachinko '
link: "https://www.waterstones.com/events/min-jin-lee-and-erica-wagner-in-conversation-at-piccadilly-london/london-piccadilly"
show_time: true
venue:
address: 203-206 Piccadilly, St. James's
city: London
name: '<NAME> '
state: ''
zip: 'W1V 9LE, UK '
---
<file_sep>/content/news/pbs-newshour-making-kimchi-with-mom.md
---
title: 'PBS NewsHour: Making Kimchi with Mom (Video)'
date: 2018-07-30 18:18:15 -0400
link_to_original: https://www.pbs.org/newshour/arts/min-jin-lees-easy-family-recipe-recipe-for-stuffed-cucumber-kimchi-oi-soh-bahgi
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/event/festival-neue-literatur-another-country-distant-lands-up-close-and-personal-1.md
---
title: 'NYPL: One Book, One New York'
date: 2019-04-23 18:30:00 -0400
show_time: true
venue:
name: <NAME>, Celeste Bartos Forum
address: New York Public Library
city: New York
state: NY
zip: 10018
link: https://www.nypl.org/events/programs/2019/04/23/one-book-one-new-york-launch-event?nref=370068
---
The Mayor’s Office of Media and Entertainment and the BuzzFeed Book Club introduce all five nominated books and authors for One Book, One New York in a special evening of conversation at The New York Public Library. Hear what inspired the authors to write these celebrated titles, check-out the books and then cast your vote for the One Book we should read altogether.<file_sep>/content/event/brooklyn-book-festival.md
---
title: Brooklyn Book Festival
date: 2017-09-17 11:00:00
show_time: true
venue:
name: Brooklyn Historical Society
address: 128 Pierrepont Street
city: Brooklyn
state: NY
zip:
link: 'http://www.brooklynbookfestival.org/authors/#filter=.festival-day'
---
Whether a novel is set in the 1800s or the 2000s, its characters’ attitudes, actions, and behaviors reflect the particular period in history. Writers <NAME> (Song of the Shank), <NAME> (The Castle Cross the Magnet Carter), and <NAME> (Pachinko) discuss the challenges they faced when offering a new perspective on specific historical moment. Moderated by <NAME>, books editor at Buzzfeed.<file_sep>/content/news/2016-10-26-vela-magazine-6-new-books-from-diverse-voices.md
---
title: 'Vela Magazine: 6 New Books from Diverse Voices'
date: 2016-10-26 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Vela Magazine by <NAME>
link_to_original: 'http://velamag.com/6-new-books-from-diverse-voices/'
description:
---
Good novels come to readers who wait.
Fans of novelist <NAME>’s Free Food for Millionaires have been waiting a long time for her second book, Pachinko, and the decade of patience is rewarded. Pachinko is everything I want in a family saga novel, a deep dive immersion into a complete world full of rich and complex lives to follow as they tumble towards fate and fortune.
The book opens with, “History has failed us, but no matter.” Starting in 1910, during the time of Korea’s annexation by Japan (a history that I failed to learn about until reading the novel), we follow 80 years in the life of a family, from humble beginnings in a small village in Korea to the shimmering sights and sounds of big cities in Japan. Characters are swept up in historical forces, such as World War II, and profoundly changed by medical realities like cleft palate, infant death and tuberculosis, which today don’t have the same impact.
Don’t be intimidated by this almost-500 page book. Try the first chapter, only several pages long, and you’ll see: Pachinko will break your heart in all the right ways.<file_sep>/content/news/2017-12-18-literary-hub-the-ultimate-best-books-of-2017-list.md
---
title: 'Literary Hub: The Ultimate Best Books of 2017 List'
date: 2017-12-18 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Literary Hub
link_to_original: 'http://lithub.com/the-ultimate-best-books-of-2017-list/'
description:
---
By <NAME>
It’s the end of the year, and everybody has an opinion. And of course, where there’s an opinion, there’s a listicle. The river of Best of 2017 lists can be exhausting this time of year, so as a public service, and because my math skills are always in need of a little exercise, I’ve created a streamlined master list of the books that the most people loved this year. Of course, I couldn’t include everything (like NPR’s enormous list of favorites). But I looked at the end-of-year roundups from 35 outlets and tracked a total of 520 discrete books in order to figure out the most critically popular books of the year. Does that mean they are the Best? You’ll have to decide for yourself, by reading them.
It’s interesting to compare this list of the “best” books to the most recommended books of fall (though it’s not a perfect match-up, of course, because many of these books came out in other seasons)—for instance, everyone was pretty sure they were going to like <NAME>’s Sing, Unburied, Sing, and Celeste Ng’s Little Fires Everywhere, and then they did! Success. Other books fell a little in the relative rankings. But all in all, it’s pretty satisfying to see how much people loved and recommended books by women and people of color this year.
For the record, the best-of lists I consulted for this master list are from the following outlets: GQ, The New York Times, Vogue, Vulture, USA Today, Luna Luna, Publisher’s Weekly (Top 10), The Washington Post, The Chicago Review of Books (Fiction, Poetry, and Nonfiction), The New York Public Library, The LA Times (Fiction and Nonfiction), Financial Times (Fiction, Poetry, and Literary Nonfiction), Popsugar, Newsday, Library Journal, Elle, Amazon, Book Riot, EW, Cosmopolitan, The Economist, The Stranger, The Wall Street Journal, Bookpage, Shelf Awareness, NYLON (Fiction and Nonfiction), Entropy (Fiction and Nonfiction), Buzzfeed (Fiction), HuffPost (Fiction), Paste (Nonfiction and Novels), Esquire, The Boston Globe, TIME (Novels and Nonfiction), The Chicago Tribune, The Brooklyn Rail. NB: wherever publications had multiple lists, I went with the shorter one—so, for instance, I counted the NYT “Best Books” list but not their “Notable Books” list. This choice was made for my sanity.
(Some of these lists, I should say, bizarrely included books published in 2016—I caught what I could, but all mistakes in that area are the responsibility of the outlet in question.)
And now, without further ado…
The Best Books of 2017, per the power of the list:
On 22 lists<br>Lincoln in the Bardo, <NAME>
On 19 lists
Exit West, <NAME>
Sing, Unburied, Sing, <NAME>
On 14 lists
Killers of the Flower Moon, <NAME>
On 13 lists
Pachinko, <NAME>
Priestdaddy, <NAME>
Little Fires Everywhere, <NAME>
On 12 lists
Hunger, <NAME>
Her Body and Other Parties, <NAME>
On 9 lists
We Were Eight Years in Power, Ta-Nehisi Coates
Sour Heart, <NAME>
On 8 lists
You Don’t Have To Say You Love Me, <NAME>
On 7 lists
The Power, <NAME><br>Manhattan Beach, <NAME><br>The Future is History, <NAME><br>The Leavers, <NAME><br>White Tears, <NAME><br>The Answers, <NAME>
The Rules Do Not Apply, <NAME>vy
Home Fire, <NAME>
Borne, <NAME>
FOR THE REMAINDER OF THE ARTICLE, PLEASE CLICK THE LINK.<file_sep>/content/event/johns-hopkins-university-pachinko-symposium.md
---
title: 'Johns Hopkins University: PACHINKO Symposium'
date: 2018-04-12 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2008-05-14-fallout_central_interview_with_min_jin_lee.md
---
title: "Fallout Central Interview with <NAME>"
published: false
date: 2008-05-14T22:37:00-05:00
categories: ["Media"]
tags:
- Video
attribution: "Fall Out Central"
link_to_original: "http://www.falloutcentral.com/news/2008/04/28/podcast-episode-min-jin-lee-author-_free-food-for-millionaires_/"
description: ""
_slug: 2008-05-14-fallout_central_interview_with_min_jin_lee
---
<object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/_wNtnmInv4Y"><param name="wmode" value="transparent"><embed src="http://www.youtube.com/v/_wNtnmInv4Y" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></object>
[[part 2](http://www.youtube.com/watch?v=5kNPLJTn0Po "part 2")] [[part 3](http://www.youtube.com/watch?v=s6YDGxQ0waQ "part 3")] [[part 4](http://www.youtube.com/watch?v=cxZIo1V70xU "part 4")]
<file_sep>/content/event/books_inc_laurel_village.md
---
title: Books Inc. Laurel Village
date: 2008-04-29T05:24:00-05:00
venue:
name: Books, Inc., Laurel Village, SAN FRANCISCO, CA
link: www.booksinc.net
_slug: books_inc_laurel_village
---
Reading and Q&A
7PM
3515 California Street
Laurel Village, San Francisco
FREE FOOD FOR MILLIONAIRES is a BOOKS INC. FIRST FICTION BOOK CLUB selection.
<file_sep>/content/event/man_hong_kong_international_literary_festival.md
---
title: MAN HONG KONG INTERNATIONAL LITERARY FESTIVAL
date: 2009-03-14T12:52:00-05:00
venue:
name: MAN HONG KONG INTERNATIONAL LITERARY FESTIVAL
link: www.festival.org.hk
_slug: man_hong_kong_international_literary_festival
---
Saturday, 14 March at 12:30pm (at M)
M Literary Lunch: Free Food for Millionaires—Min Jin Lee exquisitely evokes what it’s like to be an immigrant, and more specifically the child of immigrants. As much as Free Food for Millionaires is an immigrant story, it’s also a story full of class struggle, rugged individualism, social status, and above all, the money haves and have-nots. And, it is an epic meditation on love littered with betrayals, illicit sex, numerous levels of unfaithfulness, surprise twists and unexpected turns of the heart. Enjoy M’s lovely lunch followed by Min Jin Lee in conversation with <NAME>.
Saturday, 14 March at 3:30pm (at the Fringe Club)
Family Dysfunction—His father is a half-mad, violent Eastern European artist. His Chinese mother is subservient, and much-suffering; she buffers herself from the dysfunctional family by quoting Buddhist wisdom. In Thad<NAME>’s offbeat coming-of-age novel, a biracial narrator tells of growing up in rural America and later escaping to a new life in New York City. Min Jin Lee discusses the tenuous relationship between first generation immigrant parents and their hip young offspring. Her novel, Free Food for Millionaires centers on the tightly knit social world of Korean immigrants, whose children strive to blend into their American foreground without clashing with their distinctive background. Moderated by <NAME>
For tickets (starting Feb. 3) www.festival.org.hk
<file_sep>/content/event/la_times_book_festival.md
---
title: LATIMES FESTIVAL OF BOOKS
date: 2008-04-27T04:28:00-05:00
venue:
name: The Los Angeles Times Festival of Books
link: http://www.latimes.com/extras/festivalofbooks/
_slug: la_times_book_festival
---
FIRST FICTION: STARTING OUT
Moderator: <NAME>
Panelists: <NAME>, <NAME>, <NAME> and <NAME>
10AM
UCLA, Westwood, CA
Young Hall CS 50
Book Signing to follow
<file_sep>/content/review/beattiesbookblog-on-free-food-for-millionaires.md
---
title: Beattiesbookblog on Free Food for Millionaires
attribution: Beattiesbookblog
date: 2007-03-11 18:01:29 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
This new title, published 1 July, by Korean American writer <NAME> is causing a stir…<file_sep>/content/event/bunch_of_grapes_august_1.md
---
title: Bunch of Grapes, August 1
date: 2007-08-01T20:30:00-05:00
venue:
name: Bunch of Grapes, Vineyard Haven, MA
link: www.bunchofgrapes.com
_slug: bunch_of_grapes_august_1
---
<file_sep>/content/_index.md
---
title: '<NAME> - The official site of the author of FREE FOOD FOR MILLIONAIRES
and PACHINKO '
linktitle: Home
menu:
main:
weight: 1
outputs:
- HTML
- tnd_redirects_netlify
- tnd_headers_netlify
---
<file_sep>/content/news/2007-07-10-writerinterviews.md
---
title: "Writerinterviews"
date: 2007-07-10T22:10:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Writerinterviews"
link_to_original: "http://writerinterviews.blogspot.com/2007/07/min-jin-lee.html"
description: ""
_slug: 2007-07-10-writerinterviews
---
<NAME> is the author of Free Food for Millionaires. From an interview posted on her website:. Q: You’ve chosen to write this book showing many points of view. Is there a reason why? More than anything, I wanted to try to write ...
<file_sep>/content/writing/the-new-yorker-stonehenge.md
---
title: 'NPR On Point: Writer <NAME> On Life As An Immigrant At Elite Colleges
— And In America'
date: 2019-06-10T06:00:13.000+00:00
categories:
tags: []
where_published: On Point (NPR)
link_to_original: https://www.wbur.org/onpoint/2019/06/10/min-jin-lee-immigrant-college-school-america-stonehenge-new-yorker
link_to_pdf:
description:
_slug: '2019-06-10T06:00:00.000+00:00'
---
<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-.md
---
title: '"Writer <NAME> to Teach at Amherst College" '
date: 2018-09-28 00:50:11 -0400
link_to_original: https://amherststudent.com/article/writer-min-jin-lee-to-teach-at-college
images: []
tags: []
categories: []
description: "\"Above all, I would like to create a welcoming space for non-writers
and advanced writers to take greater risks in their written expression.” She hopes
to help students “fall in love with the generative process,” she said. “Each draft
teaches us more about what we want to say, and I would be happy if my students learned
to see that in their work — that with their efforts, they are approaching who they
are, what they want to say, and what they care about.”"
---
<file_sep>/content/event/amherst-college-8.md
---
title: Writer’s Digest Annual Conference, Closing Keynote
date: 2019-08-25T09:00:00-04:00
show_time: true
venue:
name: ''
address: ''
city: New York
state: NY
zip: ''
link: https://writersdigestconference.com/min-jin-lee/
description: Followed by Book Signing
images: []
---
<file_sep>/content/event/new-york-city-launch-barnes--nobles-upper-east-side.md
---
title: 'New York City Launch: Barnes & Noble Upper East Side'
date: 2017-02-07 19:00:00
show_time: true
venue:
name: '<NAME>'
address: 150 East 86th Street
city: New York
state: NY
zip:
link:
---
In Conversation with <NAME>, author of *The Interestings*, *The Wife*, *The Ten-Year Nap* and *The Uncoupling*.<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college.md
---
title: 'Harvard Magazine: <NAME> on Her New Novel and Writing about the Korean
Diaspora'
date: 2019-02-13 00:50:11 -0500
link_to_original: https://www.harvardmagazine.com/2019/02/min-jin-lee-on-her-new-novel-and-writing-about-the-korean-diaspora
images:
- "/uploads/radcliffe-institute-min-jin-lee_ella-rinaldo-photography_2-12-19_dsc_9227_sm.jpg"
tags: []
categories: []
description: “I’ve been asked why I write about Koreans,” Lee said. “And it seems
like such a strange question. Because why wouldn’t I write about Koreans? To me,
Koreans are mothers and fathers and daughters and sons, which means Koreans are
like us; we are worthy of consideration and reflection."
---
<file_sep>/content/event/monmouth-college-commencement.md
---
title: Monmouth College's 161st Commencement
date: 2018-05-13 12:00:00
show_time: true
venue:
name: Wallace Hall Plaza
address:
city:
state:
zip:
link: >-
http://www.reviewatlas.com/news/20171124/national-book-award-finalist-min-jin-lee-to-give-monmouth-commencement-address
---
<file_sep>/content/review/outofthewoods.com-on-free-food-for-millionaires.md
---
title: Outofthewoods.com on Free Food for Millionaires
attribution: Outofthewoods.com
date: 2007-03-11 18:05:28 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
But <NAME> is unrelentingly fair to her characters, letting us into their heads….<file_sep>/content/news/2007-06-05-san_francisco_chronicle.md
---
title: "San Francisco Chronicle"
date: 2007-06-05T22:47:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "San Francisco Chronicle"
link_to_original: ""
description: ""
_slug: 2007-06-05-san_francisco_chronicle
---
Poor people stay poor because “they spend all their money on pride.” So says one of the characters in Min Jin Lee’s expansive first novel ...
<file_sep>/content/news/2007-06-01-daily_camera.md
---
title: "Daily Camera"
date: 2007-06-01T23:12:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Daily Camera"
link_to_original: "http://www.dailycamera.com/news/2007/jun/01/food-for-thought-korean-american-writers-debut/"
description: ""
_slug: 2007-06-01-daily_camera
---
The first novel by <NAME> - a Korean immigrant who went to Yale University - looks at the precarious time after college graduation when .
<file_sep>/content/news/pachinko-long-listed-for-the-the-international-dublin-literary-award-2019.md
---
title: PACHINKO long-listed for the the International Dublin Literary Award 2019
date: 2018-11-20 14:16:52 -0500
link_to_original: http://www.dublinliteraryaward.ie/nominees/pachinko/
images:
- "/uploads/image.jpg"
tags: []
categories: []
description: ''
---
<file_sep>/content/event/brisbane-writers-festival-saturday-panel.md
---
title: 'Brisbane Writers Festival: Saturday Literary Salon'
date: 2017-09-09 19:00:00
show_time: true
venue:
name: 'The Edge, State Library of Queensland'
address: Stanley Place
city: South Brisbane QLD
state:
zip:
link: 'http://uplit.com.au/festival/brisbane-writers-festival-2017/program/a-world-without-writers'
---
What would the world look like if we did not have writers? In this special Brisbane Writers Festival Literary Salon, great writers will contemplate how they, and others in their field contribute to the world. Join them for an evening of big ideas. With <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.<file_sep>/content/event/the-pen-faulkner-foundation-literary-conversations-intersections.md
---
show_time: true
title: 'The PEN/Faulkner Foundation - Literary Conversations: Intersections'
date: 2021-02-09T19:00:00-05:00
description: Join us for this discussion of intersectionality in literature featuring
novelists <NAME>, <NAME>, and <NAME>!
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.eventbrite.com/e/literary-conversations-intersections-tickets-136730928889
images: []
---
<file_sep>/content/news/2017-12-04-irish-independent-pat-kennys-top-book-picks.md
---
title: 'Irish Independent: <NAME>''s Top Book Picks'
date: 2017-12-04 12:00:00
categories: ["News"]
tags:
- News
- Reviews
attribution: Independent
link_to_original: >-
https://www.independent.ie/entertainment/books/take-your-pick-from-2017s-favourite-pageturners-36371460.html
description:
---
I read at least a book a week for the radio programme, so after a while they all blur a bit, but there are a few that stick in my mind. The first is a big doorstop of a book called Pachinko, (Head of Zeus, €11.70) by <NAME>, a Korean-American author. It's a multi-generational saga and a wonderful story. Of all the books that I've read this year, it's the one that springs to mind, as a great read, and an unexpected one. Another one that comes to mind is <NAME>'s Eleanor Oliphant is Completely Fine (HarperCollins, €16.90). This was one of the books that we selected for our Eason Book Club. It's about a woman who's on the spectrum, it would appear, but she has been through a trauma which is only revealed in trickles throughout the narrative until we finally get a full picture of her life. It's a tale of redemption.
The third one that I would say was a surprise was The End of Eddy, (Vintage, €16.90) by <NAME>. It's an autobiography. Eddy is a young, working-class kid growing up in industrial France, and he's highly put upon by his father, who mistreats him. He happens to be gay. He escapes from this milieu and writes this book. He is a sensation in France, to the point now that he is an academic in the Ecole National Superieure.
<NAME> is the presenter of The <NAME> Show on Newstalk and Pat Kenny Tonight on TV3.<file_sep>/content/news/oprah-25-books-about-immigration-that-movingly-capture-the-experience.md
---
title: 'Oprah: 25 Books About Immigration That Movingly Capture the Experience'
date: 2020-07-21T00:50:11-04:00
link_to_original: https://www.oprahmag.com/entertainment/books/g29193389/books-about-immigration/
images: []
tags: []
categories: []
description: ''
---
> "_Pachinko_ is a tale of immigration within a different context than stories of coming to the U.S. The multigenerational epic follows a Korean family who moves to Japan in the early 1900s. Their roots in Korea follow them, as they remain in a society that labels them outsiders, and estranged from their country of origin."<file_sep>/content/event/houston-inprint.md
---
title: 'Houston: The Inprint Poets & Writers Ball '
date: 2019-02-02 18:30:24 -0500
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2008-04-25-new_york_times_podcast.md
---
title: "New York Times Podcast"
date: 2008-04-25T23:29:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "New York Times Podcast"
link_to_original: "http://www.nytimes.com/2006/10/08/books/books-podcast-archive.html?_r=1&scp=3&sq=%22min%20jin%20lee%22&st=cse&oref=slogin"
description: ""
_slug: 2008-04-25-new_york_times_podcast
---
<NAME> on the vanishing black literary novel; <NAME> on <NAME>; and <NAME>, senior editor, with best-seller news… [[podcast](http://podcasts.nytimes.com/podcasts/2007/06/29/30bookupdate.mp3 "podcast")]
<file_sep>/netlify.toml
[build]
publish = "public"
command = "hugo --minify -F -e cached"
[build.environment]
GO_VERSION = "1.14"
NODE_VERSION = "15.4.0"
HUGO_VERSION = "0.83.0"
[context]
[context.production]
[context.production.environment]
HUGO_ENV = "production"
[context.deploy-preview]
command = "hugo --minify -e cached -D -b $DEPLOY_PRIME_URL"
[context.deploy-preview.environment]
HUGO_ENV = "staging"
[context.branch-deploy]
command = "hugo --minify -e cached -b $DEPLOY_URL"
[context.branch-deploy.environment]
HUGO_ENV = "staging"<file_sep>/content/review/bbc.com-on-pachkinko.md
---
title: BBC.com on Pachkinko
attribution: BBC.com (Culture) <NAME>
date: 2017-03-11 17:47:41 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Ten Books to Read in 2017<file_sep>/content/news/2016-12-15-booklist-review-starred-review.md
---
title: 'Booklist Review: Starred Review'
date: 2016-12-15 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Booklist by <NAME>
link_to_original: 'http://smithsonianapa.org/bookdragon/pachinko-min-jin-lee-booklist/'
description:
---
\*STARRED REVIEW
<br>A decade after her international best-selling debut, Free Food for Millionaires (2007), Min Jin Lee’s follow-up is an exquisite, haunting epic that crosses almost a century, four generations, and three countries while depicting an ethnic Korean family that cannot even claim a single shared name because, as the opening line attests: “History has failed us.”
In 1910, Japan annexes Korea, usurping the country and controlling identity. Amid the tragedies that follow, a fisherman and his wife survive through sheer tenacity. Their beloved daughter, married to a gentle minister while pregnant with another man’s child, initiates the migration to Japan to join her husband’s older brother and wife.
Their extended family will always live as second-class immigrants; no level of achievement, integrity, or grit can change their status as reviled foreigners. Two Japanese-born sons choose diverging paths; one grandson hazards a further immigration to the other side of the world.
Although the characters are oppressed by the age-old belief sho ga nai (it can’t be helped), “moments of shimmering beauty and some glory, too,” illuminate the narrative. Incisively titled (pachinko resemble slot machines with pinball characteristics), Lee’s profound novel of losses and gains explored through the social and cultural implications of pachinko-parlor owners and users is shaped by impeccable research, meticulous plotting, and empathic perception.<file_sep>/content/news/2007-01-23-springing_forward_fiction_first_novels_collections.md
---
title: "Springing Forward: Fiction/First Novels & Collections"
date: 2007-01-23T00:14:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "<NAME>"
link_to_original: ""
description: ""
_slug: 2007-01-23-springing_forward_fiction_first_novels_collections
---
The daughter of Korean immigrants navigates the Manhattan world of haves and have-nots.
<file_sep>/content/event/brandeis.md
---
title: Brandeis Book and Author Luncheon
date: 2017-10-30 11:30:00
show_time: true
venue:
name: Yale Club of New York
address: 50 Vanderbilt Avenue
city: New York
state: NY
zip:
link:
---
Featuring authors <NAME>, <NAME> & <NAME><file_sep>/content/event/williams-college.md
---
show_time: true
title: Williams College - Reading and Conversation
date: 2021-05-06T19:00:00-04:00
description: <NAME>, will read from her work, engage in conversation with Sam
Crane, Chair of Asian Studies and the Edward S. Greenbaum 1910 Professor of Political
Science, and take audience questions. Free and open to the public. All are invited.
Sponsored by the Asian Studies Department.
venue:
address: Virtual
city: ''
name: ''
state: ''
zip: ''
link: https://events.williams.edu/event/min-jin-lee-reading-and-conversation/
images: []
---
<file_sep>/content/news/2017-12-02-irish-times-the-best-books-of-the-year.md
---
title: 'Irish Times: The Best Books of the Year'
date: 2017-12-02 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Irish Times
link_to_original: >-
https://www.irishtimes.com/culture/books/ticket-awards-2017-the-best-books-of-the-year-1.3308403
description:
---
Pachinko makes the list. For the complete article, please click the link below.<file_sep>/content/review/historywire.com-on-free-food-for-millionaires.md
---
title: Historywire.com on Free Food for Millionaires
attribution: Historywire.com
date: 2007-03-11 18:11:36 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
As the face of America becomes stunningly diverse, the need for competent cultural translators grows apace…Now, in her first novel, Korean-American writer <NAME> helps us understand Koreans as they grapple to grab the first rung of the economic ladder.<file_sep>/content/news/2017-09-15-national-book-awards-longlist-for-fiction.md
---
title: National Book Awards Longlist for FICTION
date: 2017-09-15 12:00:00
categories: ["News"]
tags:
- News
attribution: New York Times
link_to_original: >-
https://www.nytimes.com/2017/09/15/books/review/national-book-awards-longlist.html?rref=collection%2Fsectioncollection%2Fbooks&action=click&contentCollection=books®ion=stream&module=stream_unit&version=latest&contentPlacement=3&pgtype=sectionfront&_r=0
description:
---
So profoundly honored and grateful that PACHINKO made the National Book Awards Longlist for Fiction. Thank you.
The 2017 Longlist for the National Book Award for Fiction
<NAME>, “Dark at the Crossing”
Knopf / Penguin Random House
<NAME>, “The King Is Always Above the People: Stories”
Riverhead Books / Penguin Random House
<NAME>, “<NAME>”
Grove Press / Grove Atlantic
<NAME>, “Manhattan Beach”
Scribner / Simon & Schuster
<NAME>, “The Leavers”
Algonquin Books / Workman Publishing
<NAME>, “Pachinko”
Grand Central Publishing / Hachette Book Group
<NAME>, “Her Body and Other Parties: Stories”
Graywolf Press
<NAME>, “A Kind of Freedom”
Counterpoint Press
<NAME>, “Sing, Unburied, Sing”
Scribner / Simon & Schuster
<NAME>, “Barren Island”
New Issues Poetry & Prose
For the complete article for all the awards, please click the link below.<file_sep>/content/news/2007-06-02-the_chronicle_journal.md
---
title: "The Chronicle Journal"
date: 2007-06-02T23:05:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "The Chronicle Journal"
link_to_original: ""
description: ""
_slug: 2007-06-02-the_chronicle_journal
---
In Free Food, Lee takes exquisite look at life’s uncertainties
Chronicle Journal - The Chronicle Journal - Jun 2, 2007
The first novel by <NAME> - a Korean immigrant who went to Yale University - looks at the precarious time after college graduation when dreams may not ...
<file_sep>/content/news/2008-04-25-newyorkbookfestivalcom.md
---
title: "newyorkbookfestival.com"
date: 2008-04-25T23:38:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Newyorkbookfestival.com"
link_to_original: "http://newyorkbookfestival.com/event/details.asp?event_id=9"
description: ""
_slug: 2008-04-25-newyorkbookfestivalcom
---
New York Book Festival
Runners-Up: Free Food For Millionaires – Min Jin Lee Hard-Boiled Men – <NAME> HONORABLE MENTION: Crossing the Wire - <NAME> ...
<file_sep>/content/news/2009-03-11-yonhap_news_agency_top_10_bestsellers_in_south_koreas_foreign_fiction_list.md
---
title: "Yonhap News Agency: “Top 10 Bestsellers in South Korea’s Foreign Fiction List”"
date: 2009-03-11T22:03:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Yonhap News"
link_to_original: "HTTP://english.yonhapnews.co.kr/Interview/2009/03/06/21/0901000000AEN20090306001700315F.HTML"
description: ""
_slug: 2009-03-11-yonhap_news_agency_top_10_bestsellers_in_south_koreas_foreign_fiction_list
---
A profile of my work appeared this month in the Yonhap News—South Korea’s official news agency. I was interviewed by the journalist <NAME> of Yonhap.
The interview begins… “She was once cast in with that sea of would-be authors, struggling to find a publisher for her debut novel: a lengthy, dense work full of complex characters that might intimidate even the most voracious reader.
Now, people call her the “21st century Jane Austen,” and <NAME> has become one of the few Korean-American writers to have their book translated into the language of their parents.”
M.J.L.
[Click here to read the article.](HTTP://english.yonhapnews.co.kr/Interview/2009/03/06/21/0901000000AEN20090306001700315F.HTML "Click here to read the article.")
This version of the Yonhap story ran in the Joongang Ilbo—the Korean partner paper of the International Herald Tribune: [Joongang Ilbo](http://joongangdaily.joins.com/article/view.asp?aid=2902102).
<file_sep>/content/event/2016-10-27-northern-california-independent-booksellers-association-fall-discovery-Show.md
---
title: Northern California Independent Booksellers Association Fall Discovery Show
date: 2016-10-27 12:00:00
show_time: true
venue:
name: South San Francisco Conference Center
address:
city:
state:
zip:
link: 'http://www.nciba.com'
---
NCIBA Author Buzz Lunch with authors <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME><file_sep>/content/news/writers-are-reaching-for-our-thorns-the-thorns-which-define-our-entire-being.md
+++
categories = []
date = 2022-01-06T05:50:11Z
description = "\"Award-winning author <NAME> brings a fresh perspective to an ancient image of a boy pulling a thorn from his foot—Spinario—rendered exquisitely by the artist Antico (also known as <NAME>). Lee’s reflections on the daily struggle of being an artist is honest and moving, and invites a close look at and careful consideration of the Spinario itself.\""
images = ["/uploads/screenshot-2022-01-31-at-13-27-15.png"]
link_to_original = "https://www.metmuseum.org/perspectives/videos/2022/1/spotlight-min-jin-lee?utm_medium=email&utm_source=Museum&utm_campaign=2022_0106_Spotlight&promocode="
tags = []
title = "\"Writers Are Reaching for Our Thorns; the Thorns Which Define Our Entire Being\" (The Met)"
+++
"Award-winning author <NAME> brings a fresh perspective to an ancient image of a boy pulling a thorn from his foot—Spinario—rendered exquisitely by the artist Antico (also known as <NAME>). Lee’s reflections on the daily struggle of being an artist is honest and moving, and invites a close look at and careful consideration of the Spinario itself."<file_sep>/content/event/bluestockings.md
---
title: Bluestockings, New York City
date: 2007-07-26T07:00:00-05:00
venue:
name: Bluestockings, New York City
link: www.bluestockings.com
---
Contributors to WSQ: WOMEN’S STUDIES QUARTERLY: <NAME>, poet and the editor of FENCE and <NAME>, author of FREE FOOD FOR MILLIONAIRES.
Time: 7PM
<file_sep>/content/news/2017-03-07-lit-up-podcast-with-angela-ledgerwood-audio.md
---
title: Lit Up Podcast with <NAME> (AUDIO)
date: 2017-03-07 12:00:00
categories: ["Media"]
tags:
- Reviews
- Audio
- Interviews
attribution: Lit Up with <NAME>
link_to_original: 'https://itunes.apple.com/us/podcast/chapter-93-min-jin-lee-on-history-korean-families-in/id981340531?i=1000382325203&mt=2'
description:
---
I had the opportunity to talk with <NAME>, the host of the brilliant podcast, Lit Up. Angela is smart, funny and gorgeous. Oh, and she's also kindhearted.
Episode Chapter 93. It was aired on March 7, the International Women's Day.
It's on ITunes for free. To listen, please click on the link. <file_sep>/content/event/korean_community_center_gala.md
---
title: Korean Community Center Gala
date: 2016-04-16T15:32:25-05:00
venue:
name: Teaneck Marriott at Glenpointe
link:
_slug: korean_community_center_gala
---
### Korean Community Center Gala
Keynote Address by <NAME>: “The Power of My Mother’s and Father’s Stories”
---
<file_sep>/content/news/2017-05-30-wamc-the-book-show-with-joe-donahue-podcast.md
---
title: 'WAMC: The Book Show with <NAME>ue (Podcast)'
date: 2017-05-30 12:00:00
categories: ["News"]
tags:
- Reviews
- Audio
attribution: WAMC The Book Show with <NAME>ue
link_to_original: 'http://wamc.org/post/book-show-1506-min-jin-lee'
description:
---
Episode 1506
<NAME>’s historical novel, Pachinko, spans the entire 20th century through four generations, three wars and two countries with a troubled past.
The novel is a moving and powerful account of one of the world’s most persecuted immigrant communities—Koreans living in Japan.
To listen to the podcast, please click on the link below.<file_sep>/content/news/2007-07-01-new_york_times.md
---
title: "New York Times"
date: 2007-07-01T22:14:00-05:00
categories: ["News"]
tags:
- Excerpts
attribution: "New York Times (First Chapter Excerpt)"
link_to_original: "http://www.nytimes.com/2007/07/01/books/chapters/0701-1st-lee.html"
description: ""
_slug: 2007-07-01-new_york_times
---
As a capable young woman, <NAME> felt compelled to choose respectability and success. But it was glamour and insight that she craved. ...
<file_sep>/content/news/2017-07-25-new-york-public-library-conversation-with-simon-winchester-and-min-jin-lee-podcast.md
---
title: 'New York Public Library: Conversation with <NAME> and <NAME> (Podcast)'
date: 2017-07-25 12:00:00
categories: ["Media"]
tags:
- Reviews
- Audio
- Interviews
- News
attribution: Soundcloud
link_to_original: 'https://soundcloud.com/nypl/immigrant-stories-min-jin-lee-and-simon-winchester'
description:
---
I had the distinct privilege of speaking with one of my favorite writers <NAME> at one of the greatest libraries in the world, the New York Public Library on 42nd Street. This conversation was introduced by the very cool <NAME>, the Manager of Public Programs at the NYPL. This podcast came out today.
To listen to the podcast, please click the Soundcloud link. Thank you.
<file_sep>/README.md
# minjinlee.com
Using https://github.com/theNewDynamic/hugo-project-template
<file_sep>/content/event/korean-american-story--org.md
---
title: KoreanAmericanStory. org
date: 2017-12-08 18:30:00
show_time: true
venue:
name: Downtown Community Television Center
address: '87 Lafayette Street, Main Floor'
city: New York
state: NY
zip: '10013'
link: >-
https://www.eventbrite.com/e/sold-out-celebration-of-korean-american-women-authors-tickets-39667541685
---
A Celebration of Korean American Women Authors with <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> with <NAME>.
THIS EVENT IS SOLD OUT.<file_sep>/content/event/new-york-society-library.md
---
title: New York Society Library
date: 2017-03-30 18:30:00
show_time: true
venue:
name: New York Society Library
address: 53 East 79th Street
city: New York
state: NY
zip: '10075'
link: 'https://www.nysoclib.org'
---
In Conversation with <NAME>, former proprietor of Books & Co and <NAME> Bookstore; Trustee of the New York Society Library and a Director of the New York Open Center; and Level 4 practitioner of Healing Touch and certified Laughter Leader.
Booksellers provided by The Corner Bookstore www.cornerbookstorenyc.com<file_sep>/content/news/2017-12-28-the-new-york-public-librarys-10-best-books-of-2017.md
---
title: The New York Public Library's 10 Best Books of 2017
date: 2017-12-28 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: New York Public Library
link_to_original: 'https://www.nypl.org/blog/2017/12/06/nypls-10-best-books-2017#'
description:
---
By <NAME>, Manager of Reader Services
The end of the year is a natural time to reflect, to take stock. Consequently, there are many "best of" lists this time of year: best movies, best tv, best albums, and best books. These lists are validating when they include things we loved, and useful for making future plans: movies to see, tv to watch, music to check out, and books to read.
"Best" is a controversal term for librarians because we believe that any book you enjoy reading is a good book for you. There are no "good books" or "bad books" and it would follow, no "best books." However, we are a staff of readers, working in the service of New York City's readers, and we read some books published this year that we loved—and we want to list them!
We are an institution built on the principal of free and open access for all, so in keeping with that democratic spirit, we put it to a vote. We asked our staff to send us titles they read, published between January and December 2017, that they feel deserve a place on a top 10 list. The results were as broad and diverse as our collections, but there were ten titles many agreed were very special. Without further ado, NYPL's Top 10 Books of 2017.
Pachinko by <NAME>
A sweeping family saga and historical fiction that tells the story of on Korean family who moves to Japan in the early 1900s.
For the complete list, please click the link.<file_sep>/content/event/brattleboro.md
---
title: Brattleboro Literary Festival
date: 2017-10-15 11:30:00
show_time: true
venue:
name: <NAME>iver Garden
address: 157 Main Street
city: Brattleboro
state: VT
zip:
link: 'http://brattleboroliteraryfestival.org'
---
<NAME>, the author of THE WORLD BROKEN IN TWO: <NAME>, <NAME>, <NAME>, <NAME>, and the Year That Changed Literature, in conversation with <NAME>, author of PACHINKO.
Bill and Min will be introduced by <NAME>. <file_sep>/content/writing/2007-04-13-pushing_away_the_plate.md
---
title: "Pushing Away the Plate"
date: 2007-04-13T23:54:28-05:00
categories:
tags: ["Essays"]
where_published:
link_to_original:
link_to_pdf: "/uploads/pushing_away_the_plate.pdf"
description: "Published in _To Be Real_, edited by <NAME>"
_slug: 2007-04-13-pushing_away_the_plate
---
**bus stop.**
It is usually bright and slightly cool in the mornings when I wait for my bus at the Seventy -second Street and Lexington Avenue bus stop. I try to get on the M101 Limited bus when I go to work. This bus going downtown makes local stops from Seventy-second to Sixtieth Street, but it makes express stops from Sixtieth Street to Fiftieth and from Fiftieth Street to Grand Central Station without halting every two blocks. Despite its Park Avenue address, my office has another entrance on Lexington Avenue between Forty-ffith Street and Forty-sixth Street so when I get on the Limited bus, I get off at Fiftieth Street and walk a few blocks toward the shiny glass building which houses my office. But on the one or two days when I miss the Limited bus, I get on the local one, and my normal ten-minute ride extends easily to twenty minutes.
Although I get a bit annoyed at myself, because I’ll start my day a little late, secretly, the longer ride is small treat, because I know that I will see interesting people on my bus- old and young, rich and poor- and I shall have time to craft stories in my head about them. I’ll concentrate on that rich pattern of a woman’s chenille suit or gaze at the lightly textured balding spot of a man’s head and imagine her or his life outside of the bus that we share. Sometimes, I get lucky and find a comfortable window seat for myself, and then I’m not annoyed at all. I daydream for a luxurious twenty minutes before reaching my destination, my shared office with its heavy, dark wooden desk piled high with documents to draft, review, and revise.
When I am seated in my window seat, I begin to think about the passengers and I discover that I forget my own size. The people around me seem to grow in their girth and breadth and my body diminished slowly. I feel tiny and girlish, rather prim but curious about my surroundings. The worn seat of the bus swallows me up and I’ve become invisible. I am formless and all eyes. Around me are all these seated and standing adults who are on their way to work. Some women are breathtakingly beautiful. Their hair doesn’t move as they shift the sliding weight of their printed alligator leather handbags on their narrow shoulders. The lanky, beautiful women wear expensive sunglasses and smell of musky perfume. They look as if they work in the fashion or publishing industry. Then, there are women who look fatigued; their shapes are heavy and full and they often wear clothes that look uncomfortable and tight. The tired women look like housekeepers or home-care nurses. These women carry worn plastic shopping bags emblazoned with THANK YOU FOR SHOPPING HERE on them. Mingled everywhere I notice women who wear suits. The suits are often navy or gray. Sometimes, the suits look very new on the wearer. The women who wear the suits are between the ages of twenty-five and forty-five. They carry cordovan leather briefcases with squared-off handles, which slide in and out of an envelopelike opening. The briefcases have long shoulder straps. I am amazed at the number of professional women who carry them. On the outer pockets of the briefcases, glossy fashion and life-style magazine peep out behind the unread newspapers.
As the bus advances toward my stop, I remember that I am five feet nine inches tall and weigh almost one hundred and forty pounds. My large physical frame emerges from the seat of the bus, and as I straighten the skirt of my dark suit, I remind myself that I am a corporate lawyer and not a tidy immigrant girl in a shapeless outfit. I maneuver my body toward the front of the bus and disembark.
The stroll from the bus stop to my building takes two minutes and this time is enough for me to wake up, take the tortoiseshell headband off my nearly dry hair, and straighten my posture. I am a lawyer,I am a lawyer, I am a lawyer. I recite this like a mantra for two interlocked purposes: to state affirmatively that I am a female white collar professional and to nullify the negative statement belying my mantra, that I am just a young woman who has no idea what she is doing in this shiny glass building in midtown Manhattan. I start my second diurnal chant, I belong here, I belong here, I belong here.
As I get off the elevator which opens up to the wood paneled lobby of the law firm and greet the receptionist, who sits behind an impressive oval desk made of burl wood, I fell tense knots of uncertainty with respect to my new role as an attorney. As I walk in, other young women approach the reception desk. They are laughing and their formerly loud conversations of their subway, bridge, and tunnel rides cease, and they bend a little to sign in on the attendance sheets on a clipboard. I don’t sign in because the receptionist marks a check in a box for me; lawyers do not keep track of their own presence or absence, only secretaries, paralegals, and other members of support staff do. On certain mornings, the insecurity looms over and around me and I feel like a spool bound tightly under coils of dark cotton thread. On other mornings, the uncertainty enters my head intermittently in brief spurts. On a quiet month, weeks can pass without the lingering feelings of doubt, and I wonder when I shall feel less like a guest at a bal masque.
**land of lakes.**
A partner with whom I often work walked into my office a few weeks ago. He asked me how I was feeling. I lied. I replied to him that I felt fine. The corporate group had been working furiously to finish many fiscal year-end transactions for one of our big clients. As a result of the large volume of transactions, non of us were sleeping very much. The associates, legal assistants, and word processors worked straight through several weekends, and all of us complained unceasingly about our jobs. I did not feel fine. The partner then smiled and said, well, then you are going to go to Minneapolis and close this deal. He proceeded to tell me the name of the transaction and then dropped a few documents on my desk, already littered with various stages of transactional documents. He said, as he walked out the door, go speak to the senior associate in charge of the deal and find out what you are supposed to do. A secretary made airline reservations for me to fly out to Minneapolis the next morning. I had never been to Minnesota before.
I was told by a senior associate that I would meet a representative of the corporate client, Jim, at the hotel. Jim’s secretary and my secretary, via facsimile, arranged for us to meet at the lobby of the Minneapolis Radisson Hotel South at 7:30 the next morning. Jim was on time. He shook my hand and introduced himself. I had expected him to be older, somewhat heavier. I remembered reading in some memorandum that Jim worked in our client’s Texas office, so I mentioned as we marched toward the parking lot that I had heard on the television news report that the Texas Rangers had beaten the visiting team. Jim said mildly, oh. Then I asked him if he was a baseball fan, and he said no. Then I said, oh.
Once we got into his maroon-colored rental car, he mentioned how difficult it was to travel so much. There was no time to see his wife and kids, he said. This was my second business trip, ever, but I extrapolated my experience and let on that I knew how he felt. He told me a little bit about his family and said that his daughter’s swim meet went well the day before but it had been held outdoors and the temperature the day before was over 110 degrees in Plano, Texas. I told him that I had never been to Texas before. He then said in a clear and slow voice, well, don’t come now, it’s too hot. As he drove,we spoke about the beautiful weather we were experiencing in Minneapolis, the Land of Lakes. When we stopped at an intersection, I asked him how far we were from the closing site, and he said it would take about ten more minutes to get there. At that point, I took out the neatly written notes I had prepared that morning in my hotel room while I ate my breakfast of hot oatmeal and coffee. I started listing the business and legal issues that he should be aware of at this closing.
The reasons why I had decided to become a corporate lawyer as distinguished from a litigator are actually quite simple: one, I like to start and finish things within a reasonable amount of time, and two I don’t like to fight. Closings symbolize perfectly the first reason. Nearly all issues of this Minneapolis transaction were already negotiated and all of the documents had been drafted,now, the parties to this deal would join around a table and sign the many pieces of paper framed by crisp manilla legal-sized folders and give or take certified checks denominating large sums of cash. In a boxy rented Chevrolet, Jim and I sped toward the office of the lawyer of the seller; I was the lawyer of the buyer, and Jim was, effectively the buyer; we were on our way to the closing site to meet the seller and his lawyer. There, we would end our posturing, bantering, arguing, drafting, commenting, and revising: we would bring about closure.
The sun shone brilliantly over the asphalt-covered parking lot. I thought about wearing my mirrored sunglasses but decided against it. Jim remarked on the clearness of the day. We arrived early and we stood in front of the building which looked dark and empty. On the side of the building where the entrance was located, there was a small metal plaque screwed into the wall stating the name of the seller’s lawyer and on the end of his name, were the letters, J.D., signifying that he was juris doctor, a graduate of law school. The facXade of his office was not very impressive. When we walked into the roomy and cluttered office, a cheery middle-aged woman greeted us: you must be the people from New York. Jim didn’t correct her by telling her that he was in fact from Texas. I extended my hand to shake hers. She looked like someone who could have been a relative of my fourth-grade schoolteacher, Mrs. Maher. Her name was Peggy and she asked us if we would like coffee. I nodded yes while I looked around the room. Jim said no. Peggy led us to the closing room.
The seller of the business had already arrived. A portly man with lots of wrinkles under his eyes. He looked older than my father and I felt very young again. Jim and I looked like teenagers in comparison. I crossed my arms and straightened my shoulders. Feeling a little nervous, I tried to recall what Cynthia and Carol, two senior associates at the firm, had said to me before I had left New York for Minneapolis: “You have to take control of a closing, don’t let anyone rush you or push you around. It’s your show, take charge.” The seller asked us how our flight was. We spoke for a while about the Mall of America, the largest indoor shopping center in North America, located only a few miles from the closing site. Peggy chimed in at this moment to say that Jim and I should go there after the closing. We said that we might if we had any time before our respective flights, mine to Manhattan and his to Dallas. I noticed again how excited everyone in Minneapolis got when they talked about the Mall. I had scanned a brochure about it at the hotel lobby as I was checking in, so I asked a few questions about Snoopy Park, the indoor amusement attraction. Apparently, or so it was told to me, many people from places as far away as Germany or Japan fly into Minneapolis airport just to go shopping and fly right back to Munich or Osaka after a day of retail purchases.
I walked out of the closing room leaving Jim and the seller to talk about the heat in Texas, because I had to find a phone to call my office in New York. I was asking Peggy for permission to use one of the phones when the seller’s lawyer introduced himself loudly by paraphrasing his secretary: you must be the lady from New York. Yes, I am, I said.
We couldn’t actually start the closing since we were waiting for the Federal Express delivery person to bring the buyer’s check, which was being flown in from another state. Everyone seemed to be in good spirits, and I began to think that my first closing of a transaction would actualize the expectations that I had of becoming a corporate lawyer. Unlike a lawsuit where there is a guaranteed loser, in this kind of transaction, I ruminated, we would all walk away winners: the buyer gets the business and the seller gets his check. Interrupting my thoughts with an odd question, the seller’s lawyer asked me if I spoke other languages besides English. I replied Spanish, a menu knowledge of French and Italian, and a reasonable comprehension of Korean. Before I had a chance to ask him the same question, he exclaimed, I go to Korea all the time. Amused, I asked him why. He replied, for the shopping. At this point, my client and his client were listening to us intently. The check had not yet arrived and I was getting a little bored so I listened to him tell me about Korea.
I love Itaewon, he began his description, with his eyes weirdly sparkling. I tuned him out and tried to recall what I knew about Itaewon. It is the section of Seoul where most of the merchants sell knock-off designer handbags, fake Rolex watches, T-shirts with Chanel No. 5 printed on them, and brand-name sneakers to tourists and to American G.I’s who are stationed near the demilitarized zone. I also knew that at night Itaewon transforms from the bazaar of imitation good into streets full of electric lights and neon signs advertising go-go girls and discotheques. I had been to Itaewon a few times when I was last in Korea. Clearly, it was reinforced to me by my elders that a girl does not go to Itaewon by herself. During the day, when I went to buy souvenirs, I was accompanied by my mother’s best friend, and on the rare occasions that I went to Itaewon at night to go to certain approved of discotheques, I would be permitted to go only with large groups of people, many of them relatives. My uncles and aunts who lived in Korea narrated detailed and chilling stories about Korean-American girls getting kidnaped and being sold into prostitution. Over and over again, I was told that good girls do not go to Itaewon. When the seller’s lawyer finished telling us what he remembered of Itaewon, I walked out of the room to check if the delivery man had arrived. From that point on, I noticed that the seller’s lawyer began to touch me.
All of us waited for the check for nearly an hour. I asked the seller’s lawyer to revise a set of resolutions he had drafted to include another concept. He agreed and handwrote my comment in and asked Peggy to type it up. Wordlessly, he draped his arm around my waist and said that while we waited he would give me a tour of his office and show me all the things he bought in Itaewon. He directed my body toward his office and I made sure that the office door was wide open. He pointed to a huge brass elephant that must have weighed almost two hundred pounds which seemed to guard his desk. I bought that in Itaewon, he boasted. Dismayed and slightly bewildered by his choice of decorative arts, I asked him if he was a Republican. He said he was an Independent.
He relinquished my waist only to place his hand on my forearm to pull me toward another direction, look, I bought this clock from Korea. It was an old-fashioned schoolhouse clock with a small copper door at the base of its face and across the clock face the following word was etched into the plate glass, Federal. It seemed likely that the clock was made and purchased in Korea, but it looked so American. He then touched my back and directed me toward the closing room because Peggy told us that the check had arrived. I walked briskly away from the palm of his hand, which I felt was imprinted on the small of my back. When I saw the violet and orange striped express-mail package on Peggy’s desk, I told Jim that the closing check had arrived.
Signing the legal papers and handing the seller the certified bank check took less than twenty minutes. I gathered all the folders and called New York to report to the partner and the senior associate that the deal had closed. The partner told me that I should get on an earlier flight and head back to the office to pick up some more documents and then fly out to Los Angeles that night from New York to close another deal. The senior associate asked me how it went, and with my client standing next to me, I spoke into the receiver to say that the closing proceeded smoothly. I picked up my closing briefcase, which felt much lighter since I was leaving the seller and his lawyer two copies of everything I had brought with me, and told Jim that I would not be able to go with him to the Mall of America due to the change in my plans. Jim kindly drove me to the airport.
**pushing away the plate.**
As a young girl growing up in New York City, I dreamed of becoming many things. Between the ages of eight and twenty, I wanted to be: a cabinetmaker, an architect, a teacher, a judge, a dancer, a carpenter, a television writer, a stained-glass maker, an industrialist, a chef, and an actor. Yet in my varied and exhaustive catalogue of careers, I never wanted to be a wife or a mother. In my adolescence, donning puffy white dresses with lace veils or nursing doll babies never held much interest for me. To my surprise, however, and sometimes, dismay, I have done things I had not expected, and lately, I hesitate to rely on the conviction I felt when I was eight or twenty.
As my mother had often said, girls who never anticipated marriage always got married before the other who had longed to wed. As the middle girl of three daughters I fulfilled my mother’s sage observation. In the words of my Korean kin, I was the first on to leave my father’s house to go to my husband’s house. Christopher and I were married in the fall of last year and as quickly as our wedding ceremony passed in mere hours, our one-year wedding anniversary is fast approaching.
In thinking back to my week-long wedding festivities, the most unsettling recollection I have from all of the events is the closing remark of my father-in-law’s toast offered at the rehearsal dinner.
My father-in-law, an elegant man who had been a member of the Foreign Service, raised his glass of white wine to toast the engaged couple. Especially for the rehearsal dinner, I had my hair styled in a chignon and had my makeup applied professionally that afternoon at the coiffure at Bergdorf Goodman’s, and as I sat in my seat in the bird and flower print wallpapered room at the Sky Club, which is perched on top of the former Pan Am building, I felt certain that all the guests’ eyes were focused on my expensively decorated head. Nervously, I tucked a wisp of stray hair back into place and waited for my father-in-law to finish. Displaying the grace of a man who has spoken publicly many times, he thanked everyone for coming and stated how joyful he was about the upcoming wedding. He ended his toast by wishing Christopher and me many years of happiness and finally, many, many grandchildren. The guests cheered at this point and suddenly, I felt all pairs of the families’ eyes directing their gaze from my head to my stomach. I smiled uncomfortably.
As a New York business lawyer, I have come to know many professional women who work in my field. Despite our common career and business interests, when I talk to these women, I have noticed that we rarely speak about structuring private placement offerings, the varying tranche interest rates created from manipulating asset pools, or the financing of off-shore deals. With the exception of griping about certain projects, annoying colleagues, or the hours that we labor, the rising star of all conversation topics is motherhood. A week does not pas by where some female lawyer I know either from work, graduate school, or professional association mentions the motherhood question and its actual or perceived effects on her career and marriage.
In my single, brief year as a professional in New York City, I have learned the following from the female attorneys I have encountered: most women attorneys want children and the same women believe that having children will harm, delay, halt, obliterate, or overshadow their legal career. This dialectic of maternal desire and anticipated professional destruction invades the conversations I have with my friends, colleagues, and acquaintances who are female lawyers, and I find that the tension between such a powerful longing and an all-too-possible obstruction is transforming my budding thought about motherhood.
This is the drill: when you go to one of the top-ten law schools and you are the top third of such a law school, it is understood in the profession that certain courses are charted for you. In the fall of your second year in law school, you interview at a law firm for a summer associate position in a place like New York City for the summer months following your second year. If the firm likes you, the partners ask you to return when you graduate after completing your third and final year; this is called “the offer.” If you accept the offer, you take the bar examination after you graduate and start your career at the law firm in which you were a summer associate, but now you are deemed and associate. After eight or nine years or so of being an associate at the firm, you may be considered for partnership, and if all works out well, you become a junior partner. Keep in mind that there are many variations to this outline, but this is the stuff you are weaned on in law school if you are interested in the private sector- the goal, you are informed, is partnership. At the very minimum, however, to make partner, you must be on the track for partnership.
Fortunately or unfortunately, not everyone makes partner. In fact, fewer and fewer people are asked to be partner each year, and as I continue working, I notice everywhere fewer and fewer women are in fact partners, and since more and more female associates get off the partnership track, the future seems assured that there will always be fewer women partners. Whether it is a true theory or not, it is commonly believed that women associates leave the track to have children, either to stay home with them until the children are five or so, or to get jobs which are physically less demanding. So as a first-year associate, I look around me and I look above me and I notice we have come a long way but we have a long way to go.
I hear male associates whisper that women are in some ways lucky, since they don’t have to stay on the track, especially the married ones, and to my shock, I can’t say that I always disagree with them. In material terms, as a married woman with a husband who can support me, I would have shelter, food and comforts even if I quit my job today. Nevertheless, I have always been hungry for more than my material needs.
Lately, I have been contemplating the sheer irony of my foresisters demanding the right to get on the track and then for me to realize how brutal it is to stay on it when you want other things, too, like, children, for one. And I hear my girlfriends asking themselves as I ask myself, why stick it out? Why should I have to bill so many hours, why should I give up relationships, why should I always be politically neutral, why should I wear these incredibly boring clothes, why should I give up having children or perhaps, worse, watch another woman raise them? Are my female colleagues and I the intended heirs of the legacies of <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>? Have we eaten our fill of our portion of equal opportunities and are we pushing away our plates?
Somewhere down deep, deep beneath the fear of failure and the pain of humiliation, I ask myself seriously if I still believe that I can do anything. I haeard a clear voice cheering me on to keep at my goals as it pushed me forward when I was in elementary school, junior high school, and high school. I heard such a voice get dimmer, fuzzier when I got to college and law school. Lately, I hear a voice that doesn’t sound familiar to me in my head - no, it says, no, girl, you can’t do it all, no one can do it all. So, Harriet, Susan, Charlotte, Angela, Betty, and Emma, did you hear such a nasty voice? Would you have even attempted to bill 2,500 hours a year, stay married, and raise children? Ladies, did I miss you point? I never thought I wanted to be a wife. It just wasn’t on my list of things to do. And now that I am a wife, I feel privileged to feel such a profound level of intimacy and friendship. Because I was wrong about the institution of marriage, now I think, although I never thought I wanted to be a mother, my adolescent certainty against such a prospect has flagged. I’m not so sure anymore. Yet the downside of choosing motherhood has been spelled out to me. My female colleagues, alumnae, and girlfriends seem convinced and are warning me that, if I want children, I have to make a choice, I must give up my space on the track to drive a station wagon in suburbia.
It is spring in Central Park and I am staring at the marvelously painted horses of the merry-go-round, and as I wait in line to take my turn, I watch the brass ring revolve around the striped axis. I think to myself, I don’t know if I want to be a partner and I don’t know if I want to be a mother and I don’t know if I can be both at the same time, but I know that right now I feel cornered. I sway in time to the tinny music and I wait patiently for my ride to start.
**pain au chocolat.**
I was late for church this morning. I had forgotten that the morning service was moved up to 10:30, so I walked in half an hour late. When I walked out of the service at noon, I felt disoriented, as I usually do when I’m not on schedule. Unlike the mildewy weather of yesterday afternoon, today was breezy and light. So instead of taking a taxi directly to work like I had done yesterday, I decided to walk down Fifth Avenue and pick up a few tubes of my favorite lipstick at <NAME> before heading to the office.
Whenever I enter this New York departments store, I feel like I’ve stepped into a beautiful gift box. The floor-to-ceiling Lalique windows gleam behind the gilded cherubim standing on glass and pewter shelves holding four-ply amber-colored cashmere sweaters. Neat rows of obscure French perfumes with exotic names suggestive of vegetation indigenous to Morocco and Tunisia frame the curving staircase. Day after day of reading black and white corporate documents, it is refreshing to see colors and textures and smell floral and citrus scents from sensually shaped crystal flacons. I am out of my office and it feels good to be giddy and not so serious about the world of business transactions. At this moment, I am concerned solely with the shade of my lipstick.
After I purchased two tubes of my favorite lipstick, Auburn by MAC, I ascended the stairs clutching my miniature brown and white striped shopping bag and my brown briefcase. Treat of all treats, I decided to have a cup of coffee at the cafeX located on the second floor of the store. I was going to savor being a lady of leisure for at least thirty more minutes this Sunday afternoon before I trudged toward my office to finish drafting more documents for the four acquisition deals I had to close before the end of the month.
The host seated me near the frosted glass windows. From my table I had a view of a full street block of the Fifth Avenue Book Fair which was being held outside. Decadently, I ordered a coffee and a pain au chocolat.
Ever since I left college, I get a little sad when I see stores or vendors which sell books. I stared out of the window and saw all these people milling about the stalls covered with cheerful canopies that were filled with stacks and stacks of fresh new books. I felt a tinge of envy of all those people on the street below who had the luxury of spending the day at the book fair. Stealing these thirty minutes or so to eat my brunch at this posh cafeX filled me with guilt since I had so many items to cross off my list of to-do’s back at the office.
Sitting a table covered with demask linen and sipping a cup of bitter hot coffee cut by the sweetness of a flaky croissant, I contemplated my guilt mingled with envy. My envy is easy to explain. When I was in college, I wanted to be a fiction writer more than anything else. I took writing courses, wrote essays, and published my stories in little campus magazines. When I announced my decision to write, my parents made it very clear that they would not support such an unsound and baseless decision either economically or emotionally.
My father had said to me: “You’re too young, you haven’t lived your life yet. What could you possibly have to say? No one would care to read your books. All you’ve ever done was go to school, you can always write when you get older. You should go to law school. Learn a trade.” And I believed him.
Frankly, I was envious not only of the people outside my window who had the leisure to peruse the tables laden with books, but also of the authors of such books. When I was twenty years old, becoming twenty-five seemed very far away, and by then, I had imagined that I would have written at least two acclaimed novels with moving plots and serious characters. I had not yet done so, and in lieu of such a grandiose feat, I had learned a specialized trade so that I would no longer eat my father’s bread. I had learned to put bread on my own table, bread which happened to be at the moment a layer of chocolate enrobed in layers of buttery pastry. As I poured more hot coffee from the well-polished pewter pot into my porcelain cup resting on its gold-rimmed saucer, I shifted my gaze from the view from the window to the restaurant menu.
I had guessed that the waiter was a native French speaker from his accent when he had stopped to take my order. Hence, when he had asked me what I would like, I tried to pronounce “pain au chocolat” as artfully as possible, recollecting the acerbic comments made by a college friend who was French whenever he heard people attempting to pronounce such common menu terms. _Pain_, how could a word meaning sustenance to one man, mean hurt to another man. I wondered.
My mingled guilt is not so easy to explain. On average, as a junior associate, I work almost six days a week and each day I am at my office well over twelve hours. Surprisingly, at the end of each day, I cannot finish everything which needs to get done. My peers have the same curse it seems, so like them, I return, begrudgingly, to work on the weekends and attempt to catch up. Since I have started my job as a young lawyer, I rarely stop working and I never stop thinking about my work. No matter how hard I try. I can’t finish it all.
When I was growing up in Korea, I heard the story of _Kongji and Potji_ which is about the virtuous girl, Kongji, whose father remarries a horrible woman who has an evil daughter Potji, who abuses this girl and through certain miracles, Kongji ends up marrying a nobleman who rescues her from such hardship. Kongji is the good and beautiful heroine and each time her stepmother hands her one onerous task after another, a team of toads or a bevy of birds descends upon her home and aids her in completing the nearly impossible tasks.
There are moments when I feel like Kongji. Certain senior associates and partners begin to resemble Kongji’s stepmother, and drafting half a dozen documents or plowing through boxes of due diligence review in one night begin to parallel having to fill large clay vessels with hidden cracks with water or hulling a hundred bags of rice by hand. At my office, there are no fairy toads to sit in the bottom of the vessels to prevent the seepage so I can fill the jars with water, and there are no friendly birds to hull the mountains of rice with their tiny beaks. The evenings advance quickly, and I am alone drafting my agreements and reviewing the piles of documents. When my eyes give, I finish what I can and head home.
New York City is magical at the very early hours of the morning. The damp, tar-paved streets glisten with the reflections of the lighted storefronts. In the quiet taxi ride returning home, I remind myself gently that I am historically privileged to have this job. After all, I tell myself, my forbears could not have imagined that their girl-child descendant would be an attorney. At the same time, I try not to hear the calm voice of my father, who expected such an outcome.
<file_sep>/content/event/amherst-college-12.md
---
title: 'PEN World Voices Festival: The High Cost of Education'
date: 2019-05-06 19:00:00 -0400
show_time: true
venue:
name: The New School
address: 66 W. 12th Street
city: New York
state: NY
zip: 10011
link: https://worldvoices.pen.org/session/the-high-cost-of-education/
description: A conversation between <NAME> (author of EDUCATED) and <NAME>
images:
- "/uploads/Pen-WorldVoices-logo.png"
---
<file_sep>/content/event/babel--just-buffalo-literary-center-.md
---
title: 'Just Buffalo Literary Center '
date: 2019-03-20 20:00:30 -0400
images: []
description: ''
link: http://www.justbuffalo.org/event/babel-min-jin-lee-2019-03-20/
show_time: true
venue:
address: 3 Symphony Circle
city: Buffalo
name: <NAME>
state: NY
zip: 14201
---
<file_sep>/content/news/2017-05-20-new-statesman-book-review.md
---
title: 'New Statesman: Book Review'
date: 2017-05-20 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: New Statesman by <NAME>
link_to_original: 'http://www.newstatesman.com/culture/books/2017/05/pachinko-min-jin-lee-tells-story-koreans-living-japan'
description:
---
By <NAME>
The multigenerational family saga, spanning decades and often countries, has offered a way of looking at how individuals find themselves situated in relation to history, how they battle it and survive, sometimes even with a measure of triumph. The Korean-American novelist <NAME>’s second novel, Pachinko, marries the story of the generations with the immigrant narrative, but with a twist: instead of the now exhausted account of people fetching up in the West to forge a new life amid the travails of assimilation, Lee looks at a little-known history of exile – that of Koreans in Japan in the 20th century.
Lee’s novel begins in 1910, among poor people on the islet of Yeongdo in Busan, in a Korea that has been occupied by Japan. Hoonie, a good, simple, hard-working man with a cleft palate and twisted foot, finds a bride when he meets Yangjin, a destitute farmer’s daughter. Their only child, Sunja, becomes pregnant at 16 after a brief romance with a charismatic and mysterious older man, Hansu – who, we later discover, is a yakuza, a member of Japan’s organised crime network. Hansu is unable to marry Sunja because he already has a wife and family in Japan. A young Christian pastor, Isak, offers to marry her and give the child paternity, but he is bound for Osaka – and here Sunja moves to Japan, as does the novel. Lee’s cast of Korean characters will not be able to return home; nor will they be born on foreign soil.
In Osaka, Isak and Sunja join Isak’s brother, Yoseb, and Yoseb’s wife, Kyunghee, in a Korean ghetto called Ikaino. It is here that the outrageous discrimination against Korean immigrants begins to mark the narrative, providing the insistent moral/political heart of the book. Theirs is a hardscrabble life: Isak earns a pittance as the minister of the local church, and the family is almost entirely supported by Yoseb’s small income from his job as a foreman and mechanic at a biscuit factory.
Sunja’s first son, Noa, is born, and then her second, with Isak – Mozasu. After the Second World War breaks out, Isak is arrested on the flimsiest of charges during the crackdown on Koreans and disappears for more than two years. When he is released he is a man broken by torture and tuberculosis and he dies shortly afterwards.
Meanwhile, much against the wishes of Yoseb, the two women have set up a market stall selling home-made kimchi and sweets and, later, cooking in a restaurant. The hardship gets worse as the war progresses; then Hansu reappears and arranges for the family to be moved to a farm in the country before the Allied bombing of Japanese cities. It emerges that he has kept tabs on the family because he has a vital stake in it: Noa, his son.
After the war, the situation gets worse. Yoseb is severely burned in an accident, but despite their dismal financial situation Sunja refuses to accept help from the powerful and wealthy Hansu. Noa, taking after Isak, turns out to be a gentle, bookish, upright soul, while his brother Mozasu is more carefree, dashing and worldly. By dint of hard work, and overcoming all odds, Noa gets a place to study English literature at the prestigious Waseda University in Tokyo but the family can’t afford to send him there. Hansu steps in and paves the way, despite Sunja’s misgivings and Yoseb’s opposition.
Mozasu becomes a successful manager and, later, an owner of pachinko parlours (pachinko being the pinball-style gambling machine that gives the book its title), moving from Osaka to Yokohama. Inevitably Noa finds out who Hansu really is, and when he does the sense of shame and disgust that overcomes him has far-reaching consequences.
The self-loathing that is thrust upon Noa becomes a metaphor for Koreans living in Japan – those whom the Japanese call zainichi and look upon as less than human. Noa’s erasure of his Korean identity and transformation into “Nobuo Ban”, his Japanese name, is uneasy at best: “In no way did he see his current life as a rebirth. Noa carried the story of his life as a Korean like a dark, heavy rock within him. Not a day passed when he didn’t fear being discovered.”
It is a sentiment that recurs in the novel, echoed by several characters, with the coherence and heft of a motif. Throughout the book, spanning nearly a century and four generations, Koreanness is a flickering state, in an unstable equilibrium between erasure, first of all; problematic, even impossible assimilation; and, finally, an inchoate assertion. In Solomon, Mozasu’s son, who attends university in the US but chooses to continue his father’s pachinkobusiness over working for an investment bank, the story of those in permanent exile is not returned to, but reclaimed as a broken past.
Lee writes about every character with sympathy, generosity and understanding; in particular, Sunja, the woman who holds the story together, is a wonderful creation. The immensely dignified survivors in this story are the two women at its core, Sunja and Kyunghee: history has bent but not broken them. They have endured.
<NAME>’s third novel, “A State of Freedom”, will be published in July by Chatto & Windus
<NAME> is an Indian writer writing in English. His book The Lives of Others was shortlisted for the 2014 Man Booker Prize and he reviews fiction for the New Statesman.<file_sep>/content/event/bedford-free-library.md
---
title: Bedford Free Library
date: 2017-10-11 19:00:00
show_time: true
venue:
name: Bedford Free Library
address: 32 Village Green
city: Bedford
state: NY
zip:
link: 'http://bedfordfreelibrary.org'
---
In Conversation with <NAME>.<file_sep>/content/news/2007-06-13-the_urban_muse.md
---
title: "The Urban Muse"
date: 2007-06-13T22:09:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "The Urban Muse"
link_to_original: "http://www.urbanmusewriter.com/search?q=min+jin+lee"
description: ""
_slug: 2007-06-13-the_urban_muse
---
<NAME> is yet another example of the lawyer-turned-writer phenomenon. This Yale alum is the author of Free Food for Millionaires, a delightful debut novel about a recent college grad trying to reconcile the thriftiness of her ...
<file_sep>/content/news/2017-12-30-south-china-morning-post-james-kidds-writer-of-the-year.md
---
title: 'South China Morning Post: <NAME>''s "writer of the year"'
date: 2017-12-30 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: South China Morning Post
link_to_original: >-
http://www.scmp.com/magazines/post-magazine/books/article/2125856/2017s-best-books-big-name-writers-returned-spotlight
description:
---
By <NAME>
"My writer of the year is <NAME>, whose superb new novel Pachinko was accompanied by a timely reprint of her superb old one, Free Food for Millionaires (2007)."
For the complete list and article, please click the link.<file_sep>/content/event/free-food-for-thought-a-conversation-with-min-jin-lee.md
+++
date = 2022-04-12T22:00:00Z
description = "Join the AACC’s Alumni Engagement team for an intimate conversation on identity, literature, and life after Yale with <NAME> ‘90!"
images = []
link = "https://aacc.yalecollege.yale.edu/event/free-food-thought-conversation-min-jin-lee-0"
show_time = true
title = "Free Food for Thought: A Conversation with <NAME>"
[venue]
address = "168 Grove St"
city = "New Haven"
name = "<NAME> SC, Presidents' Room "
state = "CT"
zip = "06511"
+++
<file_sep>/content/event/tucson-festival-of-books.md
---
title: Tucson Festival of Books
date: 2018-03-11 11:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
11.30am: Panel/Endurance with <NAME>, <NAME>, and <NAME>
2.30pm: Panel/Immigration with <NAME>, <NAME>, and <NAME>
<file_sep>/content/news/2017-07-26-new-republic.md
---
title: New Republic
date: 2017-07-26 12:00:00
categories: ["News"]
tags:
- Reviews
- News
- Interviews
attribution: New Republic
link_to_original: 'https://newrepublic.com/article/144029/trump-ruining-book-sales'
description:
---
Is Trump Ruining Book Sales: Authors and publishers alike are finding that it's hard to sell books in a political climate where truth is stranger than fiction.
By <NAME>
A very interesting and smart essay written by <NAME> in the New Republic.
For the complete article, please click the link below:
"Even with these falling sales numbers, fictional political works have been given much more media attention in the Trump era, perhaps because of their newfound urgency. <NAME>, author of Pachinko, a sprawling, multi-generational saga of a Korean immigrant family that struggles to assimilate in imperial Japan, said, “My novels critique money, class, race, ethnicity, sexuality, religion and history; consequently, my politics are very evident in my books. I think readers will not read my books unless they are interested in those topics.” Evidently, many of them are. The novel was released not long after Trump’s initial executive order declaring a Muslim ban, and received rave reviews from NPR, USA Today, and The New York Times Book Review. Anne Branigin of Fusion included Pachinko as one of the books of writers shedding light on Trump’s ban."
<file_sep>/content/event/schaumburg-il.md
---
title: " Bristol Public Library- 2020 Friend's Author Luncheon"
date: 2021-10-14T00:00:00-04:00
show_time: true
venue:
name: DoubleTree Hotel
address: 42 Century Dr.
city: " Bristol"
state: CT
zip: ''
link: ''
description: ''
images: []
---
<file_sep>/content/event/the_page_series_at_the_national_arts_club.md
---
title: The PAGE Series at The National Arts Club
date: 2007-06-14T20:00:00-05:00
venue:
name: National Arts Club
link: www.nationalartsclub.org
_slug: the_page_series_at_the_national_arts_club
---
The PAGE Series at The National Arts Club
(Hosted by <NAME> and <NAME>)
<NAME>, <NAME> and <NAME>
*Please note that THIS EVENT IS AT 7PM* and not at 7.30 as previously posted. Apols.
<file_sep>/content/event/harvard-university--julia-s.-phelps-lecture-at-radcliffe-institute-for-advanced-study-.md
---
title: 'Harvard University: <NAME> Lecture at Radcliffe Institute for Advanced
Study '
date: 2019-02-12 21:00:46 +0000
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: ''
description: "In Conversation with New Yorker writer and legal scholar <NAME>
Gersen\nKnafel Center: 10 Garden Street, Cambridge, MA 02138 \nTHIS EVENT IS FREE
AND OPEN TO THE PUBLIC"
---
<file_sep>/content/event/literary-death-match-brooklyn.md
---
title: 'Literary Death Match: Brooklyn'
date: 2017-01-24 20:00:00
show_time: true
venue:
name: The Bell House
address: 149 7th Street
city: Brooklyn
state: NY
zip:
link: 'http://www.literarydeathmatch.com/upcoming-events/jan-24-at-bell-house.html#'
---
Part Literary event, part comedy show, part game show, Literary Death Match brings together four of today's finest writers to compete in an edge-of-your-seat read-off critiqued by three celebrity judges, and concluded by a slapstick showdown to decide the ultimate champion.
Judges: <NAME>, writer of The Late Show with <NAME>; co-host Another Round podcast; <NAME>, comedian, improviser writer and masterful Youtuber; <NAME>, Jr., comedian and correspondent on the The Daily Show; and <NAME>, designer, actor and fashion expert.
Readers:
Round 1: <NAME> and <NAME>
Round 2: <NAME> and <NAME>
Cost: $12 preorder; $15 at the door<file_sep>/content/event/university_of_connecticut_storrs_connecticut.md
---
title: University of Connecticut, Storrs, Connecticut
date: 2007-10-29T07:19:00-05:00
show_time: true
venue:
name: University of Connecticut
address:
city: Storrs
state: CT
zip:
link:
---
Asian American Cultural Center
slAAM! Book Club
Reading and Q&A with <NAME>
venue: University of Connecticut Co-Op Book Store
TIME: 4.30PM
Public Event
<file_sep>/content/news/2017-04-09-san-francisco-chronicle-recommended-reading.md
---
title: 'San Francisco Chronicle: Recommended Reading'
date: 2017-04-09 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: San Francisco Chronicle
link_to_original: 'http://www.sfchronicle.com/books/article/Recommended-reading-April-9-11053397.php?cmpid=fb-premium'
description:
---
Pachinko
By <NAME>
(Grand Central; 490 pages; $27)
Lee’s sweeping four-generation saga of a Korean family is an extraordinary epic, both sturdily constructed and beautiful.<file_sep>/content/news/2018-02-24-a-new-essay-appears-in-the-new-yorker.md
---
title: A new essay appears in The New Yorker
date: 2018-02-24 12:00:00
categories: ["Media"]
tags:
- Essays
attribution:
link_to_original: >-
https://www.newyorker.com/culture/culture-desk/after-the-pyeongchang-winter-olympics-healing-the-deepest-fracture
description: >-
During the opening ceremony for the Winter Olympics in Pyeongchang, I didn’t
expect to cry when athletes from two Koreas marched as one into the stadium,
carrying the flag of unification, but tears filled my eyes. It was as if my
body couldn’t be stopped from remembering some unspent grief.
---
> The twenty-third Winter Olympics are closing out their second week, and the Games may yet live up to their billing as the “Olympics of peace.”
["After the Pyeongchang Winter Olympics, Healing the Deepest Fracture"](https://www.newyorker.com/culture/culture-desk/after-the-pyeongchang-winter-olympics-healing-the-deepest-fracture) appeared in *The New Yorker* on February 24th. <file_sep>/content/event/princeton-public-library.md
---
title: 'Princeton Public Library and Labyrinth Books: Princeton Migration Project '
date: 2018-04-18 18:00:00 -0400
show_time: true
venue:
name: <NAME>
address: 122 Nassau Street
city: Princeton
state: NJ
zip: ''
link: https://www.princetonlibrary.org/event/min-jin-lee-pachinko/
description: 'The Princeton Public Library and Labyrinth Books sponsor a reading and
booksigning of PACHINKO. '
images: []
---
<file_sep>/content/news/2017-02-02-the-new-york-times-book-review-stunning-novel.md
---
title: 'The New York Times Book Review: "Stunning Novel"'
date: 2017-02-02 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The New York Times Book Review
link_to_original: 'https://www.nytimes.com/2017/02/02/books/review/pachinko-min-jin-lee.html?_r=0'
description:
---
Home but Not Home: Four Generations of an Ethnic Korean Family in Japan
By KRYS LEE
FEB. 2, 2017
PACHINKO
<br>By <NAME>
<br>490 pp. Grand Central Publishing. $27.
<NAME>’s stunning novel “Pachinko” — her second, after “Free Food for Millionaires” (2007) — announces its ambitions right from the opening sentence: “History has failed us, but no matter.”
“Pachinko” chronicles four generations of an ethnic Korean family, first in Japanese-occupied Korea in the early 20th century, then in Japan itself from the years before World War II to the late 1980s. The novel opens with an arranged marriage in Yeongdo, a fishing village at the southern tip of Korea. That union produces a daughter, Sunja, who falls in love at 16 with a prominent (and married) mobster. After Sunja becomes pregnant, a local pastor offers her a chance to escape by marrying him and immigrating together to his brother’s house in an ethnic Korean neighborhood in Osaka. Together, they embark into the fraught unknown.
Pachinko, the slot-machine-like game ubiquitous throughout Japan, unifies the central concerns of identity, homeland and belonging. For the ethnic Korean population in Japan, discriminated against and shut out of traditional occupations, pachinko parlors are the primary mode of finding work and accumulating wealth. Called Zainichi, or foreign residents, ethnic Koreans are required to reapply for alien registration cards every three years even if they were born in Japan, and are rarely granted passports, making overseas travel nearly impossible. From a young age, Sunja’s oldest son sees being Korean as “a dark, heavy rock”; his greatest, secret desire is to be Japanese. His younger brother, Mozasu, even after he accumulates great wealth through his pachinko parlors, confides to his closest Japanese friend: “In Seoul, people like me get called Japanese bastards, and in Japan, I’m just another dirty Korean no matter how much money I make or how nice I am.” Mozasu’s son, Solomon, learns this too quickly after graduating from an American university. He returns to Tokyo on an expat package with the Japanese branch of a British investment bank, then is fired once his ethnic Korean connections are no longer needed for a business deal. Still, Solomon is of a new, less wounded generation. He believes there are still good Japanese people and sees himself as Japanese, too, “even if the Japanese didn’t think so.”
Like most memorable novels, however, “Pachinko” resists summary. In this sprawling book, history itself is a character. “Pachinko” is about outsiders, minorities and the politically disenfranchised. But it is so much more besides. Each time the novel seems to find its locus — Japan’s colonization of Korea, World War II as experienced in East Asia, Christianity, family, love, the changing role of women — it becomes something else. It becomes even more than it was.
Despite the compelling sweep of time and history, it is the characters and their tumultuous lives that propel the narrative. Small details subtly reveal the characters’ secret selves and build to powerful moments. After Sunja arrives in Osaka, her modest life is underscored when she enters what is only the second restaurant of her life. When her husband, Isak, is finally cleared of trumped-up charges and released from jail looking “both new and ancient,” their oldest son is “unable to take his eyes off his father for fear he’d disappear.” Their reunion is moving yet understated: Isak simply holds his son’s hand and says: “My dear boy. My blessing.”
Dozens more characters amplify the vortex of points of views: a hostess bar girl, a farmer who has “no wish for the war to end just yet” so that he can benefit from the higher black-market prices to realize “his grandfather’s dearest wish” of buying the adjoining land. The numerous shifts are occasionally jolting, but what is gained is a compassionate, clear gaze at the chaotic landscape of life itself. In this haunting epic tale, no one story seems too minor to be briefly illuminated. Lee suggests that behind the facades of wildly different people lie countless private desires, hopes and miseries, if we have the patience and compassion to look and listen.
<NAME> is the author of the novels “Drifting House” and “How I Became a North Korean.”
| A version of this review appears in print on February 5, 2017, on Page BR18 of the Sunday Book Review with the headline: Home but Not Home. Today's Paper | Subscribe |<file_sep>/content/news/2017-03-04-the-japan-times-profile-of-min-jin-lee-and-pachinko.md
---
title: 'The Japan Times: Profile of <NAME> and PACHINKO'
date: 2017-03-04 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: The Japan Times by <NAME>
link_to_original: 'http://www.japantimes.co.jp/culture/2017/03/04/books/book-reviews/pachinko-author-min-jin-lee-japans-ethnic-koreans-keep-beating-odds/#.WNHocc5OjE4'
description:
---
‘Pachinko’ author <NAME> on how Japan’s ethnic Koreans keep beating the odds
BY <NAME>
SPECIAL TO THE JAPAN TIMES
MAR 4, 2017
“I got lost all the time,” says writer <NAME> with a charming laugh, sitting in a hotel lobby in San Francisco’s Japantown.
Before a promotional appearance at a bookstore, she spoke to The Japan Times about writing her new novel “Pachinko,” a historical saga tracing four generations of a Korean family in Japan.
Despite the acclaim of her fiction debut “Free Food for Millionaires” in 2007, which was a best-seller in the U.S., Lee suffered existential self-doubt when producing her follow-up: the first English-language novel about the experience of Japan’s ethnic Koreans.
“I thought, ‘Nobody wants this book and I’m an idiot for having worked on it so hard,’ ” says Lee, who admires writers such as <NAME> and <NAME>. “But to succeed in writing, you must be willing to look stupid for a long time. ‘Pachinko’ took so long because I got it wrong so many times.”
Factual accuracy, as it turns out, was not the main challenge. Lee managed her sweeping history — which encompasses rural Korea in 1910 as well as Osaka, Japan, during World War II — by studying personal accounts, ethnographies and war diaries.
Much harder in terms of craft, she says, was achieving emotional authenticity. Lee, who emigrated from Korea to the U.S. at the age of 7, abandoned the first draft of “Pachinko,” afraid her characters had turned out stale and were chiefly defined by their suffering. A stay in Japan from 2007 to 2011 allowed her to interview Koreans in the diaspora, which helped to rectify misconceptions.
“They didn’t see themselves as victims,” Lee explains. “They were so tough that I felt foolish for having pitied them. The things that happened in history were horrid, but the Korean-Japanese I talked to weren’t waiting for an apology. They don’t expect things to get better or anyone to start telling the truth about the war. They’ve moved on and adapted. They save money to send their kids to school in America.”
This resilience informs the book, which opens with a perfect sentence: “History has failed us, but no matter.” It is a nod, in terms of technique, to <NAME>’s classic novel “Madame Bovary,” where a nameless first-person narrator appears only on the first page.
Lee extends the idea of resilience to the titular game of pachinko, which is central to the livelihoods of her protagonists: Like balls in a slot machine, her characters are thrown off track by historical forces. The game may be rigged, but the underdog keeps on playing.
Indeed, Korean history hasn’t been easy. When Japan annexed Korea in 1910, the taxes it introduced impoverished local farmers, rendering them economic migrants. Others were sent to Japan and forced to work in mining and construction.
During World War II, Koreans toiled in military factories, and some women were lured into sexual slavery for Japanese military brothels. Korean Christians, meanwhile, could be jailed, as the Korean independence movement was led by Presbyterian pastors.
Today, ethnic Koreans are the second-largest ethnic minority in Japan, after the Chinese. Ethnic Koreans are classified as foreign residents and required to state affiliation with either the North or the South. They may attain Japanese citizenship, which is difficult, but as a group they continue to be seen as foreigners.
Faced with persistent discrimination in finding housing and work, some ethnic Koreans pretend to be Japanese, adopting Japanese names and hiding their heritage (“a merciless and endless task,” Lee says).
While all of these issues feature in “Pachinko,” Lee never casts Japanese as villains. There is no resentment, only fraught, complex interaction. Lee thinks it unfair to blame modern Japan for the past — but what might the future hold for Koreans and Japanese?
“Things seem to be getting worse because the Abe administration is conservative,” Lee says. “Koreans are worried about the Japanese right-wing people, who tend to be against foreigners. But the Koreans in Japan aren’t even foreigners. They are essentially culturally Japanese. If a family has lived in Japan for three generations, it’s absurd to see them as foreigners. Clearly, this is about blood.”
While most ethnic Koreans have moved on, many still take measures to protect their families, and the Korean community’s political activism has helped all foreign residents in Japan. It has been mostly Koreans who went to court to protest discrimination, such as to end their mandatory fingerprinting in 1993. “As a result,” Lee adds with her ready laugh, “Japanese people often say, “Oh those Koreans are always making trouble.”
Asked what would surprise most people about Koreans, Lee debunks any notion of them as tragic victims.
“Koreans love to dance, they love to sing,” she says, her voice turning wistful. “If you actually know Koreans, you see how absurd the stereotype of the ‘Asian robot’ is. They love to laugh — they’re very affectionate. Maybe because of their history of oppression, when they feel you are part of their tribe, they are intensely loyal. I love that about Koreans!”<file_sep>/content/event/tattered-cover-bookstore.md
---
title: Tattered Cover Book Store
date: 2017-02-13 19:00:00
show_time: true
venue:
name: Tattered Cover Book Store
address: 2526 East Colfax Avenue
city: Denver
state: CO
zip: '80206'
link: 'http://www.tatteredcover.com'
---
Conversation with <NAME>, Chief Animator of Museum of Contemporary Art Denver
*Pachinko* is Tattered Cover's February Autographed Book Club Selection.<file_sep>/content/writing/2007-06-18-biblical_illiteracy_or_reading_the_bestseller.md
---
title: "Biblical Illiteracy or Reading the Bestseller"
date: 2007-06-18T22:12:25-05:00
categories:
tags: ["Essays"]
where_published: "ABC News"
link_to_original: "http://abcnews.go.com/International/Story?id=3289585&page=1 "
link_to_pdf:
description: "Biblical Illiteracy or Reading the Bestseller. Writers Often Agree That the Bible Is a Good Book. OPINION By <NAME>"
_slug: 2007-06-18-biblical_illiteracy_or_reading_the_bestseller
---
There has been a great deal of froth lately about how "God Is Not Great" and how religions have made a rot of peace. The argument is fizzy yet hardly new: The world is a mess, and it has become so through those who believe in God. Well, fine.
<file_sep>/content/event/anything.md
---
title: Mo Pitkin’s June 4th
date: 2007-06-04T20:00:00-05:00
venue:
name: The Reader’s Room at Mo Pitkin’s
link: www.mopitkins.com
---
Reading, hosted by <NAME> and <NAME>
<file_sep>/content/news/2017-12-02-the-herald-glasgow-what-have-the-great-and-the-good-been-reading-in-2017.md
---
title: 'The Herald (Glasgow): "What have the great and the good been reading in 2017?"'
date: 2017-12-02 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Herald (Glasgow)
link_to_original: >-
http://www.heraldscotland.com/arts_ents/15697911.What_have_the_great_and_the_good_been_reading_in_2017_/
description:
---
<NAME>, head of literature, Creative Scotland
Between Trump and everything else I wouldn’t have got through 2017 without Rebecca Solnit’s Hope in the Dark (Canongate) which I have in recent months sometimes found myself clutching like a flotation device. The Mother of All Questions (Granta) is a welcome follow up to that and convinces that feminism is still as fierce and relevant as ever, despite, well, the world.
Bloody Scotland (Historic Environment Scotland) was a brilliant publication capturing the unstoppable Scottish crime fiction scene in all its murderous glory via 12 short stories from writers including <NAME>, <NAME> and <NAME>, and an astute publishing move from the festival.
I read <NAME>’s Pachinko (Head of Zeus) this year while in Korea which brought my surroundings and contemporary politics vividly to life via a four-generational family saga. A pilgrimage to Muriel Spark’s home in Tuscany, ahead of the forthcoming centenary celebrations of 2018, led me to Loitering with Intent for the first time too, a novel which on its own in my view makes the justification for a whole year of Muriel Spark 100.
<NAME>’s Autumn (Hamish Hamilton 16.99) is a luminous book and is my favourite type of writing, which is to say simultaneously a beautifully constructed fictional exploration and wisely observed social critique.
For the complete article, please click the link.<file_sep>/content/news/Pachinko-is-the-runner-up-for-the-Dayton-Literary-Peace-Prize.md
---
title: Pachinko is the runner-up for the Dayton Literary Peace Prize
date: 2018-09-17 15:31:11 -0400
link_to_original: http://daytonliterarypeaceprize.org/2018-winners-press_release.htm
images: []
tags: []
categories: []
description: ''
draft: true
---
<file_sep>/content/news/2007-08-21-the_publishing_spot.md
---
title: "The Publishing Spot"
date: 2007-08-21T22:02:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "The Publishing Spot"
link_to_original: "http://www.thepublishingspot.com/min_jin_lee/"
description: ""
_slug: 2007-08-21-the_publishing_spot
---
This week I’m interviewing first-time novelist, <NAME> about how she mastered this 19th Century technique in her new book. It’s called Free Food for Millionaires, an epic novel employing some unfamiliar writing tools that all ...
<file_sep>/content/event/cincinnati-oh-mercantile-library.md
---
title: 'Cincinnati, OH: Mercantile Library'
date: 2018-03-06 19:00:00
show_time: true
venue:
name: Mercantile Library
address: 414 Walnut Street
city: Cincinnati
state: OH
zip: '45202'
link: 'http://new.mercantilelibrary.com'
---
<file_sep>/content/event/an-evening-with-author-min-jin-lee-reading-and-audience-q-a.md
+++
date = 2022-04-22T00:00:00Z
description = "Reading and Audience Q&A"
images = []
link = "https://events.uiowa.edu/59583"
show_time = true
title = "The Iowa Writers' Workshop Presents: An Evening with Author <NAME>"
[venue]
address = "125 North Madison Street"
city = "Iowa City"
name = "Iowa Memorial Union"
state = "IA"
zip = "52245"
+++
<file_sep>/content/review/tina-jordan--entertainment-weekly-on-free-food-for-millionaires.md
---
title: <NAME>, Entertainment Weekly on Free Food for Millionaires
attribution: <NAME>, Entertainment Weekly
date: 2007-03-11 18:03:11 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
*Free Food for Millionaires* is different from any book I’ve ever read—a big, juicy, commercial Korean American coming-of-age novel, one that could spawn a satisfying miniseries, and one that definitely belongs in this summer’s beach bag.<file_sep>/content/event/asian_pacific_american_heritage_festival.md
---
title: AAJA
date: 2008-05-04T05:29:00-05:00
venue:
name: Asian American Heritage Festival, New York City [CANCELED]
link: www.aaja.org
_slug: asian_pacific_american_heritage_festival
---
[THIS EVENT HAS BEEN CANCELED]
Book signing at the Asian American Journalists Association (AAJA) Booth
12PM-6PM
Union Square Park
<file_sep>/content/news/2017-05-27-hay-festival-min-jin-lee-and-julianne-pachico-talk-with-lena-de-casparis-audio.md
---
title: 'Hay Festival: <NAME> and <NAME> talk with Lena de Casparis (Audio)'
date: 2017-05-27 12:00:00
categories: ["Media"]
tags:
- Audio
- Interviews
attribution: 'Hay Festival: Hay Player'
link_to_original: 'https://www.hayfestival.com/p-12140-min-jin-lee-and-julianne-pachico-talk-to-lena-de-casparis.aspx'
description:
---
<NAME> and <NAME> talk to Lena de Casparis
FICTIONS: SCALE
Hay Festival 2017, Saturday 27 May 2017
<NAME>’s novel Pachinko is an epic tale of identity and survival and love, set across four generations of a Korean family in Japan. <NAME>’s stories collected as The Lucky Ones explore the riveting lives and stories of a huge range of people caught up in the violence of Colombia’s guerrilla insurgencies. They talk to Lena de Casparis of Elle magazine.
This event is available to listen. Please pay to download or stream.
Price: £1.00<file_sep>/content/event/jp-morgan.md
---
title: <NAME>
date: 2017-05-02 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
A Celebration of Asian Pacific American History Month:
A Conversation with <NAME>, Executive Director and Recruiting Manager of JP Morgan.
Sponsored by the ASPIRE Business Resource Group
<file_sep>/content/event/sydney-writers--festival-2018--on-the-record--historical-fiction.md
---
title: 'Sydney Writers'' Festival 2018: On the Record: Historical Fiction'
date: 2018-05-03 15:00:57 -0400
images: []
description: '<NAME>, <NAME>, <NAME>, and <NAME> '
link: https://www.swf.org.au/writers/min-jin-lee/
show_time: true
venue:
address: 245 Wilson Street
city: ''
name: Carriageworks, Bay 17, Eveleigh
state: ''
zip: ''
---
<file_sep>/content/writing/2008-01-18-wonder_woman_love_and_murder_by_jodi_picoult.md
---
title: "Wonder Woman: Love and Murder by <NAME>"
date: 2008-01-18T21:25:04-05:00
categories:
tags: ["Essays"]
where_published: "The Times (London)"
link_to_original: "http://entertainment.timesonline.co.uk/tol/arts_and_entertainment/books/fiction/article3210539.ece"
link_to_pdf:
description:
_slug: 2008-01-18-wonder_woman_love_and_murder_by_jodi_picoult
---
WHEN I WAS GROWING UP in Elmhurst, New York, it was a special day when I had enough coins for an Annabelle’s Rocky ...
<file_sep>/content/news/2017-01-05-elle-25-most-anticipated-books-by-women-2017.md
---
title: 'Elle: 25 Most Anticipated Books by Women 2017'
date: 2017-01-05 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Elle by <NAME>
link_to_original: 'http://www.elle.com/culture/books/g29296/best-books-female-authors-2017/'
description:
---
The follow-up to her bestselling debut Free Food for Millionaires, Lee's new novel is a saga set in 1930s Korea and then Japan, detailing the struggles of one family's poverty, discrimination, and shame in the wake of a daughter's pregnancy and subsequent abandonment by her lover. Winning early praise from <NAME> and <NAME>, it looks like Pachinko could be headed for the bestseller lists as well<file_sep>/content/event/harvard-university--mahindra-humanities-center.md
---
title: 'Harvard University: Mahindra Humanities Center'
date: 2018-04-25 18:00:33 -0400
images:
- "/uploads/9781455563920.jpeg"
description: <NAME> in conversation with <NAME>.
link: http://mahindrahumanities.fas.harvard.edu/content/min-jin-lee-conversation-claire-messud
show_time: true
venue:
address: 25 Quincy Street
city: Cambridge
name: <NAME>, Room 210
state: MA
zip: 02138
---
<file_sep>/content/event/yalewomen-d-c-.md
---
title: YaleWomen D.C.
date: 2017-06-21 18:30:00
show_time: true
venue:
name: '<NAME> & Reed LLP'
address:
city:
state:
zip:
link: www.yalewomen.org
---
Private Event.
In Conversation with novelist <NAME>.
<NAME>’s novel, The Calligrapher’s Daughter, won Borders’ Original Voices Award, was a Washington Post Best Historical Novel, and an Amazon UK #3 bestseller. She is the Mid-Atlantic Arts Foundation Creative Fellow at Millay Colony, and a fellow at Yaddo, MacDowell, Hedgebrook, and others. She teaches at Fairfield University’s MFA program.<file_sep>/content/event/book-the-writer.md
---
title: Book the Writer
date: 2017-05-04 19:30:00
show_time: true
venue:
name: Book The Writer
address:
city:
state:
zip:
link: 'http://bookthewriter.com'
---
<file_sep>/content/news/tatler-a-united-front-asian-americans-speak-up-on-stopasianhate-and-why-it-matters.md
+++
categories = []
date = 2021-08-03T04:50:11Z
description = ""
images = ["/uploads/02091541-210701-tatlerasia-large-group-b-010-3110wa-e-fogra39l-preview-maxwidth-2000-maxheight-2000-ppi-300-quality-100_cover_2000x1333.jpg"]
link_to_original = "https://hk.asiatatler.com/society/stop-asian-hate-racial-diversity"
tags = []
title = "Tatler: \"A United Front: Asian Americans Speak Up On #StopAsianHate And Why It Matters\""
+++
<file_sep>/content/writing/2010-03-26-travel_leisure.md
---
title: "TRAVEL LEISURE"
date: 2010-03-26T22:41:02-05:00
categories:
tags: ["Essays"]
where_published: "TRAVEL + LEISURE"
link_to_original:
link_to_pdf: "/uploads/Journal.pdf"
description: "
[](/uploads/Journal.pdf) An essay on my complicated issues about traveling appears in TRAVEL + LEISURE (Southeast Asia) in the April 2009 issue. It was surprisingly funny to brood on my anxieties about leaving the house. In the process of writing this essay, I figured out that I love the learning and seeing bits of travel even more than my consuming fear of the unknown.
My T+L editors were <NAME>, <NAME> & <NAME>.
"
_slug: 2010-03-26-travel_leisure
---
<file_sep>/content/writing/_index.md
---
title: "Writing"
menu:
main:
weight: 6
---
<file_sep>/content/event/shearman--sterling.md
---
title: Shearman & Sterling LLP
date: 2018-02-21 19:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
private event<file_sep>/content/writing/new-york-times-in-praise-of-bell-hooks.md
---
title: 'NYT: Breaking My Own Silence'
date: 2019-05-20T04:00:13.000+00:00
categories:
tags: []
where_published: New York Times
link_to_original: https://www.nytimes.com/2019/05/20/opinion/confidence-public-speaking.html
link_to_pdf:
description:
_slug: '2019-05-20T04:00:00.000+00:00'
---
"I am 50 years old, and after more than four decades of living in the West, I realize that like writing, talking is painful because we expose our ideas for evaluation; however, like writing, talking is powerful because our ideas may, in fact, have value and require expression.
As a girl, I did not know this power, yet this is my power now."<file_sep>/content/event/american-university-1.md
---
title: 'Singapore Writers Festival 2019 An Hour with: <NAME>'
date: 2019-11-09T16:00:19-05:00
images: []
description: In this conversation, New York Times bestselling author <NAME> speaks
about her novel, PACHINKO, a sprawling historical saga that follows four generations
of a Korean immigrant family in 20th century Japan. Expanding on questions of family
and identity from her novel as well as her own experiences as an Asian-American,
she will examine the intricacies of being a perceived outsider and the power of
fiction in bridging cultures.
link: https://www.sistic.com.sg/events/swf1119b
show_time: true
venue:
address: ''
city: ''
name: Victoria Theatre
state: ''
zip: ''
---
<file_sep>/content/news/2017-08-21-south-china-morning-post-10th-anniversary-review-of-free-food-for-millionaires.md
---
title: >-
South China Morning Post: 10th Anniversary Review of FREE FOOD FOR
MILLIONAIRES
date: 2017-08-21 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: South China Morning Post
link_to_original: >-
http://www.scmp.com/culture/books/article/2107596/book-review-free-food-millionaires-decade-re-release-offers-reveal
description:
---
Book review: Min Jin Lee’s Free Food for Millionaires, a modern-day Middlemarch but more fun, gets deserved re-release
Now-acclaimed Korean American author <NAME>’s novel about the social-climbing daughter of immigrants is as relevant in the Trump era as it was when Wall Street millionaires lived high on the hog under George W. Bush
By <NAME>
A decade has passed since Free Food for Millionaires was published by <NAME>, the Korean American author who has been winning acclaim this year for her sprawling family epic Pachinko.
As befits a culture obsessed with anniversaries and recycling the not-so-distant past, Lee’s debut has now been re-released with an interesting introduction by the author herself. Here she relives her long, and relatively tortuous journey towards publication, the most important part of which was realising that her own life – a young, ambitious Korean girl growing up in the Queens borough of New York – was a worthy subject for fiction.
Lee’s decade-long apprenticeship culminated in the story of Casey, essentially a young, ambitious Korean girl who had grown up in Queens. Thanks to the tireless efforts of her parents, Joseph and Leah, who run a dry-cleaning business, she studied at Princeton, where she had her first brushes with the high life.
Casey learned what to wear, how to speak and who to date. Her ambitions are embodied by Jay, a clever, but shallow English major who, as the action starts, slaves away as an investment banker at Kearns Davis. Jay is the personification of Casey’s secret American self: his existence and their relationship are utterly unsuspected by Joseph and Leah.
Despite learning valuable lessons in couture and deportment, Casey’s clamber up New York’s slippery pole was never likely to be frictionless: her cultural background and innate volatility ensure that. But two traumatic events sink her choppy progress, and start the tsunami that is Lee’s large, winding novel.
Firstly, she is punched in the face by her father, who feels his suffering in Korea and America has been disrespected by his self-centred daughter, whose fundamental aimlessness he takes as a personal insult. Bruised, distraught and effectively disowned, Casey picks herself up, and heads for the sanctuary of Jay’s Manhattan apartment, only to walk in as he completes the erotic triangle of a ménage à trois. Trauma number two.
Lee follows cause to effect with an adroit precision that Victorian novelists such as <NAME> would have admired. Casey’s occasionally exasperating contradictions are exposed when she immediately blows what little money she has on clothes that only she thinks she requires. Lee teases her signature pride and vulnerability to the surface when, frozen, hungry and desperate, Casey bumps into Ella, a prettier, quieter and richer version of herself who attended the same church in Queens.
Ella is not only Casey’s short-term saviour; she is the second of Lee’s heroines. Raised by her widowed father, <NAME>, Ella is denied a mother’s love, but granted material comforts that Casey slowly learns to accept. Ella has her own beau to be, Ted, a Korean from Alaska who treats Ella like a valuable porcelain asset, drives himself to succeed also at Kearns Davis, and finds Casey a job, with a mixture of motives (power, condescension, sexual curiosity) that make you suspect something is not entirely right in his character. And so it eventually proves, but not before he marries Ella and gets her pregnant with a daughter, Irene.
Free Food for Millionaires is ageing remarkably well. The title’s sharp joke is as telling in Trump’s America as it was at the tail end of George W. Bush’s. The millionaire bankers on Kearns Davis’ Asia desk earn a free lunch (a pointed Indian meal, in this instance) after a lucrative deal. If you needed an image for the ever-widening divides separating rich and poor, this is one.
Casey’s leap across this economic chasm is also that of Joseph and Leah who go from Korean poverty to working-class American aspiration. Lee’s thematic acuity is matched by her gifts for dialogue, and creating constant interest with plot hooks that would not be out of place on a box-set binger: infidelity, financial irresponsibility, secret longing, sudden despair, moments of warm-hearted triumph against the odds.
One’s passionate engagement with Lee’s cast owes much to a narrative method that allows constant access to each character’s thoughts within a single scene. The technique is like a film cut that not only shows you another visual point of view, but an existential point of view. Granted, it is a little disorienting, and even overwhelming in the early chapters.
Before Joseph strikes his daughter, we shuttle from Casey’s entitled rage to his entitled self-pity, from his wife Leah’s impotent desolation to Tina’s melancholy resignation. The physical blow is genuinely shocking, and not just for the violence itself. You feel over half a century of unhappy striving (Joseph), two decades of resentment as Casey strives to fulfil her parents’ hopes, which, ironically, only create fresh points of conflict.
Late in the action, Casey finds herself reading <NAME>’s seminal Victorian masterpiece Middlemarch, which exerts an unmistakable influence on Lee’s own story: an epic sweep of economics, medicine, overspending, social mobility, transgression, comedy and tragedy. Lee reconfigures the original material to her own ends.
It is no exaggeration to say that Lee’s debut deserves to be mentioned in the same breath as Eliot’s great doorstopper. What is more, it is arguably even more fun.<file_sep>/content/news/boston-globe-min-jin-lee-s-free-food-for-millionaires-in-development-at-netflix.md
---
title: 'Boston Globe: <NAME>’s ‘Free Food for Millionaires’ in development at
Netflix'
date: 2021-01-29T00:50:11-05:00
link_to_original: https://www.bostonglobe.com/2021/01/29/arts/min-jin-lees-free-food-millionaires-development-netflix/
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/news/vulture-min-jin-lee-and-alan-yang-join-forces-for-netflix-series.md
---
title: 'Vulture: <NAME> and <NAME> Join Forces for Netflix Series'
date: 2021-01-27T00:50:11-05:00
link_to_original: https://www.vulture.com/2021/01/free-food-for-millionaires-tv-shows-netflix.html
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/news/2017-01-27-san-diego-magazine-top-5-books-to-read-in-february-2017.md
---
title: 'San Diego Magazine: Top 5 Books to Read in February 2017'
date: 2017-01-27 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: San Diego Magazine
link_to_original: 'http://www.sandiegomagazine.com/San-Diego-Magazine/February-2017/Your-Shelf-Life-5-Books-to-Read-in-February/'
description:
---
Your Shelf Life: 5 Books to Read in February
A curated list of this month's top reads
BY <NAME>
Published: 2017.01.27 03:50 PM
<NAME>’s successor to her critical hit Free Food for Millionaires is a story of a Korean family in Japan. Pachinko follows a woman shunned by her family when she becomes pregnant, forcing her into a marriage and exile.
<NAME>’s Lincoln in the Bardo unfolds over a single night after the death of President Lincoln’s son Willie. The young Lincoln enters a purgatory and meets characters who allow Saunders to explore philosophical questions.
Like she did in her best-selling novel Orphan Train, <NAME> mixes historical fact and fiction in A Piece of the World. It tells the story of <NAME>, the enigmatic muse of American painter <NAME>.
Revisit Fidel Castro’s ascendancy in Castro’s Cuba. Journalist Lee Lockwood got incredible access to Castro and photographed Cuba in the ’60s for this art book, relevant again after the revolutionary’s recent death.
Viet Thanh Nguyen’s short story collection The Refugees explores the split existence of those between worlds, like a Vietnamese refugee living with two gay men in San Francisco.<file_sep>/content/event/lic-reading-series.md
---
title: LIC Reading Series
date: 2018-01-09 20:00:00
show_time: true
venue:
name: LIC Bar
address: 45-58 Vernon Boulevard
city: Long Island City
state: NY
zip: '11101'
link: 'https://www.licreadingseries.com/events'
---
Series curated by <NAME>.
Reading with <NAME>, <NAME>, and <NAME>.<file_sep>/content/event/wall-street-journal-women-in-work-.md
---
title: 'Wall Street Journal: Women in the Workplace'
date: 2018-10-23 13:30:52 -0400
images: []
description: 'In conversation with WSJ '
link: https://womenin.wsj.com/events/women-in-the-workplace-2018/
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/miami.md
---
title: BOOKS and BOOKS, MIAMI
date: 2008-04-21T05:18:00-05:00
venue:
name: Books & Books, <NAME>, Miami, FLA
link: www.booksandbooks.com
---
Reading and Q&A
7.30PM
<NAME>
9700 Collins Avenue
<NAME>, FLA 33154
305-864-4241
<file_sep>/assets/css/config/tailwind.config.js
module.exports = {
future: {
// removeDeprecatedGapUtilities: true,
// purgeLayersByDefault: true,
},
purge: require('./purge.config.js'),
theme: {
extend: {
colors: require('./colors.config.js'),
fontFamily: require('./fonts.config.js'),
maxWidth: {
'8xl': '90rem'
},
spacing: {
'4m': '1em'
}
}
},
variants: {},
plugins: [
require('@tailwindcss/typography'),
// ...
]
};
<file_sep>/content/news/2017-01-22-toronto-star-sweeping-and-powerful.md
---
title: 'Toronto Star: "Sweeping and Powerful"'
date: 2017-01-22 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Toronto Star By <NAME>
link_to_original: 'https://www.thestar.com/entertainment/books/2017/01/22/historical-fiction-to-sweep-you-to-another-time-from-the-1930s-to-the-1980s.html'
description:
---
Pachinko
By <NAME>
Grand Central, 496 pages, $35
Sweeping and powerful, Pachinko is the story of a Korean family told over seventy years and through four generations. It begins in Korea in the early 1900s: Sunja’s downtrodden family has high hopes for their glittering prize of a daughter — until she’s plucked out from under them by a charming fish broker who tells her too late that he’s already married. Pregnant and alone, Sunja is rescued by a young missionary who says he will marry her and bring her with him to Japan. Here, Koreans are considered second-class citizens and are discriminated against even if they were born in the country. Eventually Sunja and her family manage to rise above, securing their place so their descendants can live in Japan and tell their own stories. This novel is weighty and detailed, yet time passes quickly when immersed in its pages. The many characters are finely drawn and each layer of the story is expertly placed.<file_sep>/content/news/2017-04-19-columbia-university-weatherhead-east-asian-institute.md
---
title: 'Columbia University: Weatherhead East Asian Institute'
date: 2017-04-19 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
- Video
attribution: Columbia University Weatherhead East Asian Institute
link_to_original: 'http://weai.columbia.edu/watch-min-jin-lee-discuss-her-acclaimed-new-novel-pachinko/'
description:
---
April 19, 2017 by <NAME>
The Weatherhead East Asian Institute is pleased to share an April 11, 2017 interview with <NAME>, author of the acclaimed new novel Pachinko. During the interview, <NAME> discusses the experiences and research that led her to write the novel, which follows four generations of an ethnic Korean family living in Japan from 1910 to 1989.
Pachinko, published in February 2017 by Grand Central Publishing, is a national bestseller, a New York Times Editor’s Choice and an American Booksellers Association’s Indie Next Great Reads. “This stunning novel chronicling four generations of an ethnic Korean family in Japan is about outsiders and much more,” The New York Times Book Reviewstated. “A fascinating look at immigrant life among Koreans — and the prejudices they face — in Japan.”
<NAME> went to Yale College where she was awarded both the Henry Wright Prize for Nonfiction and the James Ashmun Veech Prize for Fiction. She attended law school at Georgetown University and worked as a lawyer for several years in New York prior to writing full time. From 2007 to 2011, <NAME> lived in Tokyo, where she wrote Pachinko. She lives in New York City with her family.
Please click here to see the video on YouTube.<file_sep>/content/news/2017-12-03-seattle-post-intelligencer-10-best-books.md
---
title: 'Seattle Post-Intelligencer: 10 Best Books'
date: 2017-12-03 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Seattle Post-Intelligencer
link_to_original: >-
http://www.seattlepi.com/lifestyle/blogcritics/article/Ten-Books-That-Made-2017-More-Bearable-12403181.php
description:
---
By <NAME>
Pachinko by <NAME>. In a small fishing village on the banks of the East Sea, a club-footed older man marries a fifteen-year-old girl. The couple have one child, their revered daughter Sunja. But when years later Sunja falls pregnant by a married man, the family could face ruin. Isak, a Christian minister, steps in and offers her the chance of a new life in Japan as his wife. Following a man she barely knows, to a country where she has no friends and unable to even speak the language, is just the start of Sunja's story of survival, family, love and loyalty.
For the complete list, please click the link.<file_sep>/content/news/pachinko-tv-series-in-the-works-at-apple.md
---
title: 'Hollywood Reporter: PACHINKO TV Series in the Works at Apple '
date: 2018-08-07 23:58:10 -0400
link_to_original: https://www.hollywoodreporter.com/live-feed/pachinko-tv-series-works-at-apple-1132664
images: []
tags:
- news
categories: []
description: '"History is the record of human imagination, will and decisions. I cannot
imagine a greater team than the women and men of Apple, Media Res, William Morris
Entertainment and the brilliant showrunner, <NAME>, to translate Pachinko, a novel
of history, into a visual story for a global audience," Lee told The Hollywood Reporter.
"I am honored by their faith and feel confident of their powerful and ground-breaking
vision in making history anew.”'
---
<file_sep>/content/event/dalton-book-club.md
---
title: Dalton Book Club
date: 2017-10-05 11:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Private Event<file_sep>/content/event/credit--suisse-first-boston--asian-pacific-american-heritage-month.md
---
title: Credit Suisse Securities
date: 2018-05-31 17:30:21 -0400
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2007-10-24-audio_happy_ending_reading_series.md
---
title: "Audio: Happy Ending Reading Series"
date: 2007-10-24T07:36:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "Radio-Press"
link_to_original: "http://www.radio-press.com/program.php?id=34"
description: ""
_slug: 2007-10-24-audio_happy_ending_reading_series
---
Tonight, Amanda throws candy at the crowd, it being so close to Halloween and all. And then she is bench-pressed by <NAME>. All wince as <NAME> waxes his legs as a performance art/act of protest against the Bush administration. And <NAME> lightens it up a bit by telling us a dirty joke while balancing a spoon — on her nose. They all also read engagingly, even enticingly, and the music is by <NAME>.
[The Happy Ending Reading Series](http://www.happyendingseries.blogspot.com "The Happy Ending Reading Series") is curated by [Amanda Stern](http://www.amandastern.com "Amanda Stern").
<file_sep>/content/event/greenwich-library.md
---
title: Greenwich Library
date: 2018-03-13 18:30:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/the-new-york-times-travel-show.md
---
title: The New York Times Travel Show
date: 2018-01-28 15:00:00
show_time: true
venue:
name: <NAME> Convention Center
address:
city:
state:
zip:
link:
---
THE BEST BOOKS FOR YOUR NEXT VACATION with <NAME>, <NAME>, <NAME>, and <NAME>. <file_sep>/content/event/national-book-awards-finalist-reading.md
---
title: National Book Awards Finalists Reading
date: 2017-11-14 19:00:00
show_time: true
venue:
name: 'The Auditorium, <NAME>/J.M. Kaplan Hall'
address: 66 West 12th Street
city: New York
state: NY
zip: '10011'
link: 'http://www.nationalbook.org/nba_finalists_reading.html#.WdW5585OjE4'
---
Sponsored by the National Book Foundation and <br>The New School's Creative Writing Program
On the eve of the 2017 National Book Awards Ceremony, The New School hosts a reading with the Finalists in the categories of Poetry, Fiction, Nonfiction, and Young People’s Literature.
Hosted by BuzzFeed's <NAME> and <NAME>.
Tuesday, November 14, 2017 at 7:00 PM to 10:00 PM
The Auditorium, <NAME>/J.M. Kaplan Hall<br>66 West 12th Street, New York, NY 10011
Tickets are $10.00
PURCHASE TICKETS (please click on the link)
Books will be available for purchase.
ABOUT OUR HOSTS:
<NAME> <br>Co-host of BuzzFeed News morning show AM to DM, <NAME> is an award-winning author and founding editor of BuzzFeed Books. He has been a firefighter, worked on a boat, and was once given a sword by a king, thereby accomplishing three out of five of his childhood goals. A Boston native, he is a graduate of George Washington University and briefly worked in politics before joining the literary scene. He previously worked at The Rumpus and McSweeney's and frequently appears on The Today Show to talk books. Co-author of Pen & Ink: Tattoos and the Stories Behind Themand Knives & Ink: Chefs and the Stories Behind Their Tattoos (with Recipes) (winner of an IACP award), he is currently writing his forthcoming 2018 Young Adult novel and picture book from Bloomsbury. Find him on Twitter.
<NAME> <br>Co-host of BuzzFeed News morning show AM to DM, award-winning writer <NAME> most recently served as executive editor, culture at BuzzFeed. Jones’ debut poetry collection Prelude To Bruise (Coffee House Press) was the 2015 winner of the PEN/Joyce Osterweil Award For Poetry and the Stonewall Book Award/Barbara Gittings Literature Award, and a finalist for National Book Critics Circle Award and the Lambda Literary and the Publishing Triangle awards. Jones won a Pushcart Prize for poetry in 2013 and 2016. His poetry and essays have appeared in The New York Times, NPR and Best American Poetry, among others. A Memphis native, he grew up in Lewisville, Texas, attended Western Kentucky University for undergrad and earned his MFA at Rutgers University. The Advocate Magazine recently named him as one of the "50 Most Influential LGBT People in Media." His memoir, How We Fight For Our Lives, is forthcoming from <NAME> in 2018. Find him on Twitter.<file_sep>/content/event/brooklyn-book-are-magic.md
---
title: 'Brooklyn: Books Are Magic'
date: 2017-11-29 19:30:00
show_time: true
venue:
name: Books Are Magic
address: 225 Smith Street
city: Brooklyn
state: NY
zip: '11231'
link: 'https://www.booksaremagic.net/?q=h'
---
Conversation with the brilliant novelist <NAME> about PACHINKO at the Cobble Hill independent bookstore, BOOKS ARE MAGIC.
Please join us.
<file_sep>/content/event/miami-writers-institute.md
---
title: 2018 Miami Writers Institute
date: 2018-05-09 12:00:00 +0000
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: www.miamibookfair.com
description: ''
images: []
---
Intensive Creative Writing Conference: May 9-11, 2018
I will be teaching a 4-day fiction workshop. <file_sep>/content/event/amherst-college-13.md
---
title: 'Conversations with Kirkland Presents: <NAME>'
date: 2019-04-16 19:00:00 -0400
show_time: true
venue:
name: Kirkland House Senior Common Room
address: ''
city: ''
state: ''
zip: ''
link: https://docs.google.com/forms/d/1lfx9Zr8gV9fS7k0KyUI3UQruXYJTECGtz-a3qMUcVIc/viewform?edit_requested=true
description: ''
images: []
---
<file_sep>/content/event/erica_jong_and_contributors_daphne_merkin_min_jin_lee_and_susan_kinsolving.md
---
title: <NAME> and Contributors <NAME>, <NAME> and Susan Kinsolving
date: 2011-06-15T12:30:38-05:00
venue:
name: "Bryant Park Reading Room - 42nd St and 5th Ave New York, NY 10110 (212) 768-4242"
link:
_slug: erica_jong_and_contributors_daphne_merkin_min_jin_lee_and_susan_kinsolving
---
Hear from the author who brought you FEAR OF FLYING, whose latest compilation of essays by contributors like <NAME>, <NAME>, and <NAME>, tackle the ever so elusive question: What do women really want? In the free, unfettered spirit of THE BITCH IN THE HOUSE, SUGAR IN MY BOWL explores the bedroom lives of women with daring, wit, intelligence, and candor.
The event is FREE and open to the public. For updates and additional information, please visit the website at http://www.bryantpark.org. The Bryant Park Reading Room located on the 42nd Street side of the park - under the trees - between the back of the NYPL & 6th Avenue. Look for the burgundy and white umbrellas. Rain Venue: Library of the General Society of Mechanics and Tradesmen 20 West 44th Street (between 5th & 6th Avenue).
“Word for Word Author” is an outdoor reading series that features bestselling authors, celebrity writers, and expert-panelists sharing anecdotes, answering questions from the audience, and signing copies of their latest books.
<file_sep>/content/writing/2007-06-18-pay_yourself_first.md
---
title: "Pay Yourself First"
date: 2007-06-18T22:14:50-05:00
categories:
tags: ["Essays"]
where_published: "Moleskinerie"
link_to_original: "http://www.moleskinerie.com/2007/06/guest_essay_pay.html "
link_to_pdf:
description:
_slug: 2007-06-18-pay_yourself_first
---
When I was growing up, my mother always earned money. In Korea, she taught piano to the local children, and in America, she worked alongside my father at their small wholesale jewelry shop in Manhattan. When I married my husband, I was a first year corporate lawyer and he was a junior salesman at a bank. I made more money than he did. Two years after lawyering, I quit to write fiction. He became the sole breadwinner. This was in 1995\. We didn’t have much left over after we paid the mortgage on our tiny apartment, and my husband had to take lunch to work, and I refused to meet friends from my old job for a drink because I was too ashamed to admit that I couldn’t afford my share.
<file_sep>/content/review/the-missouri-review-on-free-food-for-millionaires.md
---
title: The Missouri Review on Free Food for Millionaires
attribution: The Missouri Review
date: 2007-03-11 18:02:05 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Five years ago we published a story called “Motherland” by an emerging author named <NAME>. We were unanimous in our admiration of what was later selected as the best fiction of that volume year. It’s the story of a Japanese woman…<file_sep>/content/event/brisbane-writers-festival-university-of-queensland-fryer-library.md
---
title: 'Brisbane Writers Festival: University of Queensland Writer-in-Residence'
date: 2017-09-06 15:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Conversation at the Fryer Library with Professor <NAME> at 3PM
Conversation at WRIT3000 Creative Writing: Advanced Project with Professor <NAME> at 5pm<file_sep>/content/event/book-launch-douglas-stuart-presents-young-mungo-with-min-jin-lee.md
+++
date = 2022-04-05T23:00:00Z
description = "A story of queer love and working-class families, Young Mungo is the brilliant second novel from the Booker Prize-winning author of <NAME>"
images = []
link = "https://www.mcnallyjackson.com/event/book-launch-douglas-stuart-presents-young-mungo"
show_time = true
title = "Book Launch: <NAME> presents Young Mungo with <NAME>"
[venue]
address = "55 Washington Square South"
city = "New York"
name = "<NAME>"
state = "NY"
zip = "10012"
+++
<file_sep>/content/event/odyssey_bookstore.md
---
title: ODYSSEY BOOKSTORE
date: 2008-05-02T20:00:00-05:00
venue:
name: Odyssey Bookshop, South Hadley, MA
link: www.odysseybks.com
_slug: odyssey_bookstore
---
Reading & Q&A
7PM
9 College St.
South Hadley, MA 01705
<file_sep>/content/review/simon-winchester-on-pachkinko.md
---
title: <NAME> on Pachkinko
attribution: '<NAME>, New York Times bestselling author of *The Professor
and the Madman* and *Korea: A Walk through the Land of Miracles*'
date: 2017-03-11 17:45:37 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Both for those who love Korea, as well as for those who know no more than Hyundai, Samsung and kimchi, this extraordinary book will prove a revelation of joy and heartbreak. I could not stop turning the pages, and wished this most poignant of sagas would never end. <NAME> displays a tenderness and wisdom ideally matched to an unforgettable tale that she relates just perfectly.<file_sep>/content/event/muse-marketplace-writing-conference-a-conversation-with-min-jin-lee.md
---
title: 'Muse & Marketplace Writing Conference: A Conversation with <NAME>'
date: 2019-04-06 15:00:00 -0400
images: ["/uploads/thumb_512_muse.png"]
description: 'Join a fascinating Q&A with <NAME>, author of Pachinko, on writing stories that span large swaths of time and geography. What are the uniques challenges of such a large scope? How to transition through huge leaps in time or location? How to sustain tension in a book that requires many hours to read? What research might be required, and how can you keep track of it all? And do epic stories take an epic time to write?'
link: 'https://musethemarketplace2019.sched.com/event/IrAd/7l-on-writing-epic-novels-a-conversation-with-min-jin-lee'
show_time: true
venue:
address: 'Park Plaza'
city: 'Boston'
name: 'White Hill Room - 4th Floor'
state: 'MA'
zip: ''
---
<file_sep>/content/writing/2007-07-21-the_page_99_test.md
---
title: "The Page 99 Test"
date: 2007-07-21T22:19:49-05:00
categories:
tags: ["Essays"]
where_published: "The Page 99 Test"
link_to_original: "http://page99test.blogspot.com/2007/07/min-jin-lees-free-food-for-millionaires.html"
link_to_pdf:
description:
_slug: 2007-07-21-the_page_99_test
---
On page 99 of Free Food for Millionaires, my main character <NAME> is smoking on the roof of her friend <NAME>’s apartment building. It is Sunday morning, and Casey can’t decide whether or not she is going to accompany Ella to church. From the roof, she catches a glimpse of Ella’s cousin, <NAME> who has just moved into the building across the street. Her cigarettes smoked, Casey goes downstairs to Ella’s apartment and tells Ella that she will go to church after all. Ella is horrified, because though she had wanted Casey to come to church with her and her fiancé Ted, Ted has just told her that he informed Casey’s ex-boyfriend Jay that Casey is staying at Ella’s apartment. Casey does not want Jay to find her, and Ted knew this. Ted has betrayed Ella’s confidence, and now, Ella has to conceal something from her friend Casey as they head off to church. Presently, Unu will meet them after church ends, and he will witness Casey and Jay’s first encounter since Jay’s sexual betrayal of Casey.
<file_sep>/content/review/kate-christensen-on-pachinko.md
---
title: <NAME> on Pachinko
attribution: <NAME>, Pen/Faulkner-winning author of *The Great Man* and *Blue
Plate Special*
date: 2017-03-11 17:44:21 +0000
book: book/pachinko.md
description: ''
featured: false
---
*Pachinko* is elegant and soulful, both intimate and sweeping. This story of several generations of one Korean family in Japan is the story of every family whose parents sacrificed for their children, every family whose children were unable to recognize the cost, but it's also the story of a specific cultural struggle in a riveting time and place. Min Jin Lee has written a big, beautiful book filled with characters I rooted for and cared about and remembered after I'd read the final page.
<file_sep>/content/review/bookbub.com.md
---
title: BookBub.com on Pachkinko
attribution: BookBub.com
date: 2017-03-11 17:50:05 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
Most Anticipated Book Club Reads of 2017 and Biggest Historical Fiction Release of 2017<file_sep>/content/review/usa-today-on-free-food-for-millionaires.md
---
title: USA Today on Free Food for Millionaires
attribution: USA Today
date: 2007-03-11 17:58:44 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Critic’s pick: _Free Food for Millionaires_, by <NAME> (Grand Central, $13.99). USA TODAY’s Carol Memmott says this “vastly ambitious” and “stirring"<file_sep>/content/news/2008-04-25-wamc.md
---
title: "WAMC Roundtable"
date: 2008-04-25T23:28:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "WAMC Roundtable"
link_to_original: "http://www.wamcarts.com/bookpicks.html "
description: ""
_slug: 2008-04-25-wamc
---
<file_sep>/content/news/2007-07-25-npr_fresh_air.md
---
title: "NPR, Fresh Air"
date: 2007-07-25T23:21:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "NPR, Fresh Air"
link_to_original: "http://www.npr.org/templates/story/story.php?storyId=12225079"
description: ""
_slug: 2007-07-25-npr_fresh_air
---
<NAME>’s debut novel Free Food for Millionaires tells the story of a young Korean-American woman whose Ivy League education exposes her ...
<file_sep>/content/event/lillian-vernon-creative-writers-house-nyu-mfa-program.md
---
title: '<NAME> Creative Writers House: NYU'
date: 2018-04-20 19:00:00 -0400
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
---
<file_sep>/content/event/amherst-college-15.md
---
title: New American Festival
date: 2019-09-14T13:30:00-04:00
show_time: true
venue:
name: NeueHouse
address: 110 E 25th St
city: New York
state: New York
zip: "10010"
link: https://www.newamericanfestival.com/#festival-schedule
description: Literary Panel curated by <NAME> featuring <NAME> and Daniel
<NAME>
images:
- "/uploads/static1.squarespace.png"
---
<file_sep>/content/event/cape-cod-author-literary-luncheon.md
---
title: 'Cape Cod: Literary Luncheon'
date: 2017-08-03 12:00:00
show_time: true
venue:
name: Author Literary Luncheon Series in Cape Cod
address:
city:
state:
zip:
link: 'http://www.booksonthecape.com/author-literary-luncheon-series/'
---
Hosted at The Wequassett Resort and the independent bookseller Where the Sidewalk Ends Bookstore & Children's Annex. <file_sep>/content/event/stanford.md
---
title: STANFORD
date: 2008-04-25T22:55:00-05:00
venue:
name: Stanford University, Palo Alto, CA
link:
---
A conversation with <NAME>, Professor English and Director of the Program in American Studies, Stanford University
and <NAME>
STANFORD BOOKSTORE
5.15pm
THIS EVENT IS OPEN TO THE PUBLIC
<file_sep>/content/event/pittsburgh-city-of-asylum.md
---
title: 'Pittsburgh: City of Asylum'
date: 2018-02-20 20:00:00
show_time: true
venue:
name: Alphabet City
address: 40 W. North Avenue
city: Pittsburgh
state: PA
zip: '15212'
link: 'http://www.alphabetcity.org'
---
<file_sep>/content/event/ursinus-college-commencement.md
---
show_time: true
title: Ursinus College Commencement
date: 2021-05-15T10:15:00-04:00
description: Commencement Speach
venue:
address: 601 E. Main St.
city: Collegeville
name: <NAME>
state: PA
zip: "19426"
link: ''
images: []
---
<file_sep>/uploads/index.md
---
title: uploads
_build:
render: never
list: never
publishResources: true
---<file_sep>/content/event/nypl-bandi-north-korea.md
---
title: 'NYPL: Author Talks—Bandi''s North Korea'
date: 2018-01-16 18:30:00
show_time: true
venue:
name: 'NYPL: <NAME>'
address:
city:
state:
zip:
link:
---
<file_sep>/content/event/melbourne-writers-festival.md
---
title: 'Melbourne Writers Festival 2017: Sunday—PACHINKO'
date: 2017-09-03 13:00:00
show_time: true
venue:
name: ACMI Cinema 1
address:
city:
state:
zip:
link:
---
<NAME> discusses her novel PACHINKO with <NAME>, Program Manager of the Melbourne Writers Festival.<file_sep>/content/event/hugo-house.md
---
title: 'Seattle: Hugo House'
date: 2019-05-02 19:00:20 -0400
images:
- "/uploads/HugoHouse_Logo-Square_color-cmyk.png"
description: 'Word Works: Min Jin Lee on Having Faith'
link: |2-
https://hugohouse.org/event/word-works-min-jin-lee-on-having-faith/
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2017-03-24-ilkley-gazette-uk-book-review.md
---
title: Ilkley Gazette UK (Book Review)
date: 2017-03-24 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Ilkley Gazette UK
link_to_original: 'http://www.ilkleygazette.co.uk/leisure/leisure_ents/15180370.A_story_of_survival_against_all_the_odds/'
description:
---
Book Review by <NAME> of The Grove Bookshop: Pachinko by <NAME>, published in hardback by Apollo at £18.99
PACHINKO, the new novel by South Korean-American author <NAME>, follows several generations of a Korean family during the course of the twentieth century - through all the happiness and hardships that come with life, and the struggles of being a Korean immigrant in Imperial Japan. Opening in 1910 with events that lead to the birth of Sunja, the leading protagonist, it takes us all the way through to the late 1980s, with Sunja's family having been through trials that no family should have to go through - and yet, that families everywhere do.
When, as a young girl working in her widowed mother's boarding house, Sunja discovers she is unable to marry the rich fish broker whose baby she is carrying, she is convinced she has brought shame upon her family. Yet a kindly, frail, Presbyterian minister from Pyongyang, Isak Baek, intervenes and offers to take her to Japan as his wife. As they move in with Isak's brother Yoseb and his wife Kyunghee in the Korean ghetto in Osaka, Sunja experiences the ordeals that come with living in a country in which she is not welcome. Gender roles are tested as Sunja and Kyunghee fight Yoseb to be allowed to work; even when they succeed, there are tribulations along the way and they are never made to feel fully comfortable in their new role. "A woman's lot is to suffer" is an idea they sadly come to accept, after struggling to keep their family surviving together.
Their experience as arrivals in a new country is equally tense, as the family experiences widespread prejudice against immigrants. The Koreans are characterised by the Japanese as "natural troublemakers" from a "cunning and wily tribe". With Korea annexed by Japan from 1910-1945, the tensions between the two countries - and indeed, tensions in the rest of the world - make life unpredictable and often dangerous. Even after Japan’s defeat, Koreans continued to be oppressed and excluded from Japanese society, yet the post-WWII fighting in Korea leaves the family unable to go home; in the words of one Korean character, "for people like us, home doesn't exist".
Going into this book with no knowledge of the history of Japan or Korea, I was expecting to feel slightly overwhelmed with a plot to follow on top of becoming familiar with new cultures. Yet Min Jin Lee performs her job so well that the characters feel like family and cultural explanations never overwhelm the plot - in fact, it's hardly noticeable at all that you're getting an in-depth education on East Asian history. Pachinko effectively tells a universal story, while Lee's exhaustive research on the Korea-Japan relationship of the time lends a hugely fascinating and informative tone to the novel. The characters are likeable even when we know they shouldn’t be, and both the plot and wider world events are remarkably easy to follow for such a large and sweeping novel. There are horrors that will bring tears to your eyes, but the beautiful, overwhelming tone of the novel – and the one that will stay with you at the end - is one of hope, courage, and survival against all the odds.<file_sep>/content/event/farm-and-coast-market.md
---
title: Farm and Coast Market
date: 2018-03-15 19:00:00
show_time: true
venue:
name: Farm and Coast Market
address: 7 Bridge Street
city: Dartmouth
state: MA
zip: 02748
link:
---
In Conversation with author <NAME> and <NAME> about PACHINKO<file_sep>/content/event/morikami-garden.md
---
title: 'DelRay Beach, FLA: Morikami Museum and Japanese Garden'
date: 2018-01-11 19:00:00
show_time: true
venue:
name: <NAME>
address: 4000 Morikami Park Road
city: DelRay Beach
state: FL
zip: '33446'
link: >-
https://morikami.org/event/a-morikami-literary-evening-with-bestselling-author-min-jin-lee/
---
To purchase tickets, please click the link. <file_sep>/content/news/2017-12-31-nbc-new-york-bills-bookstop-5-books-of-2017.md
---
title: 'NBC New York: Bill''s Books—Top 5 Books of 2017'
date: 2017-12-31 12:00:00
categories: ["Media"]
tags:
- Reviews
- News
- Video
attribution: NBC New York
link_to_original: >-
https://www.nbcnewyork.com/news/local/Here-Are-Bill-Goldsteins-Book-Choices-for-Dec-29-467398533.html
description:
---
<NAME> selects Pachinko in his Top 5 Books of 2017 in NBC New York's Bill's Books. To see the video, please click the link.<file_sep>/assets/js/index.js
import "./forms.js"
import "./lazysizes.js"
import "./quicklink.js"
import "./nojs.js"
<file_sep>/content/news/2017-03-04-japan-times-book-review.md
---
title: Japan Times (Book Review)
date: 2017-03-04 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Japan Times
link_to_original: 'http://www.japantimes.co.jp/culture/2017/03/04/books/book-reviews/pachinko-min-jin-lee-writes-struggle-ethnic-korean-family-japan/#.WNHn1c5OjE4'
description:
---
‘Pachinko’: <NAME> writes the struggle of an ethnic Korean family in Japan
BY <NAME>
SPECIAL TO THE JAPAN TIMES
MAR 4, 2017
<NAME>’s second novel, “Pachinko,” charts the fortunes and misfortunes of four generations of a Korean family.
Pachinko, by <NAME>.
<br>490 pages
<br>GRAND CENTRAL PUBLISHING, Fiction.
Beginning in Yeongdo in 1910 with the marriage of Hoonie and Yangjin against the backdrop of Japanese annexation of the peninsula, we follow their daughter, Sunja, to Osaka and wartime Japan. After the war, the focus shifts to Sunja’s children, Noa and Mozasu, and finally to Mozasu’s son, Solomon.
The emphasis is bleak: the suffering of Koreans under Japanese occupation, the persecution of foreign nationals and Christians and the ongoing discrimination against Zainichi Koreans. A particularly moving scene shows Solomon on his 20th birthday applying for a visa to stay in the country of his birth. The family does prosper over the decades, albeit in the only industry really open to them: pachinko.
Scenes of domestic drama are intertwined with discussions of political and social realities, and all points of relevant history are touched upon and examined through the experiences of a family member. In this way the novel is somewhat Dickensian, though the tight focus on the family keeps it from running into Victorian indulgence.
While the book is critical, it is fairly balanced overall. The philosophical heart of “Pachinko” resides in a line given to Solomon: “Sure there were assholes in Japan, but there were assholes everywhere.” As an examination of immigration over generations, in its depth and empathy, “Pachinko” is peerless.<file_sep>/content/news/2017-04-21-the-boston-globe-the-story-behind-the-book.md
---
title: 'The Boston Globe: The Story Behind the Book'
date: 2017-04-21 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: The Boston Globe
link_to_original: 'http://www.bostonglobe.com/arts/books/2017/04/20/korean-immigrants-struggle-hostile-japan/HyOKR60DOVqmrSXYNAqDOK/story.html?event=event25%20via%20@BostonGlobe'
description:
---
By <NAME> GLOBE CORRESPONDENT APRIL 21, 2017
<NAME>’s second novel, “Pachinko,” begins with a line that can read like pure fatalism: “History has failed us, but no matter.” As the book unspools over four generations of a Korean family that migrates to Japan, it begins to feel more like a kind of determination to survive, even in a country and culture hostile to them.
“Most people don’t really want to hire Korean Japanese,” Lee said. “Men couldn’t become police officers or teachers or postal workers — ordinary middle-class jobs people aspired to have — let alone enter the white-collar world,” she added. Prejudice against Koreans is common in Japan, Lee said, but it’s a story that’s not well-known outside of Asia.
For Korean-born Lee, who moved to the United States at seven, it wasn’t an easy story to tell. “I had an entire manuscript in 2007,” she said, but upon moving to Japan and meeting Korean Japanese people, she realized she needed to rewrite the novel and include their voices. The key, Lee said, was women her grandmother’s age, people who were often illiterate, who “went to this other country where everyone thought you were garbage. You had to live in ghettos. You might have a pig living in your house. Sometimes you were making moonshine to make money.”
She rewrote the book, naming it for the vertical pinball machine that many Americans think of as a children’s game. In Japan, it is a $230 billion industry, Lee explained, and one that’s dominated by ethnic Koreans, who found a niche in an economy that discriminated against them.
“Pachinko, like all gambling, is rigged,” Lee said. “The house always wins. It’s a central metaphor of life. It’s rigged, but you keep playing.”
Lee will read 7 p.m. April 29 at La Rana Rossa, 154 Green St., Jamaica Plain.
<NAME>, president of the National Book Critics Circle, can be reached at <EMAIL>.<file_sep>/content/news/2017-10-10-hyphen-asian-america-unabridged-interview-with-timothy-tau.md
---
title: 'Hyphen: Asian America Unabridged (Interview with Timothy Tau)'
date: 2017-10-10 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution:
link_to_original:
description:
---
<NAME>'s Pachinko is an epic, sweeping saga of four generations in a Korean family that spans nearly seven decades and three continents and has just been longlisted for the National Book Award. After the publication of Lee's first novel, Free Food for Millionaires, Lee moved to Japan to research a new novel. That novel, Pachinko, is a marvel of masterful storytelling. The novel has garnered accolades from literary critics and book reviewers, making the “Best Fiction of 2017” list for Amazon.com, Esquire, BBC, Entertainment Weekly, The Guardian and Book Riot, among others. Lee's short story “Motherland” won the Peden Prize from The Missouri Review and also focused on the topic of Koreans living in Japan. I recently interviewed Min Jin Lee about her past and current work and her next upcoming novel, American Hagwon.
TT: I remember hearing about your plans working on Pachinko after Free Food for Millionaires ("Millionaires") was published, and before Millionaires was released, you wrote an award-winning short story, "Motherland" (which, as noted above, won the Peden Prize in the Missouri Review). Pachinko appears to be a continuation or an expansion of "Motherland" and seems to involve the same characters from the novel (e.g., Etsuko, Mozasu, Solomon, Hana, etc.) When you were crafting the epic span of the canvas that eventually became the novel, did you start with this short story as a narrative kernel? Or did you end up creating the timelines of the novel first and realize that this story would fit in nicely within this larger world? What was your methodology and process in writing and building Pachinko?
MJL: I had written a complete manuscript of Pachinko from 1996-2003 in another form, which I never submitted for publication. The story you mention, “Motherland,” is from that first manuscript. It is the only section which made it into the final version of Pachinko, which was eventually published in 2017. I have worked on this book off and on since 1996. I got the idea for the book in 1989. I had not meant to work on this for so long. It was trial and error and mostly error.
TT: The extensive research you went through to accurately flesh out the historical periods rendered in the novel really shows. I feel as if I am transported to those eras in a very cinematic way when I am reading, yet taken beyond the visual realm because I also experience many other senses through your words. Can you describe your research methodology?
MJL: I do extensive book research for all of my projects, both fiction and nonfiction. Also, I do a lot of personal interviews with dozens of subjects. I don’t think my way of working is smart or efficient, but I think my working style alleviates my personal anxieties about getting things right.
TT: The characters are very memorable, and in some ways reminded me of some of the characters from Millionaires as well. Sunja, for example, appears to be the protagonist of the novel as we mainly follow her through most of the major story arcs. In many ways she is a contrast to Casey Han of Millionaires (primarily due to the chronological difference in the eras or time periods) but in some ways they share similar traits, perhaps resilience being the most apparent commonality. What made you decide to center the narrative around Sunja's point of view and her family/timeline?
MJL: At the risk of sounding odd, for me, Sunja is not the central character because I work in an omniscient point of view. Sunja is an ordinary working class woman who becomes a matriarch of an ordinary family. She is not powerful in the world, but she is important to her family. I wanted to write about an ajumma who is unheralded in history books but who is so important in our daily lives. Moreover, I wanted very much to write about regular men and boys who make up so much of ordinary history. I explore the masculinity of oppressed minority men in this book, and that was one of my most important challenges in this work. I want to write community novels, and the interconnections of themes and multiple characters are far more important to me than one character.
TT: Koh Hansu appears to be one of the most interesting characters I've encountered in literature and probably my favorite one in the entire novel — very compelling, charismatic, cool, but you later see his more villainous aspects — really not a character intending to be evil or criminal, but because he wields so much power and resources and is ambitious as well as disciplined, intelligent and talented, he just can't help it. I also found in Koh Hansu some similarities to the character of <NAME> from Millionaires, who was, quoting a line from that novel, "fairy godmother, mentor and bad cop" to <NAME>. Koh Hansu seems to be a gangster godfather, mentor and good cop/bad cop to many characters in the book as well. What were some inspirations in constructing both characters?
MJL: Characters like Sabine and Hansu populate the upper echelons of the world. Strong and powerful people are remarkably similar because they have clear codes of behavior, which are often nonnegotiable. They also cannot exist without subjects to dominate.
TT: Building on the last question, Koh Hansu wants so much to exert an influence over Noa and pave a promising future for him. However, I found it interesting that you made Hansu financially support Noa so he could wholeheartedly study English literature without distraction — which seems a bit at odds with the normally expected "useful/pragmatic/practical" degrees and careers that Asian immigrants want their children to pursue (e.g., the pachinko manager comments on the "uselessness" of an English degree before he hires Noa; I can also easily imagine <NAME> or even <NAME> balking at this choice of academic path). Was the choice to make Noa study English deliberate?
MJL: I think Hansu has none of the traditional immigrant anxieties because he is not someone who is obsessed with money and conventional security. He is an intellectual and a philosopher, and I think it delights him that his own blood has strains of genius with a strong work ethic.
TT: Out of curiosity, are Millionaires and Pachinko based in the same universe? Also, I was wondering what you thought the characters of Millionaires are currently up to now?
MJL: The characters exist and continue vibrantly, but I couldn’t speculate here as to what they are doing.
TT: The influence and dominance of South Korean culture now, not just on Japan but also worldwide — e.g., the global takeover of hallyu, K-Pop, K-dramas, Samsung/LG/tech, leading world cinema and film from acclaimed auteurs, all of that — was that something that can be historically predicted or how do you think it was caused by, or could be explained by the characters in Pachinko — do you feel contemporary Koreans in Japan exhibit more nationalist-like pride for their home country? Also in Japan now, is it easier to become a citizen or to formally integrate if you are Korean, or do you think vestiges of discrimination against Koreans or non-Japanese "others" still exist, similar to the type the characters of Pachinko faced?
MJL: Korean-Japanese are still perceived to be an inferior and suspect class of people today. Unfortunately, “foreigners” are considered untrustworthy in Japan. However, it is worth noting that many foreigners are treated miserably in South Korea today, too. As for predicting the rise of hallyu, I think in many ways, it is fun and cool, but I think it conceals the great deal of suffering and mental anguish of a nation which has grown remarkably quickly without enough time to lament. South Korea is now an OECD country, and it has the highest rate of suicide of all OECD countries. I want very much to respect the extraordinary complexity and resilience of the Korean people, but I want to acknowledge their vulnerability to suffering, too.
TT: Have you ever thought of writing a novel about the world of (maybe Asian American or Korean American) attorneys, judges, judicial law clerks, law professors and the law? Which brings me to my next and final question: What is next for you in terms of projects, and what are you currently working on?
I wrote a story about lawyers called “Axis of Happiness,” which was published in Narrative Magazine. I think a novel about lawyers could be very fun. My next novel is the third of my “The Koreans” trilogy, and it is called American Hagwon, which will explore the role of education in the lives of modern Koreans in the world. [Note: "Hagwons" are private cram schools or academies prevalent in South Korea].
<NAME>
<NAME> is an award-winning writer and filmmaker and was recently named by PolicyMic magazine as "6 Young Asian-American Filmmakers Who Are Shattering America's Asian Film Bias." His short story "The Understudy" won Grand Prize in the 2011 Hyphen Asian American Writer's Workshop Short Story Contest and is published in the 2011 Issue of Hyphen Magazine as well as online. His short story, "Land of Origin" also won 2nd Prize in the 2010 Playboy College Fiction Contest (See October 2010 Issue of Playboy Magazine). Both stories are being developed into feature film projects.<file_sep>/content/event/book_club_tokyo.md
---
title: Book Club Tokyo
date: 2008-05-21T23:43:01-05:00
venue:
name: Tokyo, Japan
link:
_slug: book_club_tokyo
---
Book Club
PRIVATE EVENT
<file_sep>/content/news/2017-12-14-wbur-on-point-radiobest-books-of-2017.md
---
title: 'WBUR: On Point Radio—Best Books of 2017'
date: 2017-12-14 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: 'On Point Radio: WBUR'
link_to_original: >-
http://www.wbur.org/onpoint/2017/12/14/on-point-staff-picks-for-best-books-of-2017
description:
---
<NAME>, executive producer: "Pachinko," by <NAME>.
Every time <NAME> writes a book, it ends up as my pick for the Best Book of the Year. In 2008, it was "Free Food for Millionaires," a book about a Korean-American family and a daughter’s struggle to fit in to both cultures. I recommended it to everyone and my copy made the rounds. I loved it so much that I started an email correspondence with the author and kept asking “When is your next book coming out?” This year, she’s out with "Pachinko," and it was worth the long wait. This time, Lee tells the story of four generations of Koreans living in exile in Japan. There are some familiar themes in this book: racism, social mobility, and clash of cultures. In case you’re wondering, pachinko is a Japanese-style slot machine. Lee uses it to tell the stories of people trying to beat the odds in a world stacked against them. After reading a few pages, you’ll be rooting for them, too. Make sure you have a box of tissues nearby.
For the remainder of the article, please click the link.<file_sep>/content/news/2007-07-28-the-times-of-london-book-review-of-free-food-for-millionaires.md
---
title: The Times (of London) Book Review of Free Food for Millionaires
date: 2007-07-28 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: The Times
link_to_original: 'https://www.thetimes.co.uk/article/free-food-for-millionaires-8806w6m87rd'
description:
---
By <NAME>ulis July 28, 2017
IF YOU DON’T KNOW YOUR kimbop from your bop, and have never tasted the delights of pâte à choux cream puffs with hong cha, you may never have considered the fact that although there are more than 2 million ethnic Koreans in America, their arrival on the mainstream cultural scene is long overdue. It is a good 40 years since the diaspora got going, so what – if not producing novels, films and music – have they been doing all this time?
The short answer, according to the New York-based writer <NAME>, is laundry. That’s the business of her fictional couple, Joseph and <NAME> who, like countless others in their community, have worked themselves to the bone to get Manhattan’s whites whiter, while saving every penny to give their two daughters a good education.
One of their daughters is <NAME>, a classical Korean beauty and virginal med-student, and the spit of her young mother. The other – the book’s protagonist – is Casey, a decidedly less traditional sort. Strong of limb and firm of mind, she has been indulging in fornication, cigarettes and subversive thoughts of not becoming a lawyer for years.
The novel opens around the Hans’ kitchen table in Queens, with Casey and her embittered, Korean-riches-to-American-rags father at loggerheads. Casey, fresh from Princeton, is idly wondering whether to look for a job or apply to graduate school. This shilly-shallying, and its attendant rejection of the time-is-money ethos, drives her father wild, so he does what he always does and starts telling the heartbreaking story of his final leave-taking from his poor mother in Korea. For some reason, tonight Casey decides to speak her mind, and she lets rip with details of her own tough journey: how at college she “had kids step away from me like I’m unwashed after I tell them you manage a dry-cleaner . . . people who are supposed to be your equals look through you like you were made of glass and what they see inside looks filthy”.
So her father beats her up. So she leaves home. And so begins her bittersweet adventures with lovers Waspy and Korean, jobs in banking and in clothes shops, role-models young and old and, always lurking beneath the surface, a dark desire that dare not speak its name: what she really, really wants is to make hats for a living.
But first, she throws herself in to corporate life, just to check it’s as soulless as she fears. At the investment bank, <NAME>, she meets men who make <NAME>’s masters of the universe seem like progressive wee softies. When they close a deal, vast feasts of exotic foodstuffs are ordered in on the company account. Casey holds back politely while her millionaire colleagues load up their plates with free food as if they’re starving. She sleeps with, cheats on and is betrayed by various white-collar love-criminals, but only Umu, a sweet Korean-American of whom her parents might just approve, really makes her feel good. However, he has a not-so-sweet secret habit that is incompatible with being a good boyfriend.
After a period of abstinence from family life, Casey starts to see her mother again, and through <NAME>’s timid, uncomprehending eyes, yet another layer of Korean New York is revealed. At her beloved church, Leah is more than just a laundress in a homemade winter coat. She is De<NAME>, the one with the angelic voice. If she is not singing hymns and arranging choir practice, she is out visiting the sick, attending weddings and preparing food for festivals. But one day she returns from visiting the impressive new choirmaster, <NAME>, on whom she has an innocent crush, and Casey realises that something has changed in her. Casey is changing, too, in her attitude to the Church Elders, some of whom, she realises, could be abusing their power. When one commits a startling transgression, she attacks him with a disrespectful ruthlessness that her father would never have been able to display.
Intergenerational fault-lines intersect with those of race and gender to create new worlds of possibility for Lee’s heroine, and ultimately she surprises herself with how much freedom she has. The girl making trouble at the dinner table in Book 1 (“Works”) is, by Book 3 (“Grace”), a woman who dares not only to dream, but to try making hats instead of millions. Because, for some reason, hats make her happy. And although Mr and Mrs Han don’t know it in the same way that she does, that is what leaving Korea was for.
This big, beguiling book has all the distinguishing marks of a Great American Novel: brilliant set-pieces (the golf club, the trading floor, the janitor’s room, the cosmetics counter); an outsider/ insider point of view; and a complex, modern voice that seems to speak more clearly than most.
Most importantly, Lee shows that the core values of this particular community are matched exactly in the mainstream culture. Traditions – fetishised because half-forgotten – of charity, gift-giving, churchgoing and family life are what hold both groups together. When they work they work like magic. But Lee is a realist and, as her novel demonstrates, men and women – wherever they come from – still have a lot to learn. Perhaps, this remarkable writer dares to wonder, they should try learning together?<file_sep>/content/review/bookreporter.com.md
---
title: Bookreporter.com on Free Food for Millionaires
attribution: Bookreporter.com
date: 2007-03-11 18:10:44 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
<NAME> gets into the heads of a dry cleaner operator and a Julliard alumnus, an aging bookstore owner and a stockbroker on Wall Street. …<file_sep>/content/news/2017-05-29-radio-gorgeous-uk-podcast-with-donna-freed.md
---
title: Radio Gorgeous UK (Podcast with <NAME>)
date: 2017-05-29 12:00:00
categories: ["Media"]
tags:
- Reviews
- News
- Audio
- Interviews
attribution: Radio Gorgeous UK
link_to_original: 'http://radiogorgeous.com/podcasts/min-jin-lee-pachinko/'
description:
---
I had a terrific time speaking with <NAME> on RADIO GORGEOUS. To listen to the podcast, please click on the link below.<file_sep>/content/news/2017-06-10-world-magazine.md
---
title: World Magazine
date: 2017-06-10 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: World Magazine
link_to_original: 'https://world.wng.org/2017/05/beach_reads'
description:
---
By <NAME>
Summertime, and the reading is easy. On the following pages four WORLD writers recommend their favorite light reading, including popular history books, travel books, detective novels, and a couple of literary choices. Then comes a profile of best-selling nonfiction writer <NAME> and two pages of reading suggestions from other staff members.
But first, here’s some of what I’ve enjoyed from 10 p.m. until midnight, my daily reading time. The best novel I’ve read recently is Pachinko by <NAME> (Grand Central Publishing, 2017), a moving multigenerational saga of Koreans in Japan that provides a positive view of Christianity. (Note: Some bad words occasionally flow out of the mouths of bad characters.) Born in South Korea, Lee came to America at age 7, studied history at Yale, and came out 10 years ago with Free Food for Millionaires, a realistic novel centering on Korean-Americans in New York City.
If you’re heading to the beach and want epic fiction that will last you for a vacation, try <NAME>’s sweeping World War II novels, The Winds of War and War and Remembrance: adventure and romance without pornography. Wouk, born in 1915, published those in 1971 and 1978, so they reflect a mature wisdom—and he’s still alive, with May 27 marking his 102nd birthday.
If you like <NAME>, you may also like <NAME>’s Signals: New and Selected Stories (Knopf, 2017). I worried that his emphasis on grotesque Cajun people and places might leave Northern readers with a sense of superiority rather than an awareness of our common need for redemption—but the last two stories in the collection, “Welding with Children” and “What We Don’t See in the Light,” are perfect. Another short story collection, What’s Left Out by physician <NAME> (Kent State University Press, 2015), includes tales by what he knows well, life within hospitals and clinics.
If you like spy novels, I recommend <NAME>, <NAME> (his World War II series), <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>: None of their novels overflows with objectionable elements, but the main characters are in an occupation where violence is inevitable, sex is sometimes weaponized, and some words resemble grunts. So, round up the usual caveats.
That also goes for detective fiction that typically features moral heroes in corrupt societies: Since it’s harder to find more corruption than Russians have put up with for a century, you might try novels by <NAME>, <NAME>, and <NAME> set in Moscow or thereabouts. Qiu Xiaolong looks at Chinese society similarly. For more about these books, see “Down Moscow’s mean streets” (WORLD, April 18, 2015) and “Down Berlin’s mean streets” (May 17, 2014).
I’ve just read my first spy novel by <NAME>, who has a series of 11 starring <NAME>, a maverick CIA fighter against Islamic terrorists. Wells curiously becomes a Muslim in an early book, but comments like this from his girlfriend are rare in contemporary fiction: “I’m barely in the door, say I’m pregnant, the first thing the tech says, Is this baby desired? Like, You like this sweater or should I put it back on the shelf? … This baby desired? Is that really the relevant question? This baby’s a baby. I guess some women say no.”
Berenson also brings us into the brain of a French spy chief who had often gone to interments at Père Lachaise, the largest cemetery in Paris. A hand grenade is about to put him there as a victim, not a mourner: “His last thought, not a prayer. For like so many French, he was a rationalist, an atheist. Even now, God didn’t come for him. Instead … All those trips to Père Lachaise, I never guessed at the evil in this world.”
After this look at life-and-death novels, you might enjoy Angela Lu’s look at books that generate more laughs.
<NAME>
Marvin is editor in chief of WORLD News Group and the author of more than 20 books, including The Tragedy of American Compassion. Follow Marvin on Twitter @MarvinOlasky.<file_sep>/content/news/2017-02-07-national-book-review-conversation-with-sharon-pomerantz.md
---
title: 'National Book Review: Conversation with <NAME>'
date: 2017-02-07 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: National Book Review
link_to_original: 'http://www.thenationalbookreview.com/features/2017/2/7/9se9untx72hhi3y057kb7hckcnwak8'
description:
---
<NAME>’s 2007 national bestselling novel Free Food for Millionaires was set in the world of Korean immigrants and their children striving for success in New York. Addictively readable, it headed up “top ten novels of the year” lists everywhere from The Times of London to NPR and USA Today. Readers and critics alike found it both intellectually compelling and hard to put down (I remember several nights of turning pages at 2 a.m.). Both a feminist story of one young woman’s quest to break away from her immigrant family’s demands and find personal fulfillment, and a hard-hitting social commentary on the toll exacted by the American Dream, Free Food For Millionaires reads less like a debut and more like the work of a long established master. <NAME>, writing in the New York Times Sunday Book Review, compared the book to Middlemarch by <NAME>; Can You Forgive Her? by <NAME> and Pride and Prejudice by <NAME>.
Lee’s new novel, Pachinko, published by Grand Central Books, has already been hailed by writers like <NAME>, <NAME> and <NAME>, and for good reason. Once again, I found myself up at 2 a.m., compulsively turning the pages. Lee is a master plotter, but the larger issues of class, religion, outsider history and culture she addresses in Pachinko make this a tour de force you’ll think about long after you finish reading. The book follows a family through four generations, starting in Korea in 1900, and then moving to Japan just before World War II, where they are stranded by history, fighting to make a life in a country that continually segregates and belittles them. Even for characters who learn Japanese and seek citizenship, or, as the novel moves into the later 20th century, are born, raised and educated in Japan, there is little relief outside the embrace of the family circle. Among other things, Pachinko is about the primacy of family love in the context of survival.
As someone who’s known <NAME> for two decades now (how is this possible?), I’m not at all surprised to hear her described by <NAME> as one of our finest novelists. I’ve always been awed by the architectural intricacy and scope of her writing, along with its great psychological acumen and sense of intimacy. Lee is not afraid of the large questions—of belonging, religion, class, love and sex–either in her work or in conversation over a cup of coffee. –<NAME>
Q: Speaking of belonging, the question of home, and where characters belong comes up a lot in Pachinko. Just like in the Bible, where Jacob has to wait to die before his bones are carried from Egypt back to the Holyland, in Pachinko the Korean characters only seem to go back to the motherland in death. You lived your early childhood in Korea, and came to New York at age seven. Then as an adult, you spent several years in Japan with your husband and son. How did those experiences shape your feelings about home and exile?
A: If I had to draw a timeline of my life, I think seven is the age where I would divide childhood from an almost adult-like state of awareness. The memories I have of my life in Seoul before 1976 were the memories of a child—hazy and sunny with sounds of piano music and laughter; whereas, the memories I have of growing up in Elmhurst feel far more mature and sober, because I was aware of my family’s immigrant tensions.
My parents were middle class in Korea—my father worked as a cosmetics marketing executive for a well-known brand, and my mother was the neighborhood piano teacher with many students. Because my mother worked at home when she taught piano, the house was full of children, and the atmosphere was cheery. When we moved to America in March of 1976, we lived in a blue-collar neighborhood in rental apartments, which were not very nice. I didn’t speak English, and I was very shy so I found the local public schools very tough to comprehend.
Over thirty years later, we moved to Tokyo in 2007 when my husband Chris got a better job, and I couldn’t speak the language, and this time, I had to witness my son who was then nine years old go through what I had gone through in some ways. Thankfully, he was able to attend an English-speaking school, but unlike me, he didn’t have any siblings to soften the loneliness. I was working on my book and as a freelance journalist, and I couldn’t find the time to learn Japanese seriously. I think the experiences in Japan from 2007-2011 made me recall the feelings of isolation and alienation I’d fought to forget. As an American expatriate, I was able to appreciate the beauty and goodness of Japan in countless ways. However, interviewing many Korean-Japanese and studying the history of the Korean-Japanese altered my ideal perception as an admiring visitor. I think the historical correction was ultimately a good thing, but it affected my sense of ease and belonging in my temporary home.
Q: I know you’ve been strongly influenced by the omniscient novels of the 19th century. Can you talk about your use of the omniscient, or God-like, point of view in both Free Food for Millionaires and Pachinko? Omniscient is a great POV for creating narrative sweep and authority, but it’s technically difficult (arguably the most difficult of any point of view). What are the challenges and rewards of telling a story this way?
A: I think the omniscient point of view is ideal for community novels, and as you know, it is used in my favorite works of fiction. The challenges are that I need to inhabit the points of view of so many characters and find access to such characters. I learn about characters and their lives primarily through personal interviews. Doing 50-60 interviews per book and sorting through the stories take a lot of time and resources. Also, to get the right interview sometimes requires more than one introduction or meeting.
As for the rewards of using an omniscient point of view, I feel more expansive after having done the interviews and from having lived with such diverse characters for so many years. I may not agree with everyone, but I feel a lot more open to considering different kinds of lives, work, habits, families, political positions, class stations, and identities as a result of using an all-seeing, all-feeling and all-knowing point of view.
Q: Pachinko was meticulously researched over many years. I find research always changes my understanding of the story I want to write. Was this the case for you?
A: You bet. I find research humbling. I have this fantasy that I can write something good by sitting down and writing every day—just sitting is not easy and there should be some reward for this. However, I don’t think I’m that kind of writer. I am an anxious writer—worried about accuracy and story. I worry about beauty and balance—in a classical way of understanding aesthetics. I worry about how the research affects how a story is laid out in a structurally coherent way to achieve things like anagnorisis (recognition), catharsis (purgation), peripeteia (reversal)—that Artistotle discusses in Poetics; I mention this because I have the anxieties of a foreign-born writer from the East who is writing in English and in a Western literary mode. I think a lot about the rules and broken rules in literature, and how research can affect the requirements of aesthetics.
Q: I’m fascinated by the way you treat the issue of “passing” in this novel. Noa, in particular, lives his later life as a Korean “passing” for Japanese, and even his nephew, Solomon, though clearly identified as Korean, works for a British investment bank and thinks he’s going to get a fairer shot there, functioning in English. Passing is an issue that’s been written about a lot by minority writers in America—<NAME>, <NAME>, <NAME>, <NAME>, come to mind—but the idea of one Asian community passing within another brings up a unique set of challenges. Did you witness this while you lived in Japan? As a Korean immigrant growing up in Queens, did you feel the pull of assimilation more strongly than your parents might have liked? How did you get into the head of a character as desperate as Noa?
A: I think most of us are Noa in some parts of our lives—most of us have a deeply held view that by the dint of our efforts, we will be accepted. Every successful person I have ever met assimilated at a very high level into the culture of her field—complete with its own rules, moral code and jargon/language. If we are not Noa, we have a Noa part within us. With that preface, I have to say that I met enough Korean-Japanese people who were literally passing in Japan for Japanese that I could not not write about it. Also, Noa suffered, the way <NAME> in The House of Mirth suffered, because passing is a merciless and endless task. When I moved to America, I began the process of assimiliation that ended with me no longer being able to speak Korean fluently, and I think that loss of my first language is akin to a kind of death of a part of myself. I feel deeply for Noa, and I have known many, many Noas.
Q: We’ve talked a lot over the years about the challenges of rendering sex on the page. In Pachinko, you show us a lot of different kinds of sex—everything from an erotically charged seduction at the beach at low tide, to great marital tenderness behind a screen, to sex offered in a limo in exchange for designer purses. Which kind of scene did you find the most challenging to render? Is sex that’s purely about money and/or power easier to write than a scene of true emotional intimacy?
A: Oh, gosh. Writing about sex is difficult, and I think you are very smart to think of the distinct frames/paradigms of sex. I had to write these sex scenes, because they helped to characterize the relationships in the book, and importantly, the sex scenes had to humanize some of my characters who had lives of terrible deprivation and despondency.
That said, I think we have to go through our discomfort because literary sex is always far more informative in a way that literal sex cannot be, because in literary sex, we get to watch, feel, hear and engage with everyone who is in the scene. I’m not sure which sex scenes are easier to write; I do know that I tried to be spare about them. What I find interesting is writing the scenes with the same characters immediately following sex, because sex, well, sex changes the molecules in the air and our perception.
Q: Lastly, I know you’re always working on something interesting. What’s next for you?
A: I’ve started outlining my novel American Hagwon, which is about the role of education for Koreans around the world. I see Free Food for Millionaires, Pachinko, and American Hagwon as my trilogy about Korea. Hagwon is the Korean word for cram-school or study center. I’m in the doodling stage, and I have started to do some research, and I hope to do many interviews this year.
<NAME>, author of <NAME> (Twelve), is currently at work on her second novel.<file_sep>/content/review/nylon.md
---
title: Nylon on Pachkinko
attribution: Nylon
date: 2017-03-11T17:51:52.000+00:00
book: book/pachinko.md
description: ''
featured: false
weight:
---
50 Most Anticipated Books of 2017<file_sep>/content/event/politics--prose.md
---
title: Politics & Prose at The Wharf
date: 2018-02-26 19:00:00
show_time: true
venue:
name: Politics & Prose at the Wharf
address: 70 District Square SW
city: 'Washington, DC'
state:
zip: '20024'
link: 'http://www.politics-prose.com'
---
In conversation with author and critic, <NAME> of The Book Maven.<file_sep>/content/event/pen-americastrand-books.md
---
title: Pen America/Strand Books
date: 2016-08-01 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2017-12-20-canadian-broadcasting-corporation-10-best-international-fiction-2017.md
---
title: 'Canadian Broadcasting Corporation: 10 Best International Fiction 2017'
date: 2017-12-20 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Canadian Broadcasting Corporation
link_to_original: 'http://www.cbc.ca/books/the-best-international-fiction-of-2017-1.4453640'
description:
---
By CBC Books
<NAME>'s PACHINKO is a thoughtful look at the experience of Koreans in Japan, most of whom were born and grew up there, but are still classified as "resident aliens." In examining the complex relationship between Japan and Korea, Lee has crafted a tale that is passionate, dramatic and moving.
For the complete list, please click the link. Thank you.<file_sep>/content/event/marthas-vineyard-book-festival-sunday-pachinko-event.md
---
title: "Martha's Vineyard Book Festival (Sunday PACHINKO Event)"
date: 2017-08-06 11:45:00
show_time: true
venue:
name: 'Chilmark Community Center Campus, Stonewall Tent'
address:
city:
state:
zip:
link:
---
Introduced by Ambassador <NAME>
11:45am-12:30pm PACHINKO with <NAME>.
Chilmark Community Center Campus, Stonewall Tent
12:30-1:00pm Book Signing
<file_sep>/content/event/ka-stories.md
---
title: KA Stories
date: 2016-08-01 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2016-05-12-chicago-review-of-books-why-it-took-min-jin-lees-new-novel-30-years-to-write.md
---
title: "Chicago Review of Books: Why It Took <NAME>'s New Novel 30 Years to Write"
date: 2016-05-12 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Chicago Review of Books by <NAME>
link_to_original: 'https://chireviewofbooks.com/2016/05/12/bea-16-why-min-jin-lees-new-novel-took-30-years-to-write/'
description:
---
From <NAME>’s The Interpreter to <NAME>’s own Free Food for Millionaires, stories of Koreans and first generation Korean-Americans navigating life in the States span the hysterical, poignant, and bittersweet. But few works exist that detail an entirely different Korean immigrant community: those transplanted just across the sea to Japan. After spending four years living abroad in Tokyo herself, Korean-American lawyer-turned-writer <NAME> has tackled the stories of this underrepresented community in her second novel, Pachinko, forthcoming in February 2017 from Grand Central.
This week, <NAME> is in Chicago for BEA (Book Expo America), North America’s largest gathering of book industry professionals from around the globe. Lee is one of more than 500 participating in an author signing for an upcoming or recently-released book, in addition to the many panel and speaker events scheduled during the 4-day convention. The Chicago Review of Books spoke with Lee about her experience as an American writer abroad, her favorite sights to visit in the Windy City, and Pachinko, a book that took 30 years to write.
Your debut novel, Free Food for Millionaires, is a story about maintaining one’s identity within changing communities. Metropolitan settings—like New York City, Tokyo, or Chicago—are certainly the epitome of changing communities. How does being an urban writer affect your work and your characters’ stories?
In cities, I get to have both the nearness of many people and a kind of particular privacy found only in crowds. I was born in Seoul and have lived in New York, New Haven, Washington, D.C., and Tokyo. I feel the pull of suburbs and rural areas, too, but I feel most at home in cities. I live in Central Harlem now, and it is a quiet part of Manhattan. There is less car traffic where I live, and my neighbors are thoughtful and lovely. I live across the street from an elementary school, and the sounds of children make me feel happy and alert. I am an urban writer who feels comfortable around different types of people.
Also, there are daily surprises in cities like New York and Tokyo—some good and some not so good—which make for great material. Also, in a city, I am constantly humbled by the greatness of things and people. This, I think, is ultimately a fine thing. As I get older, I take myself less seriously.
After living (and writing) abroad for 4 years (in Tokyo from 2007 – 2011), what was it like to return stateside? Is being a writer a different sort of occupation in different countries?
I was happy to return home. I loved Tokyo in many ways, but I missed my family (parents, sisters, in-laws, nieces and nephew) and dear friends very much. Also, I missed speaking English to everyone. Americans, myself included, can talk with strangers rather easily, and I missed the brief intimacies shared among strangers. My Japanese is virtually non-existent so I felt I couldn’t do justice to my experience there. I am by nature a fairly open person, and because my language skills were so poor, I felt like I couldn’t be myself in Japan. Of course, the fault is my own.
In Japan, I worked on my novel Pachinko, and because my first book got a lot of attention, I was able to do a lot of freelance work for American, Korean and British publications. I had not done much freelance work before, so that was a little weird in a good way. For example, on one assignment, I got to choose the hottest restaurant in Tokyo, and I took that (delicious) task rather seriously, because I wanted to get it right; however, I did feel fraudulent in the endeavor, because I don’t think of myself as a cool person who could choose a hot anything, really.
In New York, I live a very quiet, anonymous existence. There are so many tremendous writers in New York, and I don’t think of my life in any kind of professional way. I stay home mostly and read and write. I do an inordinate amount of housework. I’m a very fine dinner-on-the-table-six-nights-a-week sort of cook. I suppose I think of myself as being creative in that way. I write and rewrite because that’s what I know how to do.
In a Travel & Leisure article from 2009, you discuss the importance of travel. As a young child, you traveled only within the pages of the books you read, but in adulthood you’ve made travel a central part of your life. What are your favorite sights to see in Chicago, and what are you looking forward to doing in the Windy City during your upcoming trip for BEA?
I have some very good friends in Chicago whom I don’t see enough, so I tried to get an extra day after Book Expo ends so we can hang out. My friends and I will grab some excellent Chicago coffee then start the morning with a walk through Millennium Park by the Bean then over the Gehry Bridge. I’m going to try to meet a writer pal at the Art Institute to admire the Chagall Windows then we’ll wander over to the Impressionist wing. Of course, we’ll have snack at the Art Institute Café.
Then, after a good long walk along Michigan Avenue for some window-shopping, I’m hoping that my friends and I can splurge on a big meal at Les Nomades, a favorite of my friend <NAME>, a true native of Chicago. It’s criminal to miss the pizza in Chicago, so naturally, I will have to have some every day during Book Expo.
Your second novel, Pachinko, is forthcoming in February of 2017. Can you tell us more about the book and your inspiration for writing it?
I got the idea of the story in 1989. I was a senior in college, and I attended a Master’s Tea, a talk hosted by a Master of a residential college at Yale. The Master of Trumbull, the Rev. <NAME>, was the University Chaplain, and he’d invited an American missionary who worked in Japan with the ethnic Korean population. I knew nothing then about Koreans in Japan who are called “zainichi.”
Zainichi is a misnomer used for Korean-Japanese people who either were migrants from the colonial era or descendants of such persons. Some do not like to be called zainichi because the term means “foreign resident staying in Japan,” which makes little sense since there are often third, fourth, and fifth surviving generations of Koreans in Japan. There are many ethnic Koreans who are now Japanese citizens, although this option to naturalize is not an easy one. There are also many who have intermarried with the Japanese, or who have partial ethnic Korean heritage.
Sadly, there is a long and troubled history of legal and social discrimination against the Koreans in Japan and those who have even partial ethnic Korean background. There are some who never disclose their ethnic Korean heritage, although it can follow them in their identification papers and government records.
The missionary told us a little about this history and a story of a middle school boy who was bullied in his yearbook because of his ethnic Korean background. The boy jumped off a building and died. Later, after I quit being a lawyer in 1995, I started writing fiction about the Koreans in Japan as early as 1996. I wrote several, and one of the stories called “Motherland,” which is about a Korean-Japanese boy who gets fingerprinted and receives a foreigner’s identity card on his birthday, was published in The Missouri Review in 2002 then later won the Peden Prize.
Also, I submitted a fictionalized account of the story I’d heard in college, and it allowed me to get a NYFA fellowship in fiction, which meant a great deal. I used that money to take classes and to pay for a babysitter so I could write. Also, this early recognition was critical, because as a fiction writer, it took me so long to publish my first novel unrelated to the Korean-Japanese. Finally, the recognition was most important to me, because it confirmed my belief that the stories of Koreans in Japan should be told somehow when so much of their lives had been denied, erased and despised.
I wanted very much to get this right, but I felt that I didn’t have the knowledge or the skills to do this properly.
Based on an enormous amount of historical and anthropological research, I wrote a partial draft of a novel about the Korean Japanese community. Later, when I moved to Tokyo in 2007 with my family, I got the chance to interview dozens of Koreans in Japan and learned that I got the story wrong. The Korean-Japanese may have been historical victims, but when I met them in person, none of them were as simple as that. I was so impressed by the breadth and complexity of the people I met in Japan that I had to start the book again in 2008, and I continued to write it and revise it until the sale of the manuscript in 2015.
I have had this book with me for almost 30 years.
What other projects are you currently working on?
I am working on American Hagwon, what I think of as the third of my Koreans trilogy. I want to write about the importance and dangers of education for Koreans around the world.<file_sep>/content/event/amherst-college-18.md
---
title: '92Y: <NAME>at and Ann Patchett'
date: 2019-09-25T19:30:00-04:00
show_time: true
venue:
name: <NAME>
address: 92nd Street Y
city: New York
state: NY
zip: "10128"
link: https://www.92y.org/event/edwidge-danticat-and-ann-patchett
description: Introductions by <NAME> and <NAME>
images:
- "/uploads/danticat-patchett.jpg"
---
<file_sep>/content/news/-min-jin-lee-delivers-commencement-address-to-monmouth-college-.md
---
title: Commencement Address to Monmouth College Class of 2018
date: 2018-05-13 00:13:12 -0400
images: []
image_credit: ''
categories: []
where_published: Monmouth College
link_to_original: http://www.monmouthcollege.edu/information/newsEvents/newsDetails.aspx?Channel=%2FChannels%2FCampus+Wide&WorkflowItemID=2e5abd8b-13fb-4651-9b66-9059fbca6e76
description: ''
---
<file_sep>/content/news/2008-04-27-savetheassistants.md
---
title: "Savetheassistants"
date: 2008-04-27T22:11:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Savetheassistants"
link_to_original: "http://savetheassistants.com/?p=266 "
description: ""
_slug: 2008-04-27-savetheassistants
---
<NAME>’s debut novel, Free Food for Millionaires, tells a story many of us can identify with. Casey, the daughter of working-class Korean immigrants in ...
<file_sep>/content/event/second-sundays.md
---
title: Second Saturdays Reading Series
date: 2018-01-13 19:00:00
show_time: true
venue:
name: Private home.
address:
city:
state:
zip:
link:
---
Curated by <NAME>
This event will be held at a private home with an open reading, potluck dinner, and the featured author.
Copies of PACHINKO will be available for sale from the independent bookseller REVOLUTION BOOKS.
Please RSVP to <EMAIL><file_sep>/content/news/the-new-yorker-stonehenge.md
---
title: 'NPR On Point: "<NAME> On Life As An Immigrant At Elite Colleges — And
In America"'
date: 2019-06-10T02:00:00-04:00
categories:
- Media
tags:
- Audio
- Interviews
attribution:
link_to_original: https://www.wbur.org/onpoint/2019/06/10/min-jin-lee-immigrant-college-school-america-stonehenge-new-yorker
description: " "
---
> [https://www.wbur.org/onpoint/2019/06/10/min-jin-lee-immigrant-college-school-america-stonehenge-new-yorker](https://www.wbur.org/onpoint/2019/06/10/min-jin-lee-immigrant-college-school-america-stonehenge-new-yorker "https://www.wbur.org/onpoint/2019/06/10/min-jin-lee-immigrant-college-school-america-stonehenge-new-yorker")<file_sep>/content/writing/2010-11-03-travel_leisure1.md
---
title: "TRAVEL + LEISURE November 2010"
date: 2010-11-03T09:09:43-05:00
categories:
tags:
where_published: "Travel + Leisure "
link_to_original: "http://www.travelandleisureasia.com/"
link_to_pdf:
description: "Cheju of South Korea is a place of astonishing natural beauty. An essay appears in this month's T+L. "
_slug: 2010-11-03-travel_leisure1
---
[http://www.travelandleisureasia.com/](http://www.travelandleisureasia.com/).gif)
<file_sep>/content/event/new-canaan-library.md
---
title: New Canaan Library
date: 2018-05-23 12:00:00 -0400
show_time: true
venue:
name: Country Club of Darien
address: ''
city: ''
state: ''
zip: ''
link: 'newcanaanlibrary.org '
description: 'Spring Edition Fundraiser for New Canaan Library '
images: []
---
Luncheon<file_sep>/content/news/2018-02-11-pachinko-is-an-american-library-awards-notable-book-for-2018.md
---
title: PACHINKO is an American Library Awards Notable Book for 2018
date: 2018-02-11 12:00:00
categories: ["News"]
tags:
- News
attribution:
link_to_original:
description: >-
2018 Notable Books List: Year’s best in fiction, nonfiction and poetry
announced.
---
2018 Notable Books List: Year’s best in fiction, nonfiction and poetry announced.
Read the press release at the [ALA Website](2018 Notable Books List: Year’s best in fiction, nonfiction and poetry announced).<file_sep>/content/event/amherst-college-19.md
---
title: 'Princeton University: <NAME> and <NAME> - Postponed '
date: 2020-04-29T20:30:00.000+00:00
show_time: true
venue:
name: <NAME>
address: Princeton University
city: Princeton
state: NJ
zip: '08544'
link: https://ams.princeton.edu/news/2019-20/celebrating-new-asian-american-writing
description: ''
images:
- "/uploads/Image-1.jpg"
---
<file_sep>/content/news/2008-04-27-washington_times.md
---
title: "Washington Times"
date: 2008-04-27T22:54:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Washington Times"
link_to_original: ""
description: ""
_slug: 2008-04-27-washington_times
---
Trying on different hats
<file_sep>/content/event/lynden-womens-speaker-series.md
---
title: "Lynden Women's Speaker Series: Milwaukee, WI"
date: 2017-09-28 19:00:00
show_time: true
venue:
name: Lynden Sculpture Garden
address:
city:
state:
zip:
link: 'http://www.lyndensculpturegarden.org/womens-speaker-series'
---
<NAME>, founder and executive producer of Milwaukee Reads, presents an ongoing series featuring writers of particular interest to women. The series is presented in conjunction with Boswell Books and MKELocalicious.<file_sep>/content/news/2016-05-26-korean-community-center-keynote-address-2016-video.md
---
title: Korean Community Center Keynote Address 2016 (VIDEO)
date: 2016-05-26 12:00:00
categories: ["Media"]
tags:
- Video
attribution:
link_to_original:
description:
---
<iframe width="560" height="315" src="https://www.youtube.com/embed/0otGC98IPIg" frameborder="0" allowfullscreen=""></iframe><file_sep>/content/news/2017-04-10-people-magazine-2017.md
---
title: People Magazine 2017
date: 2017-04-10 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: People Magazine
link_to_original:
description:
---
<file_sep>/content/news/2017-12-20-electric-literature-25-best-novels-of-2017.md
---
title: 'Electric Literature: 25 Best Novels of 2017'
date: 2017-12-20 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Electric Literature
link_to_original: >-
https://electricliterature.com/electric-literatures-25-best-novels-of-2017-5c0b1c67a998
description:
---
What with the impending demise of net neutrality and social media turning into a toxic snake pit, you’re going to want to be spending a lot more time curled up with a book. Celebrate the end of a lousy year and the start of a probably lousier one by picking up a few of the 25 novels that Electric Literature staff and contributors voted as our favorites of 2017. With National Book Award finalists and winners as well as weird small-press offerings, we’ve got something for every taste.
Pachinko, <NAME>
National Book Award finalist Pachinko is a family epic about Koreans in imperialist Japan. It’s a deeply-researched piece of historical fiction that still feels urgent, relevant, and full of human emotion.
For the complete list, please click the link.<file_sep>/content/event/one-story-.md
---
title: 'One Story '
date: 2018-07-26 18:30:19 -0400
images: []
description: 'In conversation with <NAME> and <NAME> '
link: ''
show_time: true
venue:
address: ''
city: ''
name: 'Community Bookstore '
state: ''
zip: ''
---
<file_sep>/content/event/pasadena-festival-of-women-authors.md
---
title: Pasadena Festival of Women Authors
date: 2018-04-14 08:00:00 -0400
show_time: true
venue:
name: <NAME>
address: 168 S. Los Robles Avenue
city: Pasadena
state: CA
zip: ''
link: www.pasadenafestivalofwomenauthors.org
description: ''
images: []
---
<file_sep>/content/news/pachinko-is-a-selection-of--now-read-this--the-joint-book-club-of-pbs-newshour-and-the-new-york-times.md
---
title: July pick for the PBS NewsHour-New York Times book club is PACHINKO
date: 2018-06-27 23:59:53 -0400
images: []
image_credit: ''
categories: []
where_published: New York Times and PBS NewsHour
link_to_original: https://www.pbs.org/newshour/arts/the-july-pick-for-the-pbs-newshour-new-york-times-book-club-is-pachinko
description: ''
---
<file_sep>/content/event/festival-neue-literatur-another-country-distant-lands-up-close-and-personal.md
---
title: NYPL Library Lunch
date: 2019-04-18 12:00:00 -0400
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: https://2019librarylunch.splashthat.com/
---
Featuring <NAME>, <NAME>, and <NAME> in conversation with <NAME><file_sep>/content/news/2007-07-24-npr_booktour.md
---
title: "NPR Booktour"
date: 2007-07-24T23:22:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "NPR Booktour"
link_to_original: "http://www.npr.org/templates/story/story.php?storyId=12128414 "
description: ""
_slug: 2007-07-24-npr_booktour
---
Keeping up with the Joneses isn’t easy ‚Äî even if you’re a fashion-conscious young woman with an Ivy League degree, a strong sense of ...
<file_sep>/content/news/2008-04-24-viewpoint_with_jean_dean.md
---
title: "Viewpoint with <NAME>"
date: 2008-04-24T13:19:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "ESPN Radio 930"
link_to_original: "http://wrvc.podOmatic.com"
description: ""
_slug: 2008-04-24-viewpoint_with_jean_dean
---
Jean’s first guest was Dr. <NAME> MS, Ph.D, Director, Center for Food Safety. Jean’s second half hour was with <NAME>, author of “Free Food For Millionaires.”
<file_sep>/content/event/east-city-bookshop.md
---
title: 'Washington, D.C.: East City Bookshop'
date: 2017-06-22 18:30:00
show_time: false
venue:
name: East City Bookshop
address: '645 Pennsylvania Ave. SE, Suite 100'
city: 'Washington, D.C.'
state:
zip: '20003'
link: 'http://www.eastcitybookshop.com'
---
Co-sponsored by www.originsjournal.com
Introduction by Editor in Chief of Origins, <NAME>
In Conversation with <NAME>
<NAME> is a DC-based national correspondent at The New York Times, with a focus on technology. She previously covered technology for The Washington Post, where her stories on in-app purchases led to federal charges against Google, Apple, and Amazon. Cecilia has covered race and immigration for the San Jose Mercury News and was the bureau chief for AP-Dow Jones in South Korea during the nation's debt crisis and election of the first civilian president, <NAME>. She is a frequent guest on NPR, CNN, CNBC, MSNBC and the PBS Newshour. <file_sep>/content/event/the-kenan-institute-for-ethics-at-duke-university.md
+++
date = 2022-04-08T23:00:00Z
description = " Join Duke History professor <NAME> for a conversation with Lee on Family, Community, and the Bonds That Make Us."
images = []
link = "https://kenan.ethics.duke.edu/event/the-ethics-of-now-presents-min-jin-lee/"
show_time = true
title = "The Kenan Institute for Ethics at Duke University"
[venue]
address = "120 Morris St."
city = "Durham"
name = "<NAME>"
state = "NC"
zip = "27701"
+++
<file_sep>/content/news/2008-04-25-conversationsfamouswriters.md
---
title: "Conversationsfamouswriters"
date: 2008-04-25T22:58:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Conversationsfamouswriters"
link_to_original: "http://conversationsfamouswriters.blogspot.com/2007/07/min-jin-lee-free-food-for-millionaires.html"
description: ""
_slug: 2008-04-25-conversationsfamouswriters
---
If you want a thick, extremely well written literary novel then rush out and pick up Free Food For Millionaires. It took me a while to read but every night I crawled into bed with it and marveled at how <NAME> crafted this satisfying novel that weaves together so many themes.
<file_sep>/content/writing/2012-04-07-times_of_london_book_review_when_march_was_made_of_yarnanthology_of_march_1.md
---
title: "Times of London Book Review: WHEN MARCH WAS MADE OF YARN—anthology of March 11"
date: 2012-04-07T11:02:44-05:00
categories:
tags: ["Essays"]
where_published: "The Times of London"
link_to_original: "http://thetim.es/xxEb6u"
link_to_pdf:
description:
_slug: 2012-04-07-times_of_london_book_review_when_march_was_made_of_yarnanthology_of_march_1
---
<file_sep>/content/event/sydney-writers--festival-2018--pachinko-with-min-jin-lee.md
---
title: 'Sydney Writers'' Festival 2018: PACHINKO with <NAME>'
date: 2018-05-03 20:00:21 -0400
images: []
description: '<NAME> in conversation with <NAME> '
link: https://www.swf.org.au/writers/min-jin-lee/
show_time: true
venue:
address: '245 Wilson Street '
city: ''
name: Carriageworks, Bay 17
state: ''
zip: ''
---
<file_sep>/content/news/npr-on-point-min-jin-lee-on-life-as-an-immigrant-at-elite-colleges-and-in-america.md
---
title: 'Burdock: An Interview with <NAME>'
date: 2019-04-12T02:00:00-04:00
categories:
- Media
tags:
- Interviews
- News
attribution:
link_to_original: https://burdockmedia.com/profile/min-jin-lee-5cb3f05ffc42c5660ea0d182
description: |-
Burdock had the honor of interviewing Korean American writer <NAME> while she was working on her third book, AMERICAN HAGWON.
Words by <NAME>
---
> <file_sep>/content/news/chicago-tribune-the-biblioracle-recommends-pachinko.md
---
title: 'Chicago Tribune: The Biblioracle Recommends PACHINKO '
date: 2018-07-11 18:19:51 -0400
link_to_original: http://www.chicagotribune.com/lifestyles/books/ct-books-biblioracle-0715-story.html
images: []
tags: []
categories: []
description: 'By <NAME> '
---
<file_sep>/content/news/top-5-most-popular-books-at-cambridge-public-library-in-2018.md
---
title: Top 5 most-popular books at Cambridge Public Library in 2018
date: 2018-12-21 22:52:21 -0500
link_to_original: http://cambridge.wickedlocal.com/news/20181221/top-5-most-popular-books-at-cambridge-public-library-in-2018
images: []
tags: []
categories: []
description: '"''Pachinko'' by <NAME> was one of the most popular books at Cambridge
Public Library in 2018."'
---
<file_sep>/content/news/2017-01-04-the-millions-most-anticipatedthe-great-2017-book-preview.md
---
title: 'The Millions: Most Anticipated—The Great 2017 Book Preview'
date: 2017-01-04 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Millions by
link_to_original: 'http://www.themillions.com/2017/01/most-anticipated-the-great-2017-book-preview.html?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+themillionsblog%2Ffedw+%28The+Millions%29'
description:
---
Pachinko by <NAME>: A sweeping look at four generations of a Korean family who immigrates to Japan after Japan’s 1910 annexation of Korea, from the author of Free Food for Millionaires. <NAME> says “Pachinko confirms Lee’s place among our finest novelists.” (Lydia)<file_sep>/content/news/2017-02-09-goodreads-good-minds.md
---
title: 'Goodreads: Good Minds'
date: 2017-02-09 12:00:00
categories: ["News"]
tags:
- Reviews
- Essays
- Interviews
attribution: Goodreads February 2017
link_to_original: 'https://www.goodreads.com/interviews/show/1223.Min_Jin_Lee?utm_medium=email&utm_source=newsletter&utm_campaign=2017-02&utm_content=lee&ues=a'
description:
---
<NAME> immigrated to Queens with her mother, father, and two sisters when she was seven years old. The backdrop of her bestselling debut novel, Free Food for Millionaires, a coming-of-age story of an immigrant college graduate, was set in her childhood neighborhood of Elmhurst.
<br>
<br>Now, after ten years, Lee's second novel, Pachinko, follows a Korean-Japanese family across four generations. Lee learned about the history of the Korean-Japanese community in 1989, when she was a junior in college, and has worked on this novel ever since.
<br>
<br>Pachinko is the story of Sunja, a young woman who loves her family and struggles to survive in the face of historical upheavals and injustice. Lee says that to work on books for such a long time requires love. So, in the month of hearts and cupids, Lee shares the books that, for her, define love:
<br>
<br>Ain't I a Woman by bell hooks
"I read this powerful work at about the same time I got the idea for Pachinko. I was an immigrant girl from a modest background studying at Yale, a college steeped in tradition and privilege, and bell hooks's writings taught me to love myself as a woman of color even in such a setting. Consequently, the book also freed me to love others without judgment."
<br>
<br>The Four Loves by C.<NAME>
"My grandfather was a Presbyterian minister who ran a piano-manufacturing school for orphans after the Korean War. I grew up in the church, and I think Lewis, the renowned British author of the Chronicles of Narnia, explains the ideas of faith-based love beautifully here."
<br>
<br>The End of the Affair by <NAME>
"Greene is a master, and this is one of the most compelling stories of romantic love—complete with inconvenience, longing, and sacrifice."
<br>
<br><NAME> by <NAME>
"Balzac worked continuously and published prolifically, and it is clear in his tens of thousands of pages that he loved women and life. Balzac's Bettewants loves desperately, and this vital novel is an extraordinary treatise on the intimate relationship between hate and love."
<br>
<br>Two Lives by <NAME>
"Last year we lost a literary colossus. "Reading Turgenev," one of the two novellas in this book, knocked me out in its wise depiction of the lasting love found between the seemingly misbegotten of this world."<file_sep>/content/event/the-wing-bookclub.md
---
title: 'The Wing: Bookclub'
date: 2018-03-26 18:30:48 -0400
show_time: true
venue:
name: The Wing
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
---
Curated by <NAME>
<file_sep>/content/news/2008-04-25-as_i_am.md
---
title: "As I Am"
date: 2008-04-25T23:26:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "As I Am"
link_to_original: "http://www.asiam.us/about.html"
description: ""
_slug: 2008-04-25-as_i_am
---
The Pilot features up and coming author <NAME> as she discusses her new book Free Food for Millionaires with Boston College’s Professor <NAME> ...
<file_sep>/content/news/2017-07-19-bookbub-the-buzziest-books-of-2017-so-far.md
---
title: 'BookBub: The Buzziest Books of 2017 (So Far)'
date: 2017-07-19 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: BookBub
link_to_original: 'https://media.bookbub.com/blog/2017/07/19/popular-books-2017/'
description:
---
By <NAME>
2017 has been a great year for book lovers so far. From new releases by our favorite writers to wonderful breakout books and genre-bending novels, the list of popular books in 2017 keeps growing. We’ve compiled a list of books getting the most buzz so far this year, along with their publishers’ descriptions.
Pachinko by <NAME>
Profoundly moving and gracefully told, Pachinko follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them. Betrayed by her wealthy lover, Sunja finds unexpected salvation when a young tubercular minister offers to marry her and bring her to Japan to start a new life.
So begins a sweeping saga of exceptional people in exile from a homeland they never knew and caught in the indifferent arc of history. In Japan, Sunja’s family members endure harsh discrimination, catastrophes, and poverty, yet they also encounter great joy as they pursue their passions and rise to meet the challenges this new home presents. Through desperate struggles and hard-won triumphs, they are bound together by deep roots as their family faces enduring questions of faith, family, and identity.
For the complete list, please click the link below.<file_sep>/content/review/olsson-s-bookstore-on-free-food-for-millionaires.md
---
title: Olsson's Bookstore on Free Food for Millionaires
attribution: Olsson's Bookstore
date: 2007-03-11 18:07:52 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
<NAME>, author of Free Food for Millionaires, one of my favorite books this year, will be appearing at US-Korea Institute of the Paul H. Nitze School of Advanced International Studies (SAIS) next week, and Olsson’s will be…<file_sep>/content/news/2017-01-02-kirkus-reviews-fiction-editor-laurie-muchnicks-my-own-most-anticipated-list.md
---
title: "Kirkus Reviews: Fiction Editor <NAME>'s My Own Most-Anticipated List"
date: 2017-01-02 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: 'Kirkus Reviews by Fiction Editor, <NAME>'
link_to_original: 'https://www.kirkusreviews.com/features/my-own-most-anticipated-list/'
description:
---
One of my most treasured possessions is a list of all the books I’ve read for the past 30 years, written chronologically in a blank book I won in a high school essay contest. Every January, I print the new year at the top of the next blank page and think about all the books I’m looking forward to reading in the coming months.
This year, there are new books by writers I’ve enjoyed in the past, such as Perfect Little World (Jan. 24) by <NAME>, author of the entrancing Family Fang; Always Happy Hour (Jan. 10), a book of short stories by <NAME>, whose road-trip novel, The Last Days of California, was one of the pleasures of 2014; and All Grown Up (March 7) by <NAME>, author of one of the funniest family stories I know, The Middlesteins, which Kirkus called “a sharp-tongued, sweet-natured masterpiece of Jewish family life.”
<NAME> wrote his last novel, How to Get Rich in Rising Asia, in a daring second-person narrative voice; I can’t wait to see what he does in his new one, Exit West (March 7). <NAME> is a Canadian novelist who isn’t as well-known in the U.S.; in novels such as Mr. Sandman and The Romantic, she used what Kirkus called “dark humor and wry compassion” to explore the lives of people who proudly call themselves “freaks.” Her new novel, Little Sister (May 23), is her first in 10 years. I have happy memories of reading <NAME>’s first novel, The Big Love, a sort-of post–Bridget Jones story of a single woman in Philadelphia, so I’m looking forward to her new one, The Arrangement (March 21). George Saunders is known for his playful short stories; our review calls his first novel, Lincoln in the Bardo (Jan. 3), “an exhilarating change of pace.”
Then there are books by authors I’ve been meaning to read but haven’t yet: The Patriots (Jan. 24) by <NAME>; Pachinko (Feb. 7) by <NAME>; The Night Ocean (March 7) by <NAME>; Ill Will(March 7) by <NAME>. And first novels: Lucky Boy (Jan. 10) by <NAME>; The Futures (Jan. 17) by <NAME>; Marlena(April 4) by <NAME>. Looking ahead to the fall, both <NAME> and Jeffrey Eugenides have so-far-untitled books coming out—a novel for McDermott and short stories for Eugenides. Doesn’t look like I’ll run out of things to read any time soon. <NAME> is the fiction editor.<file_sep>/content/review/politics-prose.com-on-free-food-for-millionaires.md
---
title: Politics-Prose.com on Free Food for Millionaires
attribution: Politics-Prose.com
date: 2007-03-11 18:12:10 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
<NAME>, in her first novel, paints a vast New York landscape that brings to mind…<file_sep>/content/news/2017-12-28-vox-the-best-books-i-read-in-2017.md
---
title: 'Vox: The Best Books I read in 2017'
date: 2017-12-28 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Vox
link_to_original: 'https://www.vox.com/2017/12/28/16807326/best-books-list-2017'
description:
---
By <NAME>, Editor-at-Large
PACHINKO
The first sentence of this National Book Award finalist takes no prisoners. “History has failed us, but no matter,” writes <NAME>.
I don’t read as much fiction as I should, and the pleasure I got from reading Pachinko only deepened that shame. The book tracks multiple generations of a Korean family living in Japan as they’re buffeted by war, bigotry, and the daily struggles of life. Even as I read that last sentence, I recognize that it’s the sort of recommendation that would make me think a book is Good and Important but probably a slog. Pachinko isn’t.
What’s more, it tracks the era in which Korea is sliced into halves, in which Koreans lose control of their own destiny, in which they are treated as pawns by the Americans and as subhuman by the Japanese, and is thus powerful context for today’s geopolitics.
For the complete list, please click the link.<file_sep>/content/news/guardian-frederick-douglass-200-interview.md
---
title: 'The Guardian: <NAME> 200 Interview'
date: 2018-08-02 15:22:17 -0400
images: []
tags:
- 'Interview '
- Profile
- Award
- <NAME>
categories: ["Profile"]
description: Throughout 2018 – the bicentennial of <NAME> – The Antiracist
Research and Policy Center at American University and the Frederick Douglass Family
Initiatives are honoring 200 individuals whose modern-day work best embodies Douglass’s
enduring legacy of social change. The Guardian is publishing the names of all 200
honorees – 10 each week – between now and November. Here, <NAME>,
director of advocacy and strategic partnerships at The Antiracist Research and Policy
Center at American University, speaks to one of the honorees, <NAME>.
link_to_original: https://www.theguardian.com/commentisfree/2018/aug/02/min-jin-lee-interview-frederick-douglass-200
---
<file_sep>/content/event/amherst-college.md
---
title: Boston University, MFA Program
date: 2020-10-07T19:00:00-04:00
show_time: true
venue:
name: ''
address: ''
city: ''
state: ''
zip: ''
link: ''
description: ''
images: []
---
<file_sep>/content/event/copperfields-books.md
---
title: "Copperfield's Books"
date: 2017-02-24 19:00:00
show_time: true
venue:
name: "Copperfield's Books"
address: 140 Kentucky Street
city: Petaluma
state: CA
zip: '94952'
link: 'https://copperfieldsbooks.com/petaluma'
---
Lit Night Series: In Conversation with <NAME>, the Executive Director of Northern California Independent Booksellers Association (NCIBA). Calvin served as the president of the board of NCIBA and worked for over two decades at both Book Passage and Books Inc. Most recently, he served as the sales and marketing director of McSweeney's. <file_sep>/content/event/denver-co.md
---
title: 'Boston College: Fiction Days presents Min Jin Lee '
date: 2021-02-24T19:00:00-05:00
show_time: true
venue:
name: <NAME>
address: ''
city: Chestnut Hill
state: MA
zip: '02467'
link: http://events.bc.edu/event/fiction_days_presents_min_jin_lee_pachinko#.XV7QTJNKhmA
description: Virtual
images: []
---
<file_sep>/content/event/dublin-pat-kenny-on-newstalk-national-radio.md
---
title: 'Dublin: <NAME> on Newstalk National Radio'
date: 2017-05-25 10:35:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Live interview with <NAME>.<file_sep>/content/news/2017-05-28-hay-festival-2017.md
---
title: Hay Festival 2017
date: 2017-05-28 12:00:00
categories: ["News"]
tags:
- Essays
- News
attribution: Hay Festival
link_to_original: 'http://blog.hayfestival.org/index.php/2017/05/a-special-kind-of-star-gazing-min-jin-lee/'
description:
---
I had the pleasure of attending the Hay Festival on May 27, 2017, and the organizers asked me to record my impressions of my first time there.
By <NAME>
Authors are vulnerable to star-gazing.
I’d gotten tickets for the David Mitchell event, but because of horrid train delays, I’d missed it. I was heartbroken, because I’d wanted very much to hear him speak. As soon as I got out of the train station in Hereford, I turned to my right and spotted <NAME>, the author of White Tears. I’d just done an event in Brooklyn with his talented wife <NAME>, but I’d never met Hari before. So I ended up meeting a New York resident in Wales.
Then I got in the Hay van with other writers, and naturally, we asked each other about our respective books. Seated behind the van driver was the gracious Ed Luce, the brilliant columnist of the FT, who has written an important book called The Retreat of Western Liberalism. On the ride to our accommodations, we talked about the upcoming elections in June, and I must confess that talking in a crowded van across seats with someone who knows politics so well is a bit intimidating, but in such situations, I try to listen very carefully and take in the light.
When I finally registered at the Festival offices, I saw live screens of the different stages and caught the genius <NAME>ama. In the Green Room, I spotted <NAME>, the Olympic medallist, Charlotte Rampling, the actor, and <NAME>, the Canadian author of Do Not Say We Have Nothing.
By the time it was time to do my event with <NAME>, the author of The Lucky Ones, chaired by the brilliant Lena de Casparis, the Culture Editor of Elle UK, I felt a little like the moon, almost luminous, having reflected so many suns.<file_sep>/content/event/tacoma-wa-kings-books.md
---
title: 'Tacoma, WA: King''s Books'
date: 2018-02-15 19:00:00
show_time: true
venue:
name: King's Books
address: 218 St. Helens Avenue
city: Tacoma
state: WA
zip: '98402'
link: 'http://www.kingsbookstore.com/directions'
---
<file_sep>/content/event/los-angeles-ca.md
---
title: 'Beverly Hills High School PTSA Book Salon: In Conversation With <NAME>'
date: 2018-11-01 19:00:15 -0400
images: []
description: 'Moderated by <NAME> '
link: https://bhhsptsabooksalonpachinko.eventbrite.com
show_time: true
venue:
address: ''
city: ''
name: Temple Emanu El in Beverly Hills
state: ''
zip: ''
---
<file_sep>/content/news/2017-12-26-pbs-best-books-of-2017-video.md
---
title: 'PBS: Best Books of 2017 (Video)'
date: 2017-12-26 12:00:00
categories: ["Media"]
tags:
- Reviews
- News
- Video
- Interviews
attribution: PBS Books
link_to_original: 'http://www.pbs.org/book-view-now/best-books-of-2017/'
description:
---
Pachinko by <NAME> Lee is a sprawling, beautiful novel chronicling the cultural struggles of four generations of a Korean family, beginning in 1910 during the time of Japanese colonization. In our interview with Lee at the 2017 Miami Book Fair, she reflected on the opening lines of her book, “History has failed us. But no matter.” Lee explains, “People who are powerless are affected by history and yet have to carry on because so many of us don’t sit at the tables in which decisions are made.”
For the complete list and video interview with <NAME> of PBS Books, please click the link. <file_sep>/content/event/rj-julia.md
---
title: <NAME>
date: 2018-01-25 19:00:00
show_time: true
venue:
name: <NAME>
address: 768 Boston Post Road
city: Madison
state: CT
zip: '06443'
link: 'http://www.rjjulia.com/event/min-jin-lee-pachinko'
---
The event is FREE but please register in the link below. <file_sep>/content/event/thalia-book-club.md
---
show_time: true
title: Thalia Book Club
date: 2021-01-28T19:00:00-05:00
description: Virtual
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.symphonyspace.org/events/thalia-book-club-salon-min-jin-lee-in-conversation-with-you
images: []
---
<file_sep>/content/news/2017-03-30-esquire-top-10-best-books-of-2017-so-far.md
---
title: 'Esquire: Top 10 Best Books of 2017 (So Far)'
date: 2017-03-30 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Esquire Magazine
link_to_original: 'http://www.esquire.com/entertainment/books/a52733/best-books-of-2017/?src=socialflowFB'
description:
---
By <NAME>
Pachinko by <NAME>
Thirty years in the making, Lee's sweeping, multi-generational novel is set in 1900s Asia and is informed by stories she heard about legal and social discrimination against Koreans in Japan, a history largely denied and erased. This story kicks off with an unplanned pregnancy and the promise of a less shameful life in Japan and evolves into addictive family saga packed with forbidden love, the search for belonging, and triumph against the odds.<file_sep>/content/news/2007-07-12-newsweek_interview.md
---
title: "Newsweek Interview"
date: 2007-07-12T21:57:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: ""
link_to_original: ""
description: ""
_slug: 2007-07-12-newsweek_interview
---
<NAME>’s ambitious debut novel, “Free Food for Millionaires,” has been showered with ... <NAME>: We migrated from Korea to the US when I was 7. ...
<file_sep>/content/news/2017-01-13-the-tnb-announces-pachinko-as-its-february-book-club-selection.md
---
title: The TNB Announces PACHINKO as its February Book Club Selection
date: 2017-01-13 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Nervous Breakdown Book Club
link_to_original: 'http://www.thenervousbreakdown.com/bookclub/'
description:
---
*Pachinko* is the February TNB Book Club Selection, hand-picked by executive editor <NAME> and TNB founder <NAME>.
<NAME> will discuss *Pachinko* on the celebrated podcast *Otherppl with Brad Listi* in February 2017.<file_sep>/content/event/awp-kundiman-sigrid-nunez--harold-augenbraum.md
---
title: 'AWP: Kundiman— <NAME> & <NAME>'
description: In conversation with author <NAME> and moderated by Yale Review Editor, <NAME>
date: 2018-03-10 13:30:00
show_time: true
venue:
name: Bud's House
address: 400 West. 2202 St.
city: New York
state: NY
zip: 10025-9878
link: 'http://budparr.com'
---
<file_sep>/content/event/east-meadow-public-library.md
---
title: East Meadow Public Library
date: 2018-03-20 20:00:00
show_time: true
venue:
name:
address: 1886 Front Street
city: East Meadow
state: NY
zip: '11554'
link:
---
<file_sep>/content/news/2017-12-05-npr-best-books-of-2017.md
---
title: 'NPR: Best Books of 2017'
date: 2017-12-05 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: NPR Books
link_to_original: 'http://apps.npr.org/best-books-2017/#/book/pachinko'
description:
---
Pachinko makes the NPR Best Books of 2017 list. Selected by <NAME>, correspondent of the Arts Desk.
"Japan's bright, noisy pachinko parlors hide a dark secret. These pinball emporiums are run mostly by Japan's Korean minority because for decades it was the only employment available to them. In Pachinko, Min Jin Lee traces the difficult history of Koreans in Japan through one family's story. The saga begins before World War I in a small Korean fishing village, where a young woman becomes pregnant and is saved from disgrace by a man who offers to marry her and takes her to Japan. We follow her and her two sons as they struggle against discrimination, trying to gain respect in a hostile country. Min Jin Lee brings this corner of history to life in a tale that spans three wars and the growth of a multibillion-dollar business that offered Korean-Japanese a way out of poverty."
–<NAME>, correspondent, Arts Desk<file_sep>/content/review/gary-shteyngart-on-pachkinko.md
---
title: <NAME> on Pachkinko
attribution: <NAME>, New York Times bestselling author of *Little Failure*
and *Super Sad True Love Story*
date: 2017-03-13 14:46:00 +0000
book: book/pachinko.md
description: ''
featured: false
---
Astounding. The sweep of Dickens and Tolstoy applied to a 20th century Korean family in Japan. Min Jin Lee's *Pachinko* tackles all the stuff most good novels do—family, love, cabbage—but it also asks questions that have never been more timely. What does it mean to be part of a nation? And what can one do to escape its tight, painful, familiar bonds?<file_sep>/content/news/2009-03-25-south_china_morning_post_march_1_2009.md
---
title: "South China Morning Post - March 1, 2009"
date: 2009-03-25T10:45:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "South China Morning Post"
link_to_original: ""
description: ""
_slug: 2009-03-25-south_china_morning_post_march_1_2009
---
 A profile of my work appeared in the [Post](http://www.scmp.com/portal/site/SCMP/ "the Post") - the English-language paper of Hong Kong. It was written by <NAME>. I recently visited Hong Kong for its Man Hong Kong Literary Festival, and it was a beautiful place.
[Click here to download](/uploads/MinJinSCMP.pdf)
<file_sep>/content/event/harvard-book-store.md
---
title: Harvard Book Store
date: 2017-02-10 18:45:00
show_time: true
venue:
name: Harvard Book Store
address: 1256 Massachusetts Avenue
city: Cambridge
state: MA
zip: 02138
link: 'http://www.harvard.com'
---
In Conversation with <NAME>, <NAME> Professor of Law at Harvard Law School and author of *At Home in the Law*, *A Light Inside*, and *Postcolonial Paradoxes in French Caribbean Writing*. She is a Contributing Writer for *The New Yorker*.<file_sep>/content/news/adweek-creative-100---10-writers-and-editors-who-are-changing-the-national-conversation--.md
---
title: 'Adweek Creative 100: "10 Writers and Editors Who are Changing the National
Conversation" '
date: 2018-06-10 00:09:26 -0400
images: []
image_credit: ''
categories: []
where_published: Adweek
link_to_original: https://www.adweek.com/creativity/10-writers-and-editors-who-are-changing-the-national-conversation-2018/
description: ''
---
<file_sep>/content/event/bedford-book-club.md
---
title: Bedford Book Club
date: 2017-04-12 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
<file_sep>/content/news/2016-11-15-one-story-interview-with-editor-and-novelist-hannah-tinti.md
---
title: 'One Story: Interview with Editor and Novelist <NAME>'
date: 2016-11-15 12:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original: 'http://www.one-story.com/index.php?page=stories&pubcode=os&story_id=222'
description:
---
HT: What was the seed of this story? What was the first thing you wrote?
MJL: I lived in Japan from 2007-2011, where I had the chance to interview many Korean-Japanese. My interview subjects would talk about childhood, employment history, gender roles, education, and family background. Often, I heard stories of lost loves. I was struck by how frequently a love story from the interviewee’s teen years would change the course of his or her life. Among other things, this story investigates love and intersectionality.
HT: What was the most challenging aspect of writing this story?
MJL: I wanted to write accurately about the lives of ordinary Korean women of this era, and it was tough because there were so few primary documents about illiterate working class women. I turned to academic ethnographies and recorded interviews, then I learned more about their lives from the children and grandchildren of such women.
HT: “The Quality of Your Life” is a section of your forthcoming novel, Pachinko. Can you talk a bit about where this falls in the story, and how this meeting between Sunja and Hansu affects the rest of the book?
MJL: This story is the inciting incident, which propels the entire novel. As a result of the relationship between Sunja and Hansu, Sunja marries Isak, a Korean pastor and moves to Japan, where she settles and has two sons. She never returns to Korea. Pachinko is the story of Sunja and her family, set in the turbulent history of Koreans in Japan from the period of 1910-1989. One of things I am always puzzling through is the intersection of history, fate and personal choice, and I felt compelled by Sunja’s resistance and determination to live and flourish in a harsh and difficult environment.
HT: The details of Sunja being attacked by the Japanese students is chilling. Throughout this story, and the rest of your novel, you detail many ways Koreans struggle with their identity, especially those living in Japan. Can you talk a bit about what first drew you to this topic, and why you decided to explore it in Pachinko?
MJL: I got the seed of the novel from a lecture about the Korean-Japanese that I attended in college when I was 19 years old. During this lecture, an American missionary who worked with the Koreans in Japan relayed a story about a middle school-aged Korean-Japanese boy who died as a result of horrific bullying by his classmates. That lecture changed my life; I could not let that story go. I felt that I had to understand the power of extrinsic hate that could compel one to hate himself. I also wanted to understand the love the hated can feel and enact for the one who hates him.
HT: Hansu’s father seems to have set him on a criminal path, while Sunja remembers her handicapped father fondly, and turns to him for strength. While most of Pachinko centers around women and mothers, can you talk a bit about the influence of fathers in your story?
MJL: One of the metaphysical questions I wanted to understand is what makes a man. Sunja’s two sons must learn how to be men in a world where they are disempowered politically, socially, and financially because of their ethnic background. The role of fathers becomes extraordinarily important to both daughters and sons in this work. In connection with what makes a man, I am investigating what constitutes masculinity for men of oppressed classes. I wanted very much to understand what makes a man a father. The plot lines of the central characters are affected significantly by his or her relationship with a father, or in cases, the absence of a father.
HT: Sunja has a prophetic conversation with the ajumma at the market at the beginning of this story, when the older woman tells her, “The man you marry will determine the quality of your life…but no matter what, always expect suffering, and just keep working hard.” Later in the book, Sunja becomes an ajumma herself, selling kimchi and sweets. It almost seems like she is visiting herself from the future, and giving herself this advice. Was this your intention? And do you think time and history factors into your writing—weaving together the past, present and future?
MJL: Yes! You’re an excellent reader. It was my intention to explore this notion so widely-held by a specific generation of Koreans—that women suffer and that suffering is to be expected. Of course, men suffer, too, but as a woman, I found it disturbing to hear so many women from older generations repeat this sentiment so frequently. Also, when I heard older women say that a woman’s life is determined by her husband, it went without saying that romantic love must not be everything; in fact, perhaps romantic love was perilous. I wanted to question this ajumma’s prophecy, because the quality of Sunja’s life was certainly informed by her choice to love Hansu at this point in time, but I wanted to see how she can determine the quality of her life through her daily choices, too.
HT: How long did it take you to complete Pachinko? And what are you most excited about its publication next February?
MJL: As I mentioned, I got the seed of this story when I was 19. After I quit lawyering, I wrote a fictionalized account of the original seed of the story and submitted it as a sample chapter for a grant from the New York Foundation for the Arts, which I later received. Later, I wrote a related story about Koreans in Japan, called “Motherland,” which was published in The Missouri Review in 2002. (Yes, fourteen years ago.) Eventually, I had a full draft of a novel, which I did not show anyone because I didn’t feel ready. I worked on another novel, and in 2007, I published my debut Free Food for Millionaires. A few months after its publication, I moved to Japan. After interviewing Korean-Japanese in Japan and researching the subject in Osaka, I threw away the first version of the novel about the Korean-Japanese and wrote another manuscript, which became Pachinko. I’ve been working on this novel in some form or another since I was 19, and I am now 48 years old; it will be published in 2017 when I turn 49. In a word: nuts. I am very excited to be done. It sounds horribly dramatic, but I was possessed by this work for nearly three decades, and I am so very relieved and grateful to have the pages out.
HT: What are you working on now?
MJL: I’m doodling my third novel, American Hagwon, which will focus on the role of education for Koreans around the world. When I write fiction, I do some cursory outlines, make some thin sketches then do extensive interviews with dozens of people, which are fun for me. Then, I shut myself up in my home and write. I throw out many drafts. I keep hoping I will learn how to be efficient.
HT: What is the best bit of advice about writing you have ever received?
MJL: I heard a sermon once where a minister said that one should “choose the important over the urgent.” I use this idea in my life and in my writing. There are things in my life, which feel so terribly urgent, but when I remember what is important to me, the urgency often fades. In fiction writing, drama requires urgency, but themes and theses should be important, and I believe the correct interplay between drama and themes makes for finer work. I think about this idea of choosing the important over the urgent all the time.<file_sep>/content/event/amherst-college-11.md
---
title: 'Lakeside Lecture Series: An Evening with <NAME> '
date: 2021-03-17T19:00:00-04:00
show_time: true
venue:
name: St. <NAME>
address: Lakeside Upper School
city: Seattle
state: WA
zip: "98125"
link: https://www.lakesideschool.org/about-us/lakeside-lecture-series/lakeside-lecture-series-jewell
description: ''
images: []
---
<file_sep>/content/news/2016-10-15-library-journal-starred-review.md
---
title: 'Library Journal: Starred Review'
date: 2016-10-15 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Library Journal
link_to_original: 'http://reviews.libraryjournal.com/2016/09/books/fiction/lj-fiction-reviews-october-15-2016/'
description:
---
Set in Korea and Japan, Lee's follow-up to her acclaimed debut, *Free Food for Millionaires*, is a beautifully crafted story of love, loss, determination, luck, and perseverance. Sunja is the only surviving child of humble fisherman Hoonie (himself born with a cleft palate and twisted foot) and wife Yangjin in the early 1900s. Losing her father at age 13, Sunja appears to be a dutiful daughter by working at the boardinghouse with her mother, only to surprise the family three years later by becoming pregnant by an older married man with children. She saves face when a minister at the boardinghouse, ten years older than Sunja, offers to marry her and take her to Japan with him to start a new life. What follows is a gripping multigenerational story that culminates in 1989. There are surprising twists, especially when Sunja crosses paths with her former lover while living in Japan. **VERDICT** Lee's skillful development of her characters and story lines will draw readers into the work. Those who enjoy historical fiction with strong characterizations will not be disappointed as they ride along on the emotional journeys offered in the author's latest page-turner. —<NAME>, Orange City. P.L., Santa Ana, CA<file_sep>/content/event/patrick-henry-college-newsmaker-interview-series-with-marvin-olasky.md
---
title: '<NAME> College: Newsmaker Interview Series with <NAME>'
date: 2018-03-28 12:40:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Conversation with <NAME>, Editor in Chief of WORLD magazine<file_sep>/content/event/asij.md
---
title: ASIJ
date: 2009-02-11T23:34:00-05:00
venue:
name: AMERICAN SCHOOL IN JAPAN
link: http://community.asij.ac.jp/NetCommunity/Page.aspx?pid=200&srcid=200
---
FOR THE ASIJ COMMUNITY
<file_sep>/content/event/turn-of-the-corkscrew-literary-tea.md
---
title: Turn of the Corkscrew Literary Tea
date: 2018-09-16 14:00:26 -0400
images: []
description: Interview with <NAME> and with authors <NAME>, <NAME>, and <NAME>
link: https://madisontheatreny.org/event/turn-of-the-corkscrews-inaugural-literary-tea/
show_time: true
venue:
address: ''
city: Rockville Center, Long Island
name: 'Madison Theater at Molloy College '
state: ''
zip: ''
---
<file_sep>/content/event/harvard-radcliffe-institute-artists-surviving-and-thriving-in-recent-times.md
+++
date = 2022-03-10T16:00:00Z
description = "In the next installment of our Radcliffe on the Road series, we will consider how artists have navigated the struggles and opportunities that the COVID-19 pandemic has brought to the forefront."
images = []
link = "https://www.radcliffe.harvard.edu/event/2022-artists-surviving-thriving-recent-times-virtual"
show_time = false
title = "Harvard Radcliffe Institute - Artists Surviving and Thriving in Recent Times"
[venue]
address = "Zoom "
city = ""
name = ""
state = ""
zip = ""
+++
<file_sep>/content/event/american-university.md
---
title: American University
date: 2019-02-13 18:30:19 -0500
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2017-02-28-booktalk-with-cyd-oppenheimer-audio.md
---
title: BookTalk with Cyd Oppenheimer (AUDIO)
date: 2017-02-28 12:00:00
categories: ["Media"]
tags:
- Reviews
- Interviews
- Audio
attribution: BookTalk with Cyd Oppenheimer
link_to_original: 'http://www.booktalkradio.net/all-episodes/2016/10/31/episode-33-pachinko-by-min-jin-lee'
description:
---
Episode 34
Hosted by Cyd Oppenheimer and guest readers: <NAME> and <NAME><file_sep>/content/review/david-mitchell-on-pachinko.md
---
title: <NAME> on Pachinko
attribution: <NAME>, New York Times bestselling author of *The Bone Clocks*,
*Cloud Atlas*, and *Black Swan Green*
date: 2017-03-11 17:44:21 +0000
book: book/pachinko.md
description: ''
featured: false
---
A deep, broad, addictive history of a Korean family in Japan enduring and prospering through the 20th century.
<file_sep>/content/news/pbs-books-at-the-miami-book-festival-video.md
---
title: PBS Books at the Miami Book Festival (Video)
date: 2017-11-17 21:00:19 -0500
link_to_original: https://www.pbs.org/video/min-jin-lee-2017-miami-book-fair-0pqgsk/
images: []
tags: []
categories: []
description: ''
---
<file_sep>/content/news/2017-12-04-bookpage-best-books-of-2017.md
---
title: BookPage Best Books of 2017
date: 2017-12-04 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: BookPage
link_to_original: 'https://bookpage.com/features/22037-best-books-2017#.WiW-s85OjE4'
description:
---
Pachinko is one of the Top 25 Books of the Year in BookPage
For the complete list, please click the link.<file_sep>/content/event/class_of_2007_reading_series_boxcar_lounge.md
---
title: Class of 2007 Reading Series @ Boxcar Lounge
date: 2007-02-28T10:00:00-05:00
venue:
name: Class of 2007 Reading Series @ Boxcar Lounge
link: www.boxcarlounge.com
_slug: class_of_2007_reading_series_boxcar_lounge
---
(Hosted by <NAME>)
<NAME>, <NAME>, <NAME>, and <NAME> @ 8 PM
<file_sep>/content/news/2017-03-17-rn-abc-books--arts-australia-with-michael-cathcart-audio.md
---
title: 'RN ABC: Books & Arts (Australia) with <NAME> (AUDIO)'
date: 2017-03-17 12:00:00
categories: ["Media"]
tags:
- Reviews
- Audio
- Interviews
attribution: RN ABC Books and Arts
link_to_original: 'http://www.abc.net.au/radionational/programs/booksandarts/min-jin-lee:-pachinko/8362486'
description:
---
Friday 17 March 2017 10:05AM (view full episode)
Korean immigrants to Japan during the time of occupation were known as 'zainichi', which means 'foreign residents staying in Japan'. This idea of impermanence was passed on to their children.
When your place in the country of your birth is considered temporary, how do you find your place in the world?
<NAME> received international acclaim for her debut, Free Food for Millionaires, which took a sympathetic and entertaining look at coming of age in America.
And in her sophomore novel, Pachinko, Lee tells the story of a Korean family's search for identity, across four generations and almost a century.
To listen, please click the link.<file_sep>/content/event/madison-wi-702wi.md
---
title: 'Madison, WI: 702Wi'
date: 2017-09-27 19:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link: 'http://www.702wi.com/events.html'
---
Authors <NAME>, <NAME>, in conversation with <NAME>, Pachinko.
Tickets Available on link. <file_sep>/content/event/borders_fort_lee_new_jersey.md
---
title: Borders, Fort Lee, New Jersey
date: 2007-06-09T15:00:00-05:00
venue:
name: Borders, Fort Lee, New Jersey
link: www.borders.com
_slug: borders_fort_lee_new_jersey
---
<file_sep>/content/news/2016-12-16-bbc-com-10-books-to-read-in-2017.md
---
title: 'BBC.com: 10 Books to Read in 2017'
date: 2016-12-16 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: "BBC.com's Culture by <NAME>"
link_to_original: 'http://www.bbc.com/culture/story/20161216-ten-books-to-read-in-2017'
description:
---
This immersive novel follows four generations of a Korean family from 1910, when Japan annexed Korea, through most of the 20th Century. An aging fisherman and his wife run a boarding house in a village near the port city of Busan. Their only surviving son, who has a cleft palate and twisted foot, is married at last. When his teenage daughter Sunja becomes pregnant by a visiting businessman, a kind pastor marries her and takes her to Osaka. After he dies, Sunja’s grit and hard work keep the family afloat during the tough war years. Her elder son makes it into Waseda University. Her younger son thrives by running pachinko parlours, where gamblers play machines in a game similar to pinball. But their future is shadowed by past secrets and betrayals.<file_sep>/content/event/2017-02-18-savannah-book-festival-2017.md
---
title: Savannah Book Festival 2017
date: 2017-02-18 09:00:00
show_time: false
venue:
name: First Baptist Church Fellowship Hall
address: 102 West McDonough Street
city: Savannah
state: GA
zip:
link: 'http://www.savannahbookfestival.org'
---
<NAME> discusses PACHINKO at 9AM.<file_sep>/content/event/northeastern-university-.md
---
title: 'Northeastern University '
date: 2018-11-07 19:00:45 -0500
images: []
description: ''
link: ''
show_time: true
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/event/seoul_writers_conference_2010.md
---
title: SEOUL INTERNATIONAL WRITERS’ CONFERENCE 2010
date: 2010-05-11T23:49:00-05:00
venue:
name: SEOUL INTERNATIONAL WRITERS' CONFERENCE 2010
link: www.sywf.org
_slug: seoul_writers_conference_2010
---
KOREAN LITERATURE TRANSLATION INSTITUTE: Seoul International Writers’ Conference
Wonderspace, House of Literature, Seoul, South Korea
Fiction Public Reading on Monday, May 10, 2010:
2.30pm
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
Fiction Public Reading on Tuesday, May 11, 2010
3.30pm
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>/content/news/writer-min-jin-lee-to-teach-at-amherst-college-3.md
---
title: NYFA Inducts <NAME>, <NAME>, And <NAME> Into Hall Of Fame
date: 2019-04-12 00:50:11 -0400
link_to_original: https://www.broadwayworld.com/off-off-broadway/article/NYFA-Inducts-Sanford-Biggers-Karl-Kellner-And-Min-Jin-Lee-Into-Hall-Of-Fame-20190412
images: []
tags: []
categories: []
description: '"<NAME> discussed her process and interests, and reflected on the
hardships of being a professional artist, especially as a woman of color. She also
described the impact of receiving a NYSCA/NYFA Artist Fellowship: ''I needed to
have this kind of support that somehow what I did mattered. And that was so important
to have NYFA recognize that my little question was worth supporting, and I think
that when the average person in this country thinks that art matters, that''s a
huge step. Because it is so often seen as less important than food, and housing,
and jobs, and healthcare, and all those things are really important for me, too.
But I chose this path because I think that literature can create the level of empathy
that many things cannot. I believe that, I believe that with everything that I do.''"'
---
<file_sep>/content/event/drive-my-car-featuring-q-a-with-director-ryusuke-hamaguchi-and-min-jin-lee.md
+++
date = 2022-03-17T04:00:00Z
description = "Q&A with <NAME> and author <NAME> on March 17 at the 7pm screening. "
images = []
link = "https://www.filmlinc.org/films/drive-my-car/"
show_time = true
title = "Drive My Car - Featuring Q&A with Director <NAME> and <NAME>"
[venue]
address = "144 W 65th St"
city = "New York"
name = "<NAME> Film Center"
state = "New York "
zip = "10023"
+++
<file_sep>/content/event/odyssey-bookshop.md
---
title: Odyssey Bookshop
date: 2017-02-11 16:00:00
show_time: true
venue:
name: Odyssey Bookshop
address: 9 College Street
city: South Hadley
state: MA
zip: '01075'
link: 'http://odysseybks.com'
---
In Conversation with <NAME>, President and Owner of Odyssey Bookshop. <file_sep>/content/news/nypl-top-checkouts-of-2018.md
---
title: NYPL Top Checkouts of 2018
date: 2018-12-17 09:34:48 -0500
link_to_original: https://www.nypl.org/blog/2018/12/17/nypl-top-checkouts-2018
images:
- "/uploads/topcheckouts-img.jpg"
tags: []
categories: []
description: '"Pachinko" included in the Top 10 Books in Manhattan'
---
<file_sep>/content/news/2007-07-06-npr_tell_me_more.md
---
title: "NPR Tell Me More"
date: 2007-07-06T23:24:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "NPR Tell Me More"
link_to_original: "http://www.npr.org/templates/story/story.php?storyId=11779763"
description: ""
_slug: 2007-07-06-npr_tell_me_more
---
<NAME> wanted to capture the experience of children of immigrants living in America. Her debut novel, Free Food for Millionaires, tells the story of <NAME>, a daughter of Korean immigrants living in New York. Lee discusses her book and the passion behind her writing.
<file_sep>/content/news/2008-02-05-wall_street_journal_juggle_book_club_selection.md
---
title: "Wall Street Journal Juggle Book Club Selection"
date: 2008-02-05T21:55:01-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Wall Street Journal Juggle Book Club Selection"
link_to_original: "http://blogs.wsj.com/juggle/2008/02/05/min-jin-lee-on-leaders-good-girls-and-the-discomforts-of-wealth/"
description: ""
_slug: 2008-02-05-wall_street_journal_juggle_book_club_selection
---
**<NAME> on Leaders, Good Girls and the Discomforts of Wealth**
The Juggle spoke yesterday with <NAME>, author of “Free Food for Millionaires” the third book in our Juggle book club. <NAME> called us from Tokyo, where she lives with her husband and 10-year-old son, and where she’s working on…
<file_sep>/content/news/2017-01-11-south-china-morning-post-post-magazine.md
---
title: 'South China Morning Post: Post Magazine'
date: 2017-01-11 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: <NAME>
link_to_original: 'http://www.scmp.com/magazines/post-magazine/books/article/2060927/min-jin-lees-epic-pachinko-takes-complex-and-fraught'
description: "\"Min Jin Lee's epic PACHINKO takes on the complex and fraught history of Korea and Japan\""
---
“History has failed us, but no matter.” So begins Korean-American author <NAME>’s gripping new novel about a chapter largely ignored in English literature: the Koreans in Japan.
It is only as the reader approaches the end of the novel that the momentous historical weight and narrative ambition of this enigmatic opening hit home. Within a few scant sentences, Lee transports us directly into the joys and vicissitudes of an ageing fisherman and his wife who, in 1910, are living in the Korean fishing village of Yeongdo with their only son, a hardworking, club-footed, cleft-lipped 27-year-old named Hoonie.
Not that the page-turning quality of Lee’s unadorned prose should come as a surprise. She’s renowned for her award-winning short stories, and her debut novel, Free Food for Millionaires, was declared one of the top 10 novels of 2007 by The Timesof London and was a New York Times Editor’s Choice
[For the full review, click here](http://www.scmp.com/magazines/post-magazine/books/article/2060927/min-jin-lees-epic-pachinko-takes-complex-and-fraught)
<file_sep>/content/event/muldoons-picnic.md
---
title: "<NAME>"
date: 2017-10-09 19:30:00
show_time: true
venue:
name: Irish Arts Center
address: 553 West 51st Street
city: New York
state: NY
zip: '10019'
link: 'http://irishartscenter.org'
---
An omnioum-gatherum of words and music hosted by the Pulitzer Prize-winning poet and New Yorker poetry editor <NAME>.<file_sep>/content/event/university-of-california-san-diego-geisel-library-50th-anniversary-event.md
---
show_time: true
title: University of California San Diego Geisel Library 50th Anniversary Event
date: 2021-05-26T20:00:00-04:00
description: Join us as we honor Asian American and Pacific Islander Heritage Month
and conclude our Geisel Library 50th Anniversary Signature Events series with a
talk featuring New York Times bestselling author <NAME> and moderated by <NAME>, associate professor in the Department of History.
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://library.ucsd.edu/news-events/events/min-jin-lee/
images: []
---
<file_sep>/content/review/obama.md
---
title: President <NAME> on Pachinko
date: 2020-01-25T00:00:00-04:00
attribution: President <NAME>
book: book/pachinko.md
description: ''
featured: false
weight:
---
This is a captivating book I read at the suggestion of a young staffer on my team — a historical novel about the Korean immigrant experience in wartime Japan. <NAME>’s novel takes us through four generations and each character's search for identity and success. It’s a powerful story about resilience and compassion.<file_sep>/content/writing/guardian---north-good--south-bad--time-to-shed-the-korea-stereotypes.md
---
title: 'The Guardian: "North good, south bad? Time to shed the Korea stereotypes'
date: 2018-02-12 00:26:05 -0500
images: []
image_credit: ''
categories: []
where_published: The Guardian
link_to_original: https://www.theguardian.com/commentisfree/2018/feb/12/north-south-korea-koreans
description: ''
---
<file_sep>/content/news/the-year-in-books-what-seattle-times-arts-writers-read-and-loved-in-2018.md
---
title: 'The year in books: What Seattle Times arts writers read and loved in 2018'
date: 2018-12-14 16:24:54 -0500
link_to_original: https://www.seattletimes.com/entertainment/books/the-year-in-books-what-seattle-times-arts-writers-read-and-loved-in-2018/
images: []
tags: []
categories: []
description: '"''Pachinko'' is one of those family sagas that you get lost in, forgetting
the passage of time, disappearing into places far away — a poor fisherman’s cramped
lodging house; a fragrant restaurant kitchen where kimchee is crafted; a noisy pachinko
parlor; a hospital room where generations become linked. ''Sweeping'' and ''epic''
are words that are always applied to books like this, but they fit; you leave ''Pachinko''
feeling changed, as if your world got a little bigger."'
---
<file_sep>/content/event/2016-10-04-french-institute-alliance-francaise.md
---
title: "French Institute Alliance Francaise - CineSalon Series: Beyond the Ingenue"
date: 2016-10-04T19:30:00Z
venue:
name: FIAF, Florence Gould Hall
address: 55 East 59th Street, NY NY
city: New York
state: NY
zip:
link: http://www.fiaf.org/events/fall2016/2016-10-pauline.shtml
---
"Pauline at the Beach" by <NAME>, Introduced by <NAME>
<file_sep>/content/news/2017-07-05-irish-times-summer-reading-top-picks.md
---
title: 'Irish Times: Summer Reading Top Picks'
date: 2017-07-05 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Irish Times
link_to_original: 'http://www.irishtimes.com/culture/books/what-are-anne-enright-john-boyne-and-others-reading-this-summer-1.3139189'
description:
---
**What are <NAME>, <NAME> and others reading this Summer?**
**Some of Ireland’s best-known writers and readers share the books that will be in their suitcases**
Wed, Jul 5, 2017, 06:00 Updated: Wed, Jul 5, 2017, 13:07
Edited by <NAME>, Books Editor of the IRISH TIMES
PACHINKO was selected by:
**<NAME>**
<br>My favourite novel of the year so far is Pachinko by <NAME>, a multi-generational story of Koreans living in Japan over the last century. Elizabeth Strout’s Anything is Possible is also quite brilliant, a series of interconnected stories revealing the secrets and regrets of the inhabitants of a small town. I’ve been saving <NAME>’s Prague Nights for a trip there with my nephew and niece this summer. There’s a lot of buzz about Elizabeth Day’s The Party as well as Sarah Winman’s Tin Man, so both of these will be straight on to my reading list.
**<NAME>**
<br>One of my favorite books of 2017 was Pachinko, by <NAME>, a sweeping Korean family saga which would be perfect to get lost in on holidays. In another strong year for Irish books I particularly loved When Light is like Water by <NAME>. Meanwhile, among the many works of crime fiction I read this year, Let the Dead Speak by <NAME>y and He Said / She Said by <NAME> stood out and in non ficton I really enjoyed Gone, by <NAME>.
**<NAME>**
<br>Reading pleasures of the year to date include Min Jin Lee’s evocative immigrant story Pachinko; Tana French’s tense and salty The Trespasser; and A History of Running Away, Paula McGrath’s pugilistic follow-up to Generation. I’m currently munching through Elizabeth Strout’s Anything is Possible, which is next up at my book club. Other eagerly anticipated titles include Between Them, <NAME>’s slender memoir of his parents; and <NAME>’s new novel House of Names. I was lucky enough to hear both writers read at Listowel Writers’ Week this year, and bring their words brilliantly to life.
**<NAME>**
<br>My idea of a “summer read” doesn’t necessarily meet the general criteria. You have been warned. I’d suggest <NAME>’s wonderful The Heart’s Invisible Furies, Theft By Finding, the David Sedaris diaries, Sally Rooney’s Conversations With Friends or Min Jin Lee’s Korean family saga Pachinko. If you’re travelling after late July then one of the best books of the year is the upcoming Tin Man by <NAME>. The one I’m saving for when I go away is a gorgeous reprint I was given recently of Catch-22. I haven’t read it since I was a teenager.
Thank you so much. For the remainder of the article, please see the link below.<file_sep>/content/event/los_angeles.md
---
title: loyola Marymount University
date: 2008-04-24T05:22:00-05:00
venue:
name: Loyola Marymount University, Los Angeles, CA
link:
_slug: los_angeles
---
A Conversation with Professor <NAME> and <NAME>
Department of African American Studies
“WOMEN OF COLOR: FAITH, FRIENDSHIP and CREATIVE EXPRESSION”
5:30PM
Loyola Marymount University
University Hall 1000
THIS EVENT IS OPEN TO THE PUBLIC
<file_sep>/content/news/2017-02-23-daily-mail-uk-reviews-pachinko-a-sheer-delight.md
---
title: 'Daily Mail UK Reviews PACHINKO: "A sheer delight"'
date: 2017-02-23 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: 'Daily Mail UK: Literary Fiction by <NAME>'
link_to_original: 'http://www.dailymail.co.uk/home/books/article-4253782/LITERARY-FICTION.html'
description:
---
By <NAME>
This new novel from the Korean-American Min Jin Lee is set mainly in Japan — but, through four generations of a family, it beautifully examines the little-explored hardships often suffered by Korean exiles in Japan following that country’s occupation of Korea and the seismic upheavals of World War II.
Sunja, the unexceptional daughter of Korean peasants, is the main constant: her love affair with the criminal father of her first son, her marriage to a Korean Christian and her relationship with her new family and her two very different sons are the threads that run through this expansive, elegant and utterly absorbing book.
Each new generation is determined to better itself, yet each is snagged anew by the existential no man’s land of life in an adopted, hostile country.
Combining the detail of a documentary with the empathy of the best fiction, it’s a sheer delight.
<br>Read more: http://www.dailymail.co.uk/home/books/article-4253782/LITERARY-FICTION.html#ixzz4ZdvKZufk
<br>Follow us: @MailOnline on Twitter | DailyMail on Facebook<file_sep>/content/event/second-annual-national-antiracist-book-festival-conversation-with-jacqueline-woodson-on-the-politics-of-love.md
---
show_time: true
title: Second Annual National Antiracist Book Festival - Conversation with <NAME> on the Politics of Love
date: 2021-04-24T17:00:00-04:00
description: The National Antiracist Book Festival is the first and only book festival
that brings together, showcases, and celebrates the nation’s leading antiracist
writers and helps to prepare the writers of tomorrow. It is hosted every April in
Washington, D.C., by the BU Center for Antiracist Research. The festival assembles
a day full of author panels and editorial workshops. A vibrant crowd of authors
and attendees engage in antiracist dialogue that will challenge, inspire, and mobilize.
Workshops bring together leading book editors and literary agents to provide insight
and guidance for aspiring writers.
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.bu.edu/antiracism-center/narrative/national-antiracist-book-festival/
images: []
---
<file_sep>/content/event/race_ethnicity_and_the_american_writer_a_conversation_with_novelist_min_jin.md
---
title: "Race, Ethnicity, and the American Writer: A Conversation with Novelist Min Jin Lee"
date: 2016-02-25T15:00:22-05:00
venue:
name: Yale University, William L. Harkness Hall 100 Wall Street
link: www.erm.yale.edu
_slug: race_ethnicity_and_the_american_writer_a_conversation_with_novelist_min_jin
---
February 25, 2016, THURSDAY at 4pm
A Public Dialogue with Professor <NAME> and Novelist <NAME>
Sponsored by the Ethnicity, Race and Migration Program at Yale University
Professor <NAME> is the William Roberston Coe Professor of American Studies & History and Professor of African American Studies. Professor Jacobson is the author of What Have they Built You to Do?: The Manchurian Candidate and Cold War America, (with <NAME>alez, 2006), Roots Too: White Ethnic Revival in Post–Civil Rights America (2005), Barbarian Virtues: The United States Encounters Foreign Peoples at Home and Abroad, 1876–1917 (2000), Whiteness of a Different Color: European Immigrants and the Alchemy of Race (1998), and Special Sorrows: The Diasporic Imagination of Irish, Polish, and Jewish Immigrants in the United States (1995). He is currently at work on Odetta’s Voice and Other Weapons: The Civil Rights Era as Cultural History.
<file_sep>/content/writing/2008-11-12-walk_this_way_ed._rebecca_walker.md
---
title: "Walk This Way (ed. <NAME>)"
date: 2008-11-12T22:10:23-05:00
categories:
tags: ["Essays"]
where_published:
link_to_original:
link_to_pdf:
description:
_slug: 2008-11-12-walk_this_way_ed._rebecca_walker
---
<file_sep>/content/event/immigrant_heritage_week.md
---
title: IMMIGRANT HERITAGE WEEK
date: 2008-04-15 13:00:00
venue:
name: INTERNATIONAL IMMIGRANTS FOUNDATION
link:
_slug: immigrant_heritage_week
---
Immigrant Heritage Week 2008
April 15, Tuesday 4PM
“On Becoming a Novelist: Writing FREE FOOD FOR MILLIONAIRES” The International Immigrants Foundation The Immigrant’s Building 7 West 44th St. 2nd Floor
THIS EVENT IS OPEN TO THE PUBLIC
<file_sep>/content/event/sofija-stefanovics-at-the-strand.md
---
title: 'Book Launch: <NAME> at the Strand'
date: 2018-04-23 19:00:34 -0400
images: []
description: '<NAME>''s MISS EX-YUGOSLAVIA: In Conversation with <NAME>
Lee'
link: https://www.strandbooks.com/event/sofija-stefanovic
show_time: true
venue:
address: ''
city: 'New York City '
name: 'Strand Books '
state: ''
zip: ''
---
<file_sep>/content/event/jersey-city-public-library.md
---
title: Jersey City Public Library
date: 2017-05-17 18:00:00
show_time: true
venue:
name: Jersey City Free Public Library
address: 472 Jersey Avenue
city: Jersey City
state: NJ
zip: '07302'
link: 'http://www.jclibrary.org/programs-exhibits/icalrepeatdetail/2017/05/17/4871/min-jin-lee-pachinko-autor'
---
In Conversation with <NAME>.
Event is FREE, but please RSVP if possible:
http://JCFPLMinJinLee.eventbrite.com
Location: Biblioteca Criolla at the Main Library
4th Floor
201-547-4541
Books sold by Word Books.
Pre-order books: bit.ly/2pmqjFS<file_sep>/content/event/miami_book_fair.md
---
title: Miami Book Fair
date: 2007-11-10T01:20:00-05:00
venue:
name: Miami Book Fair, FLA
link: www.miamibookfair.com
_slug: miami_book_fair
---
Miami Book Fair
<file_sep>/content/news/2017-08-31-washington-post-pachinko-is-roxane-gays-favorite-book-of-2017.md
---
title: 'Washington Post: PACHINKO is Roxane Gay''s Favorite Book of 2017'
date: 2017-08-31 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: The Washington Post
link_to_original: >-
https://www.washingtonpost.com/express/wp/2017/08/31/8-authors-coming-to-the-national-book-festival-tell-us-the-best-thing-they-read-this-year/?utm_term=.45f163b965bc
description:
---
By <NAME>
The National Book Festival: the one day a year when a serious reader’s biggest problem isn’t that overflowing stack of books to get to. During the 10-hour event, more than 100 authors, illustrators and poets will give talks and sign their books. It’s a lot to take in, so we won’t judge if you’ve been busy finessing an Excel-sheet game plan (<NAME> or <NAME> at 10 a.m.?). To help with your prep work, we chatted with seven of this year’s featured authors — including <NAME> and the “Outlander” series’ <NAME> — about their talks and the books they’ve loved in 2017.
<NAME>
<br>Gay says she’ll be reading from “Hunger: A Memoir of (My) Body,” which was released in June, and doing a Q&A about her work. In “Hunger,” she describes her rape as a young girl and her struggles with food, weight and self-image in her trademark arresting style. “I ate and ate and ate in the hopes that if I made myself big, my body would be safe,” she writes. “I buried the girl I was because she ran into all kinds of trouble.”
<br>Favorite 2017 book: The novel “Pachinko” by <NAME>, which follows four generations of a poor Korean immigrant family in Japan.
For the complete article, please click the link.<file_sep>/content/event/happy_ending_music_and_reading_series_curated_by_amanda_stern.md
---
title: Happy Ending Music and Reading Series Curated by Amanda Stern
date: 2007-10-24T01:16:00-05:00
venue:
name: Happy Ending Music and Reading Series, New York
link: www.amandastern.com/happyending.html
_slug: happy_ending_music_and_reading_series_curated_by_amanda_stern
---
Series’ Curator: <NAME>
with <NAME>, <NAME> and <NAME>
<file_sep>/content/news/2017-05-24-asia-society-interview.md
---
title: 'Asia Society: Interview'
date: 2017-05-24 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
- News
attribution: Asia Society
link_to_original: 'http://asiasociety.org/blog/asia/novelist-min-jin-lee-eternal-foreignness-being-asian-american'
description:
---
By <NAME>, Senior Media Officer of the Asia Society
Novelist <NAME> has made a career of telling the stories of people largely neglected by literature and popular culture. Her debut novel, Free Food for Millionaires, which follows the struggles of a young Korean-American woman striking out on her own in Manhattan, became a New York Times bestseller and was named a top 10 book of 2007 by NPR’s Fresh Air, USA Today, and The Times of London. Her sophomore effort Panchinko is a large, gorgeous book centered around a little-known group — the ethnically Korean population living in Japan. Lee traces the lives of four generations of a Korean-Japanese family, from absolute poverty to immense wealth in the era spanning Japan’s occupation of Korea to the late 1980s.
<br>Every May for Asian Pacific American Heritage Month, Asia Blog interviews noteworthy Asian Americans from a diverse set of backgrounds. View the complete Q&A archive
Asia Blog recently chatted with Lee about the “eternal foreignness” of being Asian American, the dangerous lure of external validation, and living as a foreigner in Japan.
Part of the research for Pachinko involved interviewing Korean-Japanese people when you lived in Japan from 2007 to 2011. Who were some of the most memorable people that you met?
I met an ethnically Korean gentleman who rescued bar hostesses and sex workers in [Tokyo’s red-light district], Kabukichō. His father was a pimp and his mother was a prostitute, and they were not married. He grew up to become an activist helping women who had fallen into sex work. In Japan, it's really difficult for sex workers to be protected and then to get out because of the organized crime aspect and because of alcoholism or bad family situations.
He was very matter-of-fact about his situation and what he wanted to do to create change in Japan. That was a really cool way to deal with the fact that he was part of an oppressed minority. He saw himself as somebody who was kind of heroic. He was actually trying to help Japan.
What drew you to this subject?
Pachinko is an essential metaphor. I'm trying to argue that in all gambling, the house always wins and it's rigged. What I really noticed about this community is that they were in a situation created by history that was almost unwinnable. They were treated badly by history as well as by the nation in which they were living.
That said, when I visited the ethnic Koreans in Japan and spent an enormous amount of time with them, I learned that their attitude is, "I'm just going to do what I need to do. I'm going to survive because I can't count on the people who are in charge." They felt betrayed not just by the Japanese government, but by both North Korea and South Korea and by their own leaders in Japan.
They saw me as what I am, which is a progressive, liberal bleeding heart person and they were like, “Min Jin, you're getting way too upset about this; you just have to keep doing what you're doing.” I had to throw away my initial manuscript and start again because they did not see themselves as victims, but as very hardy and very resilient. This novel became about resilience, not just about oppression.
How has Pachinko been received in Japan and Korea?
I've been told several times that the English edition of the book is sold out in bookstores in Japan and Korea. It's interesting to see the English edition take over Asia. I can't tell you how surprised I am by it. I didn't think that people would care. I just thought this was my bizarro passion project. I started this book well before Free Food for Millionaires. I spent most of my life working on this book.
Have you heard directly from any readers in Japan and Korea?
The most gratifying letters I get are from people who say that they felt very recognized. They’re usually very emotional letters. An ethnically Korean person in Japan will tell me, "I don't know how you got access to all these people, but this is just like what happened to me or to my uncle or to my cousin."
<br><NAME> (<NAME>)
It's so incredibly gratifying because I was very worried about getting all this stuff wrong. I did feel this real sense of historical responsibility because I knew that there wasn't a single novel written originally in English about this subject matter. I thought that this would be an academic press kind of book, that it would be recognized as something that we needed but wasn’t necessarily popular.
When you look at the U.S. book market, the percentage of translated literature is very small, but some Korean writers like Han Kang have recently found commercial success. How do you see this development?
I've been watching this issue for a long time because I read a lot of translated literature. Personally, I think it's really important to learn about other cultures besides those that have a dominant English-speaking body of media and literature. But in terms of its development, translated literature is still such a tiny percentage. The only way it's ever going to get better is if we have a critical mass of different books and not just one kind of book that gets translated.
Han Kang's book wasn't very well received in South Korea. The Vegetarian had almost no traction there when it was published. It's actually an old book; it didn't come out recently. Later on, it was translated by <NAME> from England and then it got the Man Booker International Prize. That is an interesting thing about Asia. When do we consider our own work important before we have a Western imprimatur and a kind of prestige associated with it? That's something we all have to really consider.
If something is really good we should talk about it and we should share it because it will only increase a greater understanding of the way we see ourselves and each other. That's the thing that I really recognize when I travel to universities — just how many kids of color are not recognized in media and literature. One of the primary things I work on is addressing the invisibility of Asians and the invisibility of Asian American art. Because art is our mirror.
You have stated that you wrote your first novel, Free Food for Millionaires, partly because of the dearth of complex Asian American characters. Has this situation improved since the book was published in 2007?
I want to say yes, but in so many ways, the invisibility of Asian Americans and also the eternal foreignness of it is perplexing. I am a parent of a college student and I am constantly addressing college kids. I'm so sad because they have the same issues that I had three decades ago. In some ways, Asian American kids get lumped in with the international students and it causes a weird separation.
The whole political angle of identity is something that people are made to feel ashamed of. They're made to feel we're post-racial, but we're quite there yet. A lot of kids that I talk to have never, ever known anything about Asian American literature or even Asian American history. And there is a rich American history in this country. The absence of history, the absence of a context, is making young Asian Americans really confused because there's a huge silence about this stuff. And parents often don't want to talk about it because it scares them. Or because they think it's distracting to their pragmatic goals.
One of the characters in Pachinko breaks up with his college girlfriend after he realizes she was only dating him because he was Korean-Japanese. Are you concerned that in the U.S. today Asian Americans are still being fetishized in that way?
Absolutely. Asians and Asian Americans and people of color are fetishized. There is also a very distinct experience for Asian American women as opposed to Asian American men. The way Asian American men are treated in this country by the media is simply appalling. If you are an oppressed, minority male there is a constant emasculation that's occurring. Every single male who is in that system has to ask himself, "How will I be a man?"
In Pachinko, Mozasu decides, “I'm going to become a man by making a lot of money because obviously I'm not very bright and I'm not good at school.” Noah decides, “I'm going to becoming a man by becoming such a respectable, exceptional Korean that they'll respect me.” And <NAME> decides, “I'm going to become in this world and in this time in history by becoming a patriot.”
Those experiences reflect the way gender and race intersect to create a sense of identity as how the majority culture sees you and how you see yourself as a person of color. You can’t control the majority culture, but it's very important that you have a sense of integrity about how the world treats you and how you want to be seen, not as a reaction but as an active participant in your own life.
Is that quest to become a respectable man by seeking external validation ultimately elusive?
External validation will always destroy you. It's never enough, there's always a need for more. If you're living in New York, you know there's always somebody more attractive, more wealthy, with a better pedigree, more whatever than you. You could do this forever. This treadmill is just ruthless. At some point, you have to make peace with how you see yourself. And then the external validation, if it comes, great. If it doesn't come, I'm sure it's heartbreaking, however, you still have to manage to live with yourself.
Another character in Pachinko notes in 1989 that “nothing would ever change” in Japan, pointing to that society’s unwillingness to assimilate the Koreans born there. Has Japanese society become more tolerant?
I think Japan's approach towards non-Japanese will never change. The Japanese are a terrific people. That said, there is something about Japanese culture that takes great ownership and pride in ethnic and blood heritage. You could become a Japanese citizen today after being there for four or five generations but no one will ever think of you as Japanese. In order to be considered Japanese, you have to be fully by blood Japanese. I've interviewed hundreds of people about this issue and every Japanese person has said that a biracial Japanese person is not Japanese. I think that's fine. I think that's just the way a culture is.
I don't think South Koreans are necessarily different. I don't think Koreans approach foreigners in a better way. I've been very critical in this book as well as in public about the way South Korea treats the Korean-Japanese people. If you look at the history of how the Korean-Japanese are treated in South Korea, it's appalling.
It's not like America is perfect, but America has a very long and rich history of having to integrate different kinds of people. I'm a naturalized American citizen and in certain parts of America, I'm seen clearly as an American and people wouldn't deny this. But that doesn't happen actually in many other parts of the world. They don't see other people as being of that nation because of their bloodline.
Throughout Pachinko, the Korean-Japanese are treated like second class citizens. Today, with the so-called Korean wave, or hallyu, Korean films, music, and television are widely consumed in Japan. Would you characterize this as something of a “revenge” for South Korea?
Selling soft culture is a very explicit intention of the South Korean government in the same way South Korea wanted to join the Organisation for Economic Co-operation and Development (OECD). Hallyu is a very cool phenomenon just as Japan soft culture is probably the most amazing thing about Japan right now. We really accept sushi or Pokémon or the manga culture, all those things from Japan. The fact that we have emojis — those are Japanese creations.
I do think it's problematic to think Korean soap operas or soap stars are acceptable, while one’s Korean-Japanese neighbor is still considered a criminal. That's not okay. What I noticed when living in Japan is that people who are obsessed with hallyu, who are obsessed with South Korean TV or food, still felt very comfortable thinking that all the crime in Japan came from the Koreans and the Chinese. It's quite possible to have this bizarre binary in your head. That may not be a Japanese problem. It may just be a human problem where we are always having to make these distinctions of what's good and what's bad.<file_sep>/content/news/guardian--best-summer-books-2018-as-picked-by-writers-and-cultural-figures.md
---
title: 'Guardian: Best Summer Books 2018 as picked by writers and cultural figures'
date: 2018-07-08 01:13:04 -0400
images: []
image_credit: ''
categories: []
where_published: 'The Guardian '
link_to_original: https://www.theguardian.com/books/2018/jul/08/best-summer-holiday-reads-2018-philip-pullman-maggie-ofarrell-nina-stibbe-part-two
description: "<NAME>: \n\n\"<NAME>’s The House of Broken Angels
(Little, Brown) is a great American novel, if we understand “America” to be all
of the Americas, including Mexico. It’s profane, funny and moving. Sayaka Murata’s
Convenience Store Woman (Portobello, translated by <NAME>) takes
a universal space, the convenience store, and turns it into the setting for a darkly
comic (and very short) novel about alienation and identity in an urban, capitalist
society. <NAME>’s How to Write an Autobiographical Novel (Mariner) is a
collection of essays about race, writing, politics, queerness and sexuality that
is urgent and insightful. I’ll be in Paris for much of the summer, and I’ll be takingÉdouard
Louis’ The End of Eddy (Vintage, translated by Michael Lucey), <NAME>’s Lullaby
(Faber), Han Kang’s The Vegetarian (Portobello), <NAME> Lee’s Pachinko (Head of
Zeus), Lisa Ko’s The Leavers (Dialogue) and <NAME>hang’s Sour Heart (Bloomsbury).\""
---
<file_sep>/content/event/sonoma-valley-authors-festival.md
---
show_time: false
title: Sonoma Valley Authors Festival
date: 2021-08-27T00:00:00-04:00
description: ''
venue:
address: 100 Boyes Blvd.
city: Sonoma
name: <NAME>
state: CA
zip: "95476"
link: https://svauthorsfest.org/sonoma-valley-authors-festival.html
images: []
---
<file_sep>/content/news/2016-11-01-parchment-girl-50-amazing-new-books-2017.md
---
title: 'Parchment Girl: 50 Amazing New Books 2017'
date: 2016-11-01 12:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original: 'http://parchmentgirl.com/50-amazing-new-books-to-get-excited-about-this-winter/'
description:
---
Pachinko follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them all. Deserted by her lover, Sunja is saved when a young tubercular minister offers to marry and bring her to Japan.
So begins a sweeping saga of an exceptional family in exile from its homeland and caught in the indifferent arc of history. Through desperate struggles and hard-won triumphs, its members are bound together by deep roots as they face enduring questions of faith, family, and identity.<file_sep>/content/review/library-journal.md
---
title: Library Journal on Pachkinko
attribution: _Library Journal_ (Starred Review)
date: 2017-03-11 17:46:58 +0000
book: book/pachinko.md
description: ''
featured: false
weight: ''
---
A beautifully crafted story of love, loss, determination, luck, and perseverance.<file_sep>/content/event/duttons_brentwood_bookstore_june_26.md
---
title: Dutton’s Brentwood Bookstore, June 26
date: 2007-06-26T20:00:00-05:00
venue:
name: Dutton's Brentwood Bookstore, Los Angeles
link: www.duttonsbrentwood.com
_slug: duttons_brentwood_bookstore_june_26
---
<file_sep>/content/review/lonestar-librarian.md
---
title: Lonestar Librarian on Free Food for Millionaires
attribution: Lonestarlibrarian
date: 2007-03-11 18:09:19 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
The life and times of a Korean American girl from Queens who goes to Princeton…<file_sep>/content/news/2016-12-06-stylist-uk-top-10-new-books-of-2017.md
---
title: 'Stylist UK: Top 10 New Books of 2017'
date: 2016-12-06 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Stylist UK
link_to_original: 'http://www.stylist.co.uk/books/10-exciting-new-books-to-look-forward-to-in-2017'
description:
---
Another book following generations of the same family through history. In 1911 Busan, Korea, we meet Hoonie, born with a club foot and a cleft lip, and married to a 15-year-old girl. When the couple's one daughter, Sunja, falls pregnant by a married yakuza, salvation comes to her and the family in the form of a young Christian minister, who offers to marry Sunja and take her to Japan.
This is a long novel, but it never feels it - <NAME>'s storytelling is effortless.<file_sep>/content/event/brazos-bookstore.md
---
title: Brazos Bookstore
date: 2018-02-01 19:00:00
show_time: true
venue:
name: Brazos Bookstore
address: 2421 Bissonnet Street
city: Houston
state: TX
zip: '77005'
link: 'http://www.brazosbookstore.com/event/min-jin-lee-pachinko'
---
<file_sep>/content/event/proskauer-rose.md
---
title: "Women of Letters: Joe's Pub of The Public Theater"
date: 2017-03-03 21:00:00
show_time: true
venue:
name: "Joe's Pub of The Public Theater"
address: 425 Lafayette Street
city: New York
state: NY
zip: '10003'
link: 'http://joespub.publictheater.org/en/Tickets/Calendar/PlayDetailsCollection/Joes-Pub/2017/W/WOL-Mar-17/?SiteTheme=JoesPub'
---
Women of Letters is everyone’s favorite literary salon!
Every month, New York’s best and brightest women come together on stage to celebrate the lost art of letter writing. Expect laughter, tears, and camaraderie as host <NAME> welcomes guests reading “A letter to my taboo”. Together on stage for the first time ever:
Bestselling writer and author of <NAME>
Acclaimed comic, writer, and host of NPR’s Ask Me Another OPHIRA EISENBERG
Cult-favorite comedian JO FIRESTONE
Critically-acclaimed author of The Last Illusion POROCHISTA KHAKPOUR
Legendary musician and member of The Juan MacLean and LCD Soundsystem NANCY WHANG
Criminal justice advocate and founder of Project Liberation IVY WOOLF-TURK
The show attracts guests of the highest caliber, from all disciplines. Women of Letters veterans include: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and many more.
Proceeds from Women of Letters shows are regularly donated to charity, with over $750,000 being raised globally to date. October 5th’s proceeds will be donated to Millay Colony, an organization that helps to promote the vitality of the arts and the development of writers, visual artists, and composers by providing a retreat for creative work.www.millaycolony.org
“In our world which is becoming increasingly more disconnected by dependency on social media and our tendencies to live online, I feel that projects like Women of Letters are the antidote. Bringing people together in one room to hear people tell their stories is a powerful reminder of our humanity” — <NAME>
“Women of Letters is the perfect alchemy of literary art-party and storytelling, with drinking and bonding for all genders of truth-seekers. Marieke and Michaela deserve a medal for creating this happening while we're on earth.”— <NAME>
“You'll bond with some crazy-talented women over diverse passions, intimate struggles, and of course, drinks.” — BUST Magazine
Hosted by acclaimed author and Moth storyteller <NAME> @sstefanovic
Produced by <NAME>’s BanterGirl @BanterGirlSTW
Founded by <NAME> and <NAME>
We are: @WoL_NYC<file_sep>/content/event/literary-death-match-boston-ma.md
---
title: Literary Death Match, Boston, MA
date: 2018-09-11 19:00:15 -0400
images: []
description: 'Doors open at 7pm and the LDM begins at 8pm. '
link: http://www.literarydeathmatch.com/upcoming-events/sept-11-at-the-comedy-studio.html
show_time: true
venue:
address: One Bow Market Way, Union Square
city: 'Somerville, Boston '
name: 'Comedy Studio (New Location) '
state: MA
zip: '02143'
---
<file_sep>/content/event/georgetown-university-law-center.md
---
title: Georgetown University Law Center
date: 2018-10-19 17:00:22 -0400
images: []
description: 'A Conversation with <NAME> '
link: "https://www.law.georgetown.edu/alumni/reunion/"
show_time: true
venue:
address: 550 1st Street, NW
city: 'Washington, D.C. '
name: Hotung 2nd Floor
state: ''
zip: 20001
---
<file_sep>/content/event/tattered_cover.md
---
title: TATTERED COVER
date: 2008-01-26T02:54:00-05:00
venue:
name: TATTERED COVER, Denver, COLORADO
link: www.tatteredcover.com
_slug: tattered_cover
---
WRITERS RESPOND TO READERS 2008
Tattered Cover Bookstore (Historic LoDo)
Saturday, 9AM-5PM
<NAME>, A GOLDEN AGE
<NAME>, THE INVENTION OF EVERYTHING ELSE
<NAME>, THE USES OF ENCHANTMENT
<NAME>, FREE FOOD FOR MILLIONAIRES
Tickets: $50.00 per person
Reservations accepted by phone only after January 7th: 303-322-1965, ext. 2739
(Please leave a name and telephone number. Space is limited and they cannot accept more than two reservations per call.)
<file_sep>/content/news/2011-06-20-free_food_for_millionaires_is_junot_diazs_summer_reading_pick_at_the_new_yo.md
---
title: "Free Food for Millionaires is Junot Diaz’s Summer Reading Pick at The New Yorker"
date: 2011-06-20T16:17:27-05:00
categories: ["News"]
tags:
- News
attribution: "The New Yorker"
link_to_original: "http://www.newyorker.com/online/blogs/books/2011/06/what-im-reading-this-summer-junot-daz.html"
description: ""
_slug: 2011-06-20-free_food_for_millionaires_is_junot_diazs_summer_reading_pick_at_the_new_yo
---
"Because I teach during the regular months, summer is where I can indulge in what I love most: a free-for-all reading spree. Already got my next four victims lined up. First, a novel I’ve read once before but I can’t resist a double serving of: <NAME>’s “Free Food for Millionaires.” One of the great first novels of the past decade and a book that is simultaneously profound and un-put-down-able. From the moment Casey, our yearning kickass protagonist, finds her white boyfriend in bed with two other gals, this book just grabs on, and it don’t matter whether you’re on a ferry to somewhere awesome or stuck in a lousy job you hate, this book will thrill you to the bone. Lee writes her (and your) ass off. This is one everybody should read."
Read the rest of Junot Diaz's recommendations at [The New Yorker](http://www.newyorker.com/online/blogs/books/2011/06/what-im-reading-this-summer-junot-daz.html).
<file_sep>/content/news/wsj-making-the-leap.md
---
title: 'Wall Street Journal: "Making the Leap" (Video)'
date: 2018-10-30 15:00:47 -0400
link_to_original: https://www.wsj.com/video/events/making-the-leap/1B74DF2B-3C32-434B-8383-2AA55FDEC2A5.html
images: []
tags: []
categories: []
description: WSJ Women In Work Conference, San Francisco
---
<file_sep>/content/event/2016-04-16-korean-community-center-gala.md
---
title: "Korean Community Center Gala"
date: 2016-04-16T12:00:00Z
show_time: false
venue:
name: "Teaneck Marriott at Glenpointe"
address:
city:
state:
zip:
link:
---
Keynote Address by <NAME>: “The Power of My Mother’s and Father’s Stories”
<file_sep>/content/event/mcnally-jackson.md
---
title: <NAME>
date: 2018-01-22 19:00:00
show_time: true
venue:
name: <NAME>
address: 52 Prince Street
city: New York
state: NY
zip: '10012'
link: 'http://www.mcnallyjackson.com/event/2018-01'
---
In conversation with <NAME> and <NAME> about PACHINKO.
<NAME> is an American writer who lives between Cranbury, New Jersey and Hawkes Bay, New Zealand. An award-winning essayist, fiction writer and reviewer, she has written about The Southernmost Jewish Community in the World for Random House NZ’s JEWISH LIVES IN NEW ZEALAND. Her first novel, THE RESCUE OF MEMORY, was published by Scribner in the US and she is currently revising her second, LOST CITIES. She was one of six interviewer/presenters on Television Hawkes Bay’s half-hour interview program, CHATROOM.
<file_sep>/content/event/lighthouse-writers-workshop.md
---
title: Lighthouse Writers Workshop
date: 2018-06-04 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
June 4th-8th<file_sep>/content/contact.md
---
title: Contact
images: []
description: ''
type: page
menu:
main:
weight: 9
---
#### To Contact <NAME>
<EMAIL>
***
#### To Contact Agent:
**<NAME>**
Aragi Inc
[<EMAIL>](mailto:<EMAIL>)
Tel: 212 675 8353
#### Publicity/Public Relations inquiries:
**<NAME>**
Associate Director of Publicity
Grand Central Publishing/Hachette
212-364-1496
<EMAIL>
***
#### Speaking engagements:
For Speaking Engagements
Please contact
**<NAME>**
[<EMAIL>](mailto:<EMAIL>)
\+1-707-773-0654<file_sep>/content/writing/2008-09-10-food_wine_magazine.md
---
title: "Food & Wine Magazine"
date: 2008-09-10T00:07:44-05:00
categories:
tags: ["Essays"]
where_published: "Food & WIne Magazine"
link_to_original: "http://www.foodandwine.com/articles/why-star-chefs-revere-seiji-yamamoto"
link_to_pdf:
description: "I was fortunate enough to eat at the sublime Ryugin restaurant in Tokyo, and my essay of the delicious experience appears in the September issue of FOOD & WINE."
_slug: 2008-09-10-food_wine_magazine
---
Six days a week, my parents sold Mexican silver earrings to street peddlers for $1.50 at their cramped wholesale jewelry store in Manhattan. Every night, my mother rushed home to Queens to fix delicious Korean suppers from the meat and produce on sale at the Elmhurst Key Food supermarket. Then, in 1981, about five years after we immigrated, my father decided that knowing how to butter bread properly should be as much a part of his children’s education as algebra and spelling. He allowed me, a precocious 12-year-old, to select one fancy restaurant to study each year. On the appointed day, the Lee family would waltz into the likes of Lutèce or Le Cirque.
<file_sep>/content/event/amherst-college-9.md
---
title: 'Portland Arts & Lectures: Min Jin Lee'
date: 2020-01-15T19:30:00-05:00
show_time: true
venue:
name: <NAME>
address: 1037 SW Broadway
city: Portland
state: OR
zip: "97205"
link: https://literary-arts.org/event/2019-2020-portland-arts-lectures-min-jin-lee/
description: ''
images:
- "/uploads/D_sSmRkWwAExckH.jpg"
---
<file_sep>/content/event/miami-fla.md
---
title: 'Miami: Brickell Avenue Literary Society'
date: 2019-01-18 12:00:00 -0500
images:
- "/uploads/Brickell Literary Logo.jpg"
description: Lunch with <NAME>
link: https://brickellavenueliterarysociety.wildapricot.org/event-3069454
show_time: true
venue:
address: Temple Israel
city: ''
name: ''
state: ''
zip: ''
---
<file_sep>/content/news/2017-08-05-irish-times-book-review-by-john-boyne.md
---
title: 'Irish Times: Book Review by <NAME>'
date: 2017-08-05 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Irish Times
link_to_original: >-
https://www.irishtimes.com/culture/books/pachinko-review-a-masterpiece-of-empathy-integrity-and-family-loyalty-1.3165406
description:
---
"A MASTERPIECE OF EMPATHY, INTEGRITY AND FAMILY LOYALTY" : <NAME> tells an endearing tale of hardship and inhumanity suffered by Koreans
<NAME>: a writer in complete control of her characters and her story and with an intense awareness of the importance of her heritage.
By <NAME>
Earlier this year, I wrote about Yaa Gyasi’s debut novel Homegoing in these pages and praised the author’s use of time and generational discord to tell a story that combined politics, history and gender with page-turning appeal. The same compliment could be offered to Min Jin Lee, whose novel Pachinko was one of the most popular choices among writers offering their summer reading selections to The Irish Times.
Pachinko tells the story of Korean immigrants living in Japan between 1910 and today, a family saga that explores the effects of poverty, abuse, war, suicide, and the accumulation of wealth on multiple generations. When the novel opens, we are introduced to Hoonie, “born with a cleft palate and a twisted foot”, who enters into an arranged marriage with Yangjin and despite their age difference – he is 28, she is 15 – a mutual respect and affection builds between them, not least because of their shared love for daughter Sunja.
It is Sunja who will prove the most important character in the novel. As a teenager, she is seduced by a yakuza, <NAME>, leaving her pregnant and unmarried, but when a sympathetic young missionary asks for her hand, it seems her disgrace will be avoided.
One of the most endearing elements of Pachinko is how honourable most of the characters are. Husbands love their wives, children respect their parents. Even <NAME>, who has played fast and loose with the affections of a young girl, spends decades trying to help Sunja, and although she is dismissive of him in later life, their relationship remains one of the most intriguing in the book.
Impoverished circumstances
But for all the love scattered across the pages, there is hatred too. The monstrous degrees of hardship, disrespect and inhumanity suffered by the Koreans makes for painful reading. They live in impoverished circumstances, are paid less than their Japanese counterparts, are spoken to as if they were dogs and, in one powerful scene, are forced to register time and again as strangers in a land in which many of them have in fact been born. Lee writes of this maltreatment with a stoicism that reflects the fortitude of her characters. Surviving is what matters to them, not human rights.
As the generations continue, we are introduced to Sunja’s sons, Noa, studious and intellectual, and Mozasu, passionate but disinterested in education. The choices both boys make in their lives stand in stark contrast to each other but they pursue their goals with equal conviction, albeit with markedly different results. No spoilers, but suffice to say that as the boys’ lives diverge they arrive at opposing fates. Ultimately, the importance of family honour proves so strong that revelations from the past lead to the most heart-breaking tragedy.
Pachinko itself is a Japanese version of pinball and while pachinko parlours become the family business later in the novel, it also stands as a metaphor for the lives they lead. In a game of pinball, the initial strike of the ball against the flipper determines how the game will play out. For Sunja and her descendants, it is what happens at birth that determines their fate. Over the years they may bounce off the sides of the machine, ricocheting against the bumpers, kickers and slingshots, but there is a sense that fate has decided how their lives will develop from the moment the plunger hits the ball.
Generational sweep
While Pachinko is only <NAME>’s second novel – her first, Free Food for Millionaires, will be reissued later this summer – it is the work of a writer in complete control of her characters and her story and with an intense awareness of the importance of her heritage. In its generational sweep, it recalls John Galsworthy’s The Forsyth Saga, replicating some of that classic novel’s focus on status, money, infidelity and cruelty as it explores the effect of parental decisions on children, and the children of children. As Faulkner put it, “the past isn’t dead. It isn’t even past.”
This is a long book but is told with such flair and linguistic dexterity that I found myself unable to put it down. Every year, there are a few standout novels that survive long past the hype has died down and the hyperbolic compliments from friends scattered across the dust jacket have been forgotten. Pachinko, a masterpiece of empathy, integrity and familial loyalty, will be one of those novels.
<NAME>’s latest novel is The Heart’s Invisible Furies (Doubleday)<file_sep>/content/event/sydney-writers--festival-2018--going-rogue--north-korea.md
---
title: 'Sydney Writers'' Festival 2018: Going Rogue: North Korea'
date: 2018-05-04 13:30:36 -0400
images: []
description: <NAME>, <NAME>, <NAME>, <NAME>, and
<NAME>
link: https://www.swf.org.au/writers/min-jin-lee/
show_time: true
venue:
address: 245 Wilson Street
city: ''
name: Carriageworks, Bay 17
state: ''
zip: ''
---
<file_sep>/content/news/2017-10-24-marthas-vineyard-book-festival-2017-video-introduction-by-ambassador-caroline-kennedy.md
---
title: >-
Martha's Vineyard Book Festival 2017: Video (Introduction by Ambassador
<NAME>)
date: 2017-10-24 12:00:00
categories: ["Media"]
tags:
- Reviews
- Video
- News
attribution: Martha's Vineyard Book Festival & Martha's Vineyard Productions
link_to_original: 'https://www.youtube.com/watch?v=kscMU-W7tKU'
description:
---
This past summer, I had the great honor of being introduced by Ambassador <NAME>, who is so very cool and fun, at the MV Book Festival. Thanks to Amb. <NAME>, the Martha's Vineyard Book Festival, its valiant founder Sullen Lazarus, the great volunteers of the festival, and of course, Bunch of Grapes, independent bookstore extraordinaire.
P.S. in the Question & Answer portion (around the 26th minute?), I meant to say "Womenomics," a super idea created by <NAME>, rather than "Abenomics." Apologies.
To see the video, please click the link.<file_sep>/content/news/2017-03-21-smithsonian-asian-pacific-american-center--bloom-magazine.md
---
title: 'Smithsonian Asian Pacific American Center & Bloom Magazine'
date: 2017-03-21 12:00:00
categories: ["News"]
tags:
- Reviews
- Interviews
attribution: 'Smithsonian Asian Pacific American Center & Bloom Magazine'
link_to_original: 'http://smithsonianapa.org/bookdragon/author-interview-min-jin-lee-bloom/'
description:
---
On History, Survival & Intimacy
by <NAME>
Becoming a bestselling author took <NAME> 11 years – and so much more of her life.
She quit lawyering, but without that income, tuition for an MFA proved impossible. So she found every bargain opportunity in New York City to learn her craft, including readings, workshops, and $200 classes at the 92nd Street Y. Then money became even more scarce when she became responsible for family members facing financial ruin. At home, she had to figure out how to balance new motherhood after a difficult pregnancy; she couldn’t fund childcare to write, but she would weep over missing her young son on the rare occasion she was alone to write. Most importantly, she had to reclaim her health, fighting a serious liver condition she’d had since her teens; her “one in a million” full recovery took decades, but she was finally disease-free by the time she signed her debut contract.
Her tenacity and savvy got Lee to her third novel – rejected her first, she herself rejected her second – which hit shelves in 2007, when Lee was 39. As a lauded international bestseller, Free Food for Millionaires – about the daughter of struggling Korean immigrants who invents herself anew but struggles to make genuine connections – would make Lee a (not-quite) overnight sensation.
A decade later, Lee’s follow-up, Pachinko, published in February, gives us an exquisite, haunting epic that crosses almost a century, three countries, and four generations of an ethnic Korean family that cannot even claim a single shared name because, as the opening line declares: “History has failed us.”
In 1910, Japan annexes Korea, usurping the country with intentions to erase the Korean identity. Amid the tragedies that follow, a fisherman and his wife survive amidst near-impossible circumstances on the southern coast of the Korean peninsula. Their beloved daughter, who eventually marries a gentle minister while pregnant with another man’s child, initiates the migration to Japan to join her husband’s older brother and wife. Their extended family will always live as second-class immigrants; no level of achievement, integrity, or grit changes their status as reviled foreigners. Two Japanese-born sons choose diverging paths; one grandson hazards a second immigration to the other side of the world.
Although characters are oppressed by the traditional Japanese belief sho ga nai (it can’t be helped), “moments of shimmering beauty and some glory, too,” illuminate the narrative, Lee writes. Her profound second novel of losses and gains explored through the social and cultural milieu of pachinko parlors is shaped by impeccable research, meticulous plotting, and empathic perception.
Like so many lauded authors, you lawyered first. <NAME>, <NAME>, <NAME>, and of course <NAME>, to name a few. What are the roots of your own law-to-letter transition?
I quit being a lawyer in 1995 only after practicing for two years. I had a very serious liver disease, diagnosed when I was in high school, which made me vulnerable to fatigue and greater possibility for a fatal illness. I think illness has always clarified for me how to spend my time. I preferred writing, and, insanely, I thought that writing a novel would not be so difficult. Ahem.
That ‘ahem’ certainly leads right into what you call your 11-year apprenticeship, which produced your bestselling debut, Free Food for Millionaires. In what specific ways did illness and recovery affect your writing process?
<br>I am pretty sure that if I hadn’t been a very ill person, I wouldn’t have had the courage, especially with my very modest immigrant background, to choose writing as a profession. Also, if someone had told me that it would take 11 years to publish a novel, I would have done something more pragmatic, requiring less exertion. Isn’t that lame? But true.
You’ve written about all the learning-to-write-well opportunities during your ‘apprenticeship’ that were available to you as a New Yorker. If your address during those years had been on the other coast – say LA – do you think you would have been a different writer?
<br>Well, yes, I think it helped enormously that I was able to study with such great, great writers for very little money [in NYC]. However, I did also read a lot of writing books, too. I could probably recommend about 15 writing books I adore: <NAME>, <NAME>, and <NAME> [for example], write beautifully about craft and perseverance. As for classes, I have noticed that a lot of my gorgeous friends in LA will break for distant yoga, pilates, boxing, etc., which might require more money and time than a writing class. Also, it is possible to meet great writers (not necessarily established) and form writing communities, and I did that for many years.
Have you kept those writing communities going since becoming a two-for-two bestselling author?
<br>I am still very close friends with my writer friends, but I don’t have that many. Also, my friends and classmates with whom I started over 20 years ago ended up doing really well: <NAME> wrote <NAME>, which won the National Jewish Book Award; Rebecca Stead won the Newbery Medal; and my dear friend <NAME> has her own imprint at Random House for YA books. These are women I met in a 92nd Street Y class, which I think we paid $200 for a semester, and none of us were “established” then. However, every one of these women were heart-attack serious about books and craft.
I’ve read about how you kept those “marble” notebooks in which you recorded memorable passages. Do you still have them? Add to them?
<br>I do have marble notebooks, and I continually write down passages I admire. There are so many great writers to read and admire. I have this benefit of not knowing that many writers personally, so I feel free from any bias. I go out of my way not to listen to weird stories about writers, because I want the purity of their work.
Given your self-described “shyness,” how are you planning for your peripatetic adventures ahead? Your book tour is crazy extensive!
<br>I’m scared out of my head. I have no idea what’s going to happen. I can’t believe that this tour is the way it is. However, I know I am very very very fortunate to get a tour, so I will go and I will do what all good girls do. I will show up, and I will try not to embarrass my publisher, my agent, my family, my ancestors, my race … etc. You might think I am kidding, but the truth is that I really worry about how we are perceived, and by we, I mean, women over a certain age (I’m 48), Asian American women writers, Asian American writers of both sexes, progressives, Presbyterians, Koreans, immigrants, Korean Americans, Korean Japanese, etc. I worry and I shouldn’t worry but because there are so few who are getting good chances, I want to do well, and it sounds horribly grandiose, but I fear that if my book does not do well, somehow, I have let all these really kind people down. I would hate that. But, now you know so much of my neuroses.
Holy moly, that’s a lot of baggage to be carrying around! I predict you’re gonna be a nasty woman in a pantsuit and slay them all!
<br>You are a very kind soul. Thank you. Baggage is my middle name.
Having left Korea at such a young age – your family immigrated when you were 7, yes?—in your daily life, how connected do you feel to Korea? Do you use your writing to ‘go back’?
<br>I feel profoundly connected to Korea. My father was born in Wonsan, now in North Korea, and my mother was born in Busan, now in South Korea, and I add the word “now” because when they were young, there was only one Korea. I was born in Seoul, and I recall it very vividly. I admire Koreans and what Koreans have withstood as a people, and it is a culture of 5,000 years plus. I studied American history in college, and I love being an American, and I am proud to be an American, especially now, because I see the resistance in this country and the ability for dialogue, and it strengthens me. I think my connectedness to Korea is not just historical … it is necessary to feel a greater sense of strength when I feel lost in this country.
Beyond the Korean/Japanese history, you also have multiple levels of immigration woven into Pachinko—from north to south, Korea to Japan, Japan to the US. Given the alarming changes happening since the presidential transition, your book is even more timely. What do you hope will linger with your readers once they finish?
<br>I want my readers to see people like the people in my book as fully human, connected with history, persecution, and culture. I also want my readers to see that we were always here. What I found so moving was to know that it didn’t matter what the record said, because the record we have of history is incomplete. I think the record has to grow, and more voices have to witness. I do this in fiction, and it is a weird and odd thing, but I want the stories of very ordinary, unimportant people to reflect the beauty and courage of a larger community.
Speaking of history—somehow, miraculously, gorgeously, you succeeded in weaving the contentious 20th-century history between Korea and Japan into Pachinko. I assume living in Japan (from 2007 to 2011) provided both inspiration and information. What took you to Japan? Did you have Pachinko’s narrative already in mind before the move? How did you do the research?
<br>First, thank you for your kind remarks about the book. I say this, because the hardest part for me was to get the history right without hurting the narrative. Second, I got the idea for the book in 1989. I started writing it before I wrote Free Food for Millionaires. I had a complete draft of it before I moved to Japan in 2007 (five months after Free Food came out) because my husband got a better job in Tokyo. I had written that prior manuscript based on written research. I read perhaps three to four dozen academic texts on the Korean Japanese (also referred to as zainichi); however, the manuscript then was really not great.
After I moved to Japan, I interviewed dozens upon dozens of Korean Japanese. I was interested in what ordinary people do when those who are in charge are out to lunch. And when [those] leaders and elites are out to lunch and they make shit decisions, what do ordinary people do? They look for water, shelter, food, and they watch out for their families. People do everything possible to fight unfairness. Then I realized that the history didn’t show that, and I wanted very much to fix this. So I wrote a whole new manuscript and it became eight decades, rather than my initial three.
Given that contentious century since the annexation of Korea by Japan, how was living in Japan as a Korean American?
<br>I was very privileged because my husband’s company gave us expatriate housing and schooling for our son. Living in Tokyo was not difficult in a material way whatsoever. However, there were so many instances where I was forcefully reminded that Koreans were like this or like that, and the ones who were saying this were not just the native Japanese. I heard this insane bullshit from lots of people from all walks of life who had been around the study of Japan for many decades. It was as if the Japan experts had learned stereotypes and felt it was okay to repeat them. I cannot imagine making such generalizations about the Japanese or Koreans or Martians, but hearing people I like say really horrid things about Koreans was hard to take.
Our parents are of the generation that lived through the Japanese occupation, and I know some families still have lingering distrust and fear. Your husband is half Japanese … did that ever cause friction in your family?
<br>My mother-in-law who is deceased now came from a very prominent family in Japan. Her father was a count before the peerage was abolished after the war. Needless to say, I think everyone was surprised when I showed up to dinner. That said, my husband is an American who grew up everywhere. Our son is one-quarter Japanese and half Korean. I would never make stereotypes of the Japanese, not just because it is wrong, but because I know a more accurate history as well as the people. I find that most racism, xenophobia, and irrational hatred disappear with greater intimacy.
Have members of your family read Pachinko? I’m sure painful memories must loom in there for the oldsters?
<br>Yes. Everyone in my family has read it. They were really surprised by the history in the fiction. My mother kept asking how did I know certain stuff? And my father, who lived through the colonial era and speaks fluent Japanese as a consequence, was astonished by the details, which I have to say here, were very hard-won. Normally, I don’t pat myself on the back too much, but figuring stuff out like the price of a boardinghouse or the lack of shoe polish during the war took more time than reading a whole history book.
Might the book have Korean and Japanese translations in the near future? Would be a fabulous tool for diplomacy!
<br>[It has] sold to countries like Poland and Turkey. But Japan has yet to make an offer. I received one offer from Korea, but I don’t know what I will do yet.
Speaking of foreign … one of your Pachinko characters makes the journey from East to West. Might that be roots for a sequel?
<br>Not sure. Right now, I am sketching out the third book on Korea, which will complete my trilogy of sorts, and it is called American Hagwon. Free Food for Millionaires is about Koreans in America, Pachinko is about Koreans in Japan, and in American Hagwon, I will focus on the centrality and the idolatry of education for Koreans around the world. The book will be about a Korean American woman who owns a hagwon (cram school) in Manhattan for the very rich and powerful. I hope it doesn’t take 11 years (Free Food) or 28 years (Pachinko). That said, I have fewer censors than I used to have, which is helpful. I’m not a blocked writer, I am a bashful writer.
And short stories – that’s what you published before your novels. Will we see a collection someday?
<br>I have a full collection of stories and a personal collection of essays (about feminism, literature, art, etc.), but the powers-that-be have asked me to hold off [until after] Pachinko. I really love my stories and essays, because I feel like I earned them, but the marketplace is different for such things. For now, I do not know of a Korean American woman who has written a collection of essays, and I think that’s too bad, because even if it is not me, I think we need more Asian American perspectives in a non-fiction format.
Your publishers are very smart – I bet they’re expecting you’ll repeat Viet Thanh Nguyen’s phenomenon: Pulitzer first with a novel, and then bring out essays and short stories and make them bestsellers, too!
<br>Well, from your mouth to God’s ears. I do feel pressure to sell well, and that’s a different pressure than to write well. As I get rid of neuroses like censors or (some) perfectionism, I get new ones like ‘will I sell enough copies to warrant the next book?’ We live in big-data/meta-data world now, and everyone knows ‘how we’re doing’ in a way. Scary.
Author interview: “Q&A with <NAME>: On History, Survival & Intimacy,” Bloom, March 21, 2017<file_sep>/content/event/kgb_bar_april_13th.md
---
title: KGB Bar, april 13th
date: 2007-04-13T21:00:00-05:00
venue:
name: KGB Bar, New York, NY
link: www.kgbbar.com/bar
_slug: kgb_bar_april_13th
---
With <NAME>, <NAME> and <NAME>
<file_sep>/content/event/2016-09-16-southern-independent-booksellers-alliance-discovery-show.md
---
title: Southern Independent Booksellers Alliance (SIBA) Discovery Show
date: 2016-09-16T12:00:00Z
venue:
name: "<NAME>"
address:
city: Savannah
state: GA
zip:
link: http://www.sibaweb.com
---
SIBA Kick-off Lunch
<file_sep>/content/news/2017-11-06-new-york-times-profile.md
---
title: 'New York Times: "A Novelist Confronts the Complex Relationship Between Japan
and Korea"'
date: 2017-11-06 12:00:00 +0000
categories:
- News
tags:
- Interviews
- News
attribution: The New York Times
link_to_original: https://www.nytimes.com/2017/11/06/books/book-pachinko-min-jin-lee-japan-korea.html
description: ''
images: []
---
A Novelist Confronts the Complex Relationship Between Japan and Korea
By <NAME>
NOV. 6, 2017
TOKYO — By Japanese standards, the Tokyo neighborhood of Shin-Okubo is a messy, polyglot place. A Korean enclave that has attracted newcomers from around the world in recent years, its profusion of barbecue joints, pan-Asian street markets and halal butcher shops distinguish it in a country with a reputation for cultural homogeneity.
It is a fitting place to meet <NAME>, a chronicler of the Korean diaspora whose sweeping yet intimate historical novel “Pachinko” is a finalist for this year’s National Book Award.
In two books published a decade apart, <NAME>, a 48-year-old American, has depicted the strivings and disappointments of Korean immigrants. The first, “Free Food for Millionaires,” from 2007, was set in her hometown New York City. For “Pachinko,” she spun the globe around, taking readers to the Korean Peninsula and its onetime colonial master, Japan.
“I have romantic ideas about home and what it should mean,” said <NAME>, who was born in South Korea and moved to New York — Elmhurst, Queens, to be exact — with her family at the age of 7.
<NAME> was speaking over spicy beef and kimchi at a restaurant in Shin-Okubo staffed by “zainichi” — descendants of the hundreds of thousands of Koreans who migrated to the Japanese islands during the first half of the 20th century, after Japan’s empire swallowed up the Korean Peninsula in 1910.
The migrants, whose story Ms. Lee tells in “Pachinko,” congregated in slums and performed mostly low-paid labor. Discrimination was rampant. The eventual liberation of their homeland at the end of World War II was a mixed blessing: No longer subjects of the Japanese emperor, Koreans lost the right to reside in Japan. Many had no homes or jobs to return to, so they stayed on anyway, prompting decades of wrangling over their legal status.
At the restaurant, a television showing K-pop videos hung next to a wall covered in white cardboard squares displaying autographs from celebrity customers — Korean food is popular in Japan, a paradoxical exemption from wider social prejudices. The waiter was a young man in his 20s. Ms. Lee cycled through English (her primary language) and Japanese (his) before settling on an imperfect middle ground of Korean.
The fictional family at the center of “Pachinko,” the Baeks, grapples with problems common to transplanted people: material hardship, unwelcoming locals, the possibilities and limits of assimilation. For them, as for real-life zainichi, ethnic biases are compounded by colonial-era abuses and resentments. The physical similarities between Koreans and Japanese make “passing” as a member of the majority a tempting possibility, but a socially and psychologically risky one.
“Koreans have suffered from the discrimination that all immigrants face, plus an added dimension that comes from their having been colonial subjects,” said <NAME>, a professor of cultural anthropology at Nagoya University who has studied the zainichi population.
“Many of today’s zainichi are fourth-generation, so they’re hardly immigrants anymore. They are essentially Japanese,” Professor Ukiba added. Outright discrimination has faded, he said, since the period depicted in “Pachinko” — the 1910s through the 1980s — but has not disappeared. Some bigotry has moved online, where trolls depict zainichi as “cockroaches” or fifth-columnists for nuclear-armed North Korea.
<NAME> spent nearly two decades conceiving, writing and rewriting “Pachinko.” The seed was planted in 1989, when, as a student at Yale, she attended a talk by a Protestant missionary who had spent time among the zainichi. Until then, she said, she had never heard of this branch of the Korean diaspora. Growing up in the United States, she was used to Koreans being viewed as hardworking and upwardly mobile, a model American minority. But many zainichi, she was surprised to discover, languished at the bottom rungs of Japan’s socioeconomic ladder.
“My level of research became a little neurotic,” she said. Although she was a Korean immigrant herself, she was entering a completely new world.
For ethnic Koreans in Japan, one route to economic improvement has been pachinko, a pastime derived from pinball. Played by millions of Japanese at noisy, smoke-filled halls, many of which are operated by zainichi, pachinko occupies a legal and social gray zone. The game itself is legal, but the gambling that inevitably accompanies it is not.
“Instead of banning it, Japan tolerates it but disparages the people who run it,” said Ms. Lee. She sees a parallel with Koreans’ place in Japanese society: deeply established, yet not fully accepted as legitimate members.
Ms. Lee’s family embodied the rosier American version of the Korean immigrant story.
In South Korea, her father had worked in marketing at a cosmetics company, but fears that the Korean Peninsula could erupt into another devastating war convinced him to leave. After arriving in New York in the mid-1970s, her parents operated a news kiosk in Manhattan, at Broadway and 31st Street. They soon upgraded to a wholesale costume-jewelry business, working and saving their way into the middle class and sending their three daughters to college.
“Pachinko” is a product of persistence. Ms. Lee discarded an earlier, more narrowly focused version of the novel, which she wrote in the late 1990s and early 2000s. Its original main character was <NAME>, an aspiring ethnic Korean investment banker who is subjected to bigotry and betrayal at a financial firm in Tokyo.
“It was boring,” she said — big on social themes but short on fully realized human characters and relationships. “I didn’t talk to enough people.”
While living in Tokyo, <NAME> interviewed Koreans — business people, pachinko parlor owners, bar hostesses — as part of the research for her novel. Credit<NAME>
The chance for a fresh start came in 2007, when her husband, a banker of Japanese descent, took a job in Tokyo. While there, she started looking for zainichi to interview — business people, pachinko parlor owners, bar hostesses.
“The first few were hard to get because I didn’t have introductions,” she said. “But then it was like the floodgates opened.”
Many of her subjects told love stories. Almost every Korean she spoke to, she said, had been rejected at some point because of their ethnicity. It was startling for an American: Even considering the United States’ unbridged racial divides, the zainichi seemed inescapably stamped by difference.
As she collected more stories, the novel grew in scope. It also became more feminine, she said. Ms. Lee expanded the role of Sunja, Solomon’s quietly tenacious grandmother, who leaves her Korean fishing village for Osaka as a young bride in the 1930s.
As an American, <NAME> was partly insulated from lingering bias in Japan against zainichi. But she still encountered casual ethnic stereotyping that surprised her. When she pointed out shoddy repair work at the apartment her family rented, an employee at the management company told her, “You Koreans are always complaining.” At the church she attended, when she argued in favor of paying the homeless volunteers who cooked curry at the church soup kitchen, a Japanese fellow congregant said it was her “Korean blood” that caused her to make a fuss
“Pachinko” has been picked up by publishers in more than a dozen countries, but it has not yet found one in Japan.
Ms. Lee finished her novel after returning to the United States. During her recent visit to Japan, she noted that while “Pachinko” has been picked up by publishers in more than a dozen countries, including Turkey and Poland, it has not yet found one in Japan.
Japan’s own literature contains prominent works by and about zainichi, many exploring similar themes of identity and history. Yang Sok-il’s semiautobiographical “Blood and Bones,” one of a number of popular books by Korean-Japanese authors, was turned into a movie starring the actor and director <NAME> in 2004.
Ms. Lee said she hoped that publishers would not be put off by an unsparing look at Japan’s still only partly resolved history by an American outsider.
“I do have love for Japan. At the same time, I have a complex relationship with Japan because I’m Korean,” she said. “But I think it shows the strength of a country when you can talk about the past transparently.”
Follow <NAME> on Twitter @jonathan_soble.<file_sep>/content/event/amherst-college-5.md
---
title: 'Amherst College: 2019 DeMott Lecture'
date: 2019-09-01T16:00:00-04:00
show_time: true
venue:
name: <NAME>
address: ''
city: Amherst
state: ''
zip: ''
link: https://www.amherst.edu/news/calendar/node/747553
description: The annual DeMott lecture, a welcome address for incoming students, will
be held on Sunday, September 1, at 4 p.m. in Johnson Chapel, and will be given by
<NAME>. The DeMott lecture is open to first year students.
images: []
---
<file_sep>/content/news/2017-12-19-bookpage-readers-choice-best-books-of-2017.md
---
title: 'BookPage: Readers'' Choice Best Books of 2017'
date: 2017-12-19 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: BookPage
link_to_original: >-
https://bookpage.com/the-book-case/22152-readers-choice-best-books-2017#.WjsiJs5OjE4
description:
---
Posted by Stephanie, Editor
Little Fires Everywhere is your favorite book of 2017!
and
Who else do you love? Here are your 10 other reader favorites:
Eleanor Oliphant Is Completely Fine by <NAME>
Endurance by <NAME>
Glass Houses by <NAME>
Grant by <NAME>
The Hate U Give by <NAME>
Manhattan Beach by <NAME>
Pachinko by <NAME>
Sing, Unburied, Sing by <NAME>
Sleeping Beauties by <NAME> and <NAME>
You Don’t Have to Say You Love Me by <NAME>
For the complete article, please click the link. Thank you.<file_sep>/content/event/festival-neue-literatur.md
---
title: 'Festival Neue Literatur: "Another Country: Distant Lands Up Close and Personal"'
date: 2019-03-30 14:00:00 -0400
show_time: true
venue:
name: POWERHOUSE Arena
address: 28 Adams Street
city: Brooklyn
state: NY
zip: 11201
link: https://festivalneueliteratur.org/festival/events/the-lives-of-others/
---
Moderated by <NAME>
<file_sep>/content/event/the-white-hart-inn.md
---
title: The White Hart Inn
date: 2017-03-16 18:00:00
show_time: true
venue:
name: <NAME>
address: 15 Under Mountain Road
city: Salisbury
state: CT
zip: 06068
link: 'https://www.whitehartinn.com'
---
In conversation with <NAME> of NPR/WAMC. Sponsored by Oblong Books & Music in Rhinebeck, New York, and the Scoville Library<file_sep>/content/review/junot-diaz-on-pachinko.md
---
title: <NAME> on Pachinko
attribution: <NAME>, Pulitzer Prize-Winning author of *The Brief Wondrous Life
of Oscar Wao* and *This is How You Lose Her*
date: 2000-01-01T00:00:00-05:00
book: book/pachinko.md
featured: false
description: ''
weight:
---
Luminous…a powerful meditation on what immigrants sacrifice to achieve a home
in the world. This story confirms Lee’s place among our finest novelists.<file_sep>/content/news/2017-10-27-publishers-weekly-best-books-of-2017-top-25-fiction.md
---
title: 'Publishers Weekly: Best Books of 2017, Top 25 Fiction'
date: 2017-10-27 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: Publishers Weekly Book Books 2017
link_to_original: >-
https://best-books.publishersweekly.com/pw/best-books/2017/fiction#book/book-16
description:
---
Pachinko is a Top 25 Fiction selection for PUBLISHERS WEEKLY's BEST BOOKS OF 2017. Thank you.<file_sep>/content/news/2008-04-27-virginian_pilot.md
---
title: "Virginian Pilot"
date: 2008-04-27T22:53:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Virginian Pilot"
link_to_original: ""
description: ""
_slug: 2008-04-27-virginian_pilot
---
In ‘Free Food,’ Lee takes an exquisite…
<file_sep>/content/news/2017-12-20-lowy-institute-the-interpreterfavorites-of-2017.md
---
title: 'Lowy Institute: The Interpreter—Favorites of 2017'
date: 2017-12-20 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Lowy Institute
link_to_original: 'https://www.lowyinstitute.org/the-interpreter/favorites-2017-pachinko'
description:
---
By <NAME>
When I lived in Japan I was fascinated by the way internet tycoon Masayoshi Son broke through the bamboo ceiling that limits the citizenship rights of ethnic Koreans despite their residence in Japan for generations. And I always took visitors to a pachinko (gambling) parlour if for nothing else than the amazing aural experience. But I still didn’t understand this nether world.
It has taken Korean-American writer <NAME> since 1989 to produce her epic novel, Pachinko (published by Apollo), following a Korean family’s journey from Japanese colonisation in 1911 to life in Son’s time via the pachinko parlours that have traditionally sustained the resident Koreans. But it has certainly been worth the wait and these themes are now even relevant to managing the North Korean nuclear threat. As her unlikely survivor laments:
This country isn’t going to change. Koreans like me can’t leave. Where we gonna go? But the Koreans back home aren’t changing, either. In Seoul people like me get called Japanese bastards, and in Japan, I’m just another dirty Korean no matter how much money I make or how nice I am. So what the f—. All those people who went back to the North are starving to death.
Even if you are not intrigued by the inner life of these notionally mono-cultural but remarkably economically successful north Asian societies, don’t be put off this intimate but expansive story. As Lee begins: ‘History has failed us, but no matter.’<file_sep>/content/news/2008-05-06-upstairs_at_the_square.md
---
title: Upstairs at the Square
date: 2008-05-07 02:17:00 +0000
categories:
- Media
tags:
- Video
attribution:
link_to_original:
description: At Barnes & Noble
images: []
---
At [Barnes & Noble](http://media.barnesandnoble.com/index.jsp?fr_chl=a9b62737be3f75af1944506bf34ebd08ce5c4103)
{% comment %}<!-- <iframe src="https://media.barnesandnoble.com/linking/index.jsp?skin=oneclip&fr_story=fa4b15f436d378dd05f70bea4a2821c47f5249d6&rf=ev&hl=true" width="413" height="355" scrolling="no" frameborder="0" marginwidth="0" marginheight="0"></p><p></iframe>
-->{% endcomment %}<file_sep>/content/event/dedee-shattuck-gallery.md
---
title: 'Westport, MA: Partners Village Store at Dedee Shattuck Gallery'
date: 2018-05-24 18:00:13 -0400
images: []
description: In conversation with <NAME> and <NAME> about PACHINKO
link: ''
show_time: true
venue:
address: 1 Partners' Lane
city: Westport
name: Partners Village Storee at Dedee Shattuck Gallery
state: MA
zip: 02790
---
<file_sep>/content/event/poly-prep-high-school.md
---
title: 'Context: Conversations at Poly Prep'
date: 2019-01-14 17:00:41 -0500
images: []
description: ''
link: https://www.polyprep.org/page/event-detail?pk=8673087
show_time: true
venue:
address: 9216 Seventh Avenue (enter at 92nd Street and Parrott Place)
city: Brooklyn
name: Poly Prep Country Day School
state: New York
zip: 11228
---
<file_sep>/content/event/gold-house-book-club.md
---
show_time: true
title: 'Gold House Book Club: '
date: 2021-02-10T18:00:00-05:00
description: Join the Gold House Book Club for an intimate discussion about identity,
belonging, and generational legacy featuring February’s featured author <NAME> and her book Pachinko, moderated by <NAME> of NBC Asian America.
venue:
address: ''
city: ''
name: ''
state: ''
zip: ''
link: https://www.facebook.com/GoldHouseCo/events/
images: []
---
<file_sep>/content/event/crowell--moring-llp.md
---
title: 'Crowell & Moring LLP'
date: 2017-05-11 12:00:00
show_time: true
venue:
name:
address:
city:
state:
zip:
link:
---
Private Event
In Conversation with <NAME>, Senior Director of Diversity & Professional Development<file_sep>/content/event/ala-midwinter.md
---
title: 'American Library Association Midwinter Conference: Author Book Talk Luncheon'
date: 2017-01-21 13:00:00
show_time: true
venue:
name: Atlanta Convention Center
address:
city: Atlanta
state: GA
zip:
link:
---
Featuring authors <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
Sponsored by United for Libraries<file_sep>/content/event/sydney-writers--festival-2018.md
---
title: 'Sydney Writers'' Festival 2018: Opening Address'
date: 2018-05-01 18:30:07 -0400
images: []
description: 'Opening Address: <NAME>, <NAME> and <NAME>'
link: https://www.swf.org.au/writers/min-jin-lee/
show_time: true
venue:
address: ''
city: ''
name: Carriageworks, Bay 17, Eveleigh
state: ''
zip: ''
---
<file_sep>/content/event/book_club_princeton.md
---
title: Book Club, Princeton
date: 2008-02-25T05:42:00-05:00
venue:
name: Book Club, Princeton, New Jersey
link:
_slug: book_club_princeton
---
Book Club: FREE FOOD FOR MILLIONAIRES
Host: <NAME>, Author of THE WHITE ROSE, A JURY OF HER PEERS, and SABBATHDAY RIVER
8PM
Private Event
<file_sep>/content/event/hamilton_college.md
---
title: Hamilton College
date: 2008-02-27T23:07:00-05:00
venue:
name: Hamilton College, Clinton, New York
link:
_slug: hamilton_college
---
Fillius Events Barn
Reading and Q&A
8PM
Professor <NAME>, Department of Creative Writing
<NAME>, Author of Free Food for Millionaires
<file_sep>/content/news/2017-02-09-nyt-editors-choice-pachinko.md
---
title: "NYT Editor's Choice: PACHINKO"
date: 2017-02-09 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: New York Times Book Review
link_to_original: 'https://www.nytimes.com/2017/02/09/books/review/10-new-books-we-recommend-this-week.html?_r=0'
description:
---
10 New Books We Recommend This Week:
This week brings some serious-minded nonfiction (Wall Street wrongdoing, covert wars, depression) and meaty fiction (an epic bildungsroman, border wars, a multigenerational immigrant saga) with a glamorous dose of diverting memoir from the actress and biographer <NAME>. Plus, a new book from <NAME>, author of the beloved 2011 novel, “The Family Fang.” I’m especially heartened by the ambitious sweep of this week’s best fiction. There is nothing scaled-back or slight about the stories these writers set out to tell.
<NAME>
<br>Editor of The New York Times Book Review
PACHINKO, by <NAME>. (Grand Central, $27.) This stunning novel chronicling four generations of an ethnic Korean family in Japan is about outsiders and much more. A fascinating look at immigrant life among Koreans — and the prejudices they face — in Japan.<file_sep>/content/event/benefit-for-asian-womens-giving-circle.md
---
title: "Benefit for Asian Women's Giving Circle"
date: 2017-04-20 18:00:00
show_time: true
venue:
name: 'Project: ARTspace'
address: '156 Fifth Avenue, Suite 308'
city: New York
state: NY
zip:
link: <EMAIL>
---
In Conversation with Dr. <NAME>. Introduced by <NAME>, the Founder and Executive Director of AWGC.
6pm
The event is $20.00 at the door for the benefit of the Asian Women's Giving Circle. Please RSVP on the link below.<file_sep>/content/news/2017-04-19-australian-financial-review-best-books-of-the-month.md
---
title: 'Australian Financial Review: Best Books of the Month'
date: 2017-04-19 12:00:00
categories: ["News"]
tags:
- Reviews
- News
attribution: Australian Financial Review WEEKEND
link_to_original: 'http://www.afr.com/brand/afr-magazine/this-months-3-best-books-reviews-of-a-writing-life-house-of-names-pachinko-20170306-gurfr9'
description:
---
This month's 3 best books: Reviews of A Writing Life, House of Names, Pachinko
<NAME>'s work is put under the microscope, Agamemnon's tale retold by renowned Irish author <NAME> and a family drama by <NAME> set in Japan are our picks for the best books this month.
by <NAME>
<NAME>'s work is put under the microscope, Agamemnon's tale retold by renowned Irish author <NAME> and a family drama by <NAME> set in Japan are our picks for the best books this month.
A Writing Life: <NAME> and Her Work by <NAME>
Text
<NAME> is one of Australia's leading authors, and academic <NAME> does her proud in A Writing Life. Brennan argues that Garner's life and writing are so inextricably linked that it is not possible to understand one without the other. She has skilfully woven Garner's personal story into an illuminating literary critique of a writer with more than four decades' worth of work to her name.
The last book about Garner was published in 2006 – <NAME> <NAME>arner – so the time was ripe for an updated examination of the Melburnian's contribution to Australian letters. Garner granted Brennan unprecedented access to her personal correspondence, diaries and other archives as well as countless interviews over a two-year period.
All of which makes for an utterly compelling book, replete with biographical details which cast light on Garner as a person and also on her work. For instance, despite being dux and head prefect at school, Garner achieved only third-class honours at university. Brennan suggests this left her with a pervasive sense of inferiority, seen over the years in harsh self-criticism and an at times overly sensitive response to criticism by others.
What makes this book especially interesting is Brennan's close analysis of each of Garner's books, most of which get a chapter to themselves, in the context of her personal circumstances. Brennan argues that Garner sympathised with the errant master at the centre of the sexual harassment case in The First Stone because she saw echoes of her own sacking years earlier from Fitzroy High. In This House of Grief, Garner shows sympathy towards <NAME>, the divorced father who drove his three young sons into a dam. Brennan suggests that empathy might be a product of Garner's own experience of the pain and humiliation of divorce.
Brennan asks Garner why she married three times. The illuminating response, that her father was more comfortable with her having husbands than partners, says a lot about his influence on her, despite their tumultuous relationship.
Brennan's stated goal was not to ask whether Garner's work is autobiographical – clearly much of it is – but to explore how and why Garner writes about herself. In doing so she has produced a psychologically acute portrait of a complex writer. This is literary critique and biography at its finest.
House of Names by <NAME>
Picador
Renowned Irish author <NAME> breathes life into a classic revenge tale – the story of Agamemnon, commander of the Greek forces in the Trojan War, and his queen, Clytemnestra, whom he has wronged. Agamemnon is the first play of The Oresteia trilogy written by Aeschylus and first performed in 458BC.
House of Names is narrated by Clytemnestra and her two children by Agamemnon, son Orestes and daughter Electra. This enables Toibin to get inside the heads of his protagonists as each faces a complex moral dilemma, revealing their conflicting emotions and motives and engaging the reader's sympathy.
This works most effectively in his portrayal of Clytemnestra, who waits 10 years to wreak vengeance on her husband. She has long been painted as irredeemably evil but by giving her a voice, Toibin enables her to tell her side of the story.
This is tragedy writ large. Its themes of vengeance, justice and filial duty make it as relevant today as ever.
Pachinko by <NAME>
Apollo
Pachinko is a Japanese adult gambling game described as vertical pinball. Korean-American author <NAME> chose it as the title for her second book, a gripping novel about four generations of a Korean family living in Japan, because she saw it as a metaphor for Koreans in Japan "as they struggle for their place".
The story opens in Korea in 1911, when a match is made between disabled Hoonie and the beautiful 15-year-old Yangjin. They have a daughter, Sunja, who emigrates to Japan, where her children and grandchildren will be born, their story unfolding over eight decades.
Pachinko is ostensibly about the plight of Koreans living in Japan but it also tells the story of immigrants everywhere – their battle to assimilate and to survive in the face of hardship, whilst retaining their cultural identities. More than that, it's a profoundly moving family saga, touching on universal themes of love and courage, suffering and endurance, dislocation and resilience. It will stay with you.
| <br>Follow us: @FinancialReview on Twitter | financialreview on Facebook |<file_sep>/content/news/2007-06-27-npr_on_point.md
---
title: "NPR On Point"
date: 2007-06-27T23:23:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "WBUR On Point"
link_to_original: "http://www.onpointradio.org/shows/2007/06/20070627_b_main.asp"
description: ""
_slug: 2007-06-27-npr_on_point
---
A conversation with Korean-American novelist <NAME>. She’s getting robust praise for her debut novel “Free Food for Millionaires.”
<file_sep>/content/writing/the-new-yorker-stonehenge-1.md
---
title: 'NYT: What I Want the Woman Behind the Counter to Know'
date: 2020-05-14T02:00:13-04:00
categories:
tags: []
where_published: The New York Times
link_to_original: https://www.nytimes.com/2020/05/14/opinion/essential-workers-restaurants-covid.html?smid=em-share
link_to_pdf:
description:
_slug: '2019-06-03T06:00:00.000+00:00'
images: []
---
"'Su go ha se yo,' I said, which translates to 'Keep up your hard work,' but that isn’t it exactly. The phrase is a kindness, meaning, I recognize you’re making an effort, and I encourage you to bear up, and it also means, I admire your labor."<file_sep>/content/event/2016-08-25-asian-american-writers-workshop.md
---
title: Asian American Writers’ Workshop—THE STORY OF HONG GILDONG
date: 2016-08-25T19:00:00Z
show_time: true
venue:
name: "Asian American Writers’ Workshop"
address: 112 West 27th Street, Suite 600
city: New York
state: NY
zip: 10001
link: http://www.aaww.or
---
THE STORY OF HONG GILDONG (Penguin Classics 2016) translated by Professor <NAME>
Impressions of this seminal Korean story by <NAME>, <NAME> and <NAME>
<file_sep>/content/event/short-stories-bookstore.md
---
title: Short Stories Bookshop
date: 2017-05-06 16:00:00
show_time: true
venue:
name: 'Short Stories Bookshop & Community Hub'
address: 23 Main Street
city: Madison
state: NJ
zip: 07940
link: 'http://www.shortstoriesnj.com'
---
In Conversation with <NAME>.<file_sep>/content/writing/new-york-times-book-review---was-it-the-perfect-crime-or-a-paranoid-fantasy----.md
---
title: 'New York Times Book Review: "Was It the Perfect Crime or a Paranoid Fantasy? '
date: 2018-02-15 00:28:44 -0500
images: []
image_credit: ''
categories: []
where_published: New York Times Book Review
link_to_original: https://www.nytimes.com/2018/02/15/books/review/junichiro-tanizaki-in-black-and-white.html
description: A review of Junichiro Tanizaki's IN BLACK AND WHITE
---
<file_sep>/content/event/us_embassytokyo_american_center.md
---
title: U.S. Embassy—TOKYO AMERICAN CENTER
date: 2009-05-28T05:37:00-05:00
venue:
name: U.S. Embassy—TOKYO AMERICAN CENTER
link: tokyo.usembassy.gov/j/amc/tamcj-map.html
_slug: us_embassytokyo_american_center
---
ASIAN AMERICAN AND ASIAN: Writing as Both or Either while Living in Japan
A Conversation with <NAME>, Author of FREE FOOD FOR MILLIONAIRES and <NAME>, Professor of English at Seijo University.
Thursday, May 28, 2009
6.30PM-8PM
Tokyo American Center
8F, NOF Tameike Bldg.
1-1-14 Akasaka, Minato-ku, Tokyo 107-0052
Tel: 03-5545-7431
This event is open to the public, but please RSVP at:
<EMAIL> (Please leave your name and contact phone number)
or
FAX your RSVP to 03-3224-7977
<file_sep>/content/book/pachinko.md
---
title: Pachinko
date: 2017-02-07 00:00:00 +0000
publisher: Grand Central Publishing
subtitle: ''
genre:
- Fiction
description: "A saga about four generations of a poor Korean immigrant family fight to control their destiny in 20th-century Japan, exiled from their home."
editions:
- isbn: 9781455563920
binding: paperback
publisher:
description: Trade Paperback
date: 2017-02-07 00:00:00 +0000
cover_image: "/uploads/9781455563920.jpg"
- isbn: 9781455563937
binding: hardcover
publisher:
description: Hardcover
- isbn: 9781455563913
binding: ebook
asin: B01GZY28JA
reviews:
- attribution: <NAME>, Pen/Faulkner-winning author of *The Great Man* and
*Blue Plate Special*
copy_markdown: "*Pachinko* is elegant and soulful, both intimate and sweeping. This
story of several generations of one Korean family in Japan is the story of every
family whose parents sacrificed for their children, every family whose children
were unable to recognize the cost, but it's also the story of a specific cultural
struggle in a riveting time and place. Min Jin Lee has written a big, beautiful
book filled with characters I rooted for and cared about and remembered after
I'd read the final page."
- attribution: <NAME>, New York Times bestselling author of *The Bone Clocks*,
*Cloud Atlas*, and *Black Swan Green*
copy_markdown: A deep, broad, addictive history of a Korean family in Japan enduring
and prospering through the 20th century.
- attribution: <NAME>, New York Times bestselling author of *Little Failure*
and *Super Sad True Love Story*
copy_markdown: Astounding. The sweep of Dickens and Tolstoy applied to a 20th century
Korean family in Japan. Min Jin Lee's *Pachinko* tackles all the stuff most good
novels do—family, love, cabbage—but it also asks questions that have never been
more timely. What does it mean to be part of a nation? And what can one do to
escape its tight, painful, familiar bonds?
- attribution: <NAME>, author of *Ariel's Gift* and *Seizure*
copy_markdown: If proof were needed that one family's story can be the story of
the whole world, then *Pachinko* offers that proof. Min Jin Lee's novel is gripping
from start to finish, crossing cultures and generations with breathtaking power.
*Pachinko* is a stunning achievement, full of heart, full of grace, full of truth.
- attribution: <NAME>, National Book Critics Circle Award-winning author of
*Half a Life* and *Chang & Eng*
copy_markdown: Pachinko by Min Jin Lee is a great book, a passionate story, a novel
of magisterial sweep. It’s also fiendishly readable—the real deal. An instant
classic, a quick page-turner, and probably the best book of the year.
- attribution: '<NAME>, New York Times bestselling author of *The Professor
and the Madman* and *Korea: A Walk through the Land of Miracles*'
copy_markdown: Both for those who love Korea, as well as for those who know no more
than Hyundai, Samsung and kimchi, this extraordinary book will prove a revelation
of joy and heartbreak. I could not stop turning the pages, and wished this most
poignant of sagas would never end. Min Jin Lee displays a tenderness and wisdom
ideally matched to an unforgettable tale that she relates just perfectly.
- attribution: _Kirkus_ (Starred Review)
copy_markdown: Deeply compelling story. An old-fashioned epic whose simple, captivating
storytelling delivers both wisdom and truth.
- attribution: _Library Journal_ (Starred Review)
copy_markdown: A beautifully crafted story of love, loss, determination, luck, and
perseverance.
- attribution: BBC.com (Culture) <NAME>
copy_markdown: Ten Books to Read in 2017
- attribution: 'Book Riot: Most Anticipated Books 2017'
copy_markdown: Lee makes it impossible not to develop tender feelings towards her
characters—all of them, even the most morally compromised. Their multifaceted
engagements with identity, family, vocation, racism, and class are guaranteed
to provide your most affecting sobfest of the year. (<NAME>)
- attribution: Buzzfeed.com
copy_markdown: Most Exciting Books Coming in 2017
- attribution: BookBub.com
copy_markdown: Most Anticipated Book Club Reads of 2017 and Biggest Historical Fiction
Release of 2017
- attribution: South China Morning Post by <NAME>
copy_markdown: PACHINKO is about paying dues to a forgotten history; to the complex
and fraught Japan-Korea relationship that endured well into the 90s and lingers
to this day. But it doesn't wear its heart—or historical truths—on its sleeve.
What drives this novel is the magisterial force of Lee's characterization; her
ability to ground the narrative deeply and intimately in the details of daily
life. Also threaded through it are questions of home, identity, nationhood and
tradition—including the belief of its female protagonists that 'a woman's lot
is to suffer.'
- attribution: NYLON
copy_markdown: 50 Most Anticipated Books of 2017
- attribution: 'American Booksellers Association: INDIE NEXT Great Reads Feb 2017
(<NAME>, Boswell Book Company)'
copy_markdown: Through it all is a message about love, faith, and the deep-rooted
bonds of family. <NAME> gives us a phenomenal story about one family's struggle
that resonates with us today. It will take hold of you and not let go!
- attribution: Toronto Star
copy_markdown: Top 10 Books of February of the Canadian Library Association's Loan
Stars Program
images:
- "/uploads/9781455563920.jpg"
buy_links_external: []
---
PACHINKO follows one Korean family through the generations, beginning in early 1900s Korea with Sunja, the prized daughter of a poor yet proud family, whose unplanned pregnancy threatens to shame them all. Deserted by her lover, Sunja is saved when a young tubercular minister offers to marry and bring her to Japan.
So begins a sweeping saga of an exceptional family in exile from its homeland and caught in the indifferent arc of history. Through desperate struggles and hard-won triumphs, its members are bound together by deep roots as they face enduring questions of faith, family, and identity.
<file_sep>/content/news/2017-07-17-british-airways-high-life-recommended-books.md
---
title: 'British Airways High Life: Recommended Books'
date: 2017-07-17 12:00:00
categories: ["News"]
tags:
- Reviews
attribution:
link_to_original:
description:
---

Thank you, British Airways High Life and Joni Brown of Cook & Book of Brussels. Thank you, <NAME> for sending me the image. <file_sep>/content/news/2008-03-19-npr_kqed_the_writers_block.md
---
title: "NPR: KQED The Writer’s Block"
date: 2008-03-19T23:30:00-05:00
categories: ["Media"]
tags:
- Audio
attribution: "NPR: KQED The Writer's Block"
link_to_original: "http://www.kqed.org/arts/people/profile.jsp?id=18060"
description: ""
_slug: 2008-03-19-npr_kqed_the_writers_block
---
<file_sep>/content/news/2008-09-09-profile_in_the_japan_times.md
---
title: "Profile in The Japan Times"
date: 2008-09-09T22:24:00-05:00
categories: ["Media"]
tags:
- News
attribution: "The Japan Times"
link_to_original: "http://www.japantimes.co.jp/cgi-bin/fl20080909zg.html"
description: ""
_slug: 2008-09-09-profile_in_the_japan_times
---
Profiles about my work appeared in The Japan Times this month. The article in The Japan Times (”[Tackling the ‘Zainichi’ experience](http://www.japantimes.co.jp/cgi-bin/fl20080909zg.html "Tackling the 'Zainichi' experience")” September 9, 2008) was written by <NAME>, author of _Loving the Machine: The Art and Science of Japanese Robots_.
<file_sep>/content/news/2016-08-25-the-story-of-hong-gil-dong-penguin-classics-translated-by-minsoo-kang-video.md
---
title: The Story of <NAME> (Penguin Classics) Translated by Minsoo Kang (VIDEO)
date: 2016-08-25 19:00:00
categories: ["Media"]
tags:
- Video
attribution:
link_to_original:
description: 'The Story of Hong Gildong; A Conversation with Minsoo Kang, <NAME> and <NAME> about perhaps the most important story of Korea'
---
At the [Asian American Writers' Workshop](http://aaww.org/)
<iframe width="560" height="315" src="https://www.youtube.com/embed/c7Fitba-La8" frameborder="0" allowfullscreen=""></iframe><file_sep>/content/review/erica-wagner-on-pachkinko.md
---
title: <NAME> on Pachkinko
attribution: <NAME>, author of *<NAME>* and *Seizure*
date: 2017-03-17 17:42:35 +0000
book: book/pachinko.md
description: ''
featured: false
---
If proof were needed that one family's story can be the story of the whole world, then *Pachinko* offers that proof. Min Jin Lee's novel is gripping from start to finish, crossing cultures and generations with breathtaking power. *Pachinko* is a stunning achievement, full of heart, full of grace, full of truth.<file_sep>/content/event/nypl.md
---
title: 'The New York Public Library: Immigrant Stories'
date: 2017-04-18 18:30:00
show_time: true
venue:
name: <NAME>
address: '476 Fifth Avenue (42nd Street & Fifth Ave)'
city: New York
state: NY
zip: '10018'
link: 'https://www.showclix.com/event/immigrantstories/listing/tag/guest'
---
A discussion featuring <NAME>, the author of *Pachinko* and <NAME> that examines how writers are humanizing the experience of immigration.
This is a #OneBookNY Event at NYPL. This is a free event, but please register below.
<file_sep>/content/review/entertainment-weekly-on-free-food-for-millionaires.md
---
title: Entertainment Weekly on Free Food for Millionaires
attribution: Entertainment Weekly
date: 2007-03-11 18:14:40 +0000
book: book/free-food-for-millionaires.md
description: ''
featured: false
weight: ''
---
Free Food for Millionaires is different from any book I’ve ever read — a big, juicy, commercial Korean-American coming-of-age novel, one that could spawn a satisfying miniseries, and one that definitely belongs in this summer’s beach bag.<file_sep>/content/news/2007-05-22-out_this_week.md
---
title: "Out This Week"
date: 2007-05-22T23:04:01-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "Columbus Dispatch"
link_to_original: ""
description: ""
_slug: 2007-05-22-out_this_week
---
Other notable releases: fiction—Free Food for Millionaires, Min Jin Lee; The Overlook, <NAME>ly; nonfiction—God in My Corner: A Spiritual ...
<file_sep>/content/news/2007-08-24-the_publishing_spot1.md
---
title: "The Publishing Spot"
date: 2007-08-24T22:04:00-05:00
categories: ["Media"]
tags:
- Interviews
attribution: "The Publishing Spot"
link_to_original: "http://www.thepublishingspot.com/min_jin_lee/"
description: ""
_slug: 2007-08-24-the_publishing_spot1
---
A discussion of how to publish, specialty publishers, publishing companies, publishing opportunities, publishing agents, etc.
<file_sep>/content/event/savoy-bookshop--cafe.md
---
title: 'Savoy Bookshop & Cafe'
date: 2017-02-09 18:00:00
show_time: true
venue:
name: Savoy Books
address: 10 Canal Street
city: Westerly
state: RI
zip: 02891
link: 'http://www.savoybooks.com'
---
Conversation with <NAME>, American Booksellers Association Board member and co-owner of Bank Street Books and Savoy Books.<file_sep>/content/book/_index.md
---
title: "Books"
menu:
main:
weight: 2
---
<file_sep>/content/event/buttonwood_books_july_31.md
---
title: Buttonwood Books, July 31
date: 2007-07-31T20:00:00-05:00
venue:
name: Buttonwood Books, Cohasset, MA
link: www.buttonwoodbooks.com
_slug: buttonwood_books_july_31
---
Dinner with the Author at Buttonwood Books
Reservations and Tickets are required.
A light dinner (wraps), wine/soft drink, dessert and coffee will be served.
$7 per person.
Please call Buttonwood to reserve your seat:
781-383-2665
<file_sep>/content/event/columbia-sc.md
---
title: Tuckahoe Woman’s Club
date: 2020-03-11T10:15:00-04:00
show_time: true
venue:
name: The Tuckahoe Woman's Club
address: 4215 Dover St.
city: Richmond
state: VA
zip: "23221"
link: ''
description: ''
images: []
---
<file_sep>/content/news/2017-12-20-the-atlantic-by-heart-interview-with-joe-fassler.md
---
title: 'The Atlantic: "By Heart" interview with <NAME>'
date: 2017-12-20 12:00:00 +0000
categories:
- News
tags:
- Reviews
- Essays
- Interviews
- News
attribution: The Atlantic
link_to_original: https://www.theatlantic.com/entertainment/archive/2017/12/min-jin-lee-by-heart/548810/
description: ''
images: []
---
By <NAME>
**By Heart is a series in which authors share and discuss their all-time favorite passages in literature. See entries from <NAME>, <NAME>, <NAME>, <NAME>, and more.**
For <NAME>, the author of Pachinko, writing a novel is a nearly god-like act of creation, a way to preside over a small universe that authors fashion in the image of their beliefs. In a conversation for this series, she explained why her commitment to third-person “omniscient” narration is not just an aesthetic choice, but also an ethical one: That mode’s flexibility lets her build a functioning, self-contained world, one that’s governed by an overarching moral physics.
But if omniscient narration allows Lee to play god, the question is what kind of god to be. For inspiration, she looks to the biblical story of Joseph, a tale that’s helped to shape the way she thinks about good and evil. She explained how the story instilled her with a radical belief that supercharges her fiction: If suffering and injustice can be recast as opportunities for empathy and forgiveness, even life’s worst events can feel like divine fate.
Pachinko dramatizes this idea starting in a Korean fishing town, early in the 20th century, with a cast of characters rendered with startling humanity. As a series of unfortunate events leads Sunja, the only daughter of a widowed innkeeper, from Korea to a new life in Japan, the hard circumstances of each character—physical deformity, a case of tuberculosis, an unplanned pregnancy—become opportunities for transformation. Named for a Japanese pinball game that combines both skill and luck, Pachinko shows how momentous acts of kindness and cruelty shape lives through subsequent generations.
Pachinko was a National Book Award finalist this year, and has been named one of The New York Times’ 10 best books of 2017. Lee spent years living in Tokyo, interviewing Korean immigrants as she researched and wrote the book. Free Food for Millionaires, her first novel, was published in 2007. She lives in New York City and spoke to me by phone.
**<NAME>:**After I quit being a lawyer in ’95, I was having a lot of trouble writing. Then I read somewhere that <NAME> read a chapter of the Bible every day before she started work. I thought—okay, I’ll try it. Before each writing session, I started to read the Bible like a writer, thinking about language, character, and themes. And as I read the Book of Genesis, I started to see why the Bible has been the ur-text for so many Western writers of classics: It’s such a rich text, one that could spawn thousands if not hundreds of thousands of novels, poems, and plays.
I was especially amazed by the story of Joseph, which has stuck with me now all these years and become such an important part of the way I think about my life and work. It’s a crazy story. For those who may not know, Joseph is the beloved child of Jacob. His brothers can’t stand him because they’re jealous of his status as the favorite son, and also because he’s a tattletale. Initially, his brothers decide to kill him—though they end up selling him into slavery instead—this terrible act of betrayal that changes his life completely. We follow Joseph into slavery, and from there, into prison. After great personal trials and a miraculous deliverance based on his ability to interpret dreams, he eventually rises to the rank of vizier, the second-in-command to the Egyptian pharaoh, and ends up saving many peoples from famine, including his brothers and his father.
After Jacob’s death, Joseph’s brothers are terrified that he’ll hold a grudge against them because their father can no longer keep Joseph from harming them. The brothers concoct a story saying, essentially, “Oh, by the way—before dad died he told us to tell you that you have to forgive us for selling you into slavery. Sorry about all that.” But rather than taking revenge on his brothers, Joseph believes there has been a higher purpose to his suffering.
“You intended to harm me, but God intended it for good,” he tells them, “to accomplish what is now being done, the saving of many lives.” The gist of it is: What man intended for evil, God intended for good.
It’s just an incredible thing to say, considering everything he went through. I’m amazed by the insistence that all of the suffering, the inequity, and injustice he endured happened for a reason.
That kind of optimism or sense of divine purpose is very hard to muster as a modern person. Like Joseph, we all have inequities inflicted upon us, and when we experience inequity and injustice and evil, our sense of powerlessness and despair can be overwhelming. When will we see justice?, we want to know. When will we see fairness? When will things be okay? I understand the impulse to believe God doesn’t care. But I find that I very strongly want to believe that there’s a reason for the evil that we see and experience. Though there is so much evil, I want to believe in ultimate moral justice. I believe that, as in the story of Joseph, goodness has the potential to rise out of the darkness that befalls us.
This belief is reflected in the kind of stories I want to tell. As an artist, my wheelhouse is 19th-century literature. I want to write realist novels in a Victorian sense, and the writers I admire in that style tend to do omniscient narration. The omniscient narrator is a bizarre technique, when you think about it, and no one uses it much anymore. But for the novels I want to write, it’s the only approach that makes sense to me. Writing this way, you’re not embracing the subjectivity of a specific character. Instead—like the novelists of the 19th and early 20th centuries—you play God, effectively, manifesting a kind of complete design within the chaos of life.
When you write this way, you’ve got to ask yourself about the fictional universe you create. Will you be a morally just god or an immoral god? My art has to reflect the moral justice that I believe in. Not that I’m interested in preaching, or writing a treatise about how people should start the revolution. But I am interested, as in Joseph’s story, in showing the ways goodness can rise out of suffering. And I’m interested in creating radical empathy through art. That’s the little task that I set for myself. I don’t know if it’s for everyone, but it’s for me.
I think literature is especially good at awakening that part of our capacity. It’s one of the few things that can really convince human beings to view each other as human beings. We’re so willing to dehumanize entire populations in order for us to conveniently go along with our lives. We know exactly one North Korean, for example. The rest of them, we don’t know—but it makes it very easy to bomb North Korea if we pretend they’re all one person. Literature makes it harder to dehumanize people in this way. When I make art, my job is to create drama with dynamic characters who change convincingly over time. If I do my job well, the reader changes, too.
Film does this too, and so does television, but books require a different kind of attentiveness. There’s an activeness in the engagement with books that movies and TV can’t approach in the same way. Also, novels just take longer to read. If I can get you to participate in this world I’ve created for 10 or 20 or 30 hours, you start to see things differently. You start to participate in the struggles of people like Sunja. And as you begin to care about her husband, about the fate of her children—all of a sudden, these people you’re reading about are not just “some Koreans,” a faceless group of politically oppressed immigrants in Japan. They're people. And I have tried very hard to humanize them, to draw them with enough detail that the reader can love them.
As I wrote Pachinko, I interviewed many Korean Japanese, individuals who suffered a hundred thousand times more than I’ve ever suffered in my life. What struck me most of all was how resilient they were—how much joy they felt, despite everything that had happened to them. Their humor, their ability to sing, or dance, or make light of people who were unkind. And I found this to be incredibly gratifying, because I think I initially viewed them only through the lens of their struggles. I was stuck in a space of focusing on the world’s darkness. But the people I interviewed reminded me that, even in darkness, there are still weddings. There are still children. There’s laughter. You can’t just look at the dark and you can’t just look at the light: Real human lives are a constant interplay of light and dark. And that gave me a great deal of great hope, an idea about how to carry on.
I did not invent their optimism, and I did not expect it. They gave it to me like a present. And I realized that I was more upset about what had happened to them, in many ways, more than they were. I think I was more upset because, as an American, I feel a sense of indignation at injustice, and I also feel like I can have redress. As a lawyer, I know that I can seek justice in a very specific formal way. Not that these efforts have always had a good outcome in our legal history, and they can require people to take continuous action for a very long time. But in America there have been some wonderful overturning of inequitable things, even if it’s taken 20 years or 50 years or 100 years. As Americans, we know it’s possible. But this was a reminder that, in other parts of the world, there is often no redress for suffering or inequity. I think that’s the reason why my interviewees looked at me and said, “Wow, Min, you’re really upset about this.” I felt incredibly amazed by their graciousness in response to their suffering.
In terms of personal faith, I’m a Presbyterian, which does form my understanding of the world. Presbyterians are kind of funny Protestants because we believe in both free will and predestination—so you’re always toggling between the ideas of free will and fate. You believe that, underneath it all, there is a larger plan. But you’re not a fatalist. You believe that your free will matters. One way we exercise free will is by choosing to respond to injury with forgiveness, which is probably the hardest thing to do in the world. If someone punches you in the face, it’s tremendously hard to forgive them as you stand there with your broken nose, bleeding. But I want to believe that even the gravest injuries are an opportunity to respond with empathy, honesty, and justice, the way Joseph responds to his brothers. And I saw that grace, that capacity, in the Korean Japanese I interviewed.
Last night I was speaking at the Strand with some really smart writers, and the great, engaged audience asked us pressing questions about despair. How should we respond to this past year, they wanted to know, with our leadership behaving in ways that are so shocking? My thought is: You should despair, and you should lament. It would be cruel to say you don’t have the right to despair, just because worse atrocities are happening elsewhere in the world. But then, there’s the free will part: What is your response to that despair? Ultimately, what will you do? You can’t just give up. Compassion is so important, but if you really want justice, you have to take action.
What started out for me as a way to deal with my anxiety before I started to write—a kind of homage to <NAME>—became something that has informed me as a writer in all of my practice. I changed because I read Joseph’s story. I’m so moved by his response, the active way he responded to the deep injustices of his life. After all—it’s not like strangers sold him into slavery. His brothers sold him into slavery. They sent him down this rabbit hole of incredible unfairness. But he was able to see in his own misfortune, a call towards righteousness, and a sign that the world bends toward justice. I try to adopt this incredibly hopeful stance in my writing, even as I consider the worst suffering of my characters. Books simulate a moral universe, microcosms with the power to change how we respond to our own troubled circumstances. By reading the story of Joseph’s transformation, I was transformed, too.<file_sep>/content/event/korea-economic-institute-of-america-korean-american-day.md
---
show_time: true
title: Korea Economic Institute of America - Korean American Day
date: 2020-01-13T11:30:00-05:00
description: ''
venue:
address: 1300 Pennsylvania Ave.
city: Washington DC
name: <NAME>
state: District of Columbia
zip: "20004"
link: ''
images: []
---
<file_sep>/content/writing/2011-05-05-essay_in_vogue_up_front_after_the_earthquake.md
---
title: "Up Front: After the Earthquake"
date: 2011-05-05T09:49:28-05:00
categories:
tags: ["Essays"]
where_published: "Vogue"
link_to_original: "http://www.vogue.com/culture/article/upfront-japan/"
link_to_pdf:
description:
_slug: 2011-05-05-essay_in_vogue_up_front_after_the_earthquake
---
March 11, 2011, fell on a Friday, the day I run errands and go to the market. Until 2:46 p.m., about an hour before my thirteen-year-old son, Sam, would return home from his international school in Chofu, a suburb of Tokyo, it had been a good day. Once in a rare while in the life of a writer struggling on her sophomore novel, it’s possible to achieve a state of semi-contentedness by producing a few decent pages, and that morning was a halcyon interlude in my otherwise grumbling condition. After printing out my day’s work, I tidied the house, raced to the bank, paid my utility bills, then mulled over what to make for dinner for Sam and my husband, Christopher.
read the rest at [Vogue](http://www.vogue.com/culture/article/upfront-japan/)
<file_sep>/content/event/tenement-museum.md
---
title: 'Tenement Museum, New York City'
date: 2017-03-15 18:30:00
show_time: true
venue:
name: Tenement Museum New York City
address: 103 Orchard Street
city: New York
state: NY
zip: '10002'
link: 'https://www.tenement.org'
---
In Conversation with <NAME>, the Executive Director of the Asian American Writers' Workshop. <NAME> is the recipient of the Yale Younger Poets Prize for his poetry collection *Juvenilia*. <file_sep>/content/event/harvard_book_store.md
---
title: HARVARD BOOK STORE
date: 2008-05-01T23:27:00-05:00
venue:
name: HARVARD BOOK STORE, Boston, MA
link: www.harvard.com
_slug: harvard_book_store
---
Reading and Q&A
7PM
1256 Massachusetts Avenue
Cambridge, MA 02138
<file_sep>/content/news/2017-08-11-new-york-times-book-review-what-were-reading-podcast.md
---
title: 'New York Times Book Review: What We''re Reading (Podcast)'
date: 2017-08-11 12:00:00
categories: ["News"]
tags:
- Reviews
attribution: New York Times Book Review
link_to_original: >-
https://www.nytimes.com/2017/08/11/books/review/new-books-about-parenting.html?mcubz=0&_r=0
description:
---
On this week’s podcast, <NAME> talks about new parenting books; <NAME> discusses “The World Broke in Two: <NAME>, <NAME>, <NAME>, <NAME>, and the Year That Changed Literature”; <NAME> has news from the literary world; and <NAME>, <NAME> and <NAME> on what people are reading. <NAME> is the host.
Here are the books mentioned in this week’s “What We’re Reading”:
“Born to Run” by <NAME>
“My Private Property” by <NAME>
“The Wind in the Willows” by <NAME>
“Pachinko” by <NAME>
To listen to the podcast, please click the link below. The "What We're Reading Segment" is at the last ten minutes of this week's episode. Thank you.<file_sep>/content/event/national-sawdust--paul-muldoon--tracy-k.-smith--and-min-jin-lee-.md
---
title: 'National Sawdust in Brooklyn: <NAME>, <NAME>, and <NAME> '
date: 2019-05-23 19:00:12 -0400
images: []
image_credit: ''
categories: []
where_published: ''
link_to_original: ''
description: ''
---
<file_sep>/content/news/business-insider-20-historical-fiction-books-that-will-whisk-you-to-a-different-world.md
+++
categories = []
date = 2021-07-28T04:50:11Z
description = ""
images = []
link_to_original = "https://www.businessinsider.com/best-historical-fiction-books"
tags = []
title = "Business Insider: 20 historical fiction books that will whisk you to a different world"
+++
<file_sep>/content/event/kinokuniya-bryant-park-nyc.md
---
title: Kinokuniya Bryant Park NYC
date: 2018-04-10 18:30:02 -0400
images: []
description: Reading, Discussion and Book signing
link: https://usa.kinokuniya.com/event-calendar/2018/04/10/min-jin-lee
show_time: true
venue:
address: 1073 Avenue of Americas
city: ''
name: 'Kinokuniya USA '
state: ''
zip: ''
---
<file_sep>/content/event/writing_about_queens.md
---
title: Harvard Law School—APALSA National Conference 2013 —FEBRUARY 23, 2013, SATURDAY
date: 2013-02-23T13:30:11-05:00
venue:
name:
link: www3.law.harvard.edu
_slug: writing_about_queens
---
19th Annual National Conference on Law and Public Policy: Harvard Law School APALSA
FEBRUARY 23, 2013, Saturday.
Politics & Government Panel 2.30
Wasserstein Hall, Harvard Law School
| 2235cedc96f30cb380a7a588b5782a68fd04792e | [
"HTML",
"Markdown",
"TOML",
"JavaScript",
"Go Module"
] | 740 | Markdown | theNewDynamic/minjinlee.com | 1cba5dcea03cffe5f8ca0a2f80b46f7567f32342 | 652097943f2e431a673a4a6f33af8305130b8421 |
refs/heads/master | <repo_name>Hibss/spring-boot-rabbitmq<file_sep>/src/main/java/com/steven/service/OperatorService.java
package com.steven.service;
import com.steven.mapper.OperatorMapper;
import com.steven.model.Operator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by steven.sheng on 2018/1/9.
*/
@Service
public class OperatorService {
@Autowired
private OperatorMapper operatorMapper;
public List<Operator> getByName(String name){
return operatorMapper.getByName(name);
}
}
<file_sep>/src/main/java/com/steven/model/Operator.java
package com.steven.model;
import groovy.transform.builder.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author steven.sheng
*/
@Data
@Builder
public class Operator implements Serializable {
private Long id;
private String name;
private String card;
private String mobile;
private Long uid;
private String org;
private Short isDelete;
private Short rowState;
private Long ownerId;
private String ownerName;
private String creatorName;
private Long creatorId;
private Date createTime;
private Date updateTime;
private String updatorName;
private Long updatorId;
private Integer manageCount;
private Short isSignup;
private Short isMinister;
private Short isQualification;
}<file_sep>/src/main/java/com/steven/util/JacksonUtil.java
package com.steven.util;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JacksonUtil {
private static ObjectMapper mapper;
private static ObjectMapper mapperCamel;
private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
static {
mapper = new ObjectMapper().configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapperCamel = new ObjectMapper().configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
public static <T> T readObj(String json, Class<T> clazz) {
try {
T obj = (T) mapper.readValue(json, clazz);
return obj;
} catch (Exception e) {
logger.error("json转换异常", e);
}
return null;
}
/**
* String2Object
*
* @param json
* @param clazz
* @param isCamel
* 是否驼峰下划线转换
* @return
*/
public static <T> T readObj(String json, Class<T> clazz, boolean isCamel) {
if (isCamel) {
try {
T obj = (T) mapperCamel.readValue(json, clazz);
return obj;
} catch (Exception e) {
logger.error("json转换异常", e);
}
return null;
} else {
return readObj(json, clazz);
}
}
/**
* 复杂类型转换
*
* @param json
* @param collectionClass
* 外层集合类型
* @param elementClasses
* 元素泛型类型
* @return
*/
@SuppressWarnings("unchecked")
public static <T, R> R readObj(String json, Class<T> collectionClass, Class<?>[] elementClasses) {
try {
R obj = (R) mapper.readValue(json,
mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses));
return obj;
} catch (Exception e) {
logger.error("json转换异常", e);
}
return null;
}
/**
* 复杂类型转换
*
* @param json
* @param collectionClass
* 外层集合类型
* @param elementClasses
* 元素泛型类型
* @param isCamel
* 是否驼峰下划线转换
* @return
*/
@SuppressWarnings("unchecked")
public static <T, R> R readObj(String json, Class<T> collectionClass, Class<?>[] elementClasses, boolean isCamel) {
if (isCamel) {
try {
R obj = (R) mapperCamel.readValue(json,
mapperCamel.getTypeFactory().constructParametricType(collectionClass, elementClasses));
return obj;
} catch (Exception e) {
logger.error("json转换异常", e);
}
return null;
} else {
return readObj(json, collectionClass, elementClasses);
}
}
public static String toJSONString(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (Exception e) {
logger.error("json转换异常", e);
}
return "{}";
}
/**
* Object2String
*
* @param object
* @param isCamel
* 是否驼峰下划线转换
* @return
*/
public static String toJSONString(Object object, boolean isCamel) {
if (isCamel) {
try {
return mapperCamel.writeValueAsString(object);
} catch (Exception e) {
logger.error("json转换异常", e);
}
return "{}";
} else {
return toJSONString(object);
}
}
}
<file_sep>/src/main/java/com/steven/constants/CommonResponse.java
package com.steven.constants;
/**
* @Author steven.sheng
* @Date 2018/12/14/014.
*/
public class CommonResponse {
public static Integer NOT_UPDATE_NEWEST_CODE = -1;
public static String NOT_UPDATE_NEWEST_MSG = "版本太低";
}
<file_sep>/src/main/resources/rabbitMessage.sql
CREATE TABLE `mq_rabbit_message` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`exchange` varchar(100) DEFAULT NULL COMMENT 'direct,fanout,topic消息交换机',
`routing_key` varchar(100) DEFAULT NULL COMMENT '路由关键字',
`context` text COMMENT '消息body',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`message_type` smallint(1) DEFAULT NULL COMMENT '1发送2接收',
`remark` varchar(200) DEFAULT NULL COMMENT '备注',
`host` varchar(200) DEFAULT NULL COMMENT 'HOST NAME',
`erp_table` varchar(100) DEFAULT NULL COMMENT 'erp业务表',
`erp_id` bigint(20) DEFAULT NULL COMMENT 'erp业务主键id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8<file_sep>/src/com/jfz/mapper/rabbitMessageMapper.java
package com.steven.mapper;
import com.steven.model.rabbitMessage;
public interface rabbitMessageMapper {
int deleteByPrimaryKey(Long id);
int insert(rabbitMessage record);
int insertSelective(rabbitMessage record);
rabbitMessage selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(rabbitMessage record);
int updateByPrimaryKeyWithBLOBs(rabbitMessage record);
int updateByPrimaryKey(rabbitMessage record);
}<file_sep>/src/main/java/com/steven/mapper/OperatorMapper.java
package com.steven.mapper;
import com.steven.model.Operator;
import java.util.List;
public interface OperatorMapper {
int deleteByPrimaryKey(Long id);
int insert(Operator record);
int insertSelective(Operator record);
Operator selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Operator record);
int updateByPrimaryKey(Operator record);
List<Operator> getByName(String name);
}<file_sep>/src/main/java/com/steven/Application.java
package com.steven;
import com.steven.filter.ThreadInformationFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
/**
* @author steven.sheng
*/
@SpringBootApplication
@MapperScan("com.steven.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public FilterRegistrationBean requestFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean(new ThreadInformationFilter());
bean.addUrlPatterns("/*");
bean.setName("threadFilter");
bean.setOrder(1);
return bean;
}
}
<file_sep>/src/main/java/com/steven/filter/ThreadInformationFilter.java
package com.steven.filter;
import com.steven.constants.CommonResponse;
import com.steven.thread.ThreadInformation;
import com.steven.thread.ThreadInformationResource;
import com.steven.util.JacksonUtil;
import com.steven.util.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* @Author steven.sheng
* @Date 2018/12/14/014.
*/
public class ThreadInformationFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadInformationFilter.class);
@Autowired
private ThreadInformationResource threadInformationResource;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("token");
LOGGER.info("request url : {}",request.getRequestURL().toString());
LOGGER.info("request getQueryString : {}",request.getQueryString());
String system= request.getHeader("system");
LOGGER.info(Thread.currentThread().getName()+" clientType="+system + " token=" + token);
boolean isOK = true;
if(StringUtils.isEmpty(token)){
isOK = false;
}
if(!isOK){
RestResponse cs = RestResponse.createFailed(CommonResponse.NOT_UPDATE_NEWEST_CODE, CommonResponse.NOT_UPDATE_NEWEST_MSG);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(JacksonUtil.toJSONString(cs));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
return;
}
if(!StringUtils.isEmpty(system)){
ThreadInformation info= threadInformationResource.getThreadInfo();
info.setSystemName(system);
info.setRequestTime(new Date());
info.setThreadName(Thread.currentThread().getName());
}
filterChain.doFilter(request, response);
}
}
<file_sep>/src/main/java/com/steven/model/RabbitMessage.java
package com.steven.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import groovy.transform.builder.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author steven.sheng
*/
@Data
@Builder
public class RabbitMessage implements Serializable {
private Long id;
private String exchange;
private String routingKey;
private String context;
private Short messageType;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
private String remark;
private String host;
private String erpTable;
private Long erpId;
}<file_sep>/src/main/java/com/steven/controller/BaseController.java
package com.steven.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by steven.sheng on 2018/1/5.
*/
@RestController
public class BaseController {
@RequestMapping("/")
public String greeting() {
return "home page";
}
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
@RequestMapping("/users/{username}")
public String userProfile(@PathVariable("username") String username) {
return String.format("user %s", username);
}
@RequestMapping("/numbers/{number}")
public String userProfile(@PathVariable("number") Integer number) {
return String.format("number %d", number);
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginGet() {
return "Login Page";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginPost() {
return "Login Post Request";
}
}
<file_sep>/src/main/java/com/steven/mapper/RabbitMessageMapper.java
package com.steven.mapper;
import com.steven.model.RabbitMessage;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RabbitMessageMapper {
int deleteByPrimaryKey(Long id);
int insert(RabbitMessage record);
int insertSelective(RabbitMessage record);
RabbitMessage selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(RabbitMessage record);
int updateByPrimaryKeyWithBLOBs(RabbitMessage record);
int updateByPrimaryKey(RabbitMessage record);
List<RabbitMessage> getRabbitMessage(@Param("exchange") String channelTopic, @Param("routingKey") String routingKey,
@Param("context") String context);
Long insertAndGenIdSelective(RabbitMessage message);
}<file_sep>/src/com/jfz/model/rabbitMessage.java
package com.steven.model;
import java.util.Date;
public class rabbitMessage {
private Long id;
private String exchange;
private String routingKey;
private Date createTime;
private Short messageType;
private String remark;
private String host;
private String erpTable;
private Long erpId;
private String context;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange == null ? null : exchange.trim();
}
public String getRoutingKey() {
return routingKey;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey == null ? null : routingKey.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Short getMessageType() {
return messageType;
}
public void setMessageType(Short messageType) {
this.messageType = messageType;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host == null ? null : host.trim();
}
public String getErpTable() {
return erpTable;
}
public void setErpTable(String erpTable) {
this.erpTable = erpTable == null ? null : erpTable.trim();
}
public Long getErpId() {
return erpId;
}
public void setErpId(Long erpId) {
this.erpId = erpId;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context == null ? null : context.trim();
}
}<file_sep>/src/main/resources/application.properties
spring.application.name=erp-rabbitmq
server.port=9999
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
spring.rabbitmq.host=192.168.12.215
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=<PASSWORD>
spring.datasource.url=jdbc:192.168.12.215://localhost:3306/rabbitmq?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis.mapperLocations=classpath:mapping/*.xml
| 27d1c5d83dce831e868de32ca0d704513961e240 | [
"Java",
"SQL",
"INI"
] | 14 | Java | Hibss/spring-boot-rabbitmq | a696165a82fad2a5cfdb69809af629c9cdc24b4e | a5d79b644e4cbf97d30607f67fdda821bb67251f |
refs/heads/master | <repo_name>blakejennings/JumbleSolver<file_sep>/JumbleSolver/UJHeader.swift
//
// UJHeader.swift
// Unjumble
//
// Created by Work on 7/18/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class UJHeader: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 5.0;
self.layer.borderColor = UIColor(rgba: "#FEFEFE").CGColor
self.layer.borderWidth = 1.0
//self.backgroundColor = UIColor.blueColor()
self.textColor = UIColor.grayColor()
self.tintColor = UIColor.whiteColor()
self.layer.shadowRadius = 5.5
self.layer.shadowOpacity = 0.3
}
}<file_sep>/JumbleSolver/JumbleModel.swift
//
// JumbleModel.swift
// Unscramble
//
// Created by <NAME> on 1/27/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
class JumbleModel {
var jumbledWord: String
var sortedWord: String
var unjumbledWord: String
var dictionaryLookup = [String: Array<String>]()
init() {
self.jumbledWord = String()
self.sortedWord = String()
self.unjumbledWord = String()
let filePath = NSBundle.mainBundle().pathForResource("dict_map", ofType:"csv")
let data = NSData(contentsOfFile:filePath!)
var rawString:NSString = NSString(data: data!, encoding: NSASCIIStringEncoding)!
rawString = rawString as String!
let lines = rawString.componentsSeparatedByString("\n")
for line in lines {
var words = line.componentsSeparatedByString(",")
let key = words.removeAtIndex(0)
dictionaryLookup.updateValue(words, forKey: key)
}
}
func sortWord() {
let word = jumbledWord.lowercaseString
let characters = Array(word.characters)
let sortedArray = characters.sort(<)
sortedWord = String(sortedArray)
}
}<file_sep>/JumbleSolver/ViewController.swift
//
// ViewController.swift
// Unscramble
//
// Created by <NAME> on 1/26/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var jumbledTextField: SkeuoField!
@IBOutlet weak var unjumbledTextView: UITextView!
let jumbleModel = JumbleModel()
override func viewDidLoad() {
// jumbledTextField.frame.size.height = 500
jumbledTextField.autocapitalizationType = UITextAutocapitalizationType.None
jumbledTextField.autocorrectionType = UITextAutocorrectionType.No
jumbledTextField.addTarget(self, action:"unJumble:", forControlEvents:
UIControlEvents.EditingChanged)
jumbledTextField.becomeFirstResponder()
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func unJumble(sender : AnyObject) {
jumbledTextField.becomeFirstResponder()
jumbleModel.jumbledWord = jumbledTextField.text!
jumbleModel.sortWord()
if (jumbledTextField.text == "") {
unjumbledTextView.text = ""
} else if (jumbleModel.dictionaryLookup[jumbleModel.sortedWord] == nil){
unjumbledTextView.text = "No words found."
} else {
let words:Array<String> = jumbleModel.dictionaryLookup[jumbleModel.sortedWord]!
var wordString = "\n".join(words)
wordString = wordString.stringByReplacingOccurrencesOfString("\"", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
unjumbledTextView.text = wordString
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
jumbledTextField.becomeFirstResponder()
super.touchesBegan(touches, withEvent: event)
}
}
| 394c2ddba85399ac62197d39208da6910e97c80f | [
"Swift"
] | 3 | Swift | blakejennings/JumbleSolver | 67933f32280ab415fb03c9edb7971579e1f96bcb | a938289eec1d56233170ba11a53499e12df45ba0 |
refs/heads/master | <repo_name>richard1111d/ProgrammingAssignment2<file_sep>/cachematrix.R
## the functions in this file are designed to aid in the sometimes computational and memory intensive
## process of inverting a matrix in the R language
## two functions are in this file:
## makeCacheMatrix()
## cacheSolve()
## descriptions of each of these functions may be found in comments above the function itself
## makeCacheMatrix is an custom function designed to create a special matrix object that can cache
## its inverse
## parameter(s): a matrix
## returns: a customized list object based on the matrix passed as the input parameter
makeCacheMatrix <- function(x = matrix()) {
inverseOfMatrix <- NULL
set <- function(newMatrixValue){
x <<- newMatrixValue
# set inverseOfMatrix to NULL at higher scope because if set new matrix then any old inverse calculation
# is old and could be incorrect
inverseOfMatrix <<- NULL
}
get <- function() x
setInverse <- function(newInverseMatrix){
inverseOfMatrix <<- newInverseMatrix
}
getInverse <- function(){
inverseOfMatrix
}
list(set = set, get = get, setInverse= setInverse, getInverse = getInverse)
}
## cacheSolve actually caculates the inverse matrix and caches it so it does not have to be recalculated
## requirement for function users: the matrix supplied must be invertible.
## no error checking is done to prevent a non-invertible matrix from being used in this function
## parameters: x must be of "makeCacheMatrix" type
cacheSolve <- function(x, ...) {
inverseMatrix <- x$getInverse()
# if the inverse of the matrix contained in the speical x object has already been calculated
# then just returned that cached inverse (returns the inverse and exits the function here)
if (!is.null(inverseMatrix)){
message("returning cached inverse matrix")
return(inverseMatrix)
}
# if the inverse has not been calculated then calculate the inverse, set it, and return inverse of x
x$setInverse(solve(x$get())) # sets inverse in the special x object
## returns inverse of x as a matrix directly
x$getInverse()
}
| 92a2255ebfddac00cbd66b33bbde7f2b142e4012 | [
"R"
] | 1 | R | richard1111d/ProgrammingAssignment2 | 1594aa8de98411f0247e133bb6809e63f7e753b9 | 4b5a232901002b659f52e57162b1c67bd54b842e |
refs/heads/master | <file_sep># MNIST-recognition
The subject of the project is a comparison of deep learning algorithms in a system with a PLC controller.
Deep learning algorithms were built with the help of the Python language and Keras library.
CNNs were used to recognize images from the MNIST set and coupled to a system with a PLC controller.
The communication between the computer and PLC has been completed using the snap7 library.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 17:43:20 2019
@author: Przemek
"""
import keras
from keras.models import load_model
from matplotlib import pyplot as plt
import snap7
import snap7.client as c
from snap7.util import *
from time import sleep
#nawiazanie polaczenia ze sterownikiem
myplc = snap7.client.Client()
myplc.connect('192.168.0.1',0,1)
myplc.get_connected()
#wczytanie zapisanego modelu
model = load_model('CNN_model.h5')
#sprawdzenie cyfry image_index i predykcji modelu pred.argmax()
image_index = 500
fig = plt.figure()
plt.imshow(x_test[image_index].reshape(28, 28),cmap='gray', interpolation='none')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())
fig
#zmiana stanu wyjć cyfrowych w zaleznosci od rozpoznanego obrazu
if pred.argmax() == 0:
print("Zero")
print(pred.argmax())
WriteOutput(myplc,0,0,True)
sleep(3)
WriteOutput(myplc,0,0,False)
elif pred.argmax() == 1:
print("Jedynka")
print(pred.argmax())
WriteOutput(myplc,0,1,True)
sleep(3)
WriteOutput(myplc,0,1,False)
elif pred.argmax() == 2:
print("Dwójka")
print(pred.argmax())
WriteOutput(myplc,0,2,True)
sleep(3)
WriteOutput(myplc,0,2,False)
elif pred.argmax() == 3:
print("Trójka")
print(pred.argmax())
WriteOutput(myplc,0,3,True)
sleep(3)
WriteOutput(myplc,0,3,False)
elif pred.argmax() == 4:
print("Czwórka")
print(pred.argmax())
WriteOutput(myplc,0,4,True)
sleep(3)
WriteOutput(myplc,0,4,False)
elif pred.argmax() == 5:
print("Piątka")
print(pred.argmax())
WriteOutput(myplc,0,5,True)
sleep(3)
WriteOutput(myplc,0,5,False)
elif pred.argmax() == 6:
print("Szóstka")
print(pred.argmax())
WriteOutput(myplc,0,6,True)
sleep(3)
WriteOutput(myplc,0,6,False)
elif pred.argmax() == 7:
print("Siódemka")
print(pred.argmax())
WriteOutput(myplc,0,7,True)
sleep(3)
WriteOutput(myplc,0,7,False)
elif pred.argmax() == 8:
print("Ósemka")
print(pred.argmax())
WriteOutput(myplc,1,0,True)
sleep(3)
WriteOutput(myplc,1,0,False)
elif pred.argmax() == 9:
print("Dziewiątka")
print(pred.argmax())
WriteOutput(myplc,1,1,True)
sleep(3)
WriteOutput(myplc,1,1,False)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Jul 6 20:38:11 2019
@author: Przemek
"""
import tensorflow as tf
import keras
from keras.datasets import mnist
from matplotlib import pyplot as plt
from random import randint
#importowanie zbioru
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#wyswietla liczebnosc zbioru x i rozmiar zdjec
x_train.shape
print(x_train.shape)
print(y_test.shape)
#zmiana ksztaltu tablicy do 4-wymiarowej zeby mogla zeby mogla pracowac z KERAS
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
#upewniienie sie, ze wartosc jest zmiennoprzecinkowa aby mozna bylo uzyskac wartosci dziesietne po podziale
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
#normalizowanie wartosci RGB poprzez podzielenei przez maksymalna wartosc
x_train /= 255
x_test /= 255
#wyswietlanie liczby x_train i x_test
print('x_train shape: ', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])
#importowanie modulow z KERAS zawierajacych modele i warstwy
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
from keras.models import Sequential
#tworzenie sekwencyjnego modelu i dodawanie warstw
model = Sequential()
model.add(Conv2D(16,kernel_size=(3,3), input_shape=input_shape)) #liczba filtrów
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten()) #splaszczenie dwuwymiarowych tablic dla w pelni polaczonych warstw.
#Stosowany w celu zachowania wag przełączając model na inny format danych
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.5))
model.add(Dense(10,activation=tf.nn.softmax))
#kompilowanie i dopasowywanie modelu
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#trening algorytmu
history = model.fit(x=x_train,y=y_train,validation_split=0.2, epochs=12, batch_size=128)
#ocena modelu
model.evaluate(x_test, y_test)
#wywietlenie wykresów porównujących wartoci celnosci i bledy w treningu i
#walidacji
plt.subplot(2,1,1)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('trafnosc modelu')
plt.ylabel('trafnosc')
plt.xlabel('iteracje')
plt.legend(['trening','test'],loc='upper left')
plt.show()
plt.subplot(2,1,2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('blad modelu')
plt.ylabel('blad')
plt.xlabel('iteracje')
plt.legend(['trening', 'test'], loc='upper left')
plt.show()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 21:06:11 2019
@author: Przemek
"""
import snap7
import snap7.client as c
from snap7.util import *
def WriteOutput(dev, byte, bit, cmd):
data = dev.read_area(0x82,0,byte,1)
set_bool(data,byte,bit,cmd)
dev.write_area(0x82,0,byte,data)
| c479c01d5ac3af0e8ec30e463da621fdee14ec79 | [
"Markdown",
"Python"
] | 4 | Markdown | pbabulski/MNIST-recognition | a10c1bc6abac23ed303deecc7b5d80f53a694364 | 43601a121c14caac1f40a64972d32c6f3133fdd7 |
refs/heads/master | <repo_name>aicasas/BzztPodtaxi<file_sep>/FinalBzzt.R
'Bzzt Final Projct: <NAME>
Lines 5:110 are data cleaning, lines 110:133 are geocoding of ~26,000 datapoints. The cleaned code is
saved as BzztGeocode.csv and BzztGeocodeD.csv
and can be ran quickly from lines 139 and on'
data1 <- read.csv('201901.csv', header=FALSE)
data2 <- read.csv('201902.csv', header=FALSE)
data3 <- read.csv('201903.csv', header=FALSE)
#Combining Datasets by columns
data <- rbind(data1, data2, data3)
rm(data1, data2, data3)
#Deleting rows with missing entries
data[data==""] <- NA
data[data=="None"] <- NA
which(is.na(data))
data<- data[complete.cases(data),]
which(is.na(data))
#install.packages("stringr")
library(stringr)
#Data cleaning
#Split the first column by ; for time stamp at different stops
data <- data.frame(data,do.call(rbind,str_split(data$V1,";")))
data <- data.frame(data,do.call(rbind,str_split(data$V5,";")))
data <- data.frame(data,do.call(rbind,str_split(data$V3,";")))
#Deleting first columns that were split
data <- data[,-c(1, 3, 5, 14, 18)]
#Filling in column datasets that were not made included
names(data)[10] <- "OriginAddress"
names(data)[14] <- "DestinationAddress"
names(data)[3] <- "Code"
names(data)[4] <- "ActualOriginTS"
names(data)[5] <- "ActualDestinationTS"
names(data)[6] <- "EstimatedOriginTS"
names(data)[7] <- "EstimatedDestinationTS"
names(data)[8] <- "RideRequestTS"
names(data)[9] <- "RideAcceptedTS"
names(data)[1] <- "EstimatedEndAddress"
names(data)[11] <- "ZipCode"
names(data)[12] <- "ActualCost"
names(data)[13] <- "EstimatedCost"
names(data)[2] <- "EstimatedOriginAddress"
#Taking care of columns entries which do not match the others (inccorect entry of data, off from others)
data <- data[-grep("Stockholm", data$ZipCode), ]
data <- data[grep("[0-9]", data$EstimatedEndAddress), ]
data <- data[grep("[0-9]", data$EstimatedOriginAddress), ]
#Data cleaning for Date and Time Format
data$ActualOriginTS <- sub('([^+]+).*', '\\1', data$ActualOriginTS)
data$ActualDestinationTS <- sub('([^+]+).*', '\\1', data$ActualDestinationTS)
data$EstimatedOriginTS <- sub('([^+]+).*', '\\1', data$EstimatedOriginTS)
data$EstimatedDestinationTS <- sub('([^+]+).*', '\\1', data$EstimatedDestinationTS)
data$RideRequestTS <- sub('([^+]+).*', '\\1', data$RideRequestTS)
data$RideAcceptedTS <- sub('([^+]+).*', '\\1', data$RideAcceptedTS)
#Filling in NA
data[data==""] <- NA
data[data=="None"] <- NA
which(is.na(data))
data<- data[complete.cases(data),]
library(lubridate)
library(dplyr)
data$ActualOriginTS <- strptime(data$ActualOriginTS,format="%Y-%m-%dT%H:%M")
data$ActualDestinationTS <- strptime(data$ActualDestinationTS,format="%Y-%m-%dT%H:%M")
data$EstimatedOriginTS <- strptime(data$EstimatedOriginTS,format="%Y-%m-%dT%H:%M")
data$EstimatedDestinationTS <- strptime(data$EstimatedDestinationTS,format="%Y-%m-%dT%H:%M")
data$RideRequestTS <- strptime(data$RideRequestTS,format="%Y-%m-%dT%H:%M")
data$RideAcceptedTS <- strptime(data$RideAcceptedTS,format="%Y-%m-%dT%H:%M")
#Encoding Weekdays and Time to see which are the bussiest
data$Weekdayy <- (weekdays(data$ActualOriginTS))
data$Hour <- hour(data$ActualDestinationTS)
data$Month <- month(data$ActualDestinationTS)
#Plotting Number of rides taken on each day
data$Weekday <- factor(data$Weekday, levels=c("Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"))
freq_table <- table(data$Weekday)
margin.table(freq_table, 1)
plot(freq_table)
barplot(freq_table, main="Daily Ride Frequency",
xlab="Day of Week")
#Plotting the frequency desnity at different hours of the day
install.packages('ggpubr')
library(ggpubr)
d <- density(data$Hour)
plot(d, main="Ride Density: Hour of Day")
polygon(d, col="grey", border="blue")
freq_table2 <- table(data$Hour)
margin.table(freq_table2, 1)
plot(freq_table2)
#Plot shows that there is a peak around 8am and 5-6pm (commuter hours)
#####Applying K means to actual vs estimated cost
#######Here I begin Geocoding:##############
#There are too many addresses to generate 26,000 different geocoordinates
#I will look at just months 1:3 of data, specifically month 1 looks reasonable
sample <- data[grep("[1:3]", data$Month), ]
#install.packages("ggplot2")
library(ggplot2)
library(ggmap)
#Getting API
api <- "<KEY>" # Text file with the API key
register_google(key = api)
#concatenate the address
start_addy <- paste(sample$OriginAddress, "Stockholm, Sweden", sample$ZipCode)
end_addy <- paste(sample$DestinationAddress, "Stockholm, Sweden", sample$ZipCode)
# geocode - check for warnings
addys_coords <- geocode(start_addy)
end_addy_coords <- geocode(end_addy)
sample <- data.frame(cbind(sample, addys_coords))
sampleD <- data.frame(cbind(sample, end_addy_coords))
#write.csv(sample, file = "BzztGeocode.csv")
#write.csv(sampleD, file = "BzztGeocodeD.csv")
###########Here is the start of k means with coordinates############ Begin running from here ]:
#Cleaned data for Kmeans
#Kmeans for pick up location
bzzt <- read.csv("BzztGeocode.csv")
sample <- bzzt[,-c(1:16)]
sample$Weekday <- factor(sample$Weekday, levels=c("Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"), c(1:7))
sample <- sample[,4:5]
which(is.na(sample))
sample<- sample[complete.cases(sample),]
#removing outlier
#sample <- sample[-grep("-[0-9]", sample$lon), ]
#The elbow mehtod will help determine the number of clusters. This is the percent of variance
wcss = vector() #within cluster, sum of square. finding the closeness in the cluster
for (i in 1:10) wcss[i]= sum(kmeans(sample, i)$withinss)
plot(1:10, wcss, type='b', main=paste('The Elbow Method: Pick Up Locations'),
xlab = 'Number of Clusters',
ylab = 'WCSS')
#don't need feature scaling
#apply k-means
set.seed(42)
cluster <- kmeans(sample, 2)
sample$Borough <- factor(cluster$cluster)
ggplot(sample, aes(x=lat, y=lon, color=Borough)) + geom_point(shape=1)
#+ coord_cartesian(xlim = c(59.2, 59.4), ylim = c(17.8,18.3))
#+ coord_cartesian(xlim = c(57.2, 59.4), ylim = c(16,19))
#+ coord_cartesian(xlim = c(59.2, 59.4), ylim = c(17.8,18.3))
ggsave("pickupKmeans.png")
freq_table <- table(sample$Borough)
margin.table(freq_table, 1)
#install.packages('RgoogleMaps')
library(RgoogleMaps)
#data(sample)
col=as.numeric(sample$Borough)
par(pty="s")
plotmap(lat, lon, zoom = 13, col = col, pch=1, data = sample)
#Kmeans for drop off location
bzztD <- read.csv("BzztGeocodeD.csv")
sampleD <- bzztD[,-c(1:16)]
sampleD <- sampleD[,4:5]
which(is.na(sampleD))
sampleD<- sampleD[complete.cases(sampleD),]
#The elbow mehtod will help determine the number of clusters. This is the percent of variance
wcss = vector() #within cluster, sum of square. finding the closeness in the cluster
for (i in 1:10) wcss[i]= sum(kmeans(sampleD, i)$withinss)
plot(1:10, wcss, type='b', main=paste('The Elbow Method: Drop Off Locations'),
xlab = 'Number of Clusters',
ylab = 'WCSS')
#don't need feature scaling
#apply k-means
set.seed(42)
cluster <- kmeans(sampleD, 2)
sampleD$Borough <- factor(cluster$cluster)
ggplot(sampleD, aes(x=lat, y=lon, color=Borough)) + geom_point(shape=1) + coord_cartesian(xlim = c(59.32, 59.355), ylim = c(18,18.12))
ggsave("dropoffKmeans.png")
freq_table <- table(sampleD$Borough)
margin.table(freq_table, 1)
col=as.numeric(sampleD$Borough)
par(pty="s")
plotmap(lat, lon, zoom = 13, col = col, pch=1, data = sampleD)
<file_sep>/README.md
# BzztPodtaxi
This report contains an analysis of data on Bzzt Podtaxi, an ecofriendly transportation system in Stockholm, Sweden. An unsupervised machine learning technique, K-Means, is applied to identify boroughs throughout Stockholm based on a heat map of spatial coordinates
| f04bb052b9de5053f92f0d8b5d7c05bd91882e8c | [
"Markdown",
"R"
] | 2 | R | aicasas/BzztPodtaxi | ef1a693c3ac130dd8002f96fc59715c9ae510c27 | 86647e62a941a0b6058125965a0e7ec5df04632c |
refs/heads/master | <repo_name>TanumayDhar/greenkart2<file_sep>/target/cucumberReport/report.js
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("greenkartSearch.feature");
formatter.feature({
"line": 1,
"name": "Search for vegetables and place order in the application.",
"description": "",
"id": "search-for-vegetables-and-place-order-in-the-application.",
"keyword": "Feature"
});
formatter.background({
"line": 3,
"name": "",
"description": "",
"type": "background",
"keyword": "Background"
});
formatter.step({
"line": 4,
"name": "User navigated to the GreenKart landing page",
"keyword": "Given "
});
formatter.match({
"location": "Steps.user_navigated_to_the_greenkart_landing_page()"
});
formatter.result({
"duration": 10887457000,
"status": "passed"
});
formatter.scenario({
"line": 7,
"name": "Search for items and validate results.",
"description": "",
"id": "search-for-vegetables-and-place-order-in-the-application.;search-for-items-and-validate-results.",
"type": "scenario",
"keyword": "Scenario",
"tags": [
{
"line": 6,
"name": "@Smoke"
}
]
});
formatter.step({
"line": 8,
"name": "user searched for \"cucumber\" vegetable",
"keyword": "When "
});
formatter.step({
"line": 9,
"name": "\"Cucumber - 1 Kg\" results are displayed",
"keyword": "Then "
});
formatter.match({
"arguments": [
{
"val": "cucumber",
"offset": 19
}
],
"location": "Steps.user_searched_for_something_vegetable(String)"
});
formatter.result({
"duration": 3318723900,
"status": "passed"
});
formatter.match({
"arguments": [
{
"val": "Cucumber - 1 Kg",
"offset": 1
}
],
"location": "Steps.something_results_are_displayed(String)"
});
formatter.result({
"duration": 62875600,
"status": "passed"
});
formatter.after({
"duration": 124560600,
"status": "passed"
});
formatter.background({
"line": 3,
"name": "",
"description": "",
"type": "background",
"keyword": "Background"
});
formatter.step({
"line": 4,
"name": "User navigated to the GreenKart landing page",
"keyword": "Given "
});
formatter.match({
"location": "Steps.user_navigated_to_the_greenkart_landing_page()"
});
formatter.result({
"duration": 8635022900,
"status": "passed"
});
formatter.scenario({
"line": 12,
"name": "Search for items and navigate to check out page.",
"description": "",
"id": "search-for-vegetables-and-place-order-in-the-application.;search-for-items-and-navigate-to-check-out-page.",
"type": "scenario",
"keyword": "Scenario",
"tags": [
{
"line": 11,
"name": "@Regression"
}
]
});
formatter.step({
"line": 13,
"name": "user searched for \"brinjal\" vegetable",
"keyword": "When "
});
formatter.step({
"line": 14,
"name": "added items to cart",
"keyword": "And "
});
formatter.step({
"line": 15,
"name": "user proceed to checkout page for purchase",
"keyword": "And "
});
formatter.step({
"line": 16,
"name": "verify selected \"Brinjal - 1 Kg\" items are displayed in check out page",
"keyword": "Then "
});
formatter.match({
"arguments": [
{
"val": "brinjal",
"offset": 19
}
],
"location": "Steps.user_searched_for_something_vegetable(String)"
});
formatter.result({
"duration": 3263757800,
"status": "passed"
});
formatter.match({
"location": "Steps.added_items_to_cart()"
});
formatter.result({
"duration": 193722700,
"status": "passed"
});
formatter.match({
"location": "Steps.user_proceed_to_checkout_page_for_purchase()"
});
formatter.result({
"duration": 2209303500,
"status": "passed"
});
formatter.match({
"arguments": [
{
"val": "Brinjal - 1 Kg",
"offset": 17
}
],
"location": "Steps.verify_selected_something_items_are_displayed_in_check_out_page(String)"
});
formatter.result({
"duration": 2050887800,
"status": "passed"
});
formatter.after({
"duration": 115687900,
"status": "passed"
});
}); | 9dd7693f11cb5d0915108584834e3f16741139b7 | [
"JavaScript"
] | 1 | JavaScript | TanumayDhar/greenkart2 | 107339d9f933c49c6b18c3d0f683e770180d275a | 2aa7764e2c22ad5be2dd718e5c573158f6185234 |
refs/heads/main | <file_sep># FocusTextField
A TextField with a floating label using the new Focus system on iOS 15
<p float="left">
<img src="./Screenshots/Screenshot0.png" alt="Lock Screen" width=25% height=25%>
<img src="./Screenshots/Screenshot1.png" alt="Import Files" width=25% height=25%>
</p>
### Usage
Usage is as simple as importing `FocusTextField`, declaring a `@State` `String` variable, and initializing `FocusTextField` with a placeholder.
```swift
@import FocusTextField
...
@State var text: String = ""
...
FocusTextField(text: $text) {
Text("Placeholder")
}
```
### Features
* Use any view as the placeholder
* Set the placeholder scale
* Set the placeholder spacing
* Set the placeholder animation
### To Do
* Placeholder Active State
* Match keyboard animation curve (Maybe make animation not customizable?)
* Make Text Field customizable
### Known Bugs
* Animation looks a bit off when showing/hiding the keyboard
<file_sep>//
// Created by <NAME> on 14/6/21.
//
import SwiftUI
struct HeightPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
<file_sep>//
// ContentView.swift
// Shared
//
// Created by <NAME> on 14/6/21.
//
import SwiftUI
import FocusTextField
struct ContentView: View {
@State var text: String = ""
@FocusState public var isFocused: Bool
var body: some View {
ZStack(alignment: .center) {
Color.clear
VStack(spacing: 25) {
FocusTextField(text: $text, animation: .spring(), spacing: 5, placeholderScale: 0.5) {
Label("Enter your text...", systemImage: "square.and.pencil")
.opacity(0.5)
}
.focused($isFocused)
HStack {
Spacer()
Button(action: { isFocused = false }) {
Text("Unfocus")
}
.buttonStyle(BorderedButtonStyle(tint: .red))
Spacer()
Button(action: { isFocused = true }) {
Text("Focus")
}
.buttonStyle(BorderedButtonStyle(tint: .blue))
Spacer()
}
}
.padding()
.background(Color(.secondarySystemBackground))
.cornerRadius(10)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
<file_sep>//
// FocusTextField.swift
// FocusTextField
//
// Created by <NAME> on 14/6/21.
//
import SwiftUI
@available(iOS 15.0, *)
public struct FocusTextField<Placeholder: View>: View {
@FocusState private var isFocused: Bool
private var text: Binding<String>
private let placeholder: Placeholder
private let animation: Animation
private let placeholderScale: Double
private let spacing: Double
var activeOffset: Double {
spacing + placeholderHeight * placeholderScale
}
@State private var active: Bool = false
@State private var placeholderHeight: Double = 0
public init(text: Binding<String>, animation: Animation = .default, spacing: Double = 5, placeholderScale: Double = 0.5, @ViewBuilder placeholder: @escaping () -> Placeholder) {
self.text = text
self.placeholder = placeholder()
self.animation = animation
self.spacing = spacing
self.placeholderScale = placeholderScale
}
public var body: some View {
ZStack(alignment: .leading) {
TextField("", text: text)
.focused($isFocused)
placeholder
.background(
GeometryReader { proxy in
Color.clear
.preference(key: HeightPreferenceKey.self, value: proxy.size.height)
}
)
.scaleEffect(active ? placeholderScale : 1, anchor: .topLeading)
.offset(x: 0, y: active ? -activeOffset : 0)
.onTapGesture { isFocused = true }
}
.padding(.top, activeOffset)
.onChange(of: text.wrappedValue) { _ in updateActive() }
.onChange(of: isFocused) { _ in updateActive() }
.onPreferenceChange(HeightPreferenceKey.self) { height in
placeholderHeight = height
print(height)
}
}
func updateActive() {
withAnimation(animation) {
active = !text.wrappedValue.isEmpty || isFocused
}
}
}
@available(iOS 15.0, *)
struct FocusTextField_Previews: PreviewProvider {
static var previews: some View {
FocusTextField(text: .constant("")) {
Text("Placeholder")
}
.previewLayout(.fixed(width: 200, height: 80))
FocusTextField(text: .constant("Hello")) {
Text("Placeholder")
}
.previewLayout(.fixed(width: 200, height: 80))
}
}
| 7ae052a2dedb05ab85b37aeef12c8734b5fcb558 | [
"Markdown",
"Swift"
] | 4 | Markdown | TrendingTechnology/FocusTextField | fc8113798f6b7b232bd2a15f08a88cf22c7755c3 | b43b087c5a311bfd51287e69757ccfac869150ed |
refs/heads/master | <file_sep>package com.clunkybyte.apps.criminalintent;
import android.support.v4.app.Fragment;
/**
* Created by hybr1d on 6/29/2014.
*/
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
}
| 51b828ea13cb10bdf66625a86c811613334a1e39 | [
"Java"
] | 1 | Java | ervinb/CriminalIntent | c7445419dd3bf641af0ea5e7e0adbbad9b99a0af | 64ea80eed67678eea0abc5a5ebbe78baf3e3a5e2 |
refs/heads/master | <file_sep>import math
def main():
sum = 0
filename = "day1.txt"
for line in open(filename):
mass = int(line)
while mass > 0:
mass = max(math.floor(mass/3)-2,0)
sum += mass
print(sum)
if __name__ == "__main__":
main()
# 3279810 too low
# 4815102 too high
# 4812287<file_sep>import copy
def day2():
for line in open("day2.txt"):
program = list(map(int,line.split(",")))
for noun in range(100):
for verb in range(100):
result = run(copy.deepcopy(program),noun,verb)
if result == 19690720:
break
else:
continue
break
print(noun,verb)
def run(program,noun,verb):
program[1] = noun
program[2] = verb
pc = 0
while True:
if program[pc] == 1:
program[program[pc+3]] = program[program[pc+1]] + program[program[pc+2]]
elif program[pc] == 2:
program[program[pc+3]] = program[program[pc+1]] * program[program[pc+2]]
elif program[pc] == 99:
break
else:
raise ValueError('Unknown opcode')
pc = pc+4
return program[0]
if __name__ == "__main__":
day2()
#2692315
#9507<file_sep>def day4():
# 128392-643281
count = 0
stack = []
stack.append("")
while stack:
password = stack.pop()
for d in range(48,58):
nextpwd = password + chr(d)
if isNotInvalid(nextpwd):
if len(nextpwd) == 6:
if isValid(nextpwd):
count += 1
#print(nextpwd)
else:
stack.append(nextpwd)
print(count)
def isNotInvalid(password):
# check in range
minpwd = "<PASSWORD>"
if password < minpwd[:len(password)]:
return False
if password > "<PASSWORD>":
return False
# check for decrease
for i in range(len(password)-1):
if password[i] > password[i+1]:
return False
return True
def isValid(password):
# If exactly 2 of any element
last = 0
count = 0
for i in range(6):
if password[i] == last:
count += 1
else:
if count == 2: # previous number was a pair
return True
last = password[i]
count = 1
return count == 2 # check last pair
if __name__ == "__main__":
day4()
# 2050
# 992 too low
# 1412 too high
# 1390<file_sep>def day3():
file = open("day3.txt")
wire1 = file.readline().strip()
wire2 = file.readline().strip()
wire1 = wire1.split(",")
wire2 = wire2.split(",")
h1, v1 = getSegments(wire1, 1)
h2, v2 = getSegments(wire2, 2)
# for s in v2:
# print(s)
intersections = []
for s1 in h1:
for s2 in v2:
if intersect(s1,s2):
print(s1,s2)
print("Intersect at Line:", s1[3], "Col:", s2[3])
#intersections.append(abs(s1[2])+abs(s2[2]))
intersections.append(getStepsAtIntersection(s1,s2))
for s1 in h2:
for s2 in v1:
if intersect(s1,s2):
print(s1,s2)
print("Intersect at Line:", s2[3], "Col:", s1[3])
#intersections.append(abs(s1[2])+abs(s2[2]))
intersections.append(getStepsAtIntersection(s1,s2))
print(sorted(intersections))
#print(intersections)
def getSegments(paths,wire):
line = 0
column = 0
steps = 0
hsegments = []
vsegments = []
for path in paths:
length = int(path[1:])
if path[0] == 'R':
hsegments.append((wire,steps,'R',line,column,column+length))
column += length
elif path[0] == 'L':
hsegments.append((wire,steps,'L',line,column-length,column))
column -= length
elif path[0] == 'U':
vsegments.append((wire,steps,'U',column,line-length,line))
line -= length
elif path[0] == 'D':
vsegments.append((wire,steps,'D',column,line,line+length))
line += length
steps += length
#hsegments = sorted(hsegments, key=lambda x: x[3])
#vsegments = sorted(vsegments, key=lambda x: x[3])
return hsegments, vsegments
def intersect(s1, s2):
# line/column might be reversed
# bus s1 should be horizontal line, s2 vertical
line1 = s1[3]
lines2 = (s2[4], s2[5])
col2 = s2[3]
cols1 = (s1[4], s1[5])
return line1 >= lines2[0] and line1 <= lines2[1] and col2 >= cols1[0] and col2 <= cols1[1]
def getStepsAtIntersection(s1,s2):
# s1 is horizontal line, s2 vertical
line = s1[3]
col = s2[3]
if s1[2] == 'R':
s1steps = s1[1] + (col-s1[4])
elif s1[2] == 'L':
s1steps = s1[1] + (s1[5]-col)
if s2[2] == 'U':
s2steps = s2[1] + (s2[5]-line)
elif s2[2] == 'D':
s2steps = s2[1] + (line-s2[4])
print(s1steps, " steps, ", s2steps, " steps")
return s1steps + s2steps
if __name__ == "__main__":
day3()
# segments: wire, horizontal/vertical, line/column, start, end
# 651
# 7534 | 57f162dee81345b73dee6dff4518dc56811f1824 | [
"Python"
] | 4 | Python | neilguertin/Advent-of-Code-2019 | 8edafc6e11dc52ce565d12002316f79d5a6d9a87 | 5f57afc0fcebc8866a7cc0fc90df59575277f8c0 |
refs/heads/master | <file_sep>function deleteItem(e){
}
function getPriceByProduct(itemNode){
var price = document.getElementById('product1').innerHTML;
price = price.slice(1);
return price;
}
function updatePriceByProduct(productPrice, index){
}
function getTotalPrice() {
console.log( getPriceByProduct() * createQuantityInput());
return getPriceByProduct() * createQuantityInput();
}
function createQuantityInput(){
var quantity = document.getElementById('quant1').value;
console.log(quantity);
if (quantity === ''){
alert('Debes introducir un número');
return;
}
return parseInt(quantity);
}
function createDeleteButton(){
}
function createQuantityNode(){
var totalPrice = getTotalPrice();
document.getElementById('total').innerHTML = totalPrice;
}
function createItemNode(dataType, itemData){
}
function createNewItemRow(itemName, itemUnitPrice){
}
function createNewItem(){
}
window.onload = function(){
var calculatePriceButton = document.getElementById('calc-prices-button');
var inputPrice = document.getElementById('quant1');
var createItemButton = document.getElementById('new-item-create');
var deleteButtons = document.getElementsByClassName('btn-delete');
calculatePriceButton.onclick = getTotalPrice;
//inputPrice.onchange = document.getElementById('total').innerHTML(getTotalPrice());
inputPrice.onchange = createQuantityNode;
// createItemButton.onclick = createNewItem;
for(var i = 0; i<deleteButtons.length ; i++){
deleteButtons[i].onclick = deleteItem;
}
};
| 00fdbc9a3d70b87885e39a285d6e3e36ff2fa2f8 | [
"JavaScript"
] | 1 | JavaScript | agdwm/lab-dom-ironhack-cart | a6784fbf93d6cc1eeacabe228c9a475a6b49de6a | 089ef6facbdc5a7abaac6220f468cb27aa310e83 |
refs/heads/master | <repo_name>lkorchnoy/react_project<file_sep>/free_time_api/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Video.create(category: "Music", description: "Classical", link: "https://www.youtube.com/watch?v=9E6b3swbnWg", creator: "Chopin")
Video.create(category: "Music", description: "Classic Rock", link: "https://www.youtube.com/watch?v=CTJrBffpWBY", creator: "The Beatles")
Video.create(category: "Music", description: "Classic Rock", link: "https://www.youtube.com/watch?v=m2uTFF_3MaA", creator: "The Beatles")
Video.create(category: "Music", description: "Classic Rock", link: "https://www.youtube.com/watch?v=FVovq9TGBw0", creator: "Ozzy Osbourne")
Video.create(category: "Music", description: "Classic Rock", link: "https://www.youtube.com/watch?v=ABSXJiYQFuI", creator: "<NAME>")
Video.create(category: "Music", description: "Classic Rock", link: "https://www.youtube.com/watch?v=yKvIBkr6RZs", creator: "<NAME>")
Comment.create(content: "Great music", video_id: 1)
Comment.create(content: "Awesome", video_id: 2)
Comment.create(content: "Super", video_id: 3)
Comment.create(content: "Great music", video_id: 4)
Comment.create(content: "Awesome", video_id: 5)
Comment.create(content: "Super", video_id: 6)
<file_sep>/free_time_api/test/controllers/videos_controller_test.rb
require 'test_helper'
class VideosControllerTest < ActionDispatch::IntegrationTest
setup do
@video = videos(:one)
end
test "should get index" do
get videos_url, as: :json
assert_response :success
end
test "should create video" do
assert_difference('Video.count') do
post videos_url, params: { video: { category: @video.category, description: @video.description, linkcreator: @video.linkcreator } }, as: :json
end
assert_response 201
end
test "should show video" do
get video_url(@video), as: :json
assert_response :success
end
test "should update video" do
patch video_url(@video), params: { video: { category: @video.category, description: @video.description, linkcreator: @video.linkcreator } }, as: :json
assert_response 200
end
test "should destroy video" do
assert_difference('Video.count', -1) do
delete video_url(@video), as: :json
end
assert_response 204
end
end
<file_sep>/free_time_client/src/components/VideosContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Switch, Route } from 'react-router-dom'
import { fetchVideos } from '../actions/videosActions'
import VideosDetails from './VideosDetails'
import VideosList from './VideosList'
import VideosForm from './VideosForm'
import './Videos.css'
import Image from '../image.jpg'
class VideosContainer extends Component {
componentDidMount() {
this.props.fetchVideos()
}
render() {
return (
<>
<div className="container">
<img src={Image} alt="An image"/>
<VideosList />
<VideosForm />
</div>
</>
);
}
}
const mapStateToProps = ({ videos }) => ({ videos })
export default connect(mapStateToProps, { fetchVideos })(VideosContainer);
<file_sep>/free_time_client/src/components/VideosForm.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { addVideo } from '../actions/videosActions'
class VideosForm extends Component {
state = {
category: '',
description: '',
link: '',
creator: ''
};
handleChange = event => {
const { name, value } = event.target
this.setState({
[name]: value
})
}
handleSubmit = event => {
event.preventDefault()
this.props.addVideo(this.state)
this.resetForm()
}
resetForm = () => {
this.setState({
category: '',
description: '',
link: '',
creator: ''
})
}
render() {
console.log(this.state.creator)
return (
<div className="videos">
<form onSubmit={ this.handleSubmit }>
<label>category:</label>
<input type='text' value={this.state.category} onChange={this.handleChange} name="category"/>
< br />
<label>description:</label>
<input type='text' value={this.state.description} onChange={this.handleChange} name="description"/>
< br />
<label>link:</label>
<input type='text' value={this.state.link} onChange={this.handleChange} name="link"/>
< br />
<label>creator:</label>
<input type='text' value={this.state.creator} onChange={this.handleChange} name="creator"/>
< br />
<input type='submit' value="Create Video" />
</form>
</div>
);
}
}
export default connect(null, { addVideo })(VideosForm);
<file_sep>/free_time_client/src/reducers/rootReducer.js
import { combineReducers } from 'redux'
import { commentsReducer } from './commentsReducer'
import { videosReducer } from './videosReducer'
import { selectedVideoReducer } from './videosReducer'
//import { commentsReducer } from './commentsReducer'
export const rootReducer = combineReducers({
videos: videosReducer,
selectedVideo: selectedVideoReducer,
comments: commentsReducer
})<file_sep>/README.md
# react_project
Free time is my React-Redux Project.
Free time is a tech app. Create and share your music videos on Free Time App. Have an awesome time with Free Time!
<file_sep>/free_time_client/src/actions/commentsActions.js
export const fetchComments = () => {
return (dispatch) => {
fetch('http://127.0.0.1:3000/comments')
.then(resp => resp.json())
.then(comments => dispatch({ type: 'FETCH_COMMENTS', payload: comments }))
}
}
export const addComment = comment => {
//debugger;
return dispatch => {
fetch('http://127.0.0.1:3000/comments', {
method: 'POST',
body: JSON.stringify(comment),
headers: { 'Content-Type': 'application/json'}
})
.then(resp => resp.json())
.then(comment => dispatch({ type: 'ADD_COMMENT', payload: comment }))
}
}
<file_sep>/free_time_client/src/components/Navbar.js
import React from 'react';
class Navbar extends React.Component{
render() {
return (
<div className="Header">
<ul id="nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/form">Form</a></li>
</ul>
</div>
);
}
}
export default Navbar;
<file_sep>/free_time_client/src/components/Routing.js
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom'
import { connect } from 'react-redux'
import Home from './Home'
import About from './About'
import VideosContainer from './VideosContainer'
import VideosForm from './VideosForm'
import VideosDetails from './VideosDetails'
//import { fetchVideos } from '../actions/videosActions'
class Routing extends Component {
render() {
//debugger;
return (
<>
<Switch>
<Route exact path='/' component={VideosContainer} />
<Route exact path='/about' component={About} />
<Route path='/form' component={VideosForm} />
{/* <Route exact path="/videos/:id" component={VideosDetails} /> */}
<Route path="/videos/:id" render={() =>
<VideosDetails videos={this.props.videos} />}
/>
</Switch>
</>
);
}
}
const mapStateToProps = ({ videos }) => ({ videos })
export default connect(mapStateToProps)(Routing);
<file_sep>/free_time_client/src/components/VideosDetails.js
import React from 'react';
import { connect } from "react-redux";
import { useParams } from "react-router-dom"
import CommentsContainer from './CommentsContainer';
import VideosList from './VideosList'
const VideosDetails = (props) => {
console.log("props in VideosDetails", props)
const { id } = useParams()
const vid = props.videos.find(v =>
v.id === parseInt(id))
if (props.videos.length === 0)
return null
return (
<div className="details-container" style={{ width: "60%" }}>
<h1>Free Time App</h1>
<div className="properties">
<p>Category: {vid.category}</p>
<p>Description: {vid.description}</p>
<p>
Link: <a target="_blank" href={vid.link}>{vid.link}</a>
</p>
<p>Creator: {vid.creator}</p>
<CommentsContainer videoId={vid.id}/>
</div>
</div>
);
}
export default VideosDetails;
<file_sep>/free_time_client/src/components/VideosList.js
import React from 'react';
import { connect } from 'react-redux'
import { selectVideo } from '../actions/videosActions'
import { Link } from 'react-router-dom'
const VideosList = (props) => {
const listItems = props.videos.map((video) => {
return <div key={video.id} className="vidList">
<Link to={`/videos/${video.id}`}>{video.creator}</Link>
</div>
})
return (
<div className="list-container">
<h2>Video List</h2>
<ul>
{listItems}
</ul>
</div>
)
}
const mapStateToProps = state => {
return {
videos: state.videos
}
}
const mapDispatchToProps = {
selectVideo: selectVideo
}
export default connect(mapStateToProps, mapDispatchToProps)(VideosList);
<file_sep>/free_time_client/src/actions/videosActions.js
export const fetchVideos = () => {
return (dispatch) => {
fetch('http://127.0.0.1:3000/videos')
.then(resp => resp.json())
.then(videos => dispatch({ type: 'FETCH_VIDEOS', payload: videos }))
}
}
export const selectVideo = (video) => {
return {
type: 'VIDEO_SELECTED',
payload: video
}
}
export const addVideo = video => {
return dispatch => {
fetch('http://127.0.0.1:3000/videos', {
method: 'POST',
body: JSON.stringify(video),
headers: { 'Content-Type': 'application/json'}
})
.then(resp => resp.json())
.then(video => dispatch({ type: 'ADD_VIDEO', payload: video }))
}
}<file_sep>/free_time_client/README.md
README
Free time is my React-Redux Project.
Free time is a new age technology app. Create and share your music videos on Free Time App. Have an awesome time with Free Time!
Installing
You can clone this repo with SSH or HTTPS https://github.com/lkorchnoy/react_project.git
or open it by typing the below into your terminal
git clone https://github.com/lkorchnoy/react_project.git
Usage
Create and share your music videos.
Contributing
Bug reports and pull requests are welcome on GitHub at
https://github.com/lkorchnoy/react_project.git
License
The repository is available as open source under the terms of the MIT License https://github.com/lkorchnoy/react_project/blob/master/LICENSE
Code of Conduct
Everyone interacting in the project’s codebases, issue trackers are expected to follow the code of conduct.
Tech information:
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start` or 'npm start'
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
| b76006fb2267f9c05475c886198290fc92a8425c | [
"JavaScript",
"Ruby",
"Markdown"
] | 13 | Ruby | lkorchnoy/react_project | 19f8623bf1eba76dfd2f239d960b49cfb604d040 | b2671fb2b1d01d3d87918addaad9b02b74d2993c |
refs/heads/main | <file_sep>const cartContainer = document.querySelector('.cart-container')
const productoLista = document.querySelector('.producto-lista')
const cartLista = document.querySelector('.cart-lista');
const cartTotalValue = document.getElementById('cart-total-value');
const cartCountInfo = document.getElementById('cart-count-info');
let cartItemID = 1;
openNavbar()
function openNavbar(){
window.addEventListener('DOMContentLoaded', () => {
loadJSON();
cargarCarrito()
});
// Al hacer click en button menu se desplega
document.querySelector('.navbar-toggler').addEventListener('click', () => {
document.querySelector('.navbar-collapse').classList.toggle('show-navbar');
});
// show/hide cart container
document.getElementById('cart-btn').addEventListener('click', () => {
cartContainer.classList.toggle('show-cart-container');
});
//añadir al carrito
productoLista.addEventListener('click', purchaseProduct);
//borrar del carrito
cartLista.addEventListener('click', borrarProducto);
}
// subir carrito informacion
function subirCarrito(){
let cartInfo = findCartInfo();
cartCountInfo.textContent = cartInfo.productoContador;
cartTotalValue.textContent = cartInfo.total;
}
//CARGANDO PRODUCTO ITEM CONTENIDO DE ARCHIVO JSON
function loadJSON(){
fetch('https://my-json-server.typicode.com/fersanabria8/cervezafsAPI/product')
.then(response => response.json())
.then(data =>{
let html = '';
data.forEach(product => {
html+= `
<div class="producto-item">
<div class="producto-img">
<img src="${product.img}" alt="honey2">
<button type="button" class="add-carrito-btn"><i class="fas fa-shopping-cart"></i>Añadir al carrito
</button>
</div>
<div class="producto-contendio">
<h3 class="producto-nombre">${product.nombre}</h3>
<span class="producto-categoria">${product.tag}</span>
<p class="prducto-precio">$${product.precio}</p>
</div>
</div>
`;
});
productoLista.innerHTML = html;
})
.catch(error => {
alert(`Feeeeeeeeer`);
})
}
//purchaseProduct comprarproducto de la lista
function purchaseProduct(e){
if(e.target.classList.contains('add-carrito-btn')){
let product = e.target.parentElement.parentElement;
getProductInfo(product);
}
}
///////////////////////////////////
//despues de añadir al carrito boton click
function getProductInfo(product){
let productInfo = {
id: cartItemID,
img: product.querySelector('.producto-img img').src,
nombre: product.querySelector('.producto-nombre').textContent,
tag: product.querySelector('.producto-categoria').textContent,
precio: product.querySelector('.prducto-precio').textContent
}
cartItemID++ // incrementa
// console.log(productInfo);
addToCartList(productInfo);
guardarProductoStorage(productInfo);
}
// Añadir el producto seleccionado a la lista del carrito
function addToCartList(product){
const cartItem = document.createElement('div');
cartItem.classList.add('cart-item');
cartItem.setAttribute('data-id', `${product.id}`);
cartItem.innerHTML = `
<img src="${product.img}" alt="honey">
<div class="cart-item-info">
<h3 class="cart-item-nombre">${product.nombre}</h3>
<span class="cart-item-categoria">${product.tag}</span>
<span class="cart-item-precio">$${product.precio}</span>
</div>
<button type="button" class="cart-item-del-btn">
<i class="fas fa-times"></i>
</button>
`;
cartLista.appendChild(cartItem);
}
// Guardar producto en local Storage.
function guardarProductoStorage(item){
let productos = getProductoDeStorage();
productos.push(item);
localStorage.setItem('productos', JSON.stringify(productos));
subirCarrito();
}
//Agarrar todos los productos info de algun local storage.
function getProductoDeStorage(){
return localStorage.getItem('productos')?JSON.parse
(localStorage.getItem('productos')): [];
//retorna array vacio si no tiene algun producto.
}
//Cargar productoCarrito
function cargarCarrito(){
let productos = getProductoDeStorage();
if(productos.length < 1){
cartItemID = 1; // Si el carrito no tiene productos en el local storage
} else {
cartItemID = productos[productos.length - 1].id;
cartItemID++;
// sino, obtiene la id del producto y lo incrementa.
}
// console.log(cartItemID); ver en consola el aumento
productos.forEach(product => addToCartList(product));
//calcular y subir
subirCarrito()
}
// Calcular el total
function findCartInfo(){
let productos = getProductoDeStorage();
let total = productos.reduce((acc, product) => {
let precio = parseFloat(product.precio.substr(1)); //borrar precio
return acc += precio;
}, 0); // añadir todos los precios
return{
total: total.toFixed(2),
productoContador: productos.length // añade productos al contador
}
}
// borrar prodcuto de lista
function borrarProducto(e){
let cartItem;
if(e.target.tagName === "BUTTON"){
cartItem = e.target.parentElement;
cartItem.remove(); // borra solo desde DOM
}else if(e.target.tagName === "I"){
cartItem = e.target.parentElement.parentElement;
cartItem.remove(); // borra solo desde DOM
}
let productos = getProductoDeStorage();
let subirProductos = productos.filter(product => {
return product.id !== parseInt(cartItem.dataset.id);
});
localStorage.setItem('productos', JSON.stringify(subirProductos));// subir producto lista despúes de borrar
subirCarrito();
} | e93cee1969132512df3356d318e75607b6111258 | [
"JavaScript"
] | 1 | JavaScript | fersanabria8/cervezafs | a1b0fddde14e40d145872b490e477378cacfcd62 | 484e4633bbccaa7234639a5160a79fa3e41720bc |
refs/heads/master | <file_sep>from helpers import alphabet_position,rotate_character
def encrypt(text,key):
encrypted=[]
starting_index = 0
for letter in text:
rotation=alphabet_position(key[starting_index])
if letter.isalpha():
encrypted.append(rotate_character(letter,rotation))
else:
encrypted.append(letter)
if starting_index==(len(key)-1):
starting_index=0
else:
starting_index+=1
return ''.join(encrypted)
def main():
mytext=input("your text")
try:
myrot=input("put a clave")
if myrot.isalpha():
print(encrypt(mytext,myrot))
except ValueError:
print("Opps! That's not a valid number.Try again")
main()
if __name__=="__main__":
main()
<file_sep>from helpers import alphabet_position,rotate_character
def rotate_string_13(text):
rotated = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in text:
rotated_idx = (alphabet_position(char) + 13) % 26
if char.isupper():
rotated = rotated + alphabet[rotated_idx].upper()
else:
rotated = rotated + alphabet[rotated_idx]
return rotated
def rotate_string(text, rot):
rotated = ''
for char in text:
if (char.isalpha()):
rotated = rotated + rotate_character(char, rot)
else:
rotated = rotated + char
return rotated
def main():
from sys import argv, exit
avg=["5"]
print("This is what the user typed on the command line:", argv)
text=input("Type a message")
try:
rot=int(input("Rotate by"))
if rot.is_digit():
print(rotate_string(text,rot))
except ValueError:
print("Opps! That's not a valid number.Try again")
main()
if __name__=="__main__":
main()
| 2f8ae914249cf9e1e6cb7e6d57776f27a32663bc | [
"Python"
] | 2 | Python | lcantillo00/lc101 | 57cbeb933cbfc977f7a6e4dbc257f5ef5cb56936 | f48de2418a06d2684747ca9180595989f34ae2b7 |
refs/heads/master | <repo_name>lqwwql/GoRepository<file_sep>/src/dbconn/dbconn_test.go
package dbconn
import (
"fmt"
"testing"
)
func Test_Dbconn(t *testing.T){
user := User{}
user.Id = 1
user.Name = "去死吧"
user.ProfileId = 666
InitDB()
//result :=user.InsertUserToDb()
//result := DeleteUserFromDB(2)
//result := user.UpdateUserToDB()
//result := QueryUserBYID(1)
//result := QueryAllUser()
result := TestTimeBetween()
fmt.Println(result)
}<file_sep>/src/network/HttpPost.go
package network
import (
"net/http"
"fmt"
"io/ioutil"
"net/url"
"strings"
"encoding/json"
"encoding/base64"
)
/*图片识别文字*/
func HttpDo(filePath string) (str string,err error) {
//图片转换base64
base64img, err := TurnToBase64(filePath)
if err != nil {
fmt.Println("img turn err = ", err)
return str,err
}
//构建httpClient
client := &http.Client{}
//鉴权token,有效期一个月,start:2018/9/18
accessToken := "24.39e76639c0acfd0ea01849a4f908366e.2592000.1539828022.282335-14219223"
//百度云文字识别api
imgUrl := "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" + "?access_token=" + accessToken
//请求体body参数
var bodyInfo = url.Values{}
bodyInfo.Add("image_type", "BASE64")
bodyInfo.Add("image", base64img)
bodyInfo.Add("user_id", "1234")
bodyInfo.Add("group_id", "123")
data := bodyInfo.Encode()
//构造request请求
request, err := http.NewRequest("POST", imgUrl, strings.NewReader(data))
if err != nil {
fmt.Println("request create err:", err)
return str,err
}
//设置请求头部
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//发送请求,返回结果
response, err := client.Do(request)
//使用完毕关闭流
defer response.Body.Close()
//读取返回结果json
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return str,err
}
//构造结构体获取json数据拼接所有文字
resultInfo := ResultInfo{}
err = json.Unmarshal(body, &resultInfo)
if err != nil {
return str,err
}
for _, word := range resultInfo.WordsResult {
str += word.Words
}
return str,err
}
func TurnToBase64(filePath string) (base64img string, err error) {
ff, err := ioutil.ReadFile(filePath)
base64img = base64.StdEncoding.EncodeToString(ff)
return base64img, err
}
type ResultInfo struct {
LogId int64 `json:"log_id"`
WordsResultNum int `json:"words_result_num"`
WordsResult []WordsResult `json:"words_result"`
}
type WordsResult struct {
Location struct {
Width int `json:"width"`
Top int `json:"top"`
Left int `json:"left"`
Height int `json:"height"`
} `json:"location"`
Words string `json:"words"`
}
<file_sep>/src/channels/channelsMain.go
package channels
import (
"fmt"
"github.com/labstack/gommon/log"
"io"
"net"
"os"
)
//发送与接受 : <-
func main(){
conn,err := net.Dial("tcp","localhost:8000")
if err!=nil{
log.Fatal(err)
}
done := make(chan struct{})
go func (){
io.Copy(os.Stdout,conn)
log.Printf("done")
done <- struct{}{}
}()
mustCopy(conn,os.Stdin)
conn.Close()
<-done
}
func mustCopy (dst io.Writer,src io.Reader) {
if _,err := io.Copy(dst,src);err!=nil {
log.Fatal(err)
}
}
func TestChannel(){
ch := make(chan int , 10)
x := <-ch
fmt.Println(x)
ch <- 11
ch <- 23
close(ch)
fmt.Println(ch)
x,ok := <- ch
fmt.Println(x,ok)
}<file_sep>/src/myFlag/myFlat.go
package myFlag
import (
"flag"
"fmt"
)
//命令行读取参数
func TestFlagPackage(){
username := flag.String("name","","Input your name")
age := flag.Int("age",0,"Input your age")
flag.Parse()
fmt.Printf("name = %s , age = %d \n",*username,*age)
}
<file_sep>/src/goroutine/netcat.go
package goroutine
import (
"github.com/labstack/gommon/log"
"io"
"net"
"os"
)
func main() {
conn,err := net.Dial("tcp","localhost:8080")
if err!=nil{
log.Fatal(err)
}
defer conn.Close()
mustCopy(os.Stdout,conn)
}
func mustCopy (dst io.Writer,src io.Reader) {
if _,err := io.Copy(dst,src);err!=nil {
log.Fatal(err)
}
}
<file_sep>/src/dbconn/mysqlconn.go
package dbconn
import (
"aimsg_server/src/client"
"database/sql"
"fmt"
//_ "github.com/go-sql-driver/mysql"
"strings"
)
const(
username = "root"
password = ""
ip = "172.16.0.216"
port = "3306"
dbname = "aimsg"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
ProfileId int `json:"profile_id"`
}
var DB *sql.DB
func InitDB (){
//构建链接
dbPath := strings.Join([]string{username,":",password,"@tcp(",ip,":",port,")/",dbname,"?charset=utf8"},"")
fmt.Printf("dbPath = %s \n",dbPath)
//打开数据库
DB , _ = sql.Open("mysql",dbPath)
//设置最大连接数
DB.SetConnMaxLifetime(100)
//设置最大闲置连接数
DB.SetMaxIdleConns(10)
if err := DB.Ping();err != nil {
fmt.Printf("ping mysql err = %s \n",err)
return
}
fmt.Println("connect mysql success")
}
func TestTimeBetween()(err error){
appid := "guruselfcontact"
sql := "SELECT * FROM `client` " +
"WHERE JSON_EXTRACT(`extra_info`,'$.context.appid') = '" + appid +
"' and unix_timestamp(`create_time`) between unix_timestamp('2017-05-01 01:01:01') and unix_timestamp('2018-12-01 01:01:01')"
var client client.Client
fmt.Println(sql)
err = DB.QueryRow(sql).Scan(&client.Username,&client.PtId,&client.ClientId,&client.CustomerId,&client.CreateTime,&client.Status,&client.ExtraInfoString)
if err!=nil{
fmt.Printf("query sql errr = %s \n",err)
}
fmt.Printf("app = %+v \n",client)
return
}
func (user *User) InsertUserToDb()bool{
//开启事务
tx,err := DB.Begin()
if err!=nil{
fmt.Printf("db.begin err = %s \n",err)
return false
}
//sql
stmt,err := tx.Prepare("INSERT INTO `user` (`name`,`profile_id`) VALUES (?,?)")
if err!=nil{
fmt.Printf("prepare sql err = %s \n",err)
return false
}
res,err := stmt.Exec(user.Name,user.ProfileId)
if err!=nil{
fmt.Printf("stmt exec err = %s \n",err)
return false
}
//事务提交
tx.Commit()
//返回自增ID
fmt.Println(res.LastInsertId())
return true
}
func DeleteUserFromDB(id int)bool{
tx,err := DB.Begin()
if err!=nil {
fmt.Printf("db.begin err= %s \n",err)
return false
}
stmt,err := tx.Prepare("DELETE FROM `user` WHERE `id` = ?")
if err!=nil {
fmt.Printf("prepare sql err = %s \n",err)
return false
}
res,err := stmt.Exec(id)
if err!=nil {
fmt.Printf("exec sql err = %s \n ",err)
return false
}
tx.Commit()
fmt.Println(res.LastInsertId())
return true
}
func (user *User)UpdateUserToDB()bool{
tx,err := DB.Begin()
if err!=nil {
fmt.Printf("db.begin err= %s \n",err)
return false
}
stmt,err := tx.Prepare("UPDATE `user` SET `name`=? ,`profile_id`=? WHERE `id` = ?")
if err!=nil {
fmt.Printf("prepare sql err = %s \n",err)
return false
}
res,err := stmt.Exec(user.Name,user.ProfileId,user.Id)
if err!=nil {
fmt.Printf("exec sql err = %s \n ",err)
return false
}
tx.Commit()
fmt.Println(res.LastInsertId())
return true
}
func QueryUserBYID(id int)(user User){
err := DB.QueryRow("SELECT * FROM `user` WHERE `id`=? ",id).Scan(&user.Id,&user.Name,&user.ProfileId)
if err!=nil{
fmt.Printf("query sql errr = %s \n",err)
}
return
}
func QueryAllUser()(userList []User){
rows,err := DB.Query("SELECT * FROM `user`")
if err!=nil{
fmt.Printf("query sql errr = %s \n",err)
}
for rows.Next() {
var user User
err := rows.Scan(&user.Id,&user.Name,&user.ProfileId)
if err!=nil {
fmt.Printf("rows.scan err = %s \n",err)
}
userList = append(userList, user)
}
return
}<file_sep>/src/goroutine/goroutine_test.go
package goroutine
import "testing"
func Test_goroutineMain(t *testing.T){
GoroutineMain()
}
<file_sep>/src/myreflect/reflect.go
package myreflect
import (
"fmt"
"io"
"os"
"reflect"
)
func ReflectTest(){
//t := reflect.TypeOf(3)
//fmt.Println(t.String())
//fmt.Println(t)
var w io.Writer = os.Stdout
fmt.Println(reflect.TypeOf(w))
}
<file_sep>/src/main/main.go
package main
import (
"fmt"
"grutils/grmath"
_ "net/http/pprof"
"os"
"reflect"
"strconv"
"strings"
"time"
)
type StringS struct {
Name string `json:"name"`
}
func main() {
//network.HttpDo("C://123.jpg")
//fmt.Println(time.Now().Format("20060102"))
//str := fmt.Sprintf("已兑换%v积分,若未收到红包请联系客服!",0.01)
//fmt.Println(str)
//fmt.Println(fmt.Sprintf("%.2f",13.005))
//numString := "0.4.2.5.5"
//index := strings.Index(numString,".")
//fmt.Printf("index = %x \n",index)
//fmt.Printf("subStr := %s \n",grcommon.SubStrOnBytes(numString,0,index+3))
//goroutine.GoroutineMain()
//testScanf()
//test()
//channels.TestChannel()
//getFileName("C:\\Users\\admin\\Desktop\\error.txt")
//isImage("error.PNGs")
//ifContainKey("cageageahea","b","a")
//testTimeFormat()
//testFmtFormat()
//network.NetWorkProgram()
//var i = 11
//fmt.Printf("i = %3d0",i)
//result := fmt.Sprintf("%03d",i)
//
//fmt.Println(result)
//imsiHeader := ""
//imsiSql := "AND 1=1 "
//if imsiHeader != "" {
// imsiSql = strings.Join([]string{imsiSql," AND `imsi` LIKE '",imsiHeader,"%'"},"")
//}
//fmt.Printf("imsiSql = %s",imsiSql)
//myreflect.ReflectTest()
//stringToInt("12345")
//myFlag.TestFlagPackage()
//dbconn.InitDB()
//testStringTo01()
saveToFile()
}
func testStringTo01(){
str := "nmsl"
fmt.Println([]byte(str))
}
func saveToFile(){
fileName := "test.dat"
dstFile,err := os.Create(fileName)
if err!=nil{
fmt.Println(err.Error())
return
}
defer dstFile.Close()
s:="hello world"
dstFile.WriteString(s + "\n")
}
func testSlice(){
slicea := []int{1,2,3,4}
fmt.Println(slicea)
changeSlice(&slicea)
fmt.Println(slicea)
}
func changeSlice(slicea *[]int){
sliceb := []int{1,2,3}
*slicea = sliceb
}
func stringToInt(str string){
var result int
for i:=0;i<len(str);i++ {
s,_:= strconv.Atoi(string(str[i]))
fmt.Println(s)
result += s
}
fmt.Println(result)
}
func testFmtFormat(){
val := []int{1,2,3}
fmt.Printf("%v,%T \n",val,val)
fmt.Println(reflect.TypeOf(val))
fmt.Printf("%p,%p,%p,%p \n",val,val[0],val[1],val[2])
fmt.Printf("%p,%p,%p,%p \n",&val,&val[0],&val[1],&val[2])
}
func testTimeFormat() {
//转化为时间戳 类型是int64
//时间戳转日期
dataTimeStr := time.Unix(1420041600, 0).Format(grmath.DATETIME_FORMAT) //设置时间戳 使用模板格式化为日期字符串
fmt.Println(dataTimeStr)
}
func ifContainKey(key ... string) {
fmt.Printf("lenth = %d ", len(key))
}
func isImage(fileName string) bool {
start := strings.Index(fileName, ".") + 1
end := len(fileName)
suffix := substring(fileName, start, end)
fmt.Println(suffix)
if strings.EqualFold(suffix, "png") || strings.EqualFold(suffix, "jpg") || strings.EqualFold(suffix, "jpeg") {
fmt.Println("is image")
}
strings.EqualFold(suffix, "png")
fmt.Println("not a image")
return false
}
func getFileName(originName string) {
start := strings.LastIndex(originName, "\\") + 1
end := len(originName)
result := substring(originName, start, end)
fmt.Println(result)
}
func substring(source string, start int, end int) string {
var r = []rune(source)
length := len(r)
if start < 0 || end > length || start > end {
return ""
}
if start == 0 || end == 0 && end == length {
return source
}
return string(r[start:end])
}
func testPointer() {
var b int = 10
a := &b
var c *int
c = a
var d *int = &b
fmt.Println("a = ", *a)
fmt.Println("b = ", b)
fmt.Println("c = ", *c)
fmt.Println("d = ", *d)
}
func testScanf() {
var n int
var m int
fmt.Println("程序运行中.....")
for {
fmt.Scanf("%d%d%s", &n, &m)
if n > m {
fmt.Println("over.....")
break
}
for i := n; i < m; i++ {
if isPrime(i) == true {
fmt.Printf("%d\n", i)
continue
}
}
}
}
//判断素数
func isPrime(value int) bool {
if value <= 3 {
return value >= 2
}
if value%2 == 0 || value%3 == 0 {
return false
}
for i := 5; i*i <= value; i += 6 {
if value%i == 0 || value%(i+2) == 0 {
return false
}
}
return true
}
| 2d5f41d2ce8dae1550a1ebef2f1cc2ecc9ff779c | [
"Go"
] | 9 | Go | lqwwql/GoRepository | 67c8a3ee0bc2c9640dae5f33f0a452210952c445 | 6331a14c258fd00887620a8a58864f3a4c88e4cb |
refs/heads/master | <file_sep>student_name = Array.new(2) #{Array.new(2)}
student_ID = Array.new(2)
student_email = Array.new(2)
student_name.length.times do |i|
puts "please type in your first and last name:"
student_name[i] = gets.chomp.upcase
end
puts student_name
student_ID.length.times do |i|
student_ID[i] = rand(111111...999999)
end
puts student_ID
student_email.length.times do |i|
student_email[i] = "#{student_name[i].chars.first}#{student_name[i].split.last}#{student_ID[i].to_s.chars.last(3).join}@ada.com"
end
puts student_email
student_email.length.times do |i|
puts "name:#{student_name[i]} ID:#{student_ID[i]} EMAIL:#{student_email[i]}"
end
<file_sep>
number_of_students = 2
student_data = Array.new (number_of_students)
number_of_students.times do |i|
puts "please type your full name"
student_name = gets.chomp
student_id = rand(111111...999999).to_s
student_data[i] = [{
"name" => student_name,
"ID" => student_id,
"email" => student_name.chars.first << student_name.split.last << student_id.chars.last(3).join << "@ada.com"
}]
end
puts student_data
#"#{student_data["name"].chars.first}#{student_data["name"].split.last}#{student_data["ID"].to_s.chars.last(3).join}@ada.com"
<file_sep>Pre-Ada-Assignments
upload https://repl.it/CHws/1
<file_sep>
candy = {
"twix" => 1.45,
"mars" => 2.00,
"m&m" => 3.00
}
puts "hello, this is a pretty frustrating candy machine, you choose something and never ending up getting it... but go ahead, for some reason someone found it to be amuzing. so generaly, this is what we have here:"
candy.length.times do |i|
puts "#{candy.keys[i]} costs #{candy.values[i]}$"
end
puts "but lets start with - how much money do you have?"
budget = gets.chomp.to_f
puts "well this is what we have here that is within your budget... (or haven't really):"
candy.length.times do |i|
if budget >= candy.values[i]
puts candy.keys[i]
end
end
puts "so what do you choose not to have?"
choice = gets.chomp
if candy.keys.include? choice
puts "great, we have that in stock, now let's deal with your change!"
end
if budget == candy[choice]
puts "bon apetite!"
elsif budget >= candy[choice]
puts "great, here is your imaginary change! = #{budget - candy[choice]}"
else puts "we either don't have what you are asking for or you don't have enough money to buy it... bye bye!"
end
end
| 1c978c17bd8bfe60caf0eb0d1586996076dc1fdb | [
"Markdown",
"Ruby"
] | 4 | Ruby | yaelittle/Pre-Ada-Assignments | b60f523970fc4a7d4def2c114bccab0b8c95fbc1 | 2a16349141b93fa392e8eb2eb972d4d7e4b194f7 |
refs/heads/master | <file_sep>#' Summary table for Rdrobust estimates to export using kableExtra
#' @param rdr_out Rdrobust object
#' @param prec decimal places
#' @keywords regression-discontinuity export
#' @export
#' @examples
#' \dontrun{
#' rdrobust(df$vote, df$margin, all = T) %>% rdr_export -> rdre
#' rdre %>%
#' kable(, format = "latex", booktabs = T) %>%
#' collapse_rows(columns = 1, latex_hline = "major", valign = "middle") %>%
#' cat(., file = "table.tex")
#' }
rdr_export = function(rdr_out, prec = 3) {
outrows = c("coef", "se", "z", "ci", "bws", "N_h", "N_b")
out = rdr_out[outrows]
# conventional
ids = 1
CI = paste0(
"(", as.numeric(round(out$ci[ids, ][1], prec)),
",", as.numeric(round(out$ci[ids, ][2], prec)), ")"
)
conventional = rbind(Coef = round(out$coef[ids], prec), SE = round(
out$se[ids],
prec
), `t-stat` = round(out$z[ids], prec), CI)
# robust
ids = 3
CI = paste0(
"(", as.numeric(round(out$ci[ids, ][1], prec)),
",", as.numeric(round(out$ci[ids, ][2], prec)), ")"
)
robust = rbind(Coef = round(out$coef[ids], prec), SE = round(
out$se[ids],
prec
), `t-stat` = round(out$z[ids], prec), CI)
common_rows = rbind(bw = paste0("(", round(
out$bws[1, 1],
prec
), ",", round(out$bws[1, 2], prec), ")"), Nobs = paste0(
"(",
out$N_h[1], ",", out$N_h[2], ")"
), poly_order = rdr_out$p)
# prep output table
resout = cbind(
c(rep("Local-Linear", 4), rep("Robust", 4), rep("--", 3)),
rbind(conventional, robust, common_rows)
) %>%
data.frame(rowname = row.names(.), .)
rownames(resout) = NULL
names(resout) = c('stat', 'type', 'val')
resout$stat = gsub("poly_order", "Polynomial Order", resout$stat)
resout$stat = gsub("bw", "Bandwidth", resout$stat)
resout$stat = gsub("nobs", "Obs", resout$stat)
return(resout[, c(2, 1, 3)])
}
#' @export
matrix2latex = function(matr) {
printmrow = function(x) cat(cat(x, sep = " & "), "\\\\ \n")
cat("$$ \n", "\\begin{bmatrix}", "\n")
body = apply(matr, 1, printmrow)
cat("\\end{bmatrix}", "\n$$")
}
#' @export
checkmark = function(name, yesno, format = 'latex') {
if (format %in% c("html", "text")) {
return(c(name, ifelse(yesno, "✓", "")))
} else {
return(c(name, ifelse(yesno, "$\\checkmark$", "")))
}
}
# render html output in atom / jupyter notebooks
#' @export
chr_nb = function(...) as.character(...) |> IRdisplay::display_html()
<file_sep>#' Compute subclassification ATT and ATE
#' @param df data.table
#' @param x character vector of discrete covariates
#' @param y outcome
#' @param w treatment
#' @param debug boolean to return strata-specific estimates
#' @return list with ATE and ATT estimate in est and strata level averages in table
#' @export
#' @examples
#' data(lalonde.psid); setDT(lalonde.psid)
#' subclassify(lalonde.psid,
#' x = c("u74", "u75"),
#' y = "re78", w = "treat"
#' )
#' subclassify(lalonde.psid,
#' x = c("married", "black", "hispanic", "u74", "u75"),
#' y = "re78", w = "treat"
#' )
#'
subclassify = function(df, x, y = 're78', w = 'treat', debug = F) {
if (!data.table::is.data.table(df)) {
df = data.table::as.data.table(df)
}
N = nrow(df); N1 = sum(df[[w]])
grpmeans = df[, list(grpmean = mean(get(y)), N = .N), by = c(x, w)]
fml = as.formula(paste0(paste(x, collapse = "+"), "~", w))
strata_level = dcast(grpmeans, fml, value.var = c("grpmean", "N"))
strata_level[, `:=`(DiM = grpmean_1 - grpmean_0, N_k = N_1 + N_0)]
ATE = strata_level[, sum(DiM * (N_k / N))]; ATT = strata_level[, sum(DiM * (N_1 / N1))]
return(list(est = data.frame(ATE = ATE, ATT = ATT), table = strata_level))
}
# %%
#' Simple Double-ML implementation with cross-fitting
#' @param y The dependent variable
#' @param x Matrix of covariates
#' @param d treatment variable
#' @param D vector of factor variables to be partialed out
#' @param dreg function that wraps learner - e.g. glmnet - for pscore
#' @param yreg function that wraps learner - e.g. glmnet - for outcome regression
#' @param nfolds number of folds for cross fitting
#' @keywords double ml, causal inferenc
#' @export
#' @examples
#' \dontrun{
#' dreg = \(x, d) cv.glmnet(x, d, alpha = 1)
#' yreg = \(x, y) cv.glmnet(x, y, alpha = 1)
#' res = DMLReg(x = x, d = d, y = y, dreg = dreg, yreg = yreg, nfold = 5)
#' }
DMLReg = function(x, d, y, dreg, yreg, nfold = 5) {
require(estimatr)
# randomly split data into folds
nobs = nrow(x)
foldid = rep.int(1:nfold, times = ceiling(nobs / nfold))[sample.int(nobs)]
I = split(1:nobs, foldid)
# create residualized objects to fill
ytil = dtil = rep(NA, nobs)
# run the OOS orthogonalizations
cat("fold: ")
for (b in 1:length(I)) {
dfit = dreg(x[-I[[b]], ], d[-I[[b]]])
yfit = yreg(x[-I[[b]], ], y[-I[[b]]])
dhat = predict(dfit, x[I[[b]], ], type = "response")
yhat = predict(yfit, x[I[[b]], ], type = "response")
dtil[I[[b]]] = drop(d[I[[b]]] - dhat)
ytil[I[[b]]] = drop(y[I[[b]]] - yhat)
cat(b, " ")
}
rfit = lm_robust(ytil ~ dtil)
effect_se = summary(rfit)$coefficients[2, 1:2]
return(list(res = effect_se, dtil = dtil, ytil = ytil))
}
# %%
#' Compute OLS with arbitrary vector of weights (possibly negative)
#' @param y Response vector
#' @param X A numeric data matrix
#' @param w vector of weights (same length as y)
#' @return Regression vector beta of length ncol(X).
#' @export
#' @import car
OLSw = function(y, X, w) {
XtWX = car::wcrossprod(X, w = w)
XtWy = car::wcrossprod(X, y, w = w)
solve(XtWX) %*% XtWy
}
# %% ####################################################
#' Regression Adjustment estimation of ATE or ATT
#' @param df dataframe
#' @param y outcome name
#' @param w treatment name
#' @param xs vector of covariate names
#' @param estimand : runs Lin regression when "ATE" and Oaxaca-Blinder-Kitagawa when "ATT"
#' @return fixest model object with robust standard errors (can be summarised again with different clusters)
#' @import fixest
#' @export
#' @examples
#' data(lalonde.psid); data(lalonde.exp);
#' y = "re78"; w = "treat"; xs = setdiff(colnames(lalonde.psid), c(y, w))
#' cat("ATE in experimental sample \n")
#' reg_adjust(lalonde.exp, 'treat', 're78', xs, "ATE")
#' cat(" --------------------------- \n")
#' cat("ATT in obs sample \n")
#' reg_adjust(lalonde.psid, 'treat', 're78', xs, "ATT")
#' cat(" --------------------------- \n")
reg_adjust = function(df, w, y, xs, estimand = c("ATT", "ATE")) {
estimand = match.arg(estimand)
# for ATE, sweep out overall means, else sweep out treatment means
if (estimand == "ATE") {
d = df[, xs]
} else {
d = df[df[[w]] == 1, xs]
}
# take out means
Xbar = apply(d[, xs], 2, mean); Xdemeaned = sweep(df[, xs], 2, Xbar)
colnames(Xdemeaned) = paste0(colnames(Xdemeaned), "_dem")
# concat columns
regdf = cbind(df[, c(y, w)], df[, xs], Xdemeaned)
# interacted regression
f = as.formula(paste0(
y, "~", w, "+",
paste(xs, collapse = "+"), "+", # controls effects
w, ":(", paste(colnames(Xdemeaned), collapse = "+"), ")" # treat effects
))
m = fixest::feols(f, data = regdf, vcov = 'hc1')
m
}
<file_sep>#' Multi-core replicate.
#' Use multiple cores for repeated evaluation of an expression.
#' @param n integer; the number of replications.
#' @param expr the expression (a language object, usually a call) to evaluate n times.
#' @param mc.cores number of cores to use.
#' @param refresh status update refresh interval.
#' @examples
#' one_sim = \(n = 100, control_prob = 0.1, rel_effect = 0.01) {
#' treat_prob = control_prob + (control_prob * rel_effect)
#' cy = rbinom(n = n, size = 1, prob = control_prob)
#' ty = rbinom(n = n, size = 1, prob = treat_prob)
#' mean(ty) - mean(cy)
#' }
#' mcReplicate(10, one_sim(), mc.cores = 2)
#'
#' @returns A vector, matrix, or list of length `n`.
#' @import parallel
#' @export
mcReplicate = function(n, expr, mc.cores = 4, refresh = 0.1) {
show_progress = \(i_) {
intervaln = floor(n * refresh)
if (floor(i_ / intervaln) == i_ / intervaln) cat(paste("[", i_, "/", n, "]\r"))
}
result = simplify2array(parallel::mclapply(1:n,
eval.parent(substitute(
\(i_, ...) {
if (refresh > 0) show_progress(i_)
expr
}
)),
mc.cores = mc.cores
))
if (refresh > 0) cat("\n")
result
}
#' Multi-core sapply
#' Use multiple cores for simplifying apply.
#' @param X input vector to iterate over
#' @param FUN function
#' @param mc.cores number of cores to use.
#' @returns A vector, matrix, or list of length `n`.
#' @import parallel
#' @export
mcSapply = function(X, FUN, mc.cores = 6, ...,
simplify = TRUE) {
FUN = match.fun(FUN)
answer = parallel::mclapply(X = X, FUN = FUN, ...)
if (is.null(names(answer))) names(answer) = as.character(X)
if (!isFALSE(simplify) && length(answer))
simplify2array(answer, higher = (simplify == "array"))
else answer
}
<file_sep># library(devtools); library(roxygen2)
# %% create package
# root = "/home/alal/Desktop/code/LalRUtils/"
# setwd(root)
# create('LalRUtils') # only run once
# %% scratch - prototype here
<file_sep># %%
#' Summary table
#' @param df A dataframe , var A column in said dataframe
#' @return table with summary statistics
#' @export
#' @examples
#' summar(mtcars)
summar = function(df, prec = 2) {
df = Filter(is.numeric, df)
col1 = apply(df, 2, function(x) sum(is.na(x)))
col2 = apply(df, 2, function(x) length(unique(x)))
col3 = round(apply(df, 2, min), prec)
col4 = round(apply(df, 2, max), prec)
col5 = round(apply(df, 2, mean), prec)
col6 = round(apply(df, 2, var), prec)
col7plus = round(t(apply(df, 2, function(x) quantile(x, c(
0.25,
0.5, 0.75
)))), prec)
data.frame(
n_missing = col1, n_unique = col2, minimum = col3,
col7plus, avg = col5, variance = col6, maximum = col4
)
}
# %%
#' Summary table with percentages for categorical variables
#' @param df A dataframe , var A column in said dataframe
#' @keywords dataframe variable name categorical
#' @export
#' @examples
#' freq_table(mtcars, 'as.factor(cyl)')
freq_table = function(df, var) {
suppressMessages(library(dplyr))
ft = df %>%
count_(var) %>%
mutate(prop = prop.table(n)) %>%
arrange(desc(prop))
return(ft)
}
#' Simple Difference in Means estimator for binary treatment (for HW etc)
#' @param df A dataframe
#' @param outcome The outcome variable (in df)
#' @param treatment The treatment indicator (in df)
#' @keywords Treatment Effect ATE
#' @export
#' @examples
#' \dontrun{
#' ate_diffmeans(mtcars, outcome = mpg, treatment = vs)
#' }
#'
ate_diffmeans = function(df, outcome, treatment) {
# general function to calculate treatment effect
# and standard error for binary treatments
suppressPackageStartupMessages(library(dplyr))
outcome = enquo(outcome); treatment = enquo(treatment)
df %>%
group_by(!!treatment) %>%
summarise(
means = mean(!!outcome),
sigma_2 = var(!!outcome),
nobs = n()
) -> sumcalc
mu_diff = sumcalc$means[2] - sumcalc$means[1]
se_hat = sqrt(
sumcalc$sigma_2[1] / sumcalc$nobs[1] +
sumcalc$sigma_2[2] / sumcalc$nobs[2]
)
# report estimates and ingredients (in case order is flipped etc)
return(list(te = mu_diff, std_err = se_hat, sumstats = sumcalc))
}
#' Normalised Difference (Imbens, Rubin 2015) for observational studies
#' @param df dataframe to check balance
#' @param treat dummy for treatment
#' @param value covariate to calculate normalised difference statistic
#' @keywords regression linear model balance check
#' @export
#' @examples
#' norm_diff(mtcars, vs, gear)
norm_diff = function(df, treat, value) {
suppressPackageStartupMessages(library(tidyverse))
value = enquo(value); treat = enquo(treat)
df %>%
group_by(!!treat) %>%
summarise(mean = mean(!!value), sd = sd(!!value)) -> summ
m_t = summ %>%
filter(!!treat == 1) %>%
.$mean
s_t = summ %>%
filter(!!treat == 1) %>%
.$sd
m_c = summ %>%
filter(!!treat == 0) %>%
.$mean
s_c = summ %>%
filter(!!treat == 0) %>%
.$sd
(m_t - m_c) / sqrt((s_t^2 + s_c^2) / 2)
}
#' Balance Check for observational studies
#' @param df dataframe to check balance
#' @param treatvar dummy for treatment
#' @param bal_vars covariates to check balance in
#' @keywords regression linear model balance check
#' @export
#' @examples
#' \dontrun{
#' balance_table(mtcars, treatvar = 'vs', bal_vars = c('mpg', 'cyl', 'disp'))
#' }
#'
balance_table = function(df, treatvar, bal_vars) {
treat_all = df[which(df[, treatvar] == 1), bal_vars]
control_all = df[which(df[, treatvar] == 0), bal_vars]
bal_mat = matrix(NA, ncol = 7, nrow = length(bal_vars))
i = 1
for (bv in bal_vars) {
treat = na.omit(treat_all[, bv])
control = na.omit(control_all[, bv])
# t test output
t = t.test(df[, bv] ~ df[, treatvar], na.rm = TRUE)
# treatment effects
bal_mat[i, 1] = t$estimate[1]
bal_mat[i, 3] = t$estimate[2]
bal_mat[i, 5] = t$estimate[2] - t$estimate[1]
bal_mat[i, 6] = t$p.value
# sd and normalised difference
bal_mat[i, 2] = sd(control) / sqrt(length(control))
bal_mat[i, 4] = sd(treat) / sqrt(length(treat))
# normalised difference
bal_mat[i, 7] = (bal_mat[i, 5] / sqrt(sd(control)^2 + sd(treat)^2) / 2)
i = i + 1
}
rownames(bal_mat) = bal_vars
colnames(bal_mat) = c(
"Control Mean", "Control SE", "Treatment Mean",
"Treatment SE", "Difference in Means", "p-value",
"Normalised Difference"
)
bal_mat = round(bal_mat, digits = 4)
bal_mat
}
<file_sep># %% ####################################################
#' matrix constructor
#' @param ... Vector of numbers with "|" as row break
#' @return matrix
#' @export
matr = function(...) {
# turn into string
# args=deparse(substitute(rbind(cbind(...))))
args = ... |>
cbind() |>
rbind() |>
substitute() |>
deparse()
# create "rbind(cbind(.),cbind(.),.)" construct
args = gsub("\\|", "),cbind(", args)
# eval
eval(parse(text = args))
}
# %% ####################################################
#' Omit NA entries in list
#' @param y list of elements
#' @return y with NAs omitted
#' @export
naOmitList = function(y) {
return(y[!sapply(y, function(x) all(is.na(x)))])
}
# %% ####################################################
#' Omit element if it contains "contains"
#' @param y list of elements
#' @return y with "contains" omitted
#' @export
listOmitIf = function(lst, contains) {
lst[lapply(
lst,
function(x) length(grep(contains, x, value = FALSE))
) == 0]
}
# %% ####################################################
#' Get n'th element in list of lists
#' @param list.of.lists list of lists
#' @param nth.element index of list to return
#' @return list
#' @export
getNthElement = function(list.of.lists, nth.element) {
sapply(list.of.lists, `[`, nth.element)
}
<file_sep># %%
#' Replaces the standard errors (t and p vals)in FELM model object with robust SE
#' @param felm object
#' @export
#' @keywords hc0 robust heteroskedasticity output
#' @examples
#' \dontrun{
#' robustify(felm(y ~ x, data = df))
#' }
# returns lm summary object with cluster-robust standard errors
robustify = function(model) {
model$se = model$rse
model$tval = model$rtval
model$pval = model$rpval
return(model)
}
# %% ####################################################
#' return cross-fit predictions from glmnet object
#' @param m glmnet model object fit with keep = T
#' @return vector of cross-fit predictions
#' @export
fitGet = function(m) {
m$fit.preval[, !is.na(colSums(m$fit.preval))][
, # slice to nonmissing cols
m$lambda[!is.na(colSums(m$fit.preval))] == m$lambda.min
] # match lambda
}
# %%
#' Partial out controls and fixed effects and return residualised outcome and treatment
#' @param y outcome
#' @param a primary rhs variable
#' @param x controls
#' @param d fixed effects
#' @param df dataframe
#' @keywords Frisch-Waugh-Lovell partial out
#' @export
#' @examples
#' \dontrun{
#' residualise('mpg', 'wt', 'cyl', mtcars)
#' }
residualise = function(y, a, x = "1", d = "0", df) {
require(fixest)
y_tilde = feols(formula_fixest(y, X = x, D = d), df)$residuals
a_tilde = feols(formula_fixest(a, X = x, D = d), df)$residuals
data.frame(y_tilde, a_tilde)
}
# %% ####################################################
#' Convert a long panel to wide matrix (cleaner data.table version)
#' @param dt data.table in long panel format
#' @param unit_id unit id name
#' @param time_id time id name
#' @param treat treatement name
#' @param outcome outcome name
#' @return list with treatment matrix W, outcome matrix Y, N0 (number of control units), and T0 (number of untreated periods)
#' @import data.table
#' @export
panelMatrices = function(dt, unit_id, time_id, treat, outcome) {
dt = as.data.table(dt)
# function to extract first column, convert it to rownames for a matrix
matfy = function(X) {
idnames = as.character(X[[1]])
X2 = as.matrix(X[, -1])
rownames(X2) = idnames
X2
}
# reshape formula
fmla = as.formula(paste0(unit_id, "~", time_id))
# treatment matrix
kv = c(unit_id, time_id, treat)
W = matfy(dcast(dt[, ..kv], fmla, value.var = treat))
# outcome matrix
kv = c(unit_id, time_id, outcome)
Y = matfy(dcast(dt[, ..kv], fmla, value.var = outcome))
# move treated units to bottom of W and Y matrix
treatIDs = which(rowSums(W) > 0)
W = rbind(W[-treatIDs, ], W[treatIDs, , drop = FALSE])
Y = rbind(Y[-treatIDs, ], Y[treatIDs, , drop = FALSE])
N0 = nrow(W) - length(treatIDs)
T0 = min(which(colSums(W) > 0)) - 1
list(W = W, Y = Y, N0 = N0, T0 = T0)
}
# %%
#' Partial Residual Plot
#'
#' Makes a Partial Residual plot
#'
#' @name prplot
#' @param g An object returned from lm()
#' @param i index of predictor
#' @return none
#' @keywords regression
#' @examples
#'
#' data(stackloss)
#' g = lm(stack.loss ~ ., stackloss)
#' prplot(g, 1)
#'
#' @export prplot
prplot = function(g, i) {
# Partial residuals plot for predictor i
xl = attributes(g$terms)$term.labels[i]
yl = paste("beta*", xl, "+res", sep = "")
x = model.matrix(g)[, i + 1]
plot(x, g$coeff[i + 1] * x + g$res, xlab = xl, ylab = yl)
abline(0, g$coeff[i + 1])
invisible()
}
# %%
#' prepare X matrix with flexible interactions and polynomials
#' @description Prepare matrix with polynomial basis expansion and/or interactions.
#' @param dat data table / dataframe
#' @param dummies Names of dummy vars (null by default - auto-detected)
#' @param continuouses Names of continuous vars to modify fn form (null by default - auto detected)
#' @param corr_cut cutoff for correlation threshold to drop one of the vars (default = 0.9)
#' @param k order of interactions: defaults to pairwise interactions
#' @param m order of functions: defaults to quadratic functions
#' @param raw raw or orthogonal bases
#' @return data.frame with base terms and interactions + basis
#' @importFrom glue glue
#' @export
polySieveM = function(dat,
dummies = NULL,
continuouses = NULL,
corr_cut = 0.90,
k = 2,
m = 2,
raw = TRUE) {
# coerce to df
dat = as.data.frame(dat)
nuniqs = apply(dat, 2, function(x) length(unique(x)))
# populate lists if missing
if (is.null(dummies)) dummies = colnames(dat)[which(nuniqs == 2)]
if (is.null(continuouses)) continuouses = colnames(dat)[which(nuniqs >= 5)]
# concat names
controls = c(dummies, continuouses)
data = dat[, controls]
############################################################
# basis
############################################################
if (m > 1) {
if (!is.null(continuouses)) { # if there are any continous variables
# functional form changes for continuous vars
# polynomials (orthogonal by default)
polyfml = paste(paste0(
"poly(", continuouses, ",", m,
", raw=", raw, ")"
), collapse = " + ")
# model matrix with sieve polynomial basis
powmat = model.matrix(
as.formula(paste0("~ -1 + ", polyfml)),
dat[, continuouses]
)
# cbind base terms with smooth fns
data = cbind(data, powmat)
}
}
############################################################
# interactions
############################################################
if (k > 1) {
# all n-way interactions with polynomials and dummies
X = model.matrix(as.formula(glue::glue("~.^{k} - 1")), data)
} else {
X = as.matrix(data)
}
############################################################
# final cleanup
############################################################
# drop non-varying Xs (e.g. interactions bw mutually exclusive dummies)
varyvar = apply(X, 2, function(col) length(unique(col)) > 1)
X = X[, varyvar]
# drop highly correlated Xs - this drops polynomials of binary variables
corm = cor(X)
hc = findCorr(corm, cutoff = corr_cut) # put any value as a "cutoff"
hc = sort(hc)
return(X[, -c(hc)])
}
#' prepare sparse X matrix with interactions
#' @description Prepare sparse matrix with interactions.
#' @param data data table / dataframe
#' @param k order of interactions: defaults to pairwise interactions
#' @return matrix with interactions
#' @importFrom glue glue
#' @export
interSparseM = function(data, k = 2, corr_cut = 0.9) {
X = model.matrix(
as.formula(glue::glue("~.^{k} - 1")),
data
)
# drop non-varying Xs (e.g. interactions bw mutually exclusive dummies)
varyvar = apply(X, 2, function(col) length(unique(col)) > 1)
X = X[, varyvar]
# drop highly correlated Xs - this drops polynomials of binary variables
corm = cor(X)
hc = findCorr(corm, cutoff = corr_cut) # put any value as a "cutoff"
hc = sort(hc)
X[, -c(hc)]
}
# %% fast correlation matrix filtration
findCorr = function(x, cutoff = .90) {
if (any(!complete.cases(x)))
stop("The correlation matrix has some missing values.")
averageCorr = colMeans(abs(x))
averageCorr = as.numeric(as.factor(averageCorr))
x[lower.tri(x, diag = TRUE)] = NA
combsAboveCutoff = which(abs(x) > cutoff)
colsToCheck = ceiling(combsAboveCutoff / nrow(x))
rowsToCheck = combsAboveCutoff %% nrow(x)
colsToDiscard = averageCorr[colsToCheck] > averageCorr[rowsToCheck]
rowsToDiscard = !colsToDiscard
deletecol = c(colsToCheck[colsToDiscard], rowsToCheck[rowsToDiscard])
deletecol = unique(deletecol)
deletecol
}
<file_sep>#' fuzzy matches 2 character vectors, and returns most similar pairs
#' @param character vectors a and b
#' @keywords fuzzy match string
#' @export
#' @examples
#' \dontrun{
#' fuzzy_match(keys_A, keys_B)
#' }
fuzzy_match = function(a, b) {
# calculate a jaccard dissimilarity matrix
distance = stringdist::stringdistmatrix(a, b, method = 'jaccard')
# find the closest match for each
match = apply(distance, 1, which.min)
values = b[match] # slice b using match index
df = data.frame(key = as.character(a), values = as.character(values))
return(df)
}
<file_sep># brackets an interval in which a root of the function f (x) must lie,
# then repeatedly bisects the interval until a root is found within
# the desired precision.
#' @export
bisectionRoot = function(f, xmin, xmax, tol = 1e-5) {
a = xmin; b = xmax
# Check inputs
if (a >= b) {
cat("error: xmin > xmax \n")
return(NULL)
}
if (f(a) == 0) {
return(a)
} else if (f(b) == 0) {
return(b)
} else if (f(a) * f(b) > 0) {
cat("error: f(xmin) and f(xmax) of same sign \n")
return(NULL)
}
# If inputs OK, converge to root
iter = 0
while ((b - a) > tol) {
c = (a + b) / 2
if (f(c) == 0) {
return(c)
} else if (f(a) * f(c) < 0) {
b = c
} else {
a = c
}
iter = iter + 1
}
c(
root = (a + b) / 2,
iter = iter,
precision = (b - a)
)
}
#' solve for roots using the NR update rule x1 = x0 − f(x0)/f'(x0)
#' @export
newtonRoot = function(f, df, x0, tol = 1e-5, maxit = 20) {
root = x0
for (jit in 1:maxit) {
dx = f(root) / df(root)
root = root - dx
if (abs(dx) < tol) return(c(root = root, jit = jit, dx = dx))
}
print(" Maximum number of iterations exceeded.")
}
<file_sep># %% ####################################################
#' Bayesian bootstrap for linear regression
#' @param object model object of class lm or fixest
#' @param reps number of replications
#' @param cluster clustering variable passed as bare formula or char vector
#' @return bboot object
#' @examples
#' lm(mpg ~ wt + hp, mtcars) |>
#' bboot(reps = 1e3) |>
#' summary()
#' @export
bboot = function(object, reps = 100L, cluster = NULL, ...) {
require(data.table); require(fixest)
# flag for fixest
fixest_obj = inherits(object, c('fixest', 'fixest_multi'))
if (inherits(object, c('lm'))) {
Ymat = object$model[, 1]
} else if (fixest_obj) {
Ymat = model.matrix(object, type = 'lhs', as.matrix = TRUE)
} else {
stop('\nModel or object class not currently supported.\n')
}
Xmat = model.matrix(object)
n_weights = nrow(Xmat)
fmat = NULL
if (fixest_obj && !is.null(object$fixef_vars)) {
fmat = model.matrix(object, type = 'fixef')
}
## Have to do a bit of leg work to pull out the clusters and match to
## model matrix
if (!is.null(cluster)) {
if (inherits(cluster, "formula")) {
cl_string = strsplit(paste0(cluster)[2], split = ' \\+ ')[[1]]
} else {
cl_string = paste(cluster)
}
if (!is.null(fmat) && all(cl_string %in% colnames(fmat))) {
cl_mat = fmat[, cl_string]
} else if (all(cl_string %in% colnames(Xmat))) {
cl_mat = Xmat[, cl_string]
} else {
DATA = eval(object$call$data)
if (all(cl_string %in% names(DATA))) {
all_vars = sapply(list(Ymat, Xmat, fmat), colnames)
if (inherits(all_vars, 'list')) all_vars = do.call('c', all_vars)
all_vars = union(all_vars, cl_string)
DATA = data.frame(DATA)[, intersect(colnames(DATA), all_vars)]
DATA = DATA[complete.cases(DATA), ]
cl_mat = model.matrix(~ 0 + ., DATA[, cl_string, drop = FALSE])
} else {
stop(paste0('Could not find ', cluster, '. Please provide a valid input.\n'))
}
}
if (!inherits(cl_mat, "matrix")) cl_mat = matrix(cl_mat)
n_weights = nrow(unique(cl_mat))
## Keep track of cluster id for consistent weighting within each
## cluster later on
cl_mat = data.table::as.data.table(cl_mat)
cl_mat$cl_id = data.table::frank(cl_mat, ties.method = "dense")
}
## Pre-allocate space for efficiency
wfits = matrix(0, reps, length(object$coefficients))
for (i in 1:reps) {
if (is.null(cluster)) {
weights = rexp(n_weights, rate = 1)
} else {
weights = cl_mat[, wt := rexp(1, rate = 1), by = cl_id][, wt]
}
## Demean X and Y matrices if fixed effects are present
if (!is.null(fmat)) {
Xmat = fixest::demean(X = Xmat, f = fmat, weights = weights)
Ymat = fixest::demean(X = Ymat, f = fmat, weights = weights)
}
## Fit weighted reg
wfits[i, ] = lm.wfit(x = Xmat, y = Ymat, w = weights)$coefficients
}
colnames(wfits) = colnames(Xmat)
class(wfits) = "bboot"
return(wfits)
}
# %% ####################################################
#' summary method for bayesian bootstrap
#' @param object bboot object
#' @param level test level (0.95 by default)
#' @export
summary.bboot = function(object, level = 0.95, ...) {
alpha = 1 - level
lwr = alpha / 2
upr = 1 - lwr
out = t(apply(object, 2, \(x) c(mean(x), quantile(x, c(lwr, upr)))))
colnames(out) = c("mean", "conf.low", "conf.upper")
out
}
<file_sep># %% ####################################################
#' ggplot with frame
#' @param g geom
#' @param aes ggplot2 aesthetic
#' @param d dataframe
#' @return populated geom
#' @import ggplot2
#' @export
withFrame = \(g, aes, d, ...) do.call(g, c(list(aes, data = d), list(...)))
# %% ####################################################
#' Histogram of pscore distributions in treatment and control groups
#' @param w treatment vector
#' @param ps propensity score vector
#' @return figure with overlap
#' @import ggplot2
#' @export
#' @examples
#' data(lalonde.exp)
#' pscore = glm(treat ~ . - re78, lalonde.exp, family = binomial)$fitted.values
#' overlap_histogram(lalonde.exp$treat, pscore) + lal_plot_theme()
#'
overlap_histogram = function(w, ps) {
require(ggplot2)
d = data.frame(w, ps)
ggplot(d) +
geom_histogram(data = d[d$w == 1, ], aes(x = ps, y = ..density.., fill = 'treated')) +
geom_histogram(data = d[d$w == 0, ], aes(x = ps, y = -..density.., fill = 'control')) +
theme(
axis.text.y = element_blank(), # remove y axis labels
axis.ticks.y = element_blank() # remove y axis ticks
) +
labs(fill = "", x = "Propensity Score")
}
#' Stitches together multiple ggplot objects for export-ready graphs
#' @param ... ggplot objects
#' @keywords graphs plots
#' @export
#' @examples
#' \dontrun{
#' plot1 = ggplot(data, aes(xvar1, yvar)) +
#' geom_point()
#' plot2 = ggplot(data, aes(xvar2, yvar)) +
#' geom_point()
#' multiplot(plot1, plot2, cols = 2)
#' }
#'
#######################################################################
# Multiple plot function - stitches together multiple ggplot objects
#######################################################################
multiplot = function(..., plotlist = NULL, file, cols = 1, layout = NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots = c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout = matrix(seq(1, cols * ceiling(numPlots / cols)),
ncol = cols, nrow = ceiling(numPlots / cols)
)
}
if (numPlots == 1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx = as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(
layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col
))
}
}
}
####################################################
#' R implementation of binned scatterplot and CEF plotter, with added options for cluster variance
#' @param fmla FELM formula *as a string*
#' @param key_var X axis variable for CEF
#' @param data dataframe
#' @param plotraw T if underlying scatterplot should be plotted
#' @param bins number of bins
#' @param rawdata_colour Colour of Rawdata
#' @param rawdata_alpha Alpha of Rawdata
#' @param rawdata_size Size of Rawdata
#' @param linfit_width width of linear fit
#' @param linfit_colour colour of linear fit
#' @param cef_point_size Size of binscatter points
#' @param cef_point_colour Colour of binscatter points
#' @param ci_colour Colour of CI ribbon
#' @param ci_alpha Alpha of CI ribbon
#' @export
#' @keywords cef bins scatterplot
#' @examples
#' binscatter('Sepal.Length ~ Petal.Length + Petal.Width|Species', key_var = 'Petal.Width', iris)
#'
binscatter = function(fmla, key_var, data, plotraw = TRUE, bins = 20,
rawdata_colour = 'black', rawdata_alpha = 0.2, rawdata_size = 0.5,
linfit_width = 0.6, linfit_colour = 'blue',
cef_point_size = 1, cef_point_colour = 'red',
ci_colour = 'gray', ci_alpha = 0.3) {
# load libraries
require(lfe); require(stringr); require(ggplot2)
# FWL
y = unlist(strsplit(fmla, "~"))[1] ; x = unlist(strsplit(fmla, "~"))[2]
controls = str_replace(x, key_var, '1') # replace main X with intercept
# residualise regressions
reg_y = felm(formula(paste0(y, "~", controls)), data = data)
reg_x = felm(formula(paste0(key_var, "~", controls)), data = data)
resid_y = resid(reg_y); resid_x = resid(reg_x)
df = data.frame(resid_y, resid_x)
colnames(df) = c(paste0("residual_", names(df)[1]), paste0("residual_", names(df)[2]))
# are errors clustered
cluster_grp = trimws(unlist(strsplit(fmla, "\\|"))[4])
# regression with partialed Xs and Ys
if (is.na(cluster_grp)) {
reg = felm(resid_y ~ resid_x)
} else {
reg = felm(formula(paste0("resid_y ~ resid_x | 0 | 0 |", cluster_grp)), data)
}
intercept = coef(reg)[1] ; slope = coef(reg)[2]
# variance covariance matrix
if (is.null(reg$clustervcv)) {
vcov = reg$robustvcv; se_type = "robust"
} else {
vcov = reg$clustervcv; se_type = paste0("clustered by ", cluster_grp)
}
Terms = terms(reg); m_mat = model.matrix(Terms, data = df)
fit = as.vector(m_mat %*% coef(reg))
se_fit = sqrt(rowSums((m_mat %*% vcov) * m_mat))
# confidence intervals
df$upper_ci = fit + 1.96 * se_fit; df$lower_ci = fit - 1.96 * se_fit
df_bin = aggregate(df, by = list(cut(as.matrix(df[, 2]), bins)), mean)
# construct plot
plot = ggplot(data = df, aes(x = df[, 2], y = df[, 1]))
if (plotraw == TRUE) { # plot raw data first
plot = plot + geom_point(
data = df, aes(x = df[, 2], y = df[, 1]),
alpha = rawdata_alpha, size = rawdata_size, colour = rawdata_colour
)
}
plot = plot + # linear fit
geom_abline(
slope = slope, intercept = intercept,
color = linfit_colour, size = linfit_width
) +
# confint
geom_ribbon(aes(ymin = lower_ci, ymax = upper_ci),
alpha = ci_alpha, fill = ci_colour
) +
# binned scatterplot
geom_point(
data = df_bin, aes(x = df_bin[, 3], y = df_bin[, 2]),
color = cef_point_colour, size = cef_point_size
) +
# label slope
labs(
caption = paste0(" slope = ", signif(slope, 2), '\n SE:', se_type),
x = names(df)[2], y = names(df)[1]
)
return(plot)
}
#' plot binary treatment status for time series for panel dataset
#' @param data dataframe
#' @param time bare name of time (not in quotes)
#' @param id bare name of unit
#' @param status bare name of treatment
#' @keywords dataframe panel diff-in-diff
#' @export
#' @examples
#' \dontrun{
#' panel_treat_plot(california_prop99, Year, State, treated)
#' }
#'
panel_treat_plot = function(data, time, id, status) {
tiles_plot = ggplot(
data,
aes(x = {{ time }}, y = {{ id }}, fill = as.factor({{ status }}))
) +
geom_tile(color = "white", size = 1) +
scale_y_discrete(limits = rev) +
scale_fill_manual(values = c("#4285F4", "#DB4437", "#F4B400")) +
theme_classic(base_size = 14) +
lal_plot_theme() +
labs(fill = "Treatment :")
return(tiles_plot)
}
####################################################
#' Scatterplot with regression line and densites by grouping variable. Use this to evaluate overlap.
#' @param df dataframe
#' @param xvar x variable
#' @param yvar y variable
#' @param zvar z variable (coerced to factor)
#' @param title plot title
#' @export
#' @keywords seaborn Scatterplot
#' @examples
#' regplot_dens(mtcars, wt, mpg, am)
regplot_dens = function(df, xvar, yvar, zvar, title = "") {
require(ggExtra); require(ggplot2)
p0 = ggplot(df, aes(x = {{ xvar }}, y = {{ yvar }})) +
geom_point(aes(colour = as.factor({{ zvar }}))) +
geom_smooth(method = 'lm', alpha = 0.2) +
scale_colour_brewer(palette = "Set1") +
ggtitle(title)
p = ggMarginal(p0, type = "density", size = 7, groupColour = T, groupFill = T)
return(p)
}
#' Canned subroutine to plot time series for several variables
#' @param df A dataframe
#' @param timevar a string with a colname for the time variable
#' @keywords dataframe variable name categorical
#' @export
#' @examples
#' \dontrun{
#' overall_ineq = tsplotter(overall) + labs(title = 'Overall Inequality')
#' }
tsplotter = function(df, timevar = 'year') {
library(reshape2); library(ggplot2)
meltdf = reshape2::melt(df, id = timevar)
variable = 'variable'
value = 'value'
p = ggplot(data = meltdf, aes_string(
x = timevar,
y = value, colour = variable, group = variable
)) +
geom_point(size = 0.5) +
geom_line() +
lal_plot_theme()
return(p)
}
#' Theme for maps
#' @param ggplot object
#' @keywords maps ggplot spatial
#' @export
#' @examples
#' \dontrun{
#' map_ggp_object + lal_map_theme()
#' }
lal_map_theme = function(fontfam = "IBM Plex Sans Condensed", ...) {
theme_bw() +
theme(
text = element_text(family = fontfam, color = "#22211d"),
legend.position = 'bottom',
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_line(color = "#ebebe5", size = 0.2),
panel.grid.minor = element_blank(),
plot.background = element_rect(fill = "#f5f5f2", color = NA),
panel.background = element_rect(fill = "#f5f5f2", color = NA),
legend.background = element_rect(fill = "#f5f5f2", color = NA),
panel.border = element_blank(),
...
)
}
#' Wrapper for hrbrthemes::theme_ft_rc() with bigger font, altered legend options and dots
#' @param ggplot object
#' @keywords ggplot plots
#' @export
#' @examples
#' \dontrun{
#' plot_ggp_object + lal_plot_theme_d()
#' }
#'
lal_plot_theme_d = function(fontfam = "IBM Plex Sans Condensed", fsize = 15, axsize = 13, textangle = 0, ...) {
suppressMessages(library(hrbrthemes))
theme_modern_rc(
base_family = fontfam, subtitle_family = fontfam,
axis_title_just = 'c', base_size = fsize
) +
theme(
text = element_text(family = fontfam, size = fsize),
axis.text.x = element_text(angle = textangle, size = axsize),
axis.text.y = element_text(face = "bold", size = axsize),
strip.text = element_text(color = 'white'),
legend.position = 'bottom',
panel.border = element_blank(),
...
)
}
#' theme for nice looking plots with sensible defaults (no legend title, legend at the bottom)
#' @param ggplot object
#' @keywords ggplot plots
#' @export
#' @examples
#' \dontrun{
#' plot_ggp_object + lal_plot_theme()
#' }
#'
lal_plot_theme = function(fontfam = "IBM Plex Sans Condensed",
fsize = 14, textangle = 0, ...) {
theme_minimal() +
theme(
text = element_text(family = fontfam, size = fsize),
axis.text.x = element_text(angle = textangle),
axis.ticks = element_line(color = "grey92"),
plot.title = element_text(size = 18, face = "bold"), # title fsize
plot.title.position = "plot", # left align
plot.caption = element_text(size = 9, margin = margin(t = 15)), # caption fsize
plot.caption.position = "plot", # right align
plot.subtitle = element_text(size = 12, color = "grey30"), # subtitle
legend.position = "top",
legend.text = element_text(color = "grey30"),
legend.title = element_text(size = 12),
panel.border = element_blank(),
panel.grid.minor = element_blank(),
...
)
}
<file_sep># LalRUtils
Misc utility functions in R for personal use.
[Function reference](https://apoorvalal.github.io/LalRUtils/reference/index.html)
To install:
```R
library(devtools)
devtools::install_github("apoorvalal/LalRUtils")
```
<file_sep>#' Stitches together formula for use in fixest::feols
#' @param y The dependent variable
#' @param X vector of controls
#' @param W treatment variable
#' @param D vector of factor variables to be partialed out
#' @param Z vector of instruments
#' @keywords regression linear model variable name
#' @export
#' @examples
#' formula_fixest(y = 'mpg', X = c('hp', 'drat'), D = c('wt', 'vs'))
#' formula_fixest(y = 'mpg', X = c('hp', 'drat'), W = 'gear', Z = c('cyl', 'carb'), D = c('wt', 'vs'))
#'
formula_fixest = function(y, X, W = NULL, D = NULL, Z = NULL) {
# 'second stage' step
if (!is.null(W) & is.null(Z)) { # separate treatment dummy only
fixest_ss = paste(c(y, paste(c(W, X), collapse = "+")), collapse = "~")
} else { # no instrumented variable
fixest_ss = paste(c(y, paste(X, collapse = "+")), collapse = "~")
}
# FEs
if (!is.null(D)) facs = paste(D, collapse = "+") else facs = "0"
# first stage
if (!is.null(Z)) {
fixest_fs = paste(c(paste(c(W, paste(Z, collapse = "+")),
collapse = "~"
)), collapse = "")
# return formula
as.formula(paste(c(fixest_ss, facs, fixest_fs), collapse = "|"))
} else {
as.formula(paste(c(fixest_ss, facs), collapse = "|"))
}
}
#' Stitches together formula for use in felm
#' @param y The dependent variable
#' @param X vector of controls
#' @param W treatment variable
#' @param D vector of factor variables to be partialed out
#' @param Z vector of instruments
#' @param C vector of variables cluster standard errors (multi-way permitted by LFE)
#' @keywords regression linear model variable name
#' @export
#' @examples
#' formula_lfe(y = 'mpg', X = c('hp', 'drat'), D = c('wt', 'vs'))
#' formula_lfe(y = 'mpg', X = c('hp', 'drat'), W = 'gear', Z = c('cyl', 'carb'), D = c('wt', 'vs'), C = c('cyl', 'wt'))
formula_lfe = function(y, X, W = NULL, D = NULL, Z = NULL, C = NULL) {
# 'second stage' step
if (!is.null(W) & is.null(Z)) { # separate treatment dummy only
felm_ss = paste(c(y, paste(c(W, X), collapse = "+")), collapse = "~")
} else { # no instrumented variable
felm_ss = paste(c(y, paste(X, collapse = "+")), collapse = "~")
}
# first stage
if (!is.null(Z)) {
felm_fs = paste(c("(", paste(c(W, paste(Z, collapse = "+")),
collapse = "~"
), ")"), collapse = "")
} else { # no instrument
felm_fs = "0"
}
# FEs
if (!is.null(D)) {
facs = paste(D, collapse = "+")
} else {
facs = "0"
}
# clusters
if (!is.null(C)) {
clusts = paste(C, collapse = "+")
} else {
clusts = "0"
}
# return formula
as.formula(paste(c(felm_ss, facs, felm_fs, clusts), collapse = "|"))
}
#' Stitches together formula for use in lm/glm
#' @param Y The dependent variable
#' @param X List of independent variables (continuous/dummy variables)
#' @param factors List of factor variables (NULL by default)
#' @keywords dataframe variable name
#' @export
#' @examples
#' formula_stitcher('wage', c('age', 'experience', 'married'), c('ethnicity', 'sector'))
#'
formula_stitcher = function(Y, X, factors = NULL) {
if (!is.null((factors))) {
lapply(factors, as.factor)
fml = as.formula(paste0(
Y, '~',
paste((X), collapse = '+'), '+',
paste('factor(', factors, ')', collapse = '+', sep = '')
))
} else {
fml = as.formula(paste0(
Y, '~',
paste((X), collapse = '+')
))
}
return(fml)
}
# %% ####################################################
#' construct formula with outcome and polynomial terms
#' @param y outcome
#' @param b binary variables
#' @param c continuous vars (for polynomials)
#' @param k polynomial order
#' @return formula
#' @export
fmla_kth = function(y, b, c, k = 2) {
f = paste0(
y, " ~ ", # depvar
paste0(b, collapse = " + "), " + ", # binary variables
paste0("poly(", c, ",", k, ", raw = T)", collapse = " + ") # continuous variables with kth order term
) |> as.formula()
}
<file_sep>#' Loads specific function or list of functions f from library l
#' @param l library name (needs to be installed)
#' @param f function name
#' @export
fromLimportF = \(l, f) library(l, include.only = f, character.only = TRUE)
#' Loads a list of libraries, installs when necessary - Take 2
#' @param repo string containing repo to be passed to install.packages
#' @keywords libraries install
#' @export
#' @examples
#' \dontrun{
#' libreq(tidyverse, lfe, estimatr)
#' }
#'
libreq = function(..., repo = 'https://cloud.r-project.org/') {
wants = as.character(match.call(expand.dots = FALSE)[[2]])
has = wants %in% rownames(installed.packages())
if (any(!has)) install.packages(wants[!has], repos = repo, dependencies = TRUE)
loaded = suppressMessages(lapply(wants, require, character.only = TRUE))
print(cbind(wants, loaded))
}
#' Loads a list of libraries, installs when necessary
#' @param wants A list of R modules available on CRAN
#' @param repo string containing repo to be passed to install.packages
#' @keywords libraries install
#' @export
#' @examples
#' \dontrun{
#' load_or_install(c('tidyverse', 'Hmisc', 'glmnet'))
#' }
#'
load_or_install = function(wants, repo = 'https://cloud.r-project.org/') {
# sample use :
# load_or_install(c('tidyverse','glmnet','HMisc'))
has = wants %in% rownames(installed.packages())
if (any(!has)) install.packages(wants[!has], repos = repo, dependencies = TRUE)
loaded = suppressMessages(lapply(wants, require, character.only = TRUE))
print(cbind(wants, loaded))
}
<file_sep>#' <NAME> (2007) DGP for 'mild' confounding
#' @param n nobs
#' @param τ true effect (10 by default)
#' @export
KS2007_dgp = function(n = 1000, τ = 10){
Z = matrix(rnorm(4*n),ncol=4,nrow=n)
d = as.data.table(Z)
colnames(d) = paste0("z", 1:4)
d[, id := 1:.N][,
pscore_lin := z1 - 0.5 * z2 + 0.25*z3 + 0.1 * z4][,
π := expit(pscore_lin)][,
W := rbinom(1, 1, π), id][,
`:=`(x1 = exp(z1)/2,
x2 = z2/(1+exp(z1)),
x3 = (z1*z3/25+0.6)^3,
x4 = (z2+z4+20)^2)][,
lin := 27.4*z1 + 13.7*z2 + 13.7*z3 + 13.7*z4][,
Y0 := 200 + (-0.5) * lin][,
Y1 := 200 + τ + (1.5 - 0.5)*lin][,
Y := W * Y1 + (1-W)*Y0]
return(d)
}
<file_sep># %% ####################################################
#' test-train split
#' @param df [data.frame, matrix] data table (n x p)
#' @param k share of data obs in train
#' @return list with test and train
#' @export
ttsplit = function(df, k = 0.75) {
# sample k% of obs
trainid = sample(nrow(df), nrow(df) * k, replace = FALSE)
list(train = df[trainid, ], test = df[-trainid, ])
}
# %% ####################################################
#' create folds for cross-fitting
#' @param df dataframe - used to compute nrows
#' @param nf Number of folds
#' @return list with indices for each fold in first element, and fold assignment vector in second element
#' @export
createFolds = function(df, nf = 10) {
n = nrow(df)
foldid = rep.int(1:nf, times = ceiling(n / nf))[sample.int(n)]
list(
fold_assignments = split(1:n, foldid),
fold_indices = foldid
)
}
# %% ####################################################
#' min-max scale (maps continuous variable to [0, 1])
#' @param X vector
#' @export
mMscale = function(X) {
X = as.matrix(X)
mins = apply(X, 2, min)
maxs = apply(X, 2, max)
return(scale(X, center = mins, scale = maxs - mins))
}
# %%
#' Classification Evaluation
#'
#' @param actual vector of real labels
#' @param predicted vector of predicted labels
#' @return list of classification accuracy metrics
#' @export
classifEval = function(actual, predicted) {
cm = as.matrix(table(Actual = actual, Predicted = predicted))
n = sum(cm) # number of instances
nc = nrow(cm) # number of classes
diag = diag(cm) # number of correctly classified instances per class
rowsums = apply(cm, 1, sum) # number of instances per class
colsums = apply(cm, 2, sum) # number of predictions per class
p = rowsums / n # distribution of instances over the actual classes
q = colsums / n # distribution of instances over the predicted classes
list(
accuracy = sum(diag) / n,
precision = diag / colsums,
recall = diag / rowsums,
f1 = 2 * precision * recall / (precision + recall)
)
}
# %%
#' plot calibration
#' @param y true value (vector)
#' @param yhat predicted value (vector)
#' @param nbins number of bins (defaults to 10)
#' @return ggplot of calibration
#' @export
calibPlot = function(y, yhat, nbins = 10){
df = data.table(y, yhat)
df[, ppbin := cut(yhat, seq(0,1,,nbins), include.lowest = TRUE)]
# agged
pdf = df[, .(avg_real = mean(y), avg_pred = mean(yhat)), ppbin]
# fig
ggplot(pdf,aes(x=avg_pred,y=avg_real)) +
geom_point(color="dodgerblue") + geom_line(color="dodgerblue") +
geom_abline(intercept = 0,slope=1,linetype=2) +
xlim(0,1) + ylim(0,1) +
xlab("Mean Predicted Value") + ylab("Fraction of Positives")
}
# %%
<file_sep>#' Fork of inborutils::csv_to_sqlite to save a delimited text table into a single table
#' sqlite database that can then be munged w dplyr/ dbplyr / sqldf
#'
#' The table can be a comma separated (csv) or a tab separated (tsv) or any
#' other delimited text file. The file is read in chunks. Each chunk is copied
#' in the same sqlite table database before the next chunk is loaded into
#' memory. See the INBO tutorial \href{https://inbo.github.io/tutorials/tutorials/r_large_data_files_handling/#convertsqlite}{Handling large files in R}
#' to learn more.
#'
#' @section Remark:
#' The \code{callback} argument in the \code{read_delim_chunked} function call
#' refers to the custom written callback function `append_to_sqlite` applied
#' to each chunk.
#'
#' @param csv_file Name of the text file to convert.
#' @param sqlite_file Name of the newly created sqlite file.
#' @param table_name Name of the table to store the data table in the sqlite
#' database.
#' @param delim Text file delimiter (default ",").
#' @param pre_process_size Number of lines to check the data types of the
#' individual columns (default 1000).
#' @param chunk_size Number of lines to read for each chunk (default 50000).
#' @param show_progress_bar Show progress bar (default TRUE).
#' @param ... Further arguments to be passed to \code{read_delim}.
#' @return a SQLite database
#' @export
csv_to_sqlite = function(csv_file, sqlite_file, table_name,
delimiter = ",",
pre_process_size = 1000, chunk_size = 50000,
show_progress_bar = TRUE, ...) {
require(dplyr); require(DBI); require(lubridate); require(readr)
# init connection
con = dbConnect(SQLite(), dbname = sqlite_file)
# read a first chunk of data to extract the colnames and types
# to figure out the date and the datetime columns
df = read_delim(csv_file, delim = delimiter, n_max = pre_process_size, ...)
names = colnames(df)
date_cols = df %>%
select_if(is.Date) %>%
colnames()
datetime_cols = df %>%
select_if(is.POSIXt) %>%
colnames()
# write the first batch of lines to SQLITE table, converting dates to string
# representation
df = df %>%
mutate_at(.vars = date_cols, .funs = as.character.Date) %>%
mutate_at(.vars = datetime_cols, .funs = as.character.POSIXt)
dbWriteTable(con, table_name, df, overwrite = TRUE)
# readr chunk functionality
read_delim_chunked(
csv_file,
callback = append_to_sqlite(
con = con,
table_name = table_name,
date_cols = date_cols,
datetime_cols = datetime_cols
),
delim = delimiter,
skip = pre_process_size, chunk_size = chunk_size,
progress = show_progress_bar,
col_names = names, ...
)
dbDisconnect(con)
}
#' Callback function that appends new sections to the SQLite table.
#' @param con A valid connection to SQLite database.
#' @param table_name Name of the table to store the data table in the sqlite
#' database.
#' @param date_cols Name of columns containing Date objects
#' @param datetime_cols Name of columns containint POSIXt objects.
#'
#' @keywords internal
append_to_sqlite = function(con, table_name,
date_cols, datetime_cols) {
#' @param x Data.frame we are reading from.
function(x, pos) {
x = as.data.frame(x)
x = x %>%
mutate_at(.vars = date_cols, .funs = as.character.Date) %>%
mutate_at(.vars = datetime_cols, .funs = as.character.POSIXt)
# append data frame to table
dbWriteTable(con, table_name, x, append = TRUE)
}
}
####################################
#' Writes all dataframes to csv
#' @param dataframes = list of dataframes,
#' @param path = path of file/s
#' @export
#' @keywords write save bulk
#' @examples
#' \dontrun{
#' convert_all_to_csv(dataframes, path)
#' }
#'
####################################
# writes all dataframes to csv
####################################
#'
convert_all_to_csv = function(dataframes, path) {
for (file in dataframes) {
write.csv(mget(file, .GlobalEnv), paste0(path, '/', file, '.csv'))
}
}
# %%
#' Small summary table with stata variable labels from DTA file
#' @param df dataframe to check balance
#' @keywords stata summary labels dataframe
#' @export
#' @examples
#' \dontrun{
#' dta_vlabs(df)
#' }
#'
dta_vlabs = \(dta) sapply(dta, function(x) attr(x, "label"))
# %%
#' extracts variable labels and returns a dataframe with varname-varlabel for DTA files
#' @param dataframe (read from stata)
#' @keywords stata data labels
#' @export
#' @examples
#' \dontrun{
#' label_extractor(df)
#' }
#'
label_extractor = function(df, colnames = c('names', 'var.labels')) {
info = data.frame(attributes(df)[colnames])
return(info)
}
####################################################
#' Reads in all datasets in given location
#' @param path of file/s
#' @export
#' @keywords read stata sas spss
#' @examples
#' \dontrun{
#' read_all_files(extension = 'dta', path = '~/data/')
#' }
#'
read_all_files = function(extension, location) {
suppressMessages(library(fread))
suppressMessages(library(haven))
setwd(location)
file_pattern = paste0("\\.", extension, "$")
obj = list.files(pattern = file_pattern)
pos = regexpr(extension, obj)
objs = substr(obj, 1, pos - 2)
if (extension == 'Rdata') {
df = lapply(obj, load, envir = .GlobalEnv)
} else if (extension == 'csv') {
df = lapply(obj, fread, envir = .GlobalEnv)
} else if (extension == 'dta') {
for (n in 1:length(objs)) {
assign(paste0(objs[n]), haven::read_dta(obj[n]), envir = .GlobalEnv)
}
} else if (extension == 'sav') {
for (n in 1:length(objs)) {
assign(paste0(objs[n]), haven::read_sav(obj[n]), envir = .GlobalEnv)
}
}
return(objs)
}
# %%
####################################################
#' downloads and unzips file if it is not found in current wdir
#' @param url, filename
#' @export
#' @keywords download
#' @examples
#' \dontrun{
#' get_and_unzip('url', 'qob.txt')
#' }
get_and_unzip = function(url, filename) {
if (!file.exists(filename)) {
download.file(url, "zipped.zip", mode = "wb")
unzip(zipfile = "zipped.zip", files = filename)
}
}
#' Populates a stat-transfer script to convert files to CSV
#' @param path of file/s
#' @export
#' @keywords stat_transfer convert reader
#' @examples
#' \dontrun{
#' stat_transfer_data(path = 'C:/data/data1.sas7bdat', outpath = 'C:/working/')
#' }
#'
############################################
# runs stat-transfer from R - tested on Windows 10
############################################
# alternative to the package readr when files are very large + you have access to stat-transfer
stat_transfer_data = function(path,
stat.transfer.path = '\"C:\\Program Files\\StatTransfer12-64\\st.exe\"',
out.ext = 'csv',
outpath) {
library(tools)
inp.ext = file_ext(path)
if (missing(outpath)) {
path.out = gsub(inp.ext, out.ext, path)
print(c('Writing to ', path.out))
} else {
fn = basename(path)
fn.out = gsub(inp.ext, out.ext, fn)
path.out = paste0(outpath, '\\', fn.out)
print(c('Writing to ', path.out))
}
target = 'conv_script.stcmd'
target_full = paste0(temp.path, 'conv_script.stcmd')
sink(target_full)
cat("SET VAR_CASE_CS lower \n")
cat('copy \"', path, '\" ', '\"', path.out, '\"', ' -y \n', sep = "")
cat('quit \n')
cat('\n')
sink()
command = readlines(target_full)
print(command)
transfer_command = paste0(
stat.transfer.path,
' \"', target_full, '\" \\e'
)
system(transfer_command,
wait = TRUE,
invisible = FALSE,
show.output.on.console = TRUE
)
}
<file_sep>#' Experimental data from the job training program first studied by LaLonde (1986)
#'
#' A dataset of units in an experimental evaluation of a job training
#' program. Subset to those units with two years of pre-treatment income data.
#' \itemize{
#' \item \code{age} - age in years.
#' \item \code{education} - number of years of schooling.
#' \item \code{black} - 1 if black, 0 otherwise.
#' \item \code{hispanic} - 1 if Hispanic, 0 otherwise.
#' \item \code{married} - 1 if married, 0 otherwise.
#' \item \code{nodegree} - 1 if no high school degree, 0 otherwise.
#' \item \code{re74} - earnings ($) in 1974.
#' \item \code{re75} - earnings ($) in 1975.
#' \item \code{re78} - earnings ($) in 1978.
#' \item \code{u74} - 1 if unemployed in 1974, 0 otherwise.
#' \item \code{u75} - 1 if unemployed in 1975, 0 otherwise.
#' \item \code{treat} - 1 if treated, 0 otherwise.
#' }
#'
#' @docType data
#' @keywords datasets
#' @name lalonde.exp
#' @usage data(lalonde.exp)
#' @format A data frame with 445 rows and 12 variables
#' @references LaLonde, <NAME>. (1986). Evaluating the Econometric
#' Evaluations of Training Programs with Experimental Data. The
#' American Economic Review, 76(4), 604--620.
NULL
######################################################################
#' Non-experimental data from Lalonde (1986)
#'
#' A dataset of experimental treated units and non-experimental
#' control units from the Panel Study of Income Dynamics (PSID).
#'
#' \itemize{
#' \item \code{age} - age in years.
#' \item \code{education} - number of years of schooling.
#' \item \code{black} - 1 if black, 0 otherwise.
#' \item \code{hispanic} - 1 if Hispanic, 0 otherwise.
#' \item \code{married} - 1 if married, 0 otherwise.
#' \item \code{nodegree} - 1 if no high school degree, 0 otherwise.
#' \item \code{re74} - earnings ($) in 1974.
#' \item \code{re75} - earnings ($) in 1975.
#' \item \code{re78} - earnings ($) in 1978.
#' \item \code{u74} - 1 if unemployed in 1974, 0 otherwise.
#' \item \code{u75} - 1 if unemployed in 1975, 0 otherwise.
#' \item \code{treat} - 1 if treated, 0 otherwise.
#' }
#'
#' @docType data
#' @keywords datasets
#' @name lalonde.psid
#' @usage data(lalonde.psid)
#' @format A data frame with 2675 rows and 12 variables
#' @references LaLonde, <NAME>. (1986). Evaluating the Econometric
#' Evaluations of Training Programs with Experimental Data. The
#' American Economic Review, 76(4), 604--620.
NULL
######################################################################
#' Public use wage, education data from 1980 census.
#' Used in Mostly Harmless for Mincer Regression.
#'
#' \itemize{
#' \item \code{lwklywge} - Log Wage
#' \item \code{educ} - number of years of schooling.
#' \item \code{yob} - year of birth
#' \item \code{qob} - quarter of birth
#' \item \code{pob} - place of birth (state)
#' \item \code{age} - age in 1980
#' }
#'
#' @docType data
#' @name pums
#' @usage data(pums)
#' @format A data frame with 329,509 rows and 6 variables
NULL
######################################################################
#' California proposition 99
#'
#' A dataset containing per-capita cigarette consumption (in packs).
#' In year 1989 California imposed a Tobacco tax. The column `treated` is 1 from then on for California.
#'
#' @docType data
#' @name california_prop99
#' @format A data frame with 1209 rows and 4 variables:
#' \describe{
#' \item{State}{US state name, character string}
#' \item{Year}{Year, integer}
#' \item{PacksPerCapita}{per-capita cigarette consumption, numeric}
#' \item{treated}{the treatmed indicator 0: control, 1: treated, numeric}
#' }
#' @source Abadie, Alberto, <NAME>, and <NAME>.
#' "Synthetic control methods for comparative case studies: Estimating the effect of California’s tobacco control program."
#' Journal of the American statistical Association 105, no. 490 (2010): 493-505.
#' @usage data(california_prop99)
NULL
<file_sep># %% ####################################################
#' number of unique values in vector
#' @param x vector
#' @return scalar with number of unique values
#' @export
nunique = \(x) length(unique(x))
# %%
#' Shorter length
#' @param x object
#' @return scalar with length
#' @export
len = \(x) length(x)
# %%
#' Source all R scripts in directory
#' @param p path string
#' @export
sourceDir = \(p) {
invisible(lapply(
list.files(p, full.names = TRUE, pattern = "*.R"),
source
))
}
# %%
#' Hex codes for portal game colours (blue and orange)
#' @export
portal_hexcodes = \() c("#ff9a00", "#00a2ff", "#ff5d00", "#0065ff")
# %%
#' t-norm of a vector
#' @param x vector
#' @param t integer
#' @export
vnorm = \(x, t = 2) norm(matrix(x, ncol = 1), t)
# %% ####################################################
#' Timestamp with no spaces for filenames
#' @return character with time stamp in format ff
#' @examples
#' timeStamp()
#' @export
timeStamp = \(ff = "%d_%m_%Y__%H%M") format(Sys.time(), ff)
# %% ####################################################
#' inverse logit fn
#' @param x vector
#' @return vector with e(x)/[1+e(x)]
#' @export
expit = \(x) exp(x) / (1 + exp(x))
# %% ####################################################
#' clip vector to specified range (clone of np.clip)
#' @param x vector
#' @param l lower bound
#' @param u upper bound
#' @return clipped vector
#' @export
clip = \(x, l, u) pmax(pmin(x, u), l)
# %% ####################################################
#' last value
#' @return last value
#' @export
lv = \() .Last.value
# %% ####################################################
#' mask a matrix using another matrix
#' @param A matrix
#' @param M Mask matrix (must be same dimensions with a rectangular subset of TRUEs)
#' @return masked matrix
#' @export
maskMatrix = \(A, M) A[rowSums(M) > 0, colSums(M) > 0, drop = FALSE]
# %% ####################################################
#' list datasets in package
#' @param pkg package name in string
#' @return table with names of data objects
#' @export
dataPkg = \(pkg) data(package = pkg)$results[, 3:4]
# %% ####################################################
#' not.in function
#' @export
'%!in%' = \(x, y)!('%in%'(x, y))
# %% ####################################################
#' coerce to string
#' @export
chr = \(...) as.character(...)
# %% ####################################################
#' list methods for object
#' @export
mls = \(y) Map(function(x) methods(class = x), class(y))
| 34f47cd569e93cb52b3d49921cb344d038beb388 | [
"Markdown",
"R"
] | 19 | R | apoorvalal/LalRUtils | 718b20d0c601993c6385b8256dd40ff055b0a4e9 | 05d0fca93f543fac5c12da47c390a8c083823724 |
refs/heads/main | <repo_name>cmarialetsandra/sha512_grupo4<file_sep>/index.js
const express = require('express');
const login = require('./routes/login');
const app = express();
app.set('port', 3000);
app.use(express.json());
app.use("/login", login);
app.listen(app.get('port'), ()=>{
console.log("Node Server is running");
});<file_sep>/routes/login.js
const express = require("express");
const users = require("../services/users");
const router = express.Router();
router.post('', users.login);
module.exports = router;<file_sep>/README.md
# sha512_grupo4
Algoritmo de encriptación SHA512. Este es un algoritmo de hash criptográfico.
_SHA512 encryption algorithm. This is a cryptographic hashing algorithm._
## Comenzando 🚀
Para poder probar el algoritmo sigue las siguientes instrucciones.
_To be able to test the algorithm, follow the instructions below._
### Pre-requisitos 📋
Para poder trabajar con el proyecto deberás instalar las siguientes dependencias.
_In order to work with the project you must install the following dependencies._
```
npm install nodemon
npm install express
npm install crypto
```
### Instalación 🔧
Y para correr el proyecto simplemente ejecuta.
_And to run the project just run._
```
npm run serve
```
<file_sep>/services/users.js
var crypto = require('crypto');
const users = [
{username: 'dagmara.aburto', password: '<PASSWORD>'},
{username: 'hazel.acuna', password: '<PASSWORD>'},
{username: 'yolanda.bustamante', password: '<PASSWORD>'},
{username: 'marialetsandra.carrazco', password: '<PASSWORD>'},
];
exports.login = function(req, res){
const username = req.body.username;
const password = req.body.password;
var hash = crypto.createHash('sha512');
var data = hash.update(password, 'utf-8');
var generate_hash = data.digest('hex');
console.log("hash : " + generate_hash);
let isLogin = false;
users.forEach(user => {
if(user.username === username && user.password === <PASSWORD>){
isLogin = true;
}
});
res.json({ response: isLogin });
} | 67d7b19e112245a976a9bea0dde68875c5224575 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | cmarialetsandra/sha512_grupo4 | 7689444f44534eb58b06229a0eff6d55a0902e30 | aa6da52cd1af3f0a8d2f6aa3a76f17fc19952ea5 |
refs/heads/main | <file_sep><?php
//sort() - 对数组进行升序排列
//rsort() - 对数组进行降序排列
//asort() - 根据关联数组的值,对数组进行升序排列
//ksort() - 根据关联数组的键,对数组进行升序排列
//arsort() - 根据关联数组的值,对数组进行降序排列
//krsort() - 根据关联数组的键,对数组进行降序排列
$cars=array("Volvo","BMW","Toyota");
sort($cars);<file_sep><?php
$servername = "localhost";
$username = "root";
$password = "<PASSWORD>";
$port = 8889;
$dbname = "azhansy_db";
// 创建连接
$conn = mysqli_connect($servername . ":" . $port, $username, $password, $dbname);
// 检测连接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
} else {
echo "数据库连接成功" . "<br>";
}
// 创建数据库
//$sql = "CREATE DATABASE $dbname";
//if (mysqli_query($conn, $sql)) {
// echo "数据库创建成功";
//} else {
// echo "Error creating database: " . mysqli_error($conn);
//}
// 使用 sql 创建数据表
$sql_account = "CREATE TABLE Account (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
password VARCHAR(50),
reg_date TIMESTAMP
)";
//insert();
function insert()
{
$sql = "INSERT INTO Account (firstname, lastname, email,password)
VALUES ('John', 'Doe', '<EMAIL>,123456','<PASSWORD>')";
global $conn;
if (mysqli_query($conn, $sql)) {
echo "插入成功";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
//if ($conn->query($sql_account) === TRUE) {
// echo "Table Account created successfully";
//} else {
// echo "创建数据表错误: " . $conn->error;
//}
//mysqli_query($conn, "set character set 'utf8'");//读库
//mysqli_query($conn,"set names 'utf8'");//写库
mysqli_close($conn);
<file_sep><!DOCTYPE html>
<html lang="cn">
<body>
<h1>
My first PHP page</h1>
<?php
//php 单行注释
/*这是php
多行注释*/
echo "1、打印文案:hello world!! </br>";
$x = 5;
$y = 6;
$z = $x + $y;
echo "2、变量运算符:$x+$y=$z";
echo "</br>";
echo 'PHP变量作用域: local global static parameter';
$a = 5;//全局变量
function myTest()
{
$b = 10;//局部变量
echo "<p>测试函数内变量<p>";
global $a;
echo "变量a为:$a";
echo "<br>";
echo "变量b为:$b";
}
myTest();
echo 'PHP 将所有全局变量存储在一个名为 $GLOBALS[index] 的数组中。 index 保存变量的名称。这个数组可以在函数内部访问,也可以直接用来更新全局变量';
echo "<p>测试函数外变量:<p>";
echo "变量 a 为: $a";
echo "<br>";
//echo "变量 b 为: $b";
function globalTest()
{
$GLOBALS['a'] = $GLOBALS['x'] + $GLOBALS['y'];
global $a;
echo $a;
}
globalTest();
echo "<br>";
echo '希望某个局部变量不要被删除';
echo "<br>";
function myStaticTest()
{
static $x=0;
echo $x;
$x++;
echo PHP_EOL; // 换行符
}
myStaticTest();
echo PHP_EOL;
myStaticTest();
myStaticTest();
echo "<br>";
echo "$x";
echo "<br>";
echo "ddddd";
echo "<br>";
echo "PHP EOF(heredoc) 使用说明";
$name="runoob";
$a= <<<EOF
"abc"$name
"123"
EOF;
// 结束需要独立一行且前后不能空格
echo $a;
echo "数据类型";
?>
</body>
</html><file_sep><?php
class Car
{
var $color;
function __construct($color = "green")
{
$this->color = $color;
}
function what_color()
{
return $this->color;
}
}<file_sep><?php
$t = date("H");
echo $t;
echo "<br>";
if ($t < 20) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
echo "<br>";
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "你喜欢的颜色是红色!";
break;
case "blue":
echo "你喜欢的颜色是蓝色!";
break;
case "green":
echo "你喜欢的颜色是绿色!";
break;
default:
echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
}
echo "<br>";
$cars=array("Volvo","BMW","Toyota");
//$carsObject=array("Volvo","BMW","Toyota");
//echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
echo json_encode($cars,JSON_UNESCAPED_UNICODE);
//echo json_encode($carsObject,JSON_UNESCAPED_UNICODE);
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
<file_sep><?php
phpinfo();
// phpinfo(INFO_MODULES);
//echo "hello, PHP\n";
//echo("函数的 hello PHP\n");
//声明header为json
// header("Content-type:application/json");
// //构建数据
// $data = array(
// array(
// 'title'=>'百度',
// 'time'=>'2000',
// 'website'=>'www.baidu.com'
// ),
// array(
// 'title'=>'阿里巴巴',
// 'time'=>'1999',
// 'website'=>'www.alibaba.com'
// ),
// array(
// 'title'=>'腾讯',
// 'time'=>'1998',
// 'website'=>'www.qq.com'
// )
// );
// //转为JSON
// echo json_encode($data,JSON_UNESCAPED_UNICODE);
?><file_sep><?php
function funInt()
{
echo "var_dump 返回变量的数据类型和值";
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // 负数
var_dump($x);
echo "<br>";
$x = 0x8C; // 十六进制数
var_dump($x);
echo "<br>";
$x = 047; // 八进制数
var_dump($x);
}
function funFloat()
{
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
$x = 8E-5;
var_dump($x);
}
function funBool()
{
$x = true;
$y = false;
}
function funArray()
{
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
}
echo "<br>";
funInt();
echo "<br><br> 分割 <br><br>";
funFloat();
echo "<br><br> 分割 <br><br>";
funArray();
echo "<br><br> 分割 <br><br>";
$x="Hello world!";
$x=null;
var_dump($x);
echo "<br><br> 分割 <br><br>";
if(42 == "42") {
echo '1、值相等';
}
echo PHP_EOL; // 换行符
if(42 === "42") {
echo '2、类型相等';
} else {
echo '3、类型不相等';
}
echo "比较 0、false、null、空字符串";
echo "<br>";
echo '0 == false: ';
var_dump(0 == false);
echo '0 === false: ';
var_dump(0 === false);
echo PHP_EOL;
echo '0 == null: ';
var_dump(0 == null);
echo '0 === null: ';
var_dump(0 === null);
echo PHP_EOL;
echo 'false == null: ';
var_dump(false == null);
echo 'false === null: ';
var_dump(false === null);
echo PHP_EOL;
echo "<br>";
echo '"0" == false: ';
var_dump("0" == false);
echo '"0" === false: ';
var_dump("0" === false);
echo PHP_EOL;
echo '"0" == null: ';
var_dump("0" == null);
echo '"0" === null: ';
var_dump("0" === null);
echo PHP_EOL;
echo '"" == false: ';
var_dump("" == false);
echo '"" === false: ';
var_dump("" === false);
echo PHP_EOL;
echo '"" == null: ';
var_dump("" == null);
echo '"" === null: ';
var_dump("" === null);
echo '<br>';
echo '<br>';
// 区分大小写的常量名 常量是全局的
//const GREETING = "欢迎访问 Runoob.com";
//echo GREETING; // 输出 "欢迎访问 Runoob.com"
//echo '<br>';
//echo greeting; // 输出 "greeting"
// 不区分大小写的常量名
const GREETING = "欢迎访问 Runoob.com";
echo GREETING; // 输出 "欢迎访问 Runoob.com"
echo '<br>';
//echo greeting; // 输出 "欢迎访问 Runoob.com"
echo '<br>';
//字符串追加
$text1 = 'Hello World!';
$text2 = 'What a nice day';
echo $text1.$text2;
echo "<br>";
echo strlen("Hello world!");
echo "<br>";
echo var_dump("Hello world!");
echo "<br>";
echo var_export("Hello world!");
echo "<br>";
//该函数会返回第一个匹配的字符位置。如果未找到匹配,则返回 FALSE。
echo strpos("Hello world!","world");
echo "<br>";
///intdiv
var_dump(intdiv(10, 3));
echo "<br>";
$test = '菜鸟教程';
// 普通写法 isset 不为空
//$username = isset($test) ? $test : 'nobody';
$username = $test ?? 'nobody';
echo $username, PHP_EOL;
// PHP 5.3+ 版本写法
$username = $test ?: 'nobody';
echo $username, PHP_EOL;<file_sep><?php
//声明header为json
header("Content-type:application/json");
//构建数据
$data = array(
array(
'title' => '百度',
'time' => '2000',
'website' => 'www.baidu.com'
),
array(
'title' => '阿里巴巴',
'time' => '1999',
'website' => 'www.alibaba.com'
),
array(
'title' => '腾讯',
'time' => '1998',
'website' => 'www.qq.com'
)
);
$json = array(
'title' => '腾讯',
'time' => '1998',
'website' => 'www.qq.com'
);
echo "<br>";
echo "<br>";
echo "<br>";
//转为JSON
echo json_encode($data, JSON_UNESCAPED_UNICODE);
echo json_encode($json, JSON_UNESCAPED_UNICODE);
<file_sep># php_learning
php learning
| 392855816afe47184be58566133e027d40da3f82 | [
"Markdown",
"PHP"
] | 9 | PHP | azhansy/php_learning | 97e0abaf7b4b56f5ee447afe8954ac701bbc9303 | 6f9febfcf3d4be13029e82d09c580ff07a7c8901 |
refs/heads/master | <file_sep>import java.lang.invoke.MethodType;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import java.nio.charset.StandardCharsets;
/**
* Class for a space explorer.
*/
public class SpaceExplorer extends Thread {
/**
* Creates a {@code SpaceExplorer} object.
*
* @param hashCount
* number of times that a space explorer repeats the hash operation
* when decoding
* @param discovered
* set containing the IDs of the discovered solar systems
* @param channel
* communication channel between the space explorers and the
* headquarters
*/
Integer MyPosition;
Integer MyParentPosition;
Integer hashCount;
Set<Integer> discovered;
CommunicationChannel channel;
public SpaceExplorer(Integer hashCount, Set<Integer> discovered, CommunicationChannel channel) {
this.channel=channel;
this.discovered=discovered;
this.hashCount=hashCount;
}
@Override
public void run() {
String data;
while (true) {
//synchronized (channel) {
Message m = channel.getMessageHeadQuarterChannel();
data = m.getData();
MyParentPosition = m.getParentSolarSystem();
MyPosition = m.getCurrentSolarSystem();
if (!discovered.contains(MyPosition)) {
discovered.add(MyPosition);
String exitData = encryptMultipleTimes(data, hashCount);
Message mout = new Message(MyParentPosition, MyPosition, exitData);
channel.putMessageSpaceExplorerChannel(mout);
}
}
// }
}
/**
* Applies a hash function to a string for a given number of times (i.e.,
* decodes a frequency).
*
* @param input
* string to he hashed multiple times
* @param count
* number of times that the string is hashed
* @return hashed string (i.e., decoded frequency)
*/
private String encryptMultipleTimes(String input, Integer count) {
String hashed = input;
for (int i = 0; i < count; ++i) {
hashed = encryptThisString(hashed);
}
return hashed;
}
/**
* Applies a hash function to a string (to be used multiple times when decoding
* a frequency).
*
* @param input
* string to be hashed
* @return hashed string
*/
private static String encryptThisString(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
// convert to string
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xff & messageDigest[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
<file_sep>import javax.lang.model.type.NullType;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
/**
* Class that implements the channel used by headquarters and space explorers to communicate.
*/
public class CommunicationChannel {
/**
* Creates a {@code CommunicationChannel} object.
*/
Map<Integer,Boolean> destination= new HashMap<Integer,Boolean>(4);
int parent1;
Map<Integer,Integer> parent= new HashMap<Integer,Integer>();
Message aux1;
ArrayBlockingQueue<Message> toHeadquarters = new ArrayBlockingQueue<>(250000);
ArrayBlockingQueue<Message> toShip = new ArrayBlockingQueue<>(2500000);
public CommunicationChannel() {
}
/**
* Puts a message on the space explorer channel (i.e., where space explorers write to and
* headquarters read from).
*
* @param message bag mesaj in canal de la se
*/
public void putMessageSpaceExplorerChannel(Message message) {
try {
//toHeadquarters.remove(message);
toHeadquarters.put(message);
} catch (InterruptedException e) {
}
}
/**
* Gets a message from the space explorer channel (i.e., where space explorers write to and
* headquarters read from).
*
* @return message from the space explorer channel
* scot mesaj de la se
*/
public Message getMessageSpaceExplorerChannel() {
try {
return toHeadquarters.take();
} catch (InterruptedException e) {
return null;
}
}
/**
* Puts a message on the headquarters channel (i.e., where headquarters write to and
* space explorers read from).
*
* @param message message to be put on the channel
*/
public void putMessageHeadQuarterChannel(Message message) {
int thid= (int)Thread.currentThread().getId();
try {
if(!message.getData().equals("END") && !message.getData().equals("EXIT")) {
if (message.getData().equals("NO_PARENT")) {
destination.put(thid, false);
parent.put(thid, message.getCurrentSolarSystem());
} else {
if (destination.get(thid) == true) {
parent.replace(thid, message.getCurrentSolarSystem());
destination.replace(thid, false);
} else {
aux1 = new Message(parent.get(thid), message.getCurrentSolarSystem(), message.getData());
//toShip.remove(aux1);
toShip.put(aux1);
destination.replace(thid, true);
}
}
}
} catch (InterruptedException e) {
}
}
/**
* Gets a message from the headquarters channel (i.e., where headquarters write to and
* space explorer read from).
*
* @return message from the header quarter channel
*/
public Message getMessageHeadQuarterChannel() {
try {
return toShip.take();
} catch (InterruptedException e) {
return null;
}
}
} | 801ad2e7455254e6553b934ddfc32b6e040b5bf3 | [
"Java"
] | 2 | Java | CezarMarcu98/TemaApd2 | 2837572e24ba19afd94e6c22ac3e76f8d7af9eee | 05a494723cdbfc8dda07d093498ee70d5ad932e5 |
refs/heads/master | <file_sep>import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
import os
def plot_depth_recall_curve(method_recalls, type='', save_path=None, method_color=None):
assert type in ['pixel', 'PIXEL', 'Pixel', 'plane', 'PLANE', 'Plane']
depth_threshold = np.arange(0, 0.65, 0.05)
title = 'Per-'+type+' Recall(%)'
pre_defined_recalls = {}
if type in ['pixel', 'PIXEL', 'Pixel']:
recall_planeAE = np.array(
[0., 30.59, 51.88, 62.83, 68.54, 72.13, 74.28, 75.38, 76.57, 77.08, 77.35, 77.54, 77.86])
pre_defined_recalls['PlaneAE'] = recall_planeAE
recall_planeNet = np.array(
[0., 22.79, 42.19, 52.71, 58.92, 62.29, 64.31, 65.20, 66.10, 66.71, 66.96, 67.11, 67.14])
pre_defined_recalls['PlaneNet'] = recall_planeNet
else:
recall_planeAE = np.array(
[0., 22.93, 40.17, 49.40, 54.58, 57.75, 59.72, 60.92, 61.84, 62.23, 62.56, 62.76, 62.93])
pre_defined_recalls['PlaneAE'] = recall_planeAE
recall_planeNet = np.array(
[0., 15.78, 29.15, 37.48, 42.34, 45.09, 46.91, 47.77, 48.54, 49.02, 49.33, 49.53, 49.59])
pre_defined_recalls['PlaneNet'] = recall_planeNet
plt.figure(figsize=(5, 4))
plt.xlabel('Depth Threshold', fontsize=18)
plt.ylabel(title, fontsize=18)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
markers = {'PlaneNet': 'o', 'PlaneAE': '*'}
colors = {'PlaneNet': 'gray', 'PlaneAE': '#FFCC99'}
for method_name, recalls in pre_defined_recalls.items():
assert len(depth_threshold) == len(recalls)
plt.plot(depth_threshold, recalls, linewidth=3, marker=markers[method_name],label=method_name, color=colors[method_name])
for method_name, recalls in method_recalls.items():
assert len(depth_threshold) == len(recalls)
if method_color is not None:
plt.plot(depth_threshold, recalls, linewidth=3, marker='^', color=method_color[method_name], label=method_name)
else:
plt.plot(depth_threshold, recalls, linewidth=3, marker='^', label=method_name, color='#FF6666')
plt.legend(loc='lower right', fontsize=16)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
x_major_locator = MultipleLocator(0.1)
y_major_locator = MultipleLocator(20)
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
plt.tight_layout()
if save_path is not None:
plt.savefig(os.path.join(save_path, 'depth_recall_%s.png'%(type)))
else:
plt.savefig('../results/depth_recall_%s.png'%(type))
plt.close()
def plot_normal_recall_curve(method_recalls, type='', save_path=None, method_color=None):
assert type in ['pixel', 'PIXEL', 'Pixel', 'plane', 'PLANE', 'Plane']
normal_threshold = np.linspace(0.0, 30, 13)
title = 'Per-'+type+' Recall(%)'
pre_defined_recalls = {}
if type in ['pixel', 'PIXEL', 'Pixel']:
recall_planeAE = np.array(
[0., 30.20, 59.89, 69.79, 73.59, 75.67, 76.8, 77.3, 77.42, 77.57, 77.76, 77.85, 78.03])
pre_defined_recalls['PlaneAE'] = recall_planeAE
recall_planeNet = np.array(
[0., 19.68, 43.78, 57.55, 63.36, 65.27, 66.03, 66.64, 66.99, 67.16, 67.20, 67.26, 67.29])
pre_defined_recalls['PlaneNet'] = recall_planeNet
else:
recall_planeAE = np.array(
[0., 20.05, 42.66, 51.85, 55.92, 58.34, 59.52, 60.35, 60.75, 61.23, 61.64, 61.84, 61.93])
pre_defined_recalls['PlaneAE'] = recall_planeAE
recall_planeNet = np.array(
[0., 12.49, 29.70, 40.21, 44.92, 46.77, 47.71, 48.44, 48.83, 49.09, 49.20, 49.31, 49.38])
pre_defined_recalls['PlaneNet'] = recall_planeNet
plt.figure(figsize=(5, 4))
plt.xlabel('Normal Threshold', fontsize=18)
plt.ylabel(title, fontsize=18)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
markers = {'PlaneNet': 'o', 'PlaneAE': '*', 'PlaneRCNN': '.'}
colors = {'PlaneNet': 'gray', 'PlaneAE': '#FFCC99', 'PlaneRCNN': 'mediumaquamarine'}
for method_name, recalls in pre_defined_recalls.items():
assert len(normal_threshold) == len(recalls)
plt.plot(normal_threshold, recalls, linewidth=3, marker=markers[method_name], label=method_name,
color=colors[method_name])
for method_name, recalls in method_recalls.items():
assert len(normal_threshold) == len(recalls)
if method_color is not None:
plt.plot(normal_threshold, recalls, linewidth=3, marker='^', color=method_color[method_name], label=method_name)
else:
plt.plot(normal_threshold, recalls, linewidth=3, marker='^', label=method_name, color='#FF6666')
plt.legend(loc='lower right', fontsize=16)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
x_major_locator = MultipleLocator(5)
y_major_locator = MultipleLocator(20)
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
plt.tight_layout()
if save_path is not None:
plt.savefig(os.path.join(save_path, 'normal_recall_%s.png'%(type)))
else:
plt.savefig('../results//normal_recall_%s.png'%(type))
plt.close()
| f571c7d542d9f018b534e18ac5ff220dc911af2e | [
"Python"
] | 1 | Python | braca51e/PlaneTR3D | a1003b725f9fa505c63c72886aea96e16d794b50 | 9f32ed405476b700317c9fe91b2c4c362469caaa |
refs/heads/main | <file_sep>asp = prom = prom1 = ing = genero1 = genero2 = 0
edad = []
gen = ip = tac = " "
genero = []
tacones = []
promtac = promtac2 = 0
x = 0
i = 0
s = 0
w = 0
print("Indique el genero del aspirante con M o F")
print("Indique si posee tacones o iPhone con S o N")
print("------------------------")
for x in range(0,20):
asp = int(input("Edad del aspirante: "))
i += 1
gen =(input("Genero del aspirante: "))
tac = input("Posee iPhone: ")
ip = input("Posee Tacones: ")
print("------------------------")
genero.append(gen)
edad.append(asp)
if tac == "S":
tacones.append(asp)
w += 1
if ip == "S":
s += 1
prom = sum(edad)
prom1 = prom / 20
genero1 = genero.count("M")
genero2 = genero.count("F")
promtac = sum(tacones)
promtac2 = promtac/w
print("Promedio de edad: ",prom1)
print("Cantidad de damas: ", genero2)
print("Cantidad de caballeros: ", genero1)
print("Cantidad de personas con iPhone: ", s)
print("Promedio de personas que usan tacones: ",promtac2)
| 44a1dd80d1f385dce7791c36f656661d7b26b887 | [
"Python"
] | 1 | Python | eloyrutman/programa-con-if-y-listas | d127db1a46af872fb73cfc76e9f3ab6770799d56 | 723a4b2f7c5407f4ab42dde73d6419f40edd4c49 |
refs/heads/master | <file_sep>#include "httpmanager.h"
#include <QJsonDocument>
#include <QJsonObject>
HTTPManager::HTTPManager(QObject *parent) :
QObject(parent),
imageDownloadManager(new QNetworkAccessManager),
weatherAPIManager(new QNetworkAccessManager),
iconDownloadManager(new QNetworkAccessManager),
timeDownloadManager(new QNetworkAccessManager)
{
connect(imageDownloadManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(ImageDownloadedHandler(QNetworkReply*)));
connect(weatherAPIManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(WeatherDownloadedHandler(QNetworkReply*)));
connect(iconDownloadManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(IconDownloadedHandler(QNetworkReply*)));
connect(timeDownloadManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(TimeDownloadedHandler(QNetworkReply*)));
}
HTTPManager::~HTTPManager()
{
delete imageDownloadManager;
delete weatherAPIManager;
}
void HTTPManager::sendImageRequest(QString zip)
{
QNetworkRequest request;
QString address = "https://dev.virtualearth.net/REST/V1/Imagery/Map/Road/" +
zip +
"/13?mapSize=650,650&mapLayer=TrafficFlow&format=png&key=<KEY>";
request.setUrl(QUrl(address));
imageDownloadManager->get(request);
qDebug() << "Image Request Sent to Address " << request.url();
}
void HTTPManager::sendWeatherRequest(QString zip)
{
QNetworkRequest request;
QString address = "http://api.openweathermap.org/data/2.5/weather?zip=" +
zip +
",us&units=imperial&appid=92bf69ee666fa67e27fb57300dcab879";
request.setUrl(QUrl(address));
weatherAPIManager->get(request);
qDebug() << "Weather Request Sent to Address " << request.url();
}
void HTTPManager::sendIconRequest(QString icon)
{
QNetworkRequest request;
QString address = "http://openweathermap.org/img/wn/" +
icon +
"@2x.png";
request.setUrl(QUrl(address));
iconDownloadManager->get(request);
qDebug() << "Icon Request Sent to Address " << request.url();
}
void HTTPManager::sendTimeRequest(QString zone)
{
QNetworkRequest request;
QString address = "https://api.ipgeolocation.io/timezone?apiKey=<KEY>&tz=" + zone;
request.setUrl(QUrl(address));
timeDownloadManager->get(request);
}
// After receving the image
void HTTPManager::ImageDownloadedHandler(QNetworkReply *reply)
{
qDebug() << "Image Reply has arrived";
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
qDebug() << "Download was successful";
QPixmap *image = new QPixmap();
image->loadFromData(reply->readAll());
emit ImageReady(image);
}
// After receiving the weather
void HTTPManager::WeatherDownloadedHandler(QNetworkReply *reply)
{
qDebug() << "Weather Reply has arrived";
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
qDebug() << "Download was successful";
QString answer = reply->readAll();
reply->deleteLater();
QJsonDocument jsonResponse = QJsonDocument::fromJson(answer.toUtf8());
QJsonObject *jsonObj = new QJsonObject(jsonResponse.object());
emit WeatherJsonReady(jsonObj);
}
// After receving the icon
void HTTPManager::IconDownloadedHandler(QNetworkReply *reply)
{
qDebug() << "Icon Reply has arrived";
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
qDebug() << "Download was successful";
QPixmap *image = new QPixmap();
image->loadFromData(reply->readAll());
emit IconReady(image);
}
// After receving the time
void HTTPManager::TimeDownloadedHandler(QNetworkReply *reply)
{
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
QString answer = reply->readAll();
reply->deleteLater();
QJsonDocument jsonResponse = QJsonDocument::fromJson(answer.toUtf8());
QJsonObject *jsonObj = new QJsonObject(jsonResponse.object());
emit TimeJsonReady(jsonObj);
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
#include <QTime>
#include "httpmanager.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void setCurrentTime();
void setGlobalTime();
void changeImage();
void processImage(QPixmap *);
void processWeatherJson(QJsonObject *json);
void processIcon(QPixmap *);
void processTimeJson(QJsonObject *json);
void on_updateButton_clicked();
void on_timeUp_clicked();
private:
Ui::MainWindow *ui;
QTimer *timer;
QTimer *imageTimer;
HTTPManager *httpManager;
};
#endif // MAINWINDOW_H
<file_sep># -CSC3220-Lab-4<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QTimeZone>
int imageNum = 0;
QString zone = "UTC";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
timer(new QTimer),
imageTimer(new QTimer),
httpManager(new HTTPManager)
{
ui->setupUi(this);
connect(timer, SIGNAL(timeout()),
this, SLOT(setCurrentTime()));
connect(timer, SIGNAL(timeout()),
this, SLOT(setGlobalTime()));
connect(imageTimer, SIGNAL(timeout()),
this, SLOT(changeImage()));
setCurrentTime();
changeImage();
timer->start(1000);
imageTimer->start(10000);
connect(httpManager, SIGNAL(ImageReady(QPixmap *)),
this, SLOT(processImage(QPixmap *)));
connect(httpManager, SIGNAL(WeatherJsonReady(QJsonObject *)),
this, SLOT(processWeatherJson(QJsonObject *)));
connect(httpManager, SIGNAL(IconReady(QPixmap *)),
this, SLOT(processIcon(QPixmap *)));
connect(httpManager, SIGNAL(TimeJsonReady(QJsonObject *)),
this, SLOT(processTimeJson(QJsonObject *)));
QString zip = ui->zipcodeEdit->text();
httpManager->sendImageRequest(zip);
httpManager->sendWeatherRequest(zip);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setCurrentTime()
{
QTime time = QTime::currentTime();
QString hour = time.toString("hh");
QString minute = time.toString("mm");
QString second = time.toString("ss");
ui->hourNum->display(hour);
ui->minNum->display(minute);
ui->secNum->display(second);
}
void MainWindow::setGlobalTime()
{
httpManager->sendTimeRequest(zone);
}
void MainWindow::changeImage()
{
QString address = "C:/Users/Chari/Desktop/Qt/Dashboard/images/" + QString::number(imageNum) + ".png";
ui->pictureLabel->setPixmap(QPixmap(address).scaled(1140,650));
imageNum++;
if (imageNum == 5) {
imageNum = 0;
}
}
void MainWindow::processImage(QPixmap *image)
{
ui->imageLabel->setPixmap(QPixmap(*image).scaled(650,650,Qt::KeepAspectRatio));
}
void MainWindow::processIcon(QPixmap *image)
{
ui->iconLabel->setPixmap(QPixmap(*image).scaled(150,150,Qt::KeepAspectRatio));
}
void MainWindow::processWeatherJson(QJsonObject *json)
{
qDebug() << "Json ready";
QString icon = json->value("weather").toArray()[0].toObject()["icon"].toString();
double temp = json->value("main").toObject()["temp"].toDouble();
double humidity = json->value("main").toObject()["humidity"].toDouble();
httpManager->sendIconRequest(icon);
ui->weatherLabel->setText(QString::number(temp) + "°");
ui->humidLabel->setText("humidity: " + QString::number(humidity) + "°");
/*
* {
* http://openweathermap.org/img/wn/ +
* zip +
* @2x.png
*
* "coord": {"lon":-122.38,"lat":47.64},
* "weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],
* "base":"stations",
* "main":{"temp":288.38,"pressure":1015,"humidity":72,"temp_min":287.04,"temp_max":289.82},
* "visibility":16093,
* "wind":{"speed":2.22,"deg":329.191},
* "clouds":{"all":75},
* "dt":1558543054,
* "sys":{"type":1,"id":3417,"message":0.0113,"country":"US","sunrise":1558527857,"sunset":1558583303},
* "timezone":-25200,"id":420040214,"name":"Seattle","cod":200
* }
* */
}
void MainWindow::processTimeJson(QJsonObject *json)
{
QString time = json->value("time_24").toString();
ui->gHour->display(QString(time.at(0)) + QString(time.at(1)));
ui->gMin->display(QString(time.at(3)) + QString(time.at(4)));
ui->gSec->display(QString(time.at(6)) + QString(time.at(7)));
}
void MainWindow::on_updateButton_clicked()
{
QString zip = ui->zipcodeEdit->text();
qDebug() << zip;
httpManager->sendImageRequest(zip);
httpManager->sendWeatherRequest(zip);
}
void MainWindow::on_timeUp_clicked()
{
zone = ui->upBox->text();
}
| 8e36f3c996f41017a446e21f76f87878829ae2d2 | [
"Markdown",
"C++"
] | 4 | C++ | JonathanXu4/-CSC3220-Lab-4 | 6b72d986e6a2dcf5b144939fbeed9564c7ef49cb | 8a417d1ff6609bcc879ca8608969a974f4b8a26a |
refs/heads/master | <repo_name>chimaezeorah/edoga-<file_sep>/app.py
#import sys
#print(sys.executable)
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Output, Input
import dash_table
#import mysql.connector as mysql
#import time
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
import plotly.express as px
#from datetime import datetime, date
import dash_auth
# needed only if running this as a single page app
external_stylesheets = [dbc.themes.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
#auth = dash_auth.BasicAuth(
#app,
#{'chima': 'business-intelligence',
#'tom': 'mantom'}
#)
while True:
#time.sleep(5)
#HOST = "172.16.17.32" # or "domain.com"
# database name, if you want just to connect to MySQL server, leave it empty
#DATABASE = "getfit"
# this is the user you create
#USER = "_rchim"
# user password
#PASSWORD = <PASSWORD>"
# connect to MySQL server
#db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
#print("Connected to:", db_connection.get_server_info())
# while True:
# sleep(60 - time() % 60)
#cursor = db_connection.cursor()
# get database information
#cursor.execute("select database();")
#database_name = cursor.fetchone()
#print("[+] You are connected to the database:", database_name)
# fetch the database
#df = cursor.execute("select * from customers")
# get all selected rows #rows = cursor.fetchall()
df = pd.read_csv('data/customers.csv')
df100 = df[['id', 'name', 'phone', 'email', 'state', 'country', 'created_at', 'updated_at']]
df6 = df[df.country == 'nigeria']
#df9 = df[(df['country'] != 'Nigeria')]
df9 = df[~df['country'].isin(['Nigeria'])]
#df10 = df9['country']
#df10.count()
df1 = pd.read_csv('data/orders.csv')
#limo = df1[df1['note']].isin(['<NAME>', '<NAME>(influencer)'])
#nysc = df1[df1['note']].isin(['NYSC sales'])
#limo = df1[df1['note']].isin(['<NAME>', '<NAME>(influencer)'])
#nysc = df1[df1['note']].isin(['NYSC sales', 'NYSC SALES', 'NYSC Sales', 'nysc sales'])
df1['created_at'] = pd.to_datetime(df1['created_at']).dt.date
df1['updated_at'] = pd.to_datetime(df1['updated_at']).dt.date
df1['updated_at'] = pd.to_datetime(df1['updated_at']).dt.strftime('%Y-%m-%d')
df1['created_at'] = pd.to_datetime(df1['created_at']).dt.strftime('%Y-%m-%d')
#print(df1)
df7 = pd.read_csv('data/orderproducts.csv')
df14 = pd.read_csv('data/employees.csv')
df20 = pd.read_csv('data/products.csv')
#df2 = df6.groupby('country').size().reset_index(name='counts')
#df5 = df[(df.country =="nigeria")]
df8 = df7[['id', 'product_id', 'order_id', 'status', 'created_at']]
#print("csv imported")
df0 = df[df['country'].isin(['Nigeria', 'Ghana'])]
df10 = df[df['country'].isin(['Nigeria'])]
df2 = df10.groupby('state').size().reset_index(name='counts')
df11 = df9[df9['country'].isin(['Ghana', 'USA', 'United Kingdom', 'United States', 'Russia', 'Sweden', 'Turkey', 'Germany',
'France', 'Algeria', 'Belgium', 'Qatar', 'Benin', 'China', 'Italy', 'Spain', 'Ireland', 'Liberia', 'Switzerland',
'Zambia', 'Canada', 'Botswana', 'New Zealand', 'Australia', 'Cameroon', 'Bulgaria', 'South Africa', 'Bahrain', 'Scotland',
'Netherlands', 'Botswana'])]
df12 = df11.groupby('country').size().reset_index(name='counts')
#matching total getfit product sales
df15 = df7[df7['status'].isin([1])]
df21 = pd.merge(df15, df20, left_on="product_id", right_on="product_id")
#print(df21)
df22 = df21.groupby('name').size().reset_index(name='products sold')
#print(df22)
#df22.count()
#number of sales as per getfit employee
#print(df14.shape)
df200 = df14[~df14['name'].isin(['PROMO', '<NAME>'])]
df16 = pd.merge(df1, df14, left_on="employee_id", right_on="id")
df300 = pd.merge(df1, df200, left_on="employee_id", right_on="id")
#print(df200.shape)
df17 = df16.groupby('name').size().reset_index(name='number of sales')
df25 = df16.groupby(['name', 'created_at_x']
).size().unstack(fill_value=0)
#print(df16)
#for col in df16.columns:
#print(col)
#print(df25)
#break;
df3 = df.groupby(["state"]).size().reset_index(name='counts')
#df1['created_at_y'] = pd.to_datetime(df21['created_at_y']).dt.date
#df21['updated_at_y'] = pd.to_datetime(df21['updated_at_y']).dt.date
#df['date'] = pd.to_datetime(df['date']).dt.date
available_employee = df14['name'].unique()
#print(available_employee)
fig = px.bar(
df2, # dataframe
x="state", # x
y="counts", # y
labels={"x": "state", "y": "counts"}, # define label
color="counts",
#color=df2.groupby("country")["counts"].agg(sum),
#color_continuous_scale=px.colors.sequential.RdBu, # color
text="counts",
#text=df2.groupby("country")["counts"].agg(sum), # text
title="Nigerian Customers Count", # title
orientation="v",# horizonal bar chart
height=600
)
fig3 = px.bar(
df12, # dataframe
x="country", # x
y="counts", # y
labels={"x": "country", "y": "counts"}, # define label
color="counts",
# color=df2.groupby("country")["counts"].agg(sum),
# color_continuous_scale=px.colors.sequential.RdBu, # color
text="counts",
# text=df2.groupby("country")["counts"].agg(sum), # text
title="International Customers Count", # title
orientation="v", # horizonal bar chart
height=350
)
fig4 = px.bar(
df17, # dataframe
x="number of sales", # x
y="name", # y
labels={"x": "number of sales", "y": "name"}, # define label
color="number of sales",
# color=df2.groupby("country")["counts"].agg(sum),
# color_continuous_scale=px.colors.sequential.RdBu, # color
text="number of sales",
# text=df2.groupby("country")["counts"].agg(sum), # text
title="Total Historical Orders By Customer Rep", # title
orientation="h", # horizonal bar chart
height=550
)
fig5 = px.bar(
df22, # dataframe
x="products sold", # x
y="name", # y
labels={"x": "products sold", "y": "name"}, # define label
color="products sold",
# color=df2.groupby("country")["counts"].agg(sum),
color_continuous_scale=px.colors.sequential.RdBu, # color
text="products sold",
# text=df2.groupby("country")["counts"].agg(sum), # text
title="Total Historical Getfit Products Sold", # title
orientation="h", # horizonal bar chart
height=650
)
fig2 = dbc.Col(html.Div(children=[dash_table.DataTable(
id='table1',
columns=[{"id": i, "order_id": i} for i in df8.columns],
data=df.to_dict('records'),
# data=df1.to_dict('records'),
page_size=5,
filter_action='native',
export_format='xlsx',
export_headers='display',
merge_duplicate_headers=True,
# style_table={'margin:2px'},
# style_header={'backgroundColor': 'rgb(30, 30, 30)'},
style_cell={
# 'backgroundColor': 'rgb(50, 50, 50)',
'color': 'black'
},
),
],
),
),
#columns = ["id", "name", "phone", "email", "instagram", "state", "country", "customer_ser_id", "created_at",
#"updated_at"]
#df1 = pd.DataFrame(columns=columns)
#state = df1['state']
#state
df.rename(columns={'id': 'id',
'name': 'name',
'phone': 'phone',
'email': 'email',
'instagram': 'instagram',
'state': 'state',
'country': 'country',
'ser_id': 'ser_id',
'created_at': 'created_at',
'updated_at': 'updated_at'
},
inplace=True)
#print("all imported data")
#print("looping again")
#app = dash.Dash(__name__)
app.layout = html.Div([
#dbc.Container([
dbc.Row([
dbc.Col(html.H4('Getfit Analytics Dashboard', className="header-title", style={'text-align': 'center', 'color': 'blue'}))]),
dbc.Row([
dbc.Col(dbc.Card(html.H6(children='Customers Latest Update',
className="text-center text-light sm-dark"), body=True, color="dark")
, className="mb-2"
)
]),
dash_table.DataTable(
id='table',
columns=[{"id": i, "name": i} for i in df100.columns],
data=df100.to_dict('records'),
# data=df1.to_dict('records'),
page_size=5,
filter_action='native',
export_format='xlsx',
export_headers='display',
merge_duplicate_headers=True,
#style_table={'margin:2px'},
#style_header={'backgroundColor': 'rgb(30, 30, 30)'},
style_cell={
#'backgroundColor': 'rgb(50, 50, 50)',
'color': 'black',
'left-padding': '10%'
},
),
dcc.Markdown(id='test_cell'),
dbc.Row([
dbc.Col(html.H5(children='--------------------------------------------------', className="text-center"),
className="mt-4"),
]),
dbc.Row([
dbc.Col(
dcc.Graph(figure=fig)),
], style={"height": "120%", "width": "100%"}),
dbc.Row([
dbc.Col(
dcc.Graph(figure=fig3)),
], style={"height": "120%", "width": "100%"}),
dbc.Row([
dbc.Col(
dcc.Graph(figure=fig4)),
dbc.Col(
dcc.Graph(figure=fig5)),
], style={"height": "220%", "width": "100%"}),
#dcc.Dropdown(
# id='choose_hospital_situation',
#options=[
# {'label': 'Amaka', 'value': 'Amaka Obi'},
#{'label': 'General wards', 'value': 'General wards'},
# {'label': 'Isolation', 'value': 'In Isolation'},
# {'label': 'Total completed isolation', 'value': 'Total completed isolation'},
# {'label': 'Total discharged from hospital', 'value': 'Total discharged from hospital'},
# ],
# value=['Amaka Obi', 'General wards'],
# multi=True,
# style={'width': '70%', 'margin-left': '5px'}
# ),
#]),
#dbc.Row([
#dcc.Graph(id='situation_graph_by_period')]),
#dbc.Row([
# dbc.Col(html.H5(children='Situation in local hospitals', className="text-center"),
#className="mt-4")
# ]),
dbc.Row([
#dbc.Col(html.H5(children='Daily COVID-19 cases in Singapore', className="text-center"),
# className="mt-4"),
#dbc.Row([
#dbc.Col(
# dcc.Graph(id='local and imported'), width=6),
#dcc.Markdown(id='test_cell1'),
#dbc.Col(
#dcc.Graph(figure=fig)),
#], style={"height": "120%", "width": "100%"}),
dbc.Row([
#dbc.Col(html.H5(children="Breakdown of sales:(LOCATION)")),
#dbc.Col(html.H5(children='Breakdown of cases: whether residing in dorms', className="text-center")),
]),
#graphical
#graphical
# dbc.Row(
# [
#dbc.Col(html.Div(children="One of three columns")),
# dash_table.DataTable(
# id='table2',
#columns=[{"name": i, "id": i} for i in df8.columns],
# data=df8.to_dict('records'),
# data=df1.to_dict('records'),
# page_size=5,
# filter_action='native',
# export_format='xlsx',
# export_headers='display',
# merge_duplicate_headers=True,
# style_table={'margin:2px'},
# style_header={'backgroundColor': 'rgb(30, 30, 30)'},
# style_cell={
# 'backgroundColor': 'rgb(50, 50, 50)',
# 'color': 'black',
# 'left-padding': '10%'
#},
# ),
#dcc.Markdown(id='test_cell1'),
#dbc.Col(html.Div(children="One of three columns")),
#dbc.Col(html.Div(children="One of three columns")),
# ]
#),
#dcc.Markdown(id='test_cell1'),
]),
dbc.Row([
dbc.Col(dbc.Card(html.H3(children='Daily Getfit Conversions ( line graph per employee)',
className="text-center text-light bg-dark"), body=True, color="dark")
, className="mb-4")
]),
dcc.Dropdown(
id='emp_name',
options=[{'label': i, 'value': i} for i in available_employee],
value=['Rita'],
multi=True,
style={'width': '70%', 'margin-left': '5px'}
),
#dcc.DatePickerRange(
#id='my-date-picker-range',
#min_date_allowed=date(1995, 8, 5),
#max_date_allowed=date(2017, 9, 19),
#initial_visible_month=date(2017, 8, 5),
#end_date=date(2017, 8, 25)
#),
#html.Div(id='output-container-date-picker-range'),
dbc.Row([
dbc.Col(html.H5(children='Daily Conversions figures', className="text-center"),
className="mt-4"),
]),
dcc.Graph(id='cases_or_deaths_country'),
dbc.Row([
dbc.Col(html.H5(children='Cumulative Conversions figures', className="text-center"),
className="mt-4"),
]),
dcc.Graph(id='total_cases_or_deaths_country'),
dbc.Row([
dbc.Col(dbc.Card(html.H3(children='Offline Sales',
className="text-center text-light bg-dark"), body=True, color="dark")
, className="mb-4")
]),
dbc.Row([
dbc.Col(html.H5(children='NYSC', className="text-center"),
className="mt-4"),
dbc.Col(html.H5(children='<NAME>', className="text-center"),
className="mt-4"),
]),
dbc.Row([
dbc.Col(html.H5(children='Wuse', className="text-center"),
className="mt-4"),
dbc.Col(html.H5(children='Garki', className="text-center"),
className="mt-4"),
]),
])
@app.callback(
Output('test_cell', 'children'),
Input('table', 'active_cell'))
def return_cell_info(active_cell):
return str(active_cell)
#@<EMAIL>(
# Output('test_cell1', 'children'),
# Input('table2', 'active_cell'))
# def return_cell_info(active_cell):
# return str(active_cell)
#def update_graph(cases_or_deaths_country, total_cases_or_deaths_country):
#dfc = df16.copy()
#dfc = dfc[dfc.name.isin(['Rita', '<NAME>'])]
#dfc = pd.pivot_table(dfc, values=employee, index=['updated_at_x'], columns='name')
# dfc2 = df16.copy()
#dfc2 = dfc2[dfc2.name.isin(['Rita', '<NAME>'])]
#dfc2 = dfc2.groupby(['name', 'created_at_y']).sum()
#dfc2 = dfc2.reset_index()
#dfc2['crea'] = dfc2.groupby(['name'])['cases per 1 mil'].apply(
# lambda x: x.cumsum())
#dfc2['deaths per 1 mil'] = dfc2.groupby(['name'])['deaths per 1 mil'].apply(
# lambda x: x.cumsum())
#dfc2 = pd.pivot_table(dfc2, values=employee, index=['order_id'], columns='name')
@app.callback(
[dash.dependencies.Output('cases_or_deaths_country', 'figure'),
dash.dependencies.Output('total_cases_or_deaths_country', 'figure')],
[dash.dependencies.Input('emp_name', 'value')
#dash.dependencies.Input('my-date-picker-range', 'start_date'),
#dash.dependencies.Input('my-date-picker-range', 'end_date')
])
def update_graph(name):
#f_df = df300[df300['name'] == name]
#dfc = df16[df16['name'].isin(['emp_name'])]
#dfc = df16[(df16['name'].isin(['emp_name']))]
#filtered_data1 = df16[df16["name"] == name]
#filtered_data2 = df[df25["name"] == name]
df27 = df300.groupby(['created_at_x', 'name']).size().unstack(fill_value=0)
df25 = df300.groupby(['created_at_x', 'name']).size().unstack(fill_value=0).apply(lambda x: x.cumsum())
fig5 = go.Figure()
for col in df27.columns:
fig5.add_trace(go.Scatter(x=df27.index, y=df27[col].values, name=col, mode='markers+lines'))
fig5.update_layout(yaxis_title='Number Per 1 Million',
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
template="seaborn",
#color="df27[col].values",
#style={"height": "50%", "width": "40%"},
margin=dict(t=0))
fig6 = go.Figure()
for col in df25.columns:
fig6.add_trace(go.Scatter(x=df25.index, y=df25[col].values,
name=col,
mode='markers+lines'))
fig6.update_layout(yaxis_title='Number Per 1 Million',
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
template="seaborn",
#color="df27[col].values",
margin=dict(t=0))
return fig5, fig6
if __name__ == '__main__':
app.run_server(debug=False)<file_sep>/README.md
# edoga-
This python application uses the power of dash to visualize analytical KPIs for organizations
please contribute to my work
Thank you!
| 98ff9defc85b0f972e1826c28f7dab802b1e1f33 | [
"Markdown",
"Python"
] | 2 | Python | chimaezeorah/edoga- | de8cf07023e45297fb7a87c0da9cf58a46e4de07 | 3c056f982925f81e45e4de70e0bd1df72b326377 |
refs/heads/master | <repo_name>rupamroy/SPAWithTokenAuthentication<file_sep>/frontend/app/scripts/controllers/register.js
'use strict';
angular.module('spawithTokenAuthenticationApp')
.controller('RegisterCtrl', registerController);
registerController.$inject = ['$http', 'alert'];
function registerController($http, alert) {
var url = 'http://localhost:3000/register';
var user = {};
this.submit = function () {
user = {
email: this.email,
password: <PASSWORD>
};
$http.post(url, user)
.then(function(){
alert('success', 'Ok!', 'You are now registered');
})
.catch(function(){
alert('warning', 'Oops!!', 'Could not register');
});
}
}
<file_sep>/README.md
## Database
Setup up mongo as a docker container
```
docker run -d -p 27017:27017 -p 28017:28017 -e MONGODB_USER="rupam" -e MONGODB_DATABASE="spaWithTokenAuth" -e MONGODB_PASS="<PASSWORD>" tutum/mongodb
```
To connect to the mongodb
```
docker run -it --link spa-mongo:mongo --rm mongo sh -c 'exec mongo spaWithTokenAuth -u rupam -p tiger --host spa-mongo --port 27017'
```<file_sep>/frontend/README.md
# SPAWithTokenAuthentication
<file_sep>/frontend/Knowledge.md
# Overview
This document contains important tips and knowledge for ths project
## Why OAuth2
Because now mobiles etc cannot rely on cookies based authentication system
## JWTS
A jwt has three sections
1. Header
1. Payload
1. Signature
Steps:
1. **client Logs in** - email and password are validates. Server encodes the userid and few other things against a secret and send it to client. This is a JWT token comprised of the header, payload and signature
1. **client recieves the jwt** - client receives and stores it in local storage
1. **client restarts** - No matter how many times the client restarts he is still authenticated unless and until the jwt expires.
1. **client requests a protected resource** - The client puts the jwt in the header , server looks for it in the header , decodes it and validates that the client is a know validated client and hence sends the request.
### conclusion
1. JWTs are super simple
1. There is no state or database requirement
1. The userid is embedded in the jwt token so no need to make an extra call to get user info
1. no cookies and CORS issues , hence mobile ready
## UI
### using UI router
```js
angular
.module('spawithTokenAuthenticationApp', ['ui.router']);
```
```js
AppConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function AppConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('register', {
url: '/register',
templateUrl: '/views/register.html'
}).state('main', {
url: '/main',
templateUrl: '/views/main.html'
})
}
```
```html
<ul class="nav navbar-nav">
<li ui-sref-active="active"><a ui-sref="main">Home</a></li>
<li ui-sref-active><a ui-sref="register">Register</a></li>
</ul>
```
### Htmp snippets using bootstarp
For html snippets using bootstrap http://bootsnips.com
### Using ngModel Require
The require:'ngModel' and require:'^ngModel' allow you to inject the model attached to the element or its parent element on which the directive is bound to.
Its basically an easiest way to pass ngModel into the link/compile function instead passing it using a scope option. Once you have access to ngModel, you can change its value using $setViewValue, make it dirty/clean using $formatters, apply watchers, etc.
Below is a simple example to pass ngModel and change its value after 5 seconds.
Demo: http://jsfiddle.net/t2GAS/2/
```js
myApp.directive('myDirective', function($timeout) {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$render = function() {
$timeout(function() {
ngModel.$setViewValue('StackOverflow');
}, 5000);
};
}
};
});
```
| 45944dc228dbd4de0f4137f44156bed07772cda3 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | rupamroy/SPAWithTokenAuthentication | 8c65c2c82e3b6dcf735a101a40a11a57c04b7999 | 92db7e7f70eb2d02edae6fa1bb2f7d41f6c96d43 |
refs/heads/master | <file_sep>//package com.example.sekhar.devhelpdirect.Dagger.TwitterExample.component;
//
//import com.example.sekhar.devhelpdirect.Dagger.TwitterExample.Tweeter;
//import com.example.sekhar.devhelpdirect.Dagger.TwitterExample.module.NetworkModule;
//import com.example.sekhar.devhelpdirect.Dagger.TwitterExample.module.TwitterModule;
//
//import javax.inject.Singleton;
//
//import dagger.Component;
//
///**
// * Created by Sekhar on 3/22/15.
// */
//
//@Singleton
//@Component(modules = {
// NetworkModule.class,
// TwitterModule.class,
//})
//public interface TwitterComponent {
// Tweeter provideTwitterApi();
//}
<file_sep>package com.example.sekhar.devhelpdirect.Dagger.TwitterExample;
import android.app.Activity;
import android.os.Bundle;
import com.example.sekhar.devhelpdirect.R;
public class TwitterApplication extends Activity {
Tweeter tweeter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TwitterComponent component = Dagger_TwitterComponent.builder().twitterModule(new TwitterModule("Shekar====")).build();
// // VehicleComponent component = Dagger_VehicleComponent.builder().vehicleModule(new VehicleModule()).build();
//
// tweeter = component.provideTwitterApi();
// tweeter.tweet("Imposible is nothing");
}
}<file_sep>package com.example.sekhar.devhelpdirect.Dagger.TwitterExample.module;
/**
* Created by Sekhar on 3/22/15.
*/
//@Module
//public class NetworkModule {
//
// @Provides
// @Singleton
// OkHttpClient provideOkHttpClient() {
// return new OkHttpClient();
// }
//
// @Provides
// @Singleton
// TwitterApi provideTwitterApi(OkHttpClient client) {
// return new TwitterApi(client);
// }
//}
<file_sep>package projects.MusiShare.presenter;
/**
* Created by Sekhar on 4/6/15.
*/
public interface CategoryPresenter {
public void loadData();
public void unsubscribeFromDataStore();
}
<file_sep>package com.example.sekhar.devhelpdirect.MVPExample.Presenter;
import com.example.sekhar.devhelpdirect.MVPExample.Domain.LoginController;
import com.example.sekhar.devhelpdirect.MVPExample.Domain.LoginControllerImpl;
/**
* Created by Sekhar on 3/20/15.
*/
public class LoginPresenterImpl implements LoginPresenter, OnLoginFinishedListener {
LoginView mLoginView;
LoginController mLoginController;
public LoginPresenterImpl(LoginView mLoginView) {
this.mLoginView = mLoginView;
mLoginController = new LoginControllerImpl(this);
}
@Override
public void validateCredentials(String email, String password) {
mLoginView.showProgress();
mLoginController.login(email, password);
}
@Override
public void onUsernameError() {
}
@Override
public void onPasswordError() {
}
@Override
public void onSuccess() {
mLoginView.navigateToHome();
}
}
<file_sep>package projects.MusiShare.DataManager;
import java.util.List;
import projects.MusiShare.model.CategoryModel;
import retrofit.RestAdapter;
import retrofit.http.GET;
import rx.Observable;
/**
* Created by Sekhar on 4/6/15.
*/
public class CategoryDataManager {
public static final String ENDPOINT = "http://api-v2.hearthis.at";
private static final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
private static final CategoryAPI mCategoryApiService = restAdapter.create(CategoryAPI.class);
public static Observable<List<CategoryModel>> getCategorys() {
return mCategoryApiService.getCategorys();
}
public interface CategoryAPI {
@GET("/categories/")
Observable<List<CategoryModel>> getCategorys();
}
}
<file_sep>package com.example.sekhar.devhelpdirect.Volley;
/**
* Created by Sekhar on 3/15/15.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.sekhar.devhelpdirect.R;
import java.util.List;
public class ImageAdapter extends ArrayAdapter<ImageRecordModal> {
private ImageLoader mImageLoader;
public ImageAdapter(Context context) {
super(context, R.layout.volley_image_list_item);
mImageLoader = new ImageLoader(VolleyApplication.getInstance().getRequestQueue(), new BitmapLruCache());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.volley_image_list_item, parent, false);
}
// NOTE: You would normally use the ViewHolder pattern here
NetworkImageView imageView = (NetworkImageView) convertView.findViewById(R.id.image1);
TextView textView = (TextView) convertView.findViewById(R.id.text1);
ImageRecordModal imageRecord = getItem(position);
imageView.setImageUrl(imageRecord.getUrl(), mImageLoader);
textView.setText(imageRecord.getTitle());
return convertView;
}
public void swapImageRecords(List<ImageRecordModal> objects) {
clear();
for (ImageRecordModal object : objects) {
add(object);
}
notifyDataSetChanged();
}
}<file_sep>//package com.example.sekhar.devhelpdirect.StylingandroidMaterial;
//
//import android.os.Bundle;
//import android.support.v7.app.ActionBarActivity;
//import android.support.v7.app.ActionBar;
//import android.view.MenuItem;
//import android.webkit.WebView;
//import android.widget.TextView;
//
//import com.example.sekhar.devhelpdirect.R;
//import com.stylingandroid.materialrss.rss.model.Item;
//
//import java.text.DateFormat;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.Locale;
//
//
//public class FeedDetailActivity extends ActionBarActivity {
// public static final String ARG_ITEM = "ARG_ITEM";
// public static final String NEWLINE = "\\n";
// public static final String BR = "<br />";
// public static final String HTML_MIME_TYPE = "text/html";
//
// private DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.feed_detail);
//
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setDisplayHomeAsUpEnabled(true);
// }
//
// Item item = (Item) getIntent().getSerializableExtra(ARG_ITEM);
//
// TextView title = (TextView) findViewById(R.id.feed_detail_title);
// TextView date = (TextView) findViewById(R.id.feed_detail_date);
// WebView webView = (WebView) findViewById(R.id.feed_detail_body);
//
// title.setText(item.getTitle());
// date.setText(dateFormat.format(new Date(item.getPubDate())));
// String html = item.getContent();
//
// html = html.replaceAll(NEWLINE, BR);
// webView.loadData(html, HTML_MIME_TYPE, null);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem menuItem) {
// int id = menuItem.getItemId();
// if (id == android.R.id.home) {
// finish();
// return true;
// }
// return super.onOptionsItemSelected(menuItem);
// }
//} | 9f3484ce490bb36cacd47aaa0d9eb5c28964aadd | [
"Java"
] | 8 | Java | shekarshine/DevHelpDirect | bff388f32cee80749da48887914611c17c5c31ac | c92e8e39ef726b74ef440659e78da8dfd28f3096 |
refs/heads/master | <file_sep>
public class Automovil extends Vehiculo {
private int cantidadPuertas;
public Automovil(int cantidadPuertas, String marca, String modelo, double precio) {
super(marca, modelo, precio);
this.cantidadPuertas = cantidadPuertas;
}
public int getCantidadPuertas() {
return cantidadPuertas;
}
public void setCantidadPuertas(int cantidadPuertas) {
this.cantidadPuertas = cantidadPuertas;
}
@Override
public String toString() {
return "Marca: " + super.getMarca() + " // " + "Modelo: " + super.getModelo() + " // " + "Puertas: " + this.cantidadPuertas + " // " + super.getPrecioFormateado();
}
}
<file_sep>
import java.util.ArrayList;
import java.util.Collections;
public class Concesionaria {
ArrayList<Vehiculo> lista;
public Concesionaria() {
this.lista = new ArrayList();
cargarVehiculos();
}
public ArrayList<Vehiculo> getLista() {
return lista;
}
public void setLista(ArrayList<Vehiculo> lista) {
this.lista = lista;
}
private void cargarVehiculos() {
Vehiculo v1 = new Automovil(4, "Peugeot", "206", 200000);
Vehiculo v2 = new Motocicleta(125, "Honda", "Titan", 60000);
Vehiculo v3 = new Automovil(5, "Peugeot", "208", 250000);
Vehiculo v4 = new Motocicleta(160, "Yamaha", "YBR", 80500.5);
lista.add(v1);
lista.add(v2);
lista.add(v3);
lista.add(v4);
}
public String vehiculoMasCaro() {
String resultado = "";
boolean bandera = false;
double mayor = 0;
String vehiculoMasCaro = "";
for (Vehiculo vehiculo : lista) {
if (bandera == false) {
mayor = vehiculo.getPrecio();
vehiculoMasCaro = vehiculo.getMarca() + " " + vehiculo.getModelo();
bandera = true;
}
if (bandera && mayor < vehiculo.getPrecio()) {
mayor = vehiculo.getPrecio();
vehiculoMasCaro = vehiculo.getMarca() + " " + vehiculo.getModelo();
}
}
resultado = "Vehículo más caro: " + vehiculoMasCaro;
return resultado;
}
public String vehiculoMasBarato() {
String resultado = "";
boolean bandera = false;
double menor = 0;
String vehiculoMasBarato = "";
for (Vehiculo vehiculo : lista) {
if (bandera == false) {
menor = vehiculo.getPrecio();
vehiculoMasBarato = vehiculo.getMarca() + " " + vehiculo.getModelo();
bandera = true;
}
if (bandera && menor > vehiculo.getPrecio()) {
menor = vehiculo.getPrecio();
vehiculoMasBarato = vehiculo.getMarca() + " " + vehiculo.getModelo();
}
}
resultado = "Vehículo más barato: " + vehiculoMasBarato;
return resultado;
}
public String vehiculoQueContenga(String letra) {
String resultado = "";
for (Vehiculo vehiculo : lista) {
if (vehiculo.getModelo().contains(letra)) {
resultado += vehiculo.getMarca() + " " + vehiculo.getModelo() + " " + vehiculo.getPrecioFormateado()+ " ";
}
}
return resultado;
}
public ArrayList<Vehiculo> ordenarPorPrecio() {
ArrayList<Vehiculo> listaLocal = lista;
Collections.sort(listaLocal);
return listaLocal;
}
}
| 06606118d2657e0047b4dcd9d1228ab6dc8d6a71 | [
"Java"
] | 2 | Java | samuelrisso/EjercicioTraineeOnRead | 53b77a456e7551cfc2fd31bbceec4fd35948d645 | c77fc625765cefff74b955a9c0ecbdb493005761 |
refs/heads/master | <repo_name>Lapinte/LocaMat1<file_sep>/UI/ConsoleHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using LocaMat.UI.Framework;
namespace LocaMat.UI
{
internal static class ConsoleHelper
{
public static void AfficherEntete(string libelle)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkGray;
// Comme j'utilise "| " et " |", la ligne doit avoir 6 caractères en plus
var ligneTraits = new string('*', libelle.Length + 6);
Console.WriteLine(ligneTraits);
Console.WriteLine($"| { libelle.ToUpper() } |");
Console.WriteLine(ligneTraits);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void AfficherLignePourRetournerAuMenu()
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine();
Console.WriteLine("> Appuyez sur une touche pour retourner au menu...");
Console.ForegroundColor = ConsoleColor.Gray;
Console.ReadKey();
}
public static void AfficherVotreChoix()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine();
Console.Write("> Votre choix : ");
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void EffacerLignesConsole(int nombreLignes = 1)
{
for (int i = 1; i <= nombreLignes; i++)
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
}
public static void AfficherMessageErreur(string message)
{
EffacerLignesConsole(1);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(message);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void AfficherLibelleSaisie(string libelle)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine();
Console.WriteLine(libelle);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void AfficherListe<T>(IEnumerable<T> liste)
{
// Par réflexion, on récupère les propriétés de la classe qui ont l'attribut InformationAffichage
var type = typeof(T);
var proprietesAvecInformationAffichage = type.GetProperties()
.Where(x => x.CustomAttributes
.Any(y => y.AttributeType == typeof(InformationAffichageAttribute)))
.ToList();
if (!proprietesAvecInformationAffichage.Any())
{
Console.WriteLine("Rien à afficher...");
}
// On construit un tableau avec
// - en première ligne les entêtes,
// - en deuxième ligne les séparateurs,
// - ensuite les éléments de la liste
var contenu = new string[liste.Count() + 2, proprietesAvecInformationAffichage.Count()];
for (int i = 0; i < proprietesAvecInformationAffichage.Count; i++)
{
var propriete = proprietesAvecInformationAffichage[i];
var informationAffichage = propriete.GetCustomAttributes(false).OfType<InformationAffichageAttribute>().SingleOrDefault();
var nombreCaracteres = informationAffichage.NombreCaracteres;
// Ligne d'en-tête
contenu[0, i] = informationAffichage.Entete.ToUpper().PadRight(nombreCaracteres) + " ";
// Ligne de séparation
contenu[1, i] = new string('-', nombreCaracteres + 1);
// Eléments de la liste
for (var j = 0; j < liste.Count(); j++)
{
var element = liste.ElementAt(j);
string renduValeur = string.Empty;
var valeur = propriete.GetValue(element);
if (valeur != null)
{
if (valeur is DateTime date)
{
renduValeur = date.ToShortDateString();
}
else
{
renduValeur = valeur.ToString().Tronquer(nombreCaracteres);
}
}
contenu[j + 2, i] = renduValeur.PadRight(nombreCaracteres) + " ";
}
}
// Afficher le tableau
for (int ligne = 0; ligne < liste.Count() + 2; ligne++)
{
for (var colonne = 0; colonne < proprietesAvecInformationAffichage.Count; colonne++)
{
Console.Write(contenu[ligne, colonne]);
}
Console.WriteLine();
}
}
public static void AfficherListe<T>(IEnumerable<T> liste, IEnumerable<InformationAffichage> strategieAffichage)
{
if (!strategieAffichage.Any())
{
Console.WriteLine("Rien à afficher...");
}
// On construit un tableau avec
// - en première ligne les entêtes,
// - en deuxième ligne les séparateurs,
// - ensuite les éléments de la liste
var contenu = new string[liste.Count() + 2, strategieAffichage.Count()];
for (int i = 0; i < strategieAffichage.Count(); i++)
{
var informationAffichage = strategieAffichage.ElementAt(i);
var nombreCaracteres = informationAffichage.NombreCaracteres;
// Ligne d'en-tête
contenu[0, i] = $"{informationAffichage.GetEntete()} ";
// Ligne de séparation
contenu[1, i] = new string('-', nombreCaracteres + 1);
// Eléments de la liste
for (var j = 0; j < liste.Count(); j++)
{
var element = liste.ElementAt(j);
contenu[j + 2, i] = $"{informationAffichage.GetValeur(element)} ";
}
}
// Afficher le tableau
for (int ligne = 0; ligne < liste.Count() + 2; ligne++)
{
for (var colonne = 0; colonne < strategieAffichage.Count(); colonne++)
{
Console.Write(contenu[ligne, colonne]);
}
Console.WriteLine();
}
}
}
}
<file_sep>/Metier/Client.cs
using LocaMat.UI.Framework;
namespace LocaMat.Metier
{
public class Client
{
[InformationAffichage(Entete = "Id", NombreCaracteres = 3)]
public int Id { get; set; }
[InformationAffichage(Entete = "Nom", NombreCaracteres = 20)]
public string Nom { get; set; }
[InformationAffichage(Entete = "Prénom", NombreCaracteres = 20)]
public string Prenom { get; set; }
[InformationAffichage(Entete = "Adresse", NombreCaracteres = 50)]
public string Adresse { get; set; }
public override string ToString()
{
return $"{this.Nom.ToUpper()} {this.Prenom}";
}
}
}
<file_sep>/Dal/AgenceDal.cs
using LocaMat.Metier;
using LocaMat.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocaMat.Dal
{
public static class AgenceDal
{
public static void Supprimer(int id)
{
using (var bd = Application.GetBaseDonnees())
{
var agence = bd.Agences.Single(x => x.Id == id);
bd.Agences.Remove(agence);
bd.SaveChanges();
}
}
public static void Ajouter(this Agence agence)
{
using (var bd = Application.GetBaseDonnees())
{
bd.Agences.Add(agence);
bd.SaveChanges();
}
}
public static List<Agence> RecupererListeAgences()
{
using (var bd = Application.GetBaseDonnees())
{
var liste = Application.GetBaseDonnees().Agences.ToList();
return liste;
}
}
public static List<Agence> Rechercher(string ville, string adresse)
{
using (var bd = Application.GetBaseDonnees())
{
var resultat = bd.Agences;
if (!string.IsNullOrWhiteSpace(ville) && string.IsNullOrWhiteSpace(adresse))
return resultat.Where(x => x.Ville.Contains(ville)).ToList();
if (string.IsNullOrWhiteSpace(ville) && !string.IsNullOrWhiteSpace(adresse))
return resultat.Where(x => x.Adresse.Contains(adresse)).ToList();
if (!string.IsNullOrWhiteSpace(ville) && !string.IsNullOrWhiteSpace(adresse))
return resultat.Where(x => x.Ville.Contains(ville) && x.Adresse.Contains(adresse)).ToList();
return resultat.ToList();
}
}
}
}
<file_sep>/UI/ModuleGestionLocation.cs
using LocaMat.Metier;
using LocaMat.UI.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocaMat.UI
{
class ModuleGestionLocations
{
private Menu menu;
private void InitialiserMenu()
{
this.menu = new Menu("Gestion des Location");
this.menu.AjouterElement(new ElementMenu("1", "Afficher les Locations")
{
FonctionAExecuter = this.AfficherLocations
});
this.menu.AjouterElement(new ElementMenu("2", "Ajouter une Location")
{
FonctionAExecuter = this.AjouterLocation
});
this.menu.AjouterElement(new ElementMenuQuitterMenu("R", "Revenir au menu principal..."));
}
public void Demarrer()
{
if (this.menu == null)
{
this.InitialiserMenu();
}
this.menu.Afficher();
}
private void AfficherLocations()
{
ConsoleHelper.AfficherEntete("Locations");
var liste = Application.GetBaseDonnees().Locations.ToList();
ConsoleHelper.AfficherListe(liste);
}
private void AjouterLocation()
{
ConsoleHelper.AfficherEntete("Nouvelle location");
using (var bd = Application.GetBaseDonnees())
{
var liste = bd.Agences.ToList();
ConsoleHelper.AfficherListe(liste);
var idAgence = ConsoleSaisie.SaisirEntierObligatoire("Choisissez votre agence : ");
var listeOffres = bd.OffresProduits.Where(x => x.IdAgence == idAgence);
ConsoleHelper.AfficherListe(listeOffres);
var idOffre = ConsoleSaisie.SaisirEntierObligatoire("Choisissez l'id de l'offre : ");
var offre = listeOffres.Single(x => x.Id == idOffre);
var offreAffichage = listeOffres.Where(x => x.Id == idOffre).ToList();
var idProduit = offre.IdProduit;
ConsoleHelper.AfficherListe(offreAffichage);
var qte = ConsoleSaisie.SaisirEntierObligatoire("Choisissez la quantité : ");
int qtePossible = offre.Quantite;
if (qte > qtePossible)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Quantité non disponible");
Console.ForegroundColor = ConsoleColor.Gray;
}
var dateDebut = ConsoleSaisie.SaisirDateObligatoire("Choisissez la date de début de location : ");
var dateFin = ConsoleSaisie.SaisirDateObligatoire("Choisissez la date de fin de location : ");
var locationsDispo = bd.Locations.Where(x => x.IdProduit == idProduit && x.DateDebut > dateFin && x.DateFin < dateDebut);
}
}
}
}
<file_sep>/Metier/Agence.cs
using LocaMat.UI.Framework;
namespace LocaMat.Metier
{
public class Agence
{
[InformationAffichage(Entete = "Id", NombreCaracteres = 3)]
public int Id { get; set; }
[InformationAffichage(Entete = "Ville", NombreCaracteres = 20)]
public string Ville { get; set; }
[InformationAffichage(Entete = "Adresse", NombreCaracteres = 50)]
public string Adresse { get; set; }
public override string ToString()
{
return this.Ville;
}
public override bool Equals(object obj)
{
return (this.Id == ((Agence)obj).Id);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
<file_sep>/Dal/ProduitDal.cs
using LocaMat.Metier;
using LocaMat.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocaMat.Dal
{
public static class ProduitDal
{
public static void Ajouter(this Produit produit)
{
using (var bd = Application.GetBaseDonnees())
{
bd.Produits.Add(produit);
bd.SaveChanges();
}
}
}
}
<file_sep>/UI/ModuleGestionProduits.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using LocaMat.Dal;
using LocaMat.Metier;
using LocaMat.UI.Framework;
namespace LocaMat.UI
{
public class ModuleGestionProduits
{
private Menu menu;
private static readonly List<InformationAffichage> strategieAffichageProduits
= new List<InformationAffichage>();
static ModuleGestionProduits()
{
// On définit ici les propriétés qu'on veut afficher
// et la manière de les afficher
strategieAffichageProduits = new List<InformationAffichage>
{
InformationAffichage.Creer<Produit>(x=>x.Id, "Id", 3),
InformationAffichage.Creer<Produit>(x=>x.Nom, "Nom", 20),
InformationAffichage.Creer<Produit>(x=>x.Description, "Description", 50),
InformationAffichage.Creer<Produit>(x=>x.PrixJourHT, "Prix jour (HT)", 15),
InformationAffichage.Creer<Produit>(x=>x.Categorie, "Catégorie", 20),
};
}
private void InitialiserMenu()
{
this.menu = new Menu("Gestion des produits");
this.menu.AjouterElement(new ElementMenu("1", "Afficher les produits")
{
FonctionAExecuter = this.AfficherProduits
});
this.menu.AjouterElement(new ElementMenu("2", "Ajouter un produit")
{
FonctionAExecuter = this.AjouterProduit
});
this.menu.AjouterElement(new ElementMenu("3", "Supprimer un produit")
{
FonctionAExecuter = this.SupprimerProduit
});
this.menu.AjouterElement(new ElementMenu("4", "Rechercher un produit")
{
FonctionAExecuter = this.RechercherProduit
});
this.menu.AjouterElement(new ElementMenuQuitterMenu("R", "Revenir au menu principal..."));
}
public void Demarrer()
{
if (this.menu == null)
{
this.InitialiserMenu();
}
this.menu.Afficher();
}
private void AfficherProduits()
{
ConsoleHelper.AfficherEntete("Produits");
var liste = Application.GetBaseDonnees().Produits.ToList();
ConsoleHelper.AfficherListe(liste, strategieAffichageProduits);
}
private void AjouterProduit()
{
ConsoleHelper.AfficherEntete("Nouveau produit");
var produit = new Produit
{
Nom = ConsoleSaisie.SaisirChaine("Nom : ", false),
Description = ConsoleSaisie.SaisirChaine("Description : ", false),
PrixJourHT = ConsoleSaisie.SaisirDecimalObligatoire("Prix du Jour HT : "),
IdCategorie = ConsoleSaisie.SaisirEntierObligatoire("Id Catégorie : ")
};
//ProduitDal.Ajouter(produit);
produit.Ajouter();
}
private void SupprimerProduit()
{
ConsoleHelper.AfficherEntete("Supprimer un produit");
var liste = Application.GetBaseDonnees().Produits.ToList();
ConsoleHelper.AfficherListe(liste, strategieAffichageProduits);
var id = ConsoleSaisie.SaisirEntierObligatoire("Id à Supprimer : ");
using (var bd = Application.GetBaseDonnees())
{
var produit = bd.Produits.Single(x => x.Id == id);
bd.Produits.Remove(produit);
bd.SaveChanges();
}
}
private void RechercherProduit()
{
ConsoleHelper.AfficherEntete("Rechercher un Produit");
var saisi = ConsoleSaisie.SaisirChaine("Texte contenu dans le produit : ", false);
using (var bd = Application.GetBaseDonnees())
{
var liste = bd.Produits.Where(x => x.Nom.Contains(saisi)).ToList();
ConsoleHelper.AfficherListe(liste, strategieAffichageProduits);
}
}
}
}
<file_sep>/Metier/Produit.cs
using System.ComponentModel.DataAnnotations.Schema;
namespace LocaMat.Metier
{
public class Produit
{
public int Id { get; set; }
public string Nom { get; set; }
public string Description { get; set; }
public decimal PrixJourHT { get; set; }
[ForeignKey("IdCategorie")]
public virtual CategorieProduit Categorie { get; set; }
public int IdCategorie { get; set; }
public override string ToString()
{
return $"{this.Nom} ({this.Id})";
}
}
}
<file_sep>/Metier/OffreProduit.cs
using LocaMat.UI.Framework;
using System.ComponentModel.DataAnnotations.Schema;
namespace LocaMat.Metier
{
[Table("OffresProduits")]
public class OffreProduit
{
[InformationAffichage(Entete = "Id", NombreCaracteres = 3)]
public int Id { get; set; }
[InformationAffichage(Entete = "Produit", NombreCaracteres = 30)]
[ForeignKey("IdProduit")]
public virtual Produit Produit { get; set; }
public int IdProduit { get; set; }
public int IdAgence { get; set; }
[InformationAffichage(Entete = "Qté", NombreCaracteres = 3)]
public int Quantite { get; set; }
}
}
<file_sep>/UI/Framework/Menu.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace LocaMat.UI.Framework
{
public class Menu
{
private readonly List<ElementMenu> elements = new List<ElementMenu>();
public Menu(string libelle)
{
this.Libelle = libelle;
}
public string Libelle { get; }
public void Afficher()
{
while (true)
{
ConsoleHelper.AfficherEntete(this.Libelle);
foreach (var element in this.elements)
{
element.Afficher();
}
ConsoleHelper.AfficherVotreChoix();
ElementMenu elementCorrespondant;
do
{
var retour = Console.ReadKey();
elementCorrespondant = this.elements.FirstOrDefault(x => x.Correspondre(retour.KeyChar.ToString()));
} while (elementCorrespondant == null);
elementCorrespondant.Executer();
if (elementCorrespondant is ElementMenuQuitterMenu)
{
break;
}
}
}
public void AjouterElement(ElementMenu element)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element), "L'élément à ajouter ne peut pas être null");
}
if (this.elements.Any(x => x.Commande == element.Commande))
{
throw new InvalidOperationException(
$"Il y a déjà un élément de menu avec la commande {element.Commande}");
}
this.elements.Add(element);
}
}
}
<file_sep>/Extensions.String.cs
namespace LocaMat
{
public static class ExtensionsString
{
public static string Tronquer(this string valeur, int nombreCaracteres)
{
const string points = "...";
return valeur.Length <= nombreCaracteres
? valeur
: valeur.Substring(0, nombreCaracteres - points.Length) + points;
}
}
}
<file_sep>/UI/Framework/OutilsReflection.cs
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace LocaMat.UI.Framework
{
public static class OutilsReflection
{
public static PropertyInfo GetInformationPropriete<T>(Expression<Func<T, object>> expression)
{
if (expression.NodeType != ExpressionType.Lambda)
{
throw new ArgumentException("L'expression doit être une expression lambda", "expression");
}
var lambda = (LambdaExpression)expression;
var memberExpression = ExtraireMemberExpression(lambda.Body);
if (memberExpression == null)
{
throw new ArgumentException("L'expression doit être une expression d'accès membre", "expression");
}
if (memberExpression.Member.DeclaringType == null)
{
throw new InvalidOperationException("La propriété n'a pas de type");
}
return memberExpression.Member.DeclaringType.GetProperty(memberExpression.Member.Name);
}
private static MemberExpression ExtraireMemberExpression(Expression expression)
{
if (expression.NodeType == ExpressionType.MemberAccess)
{
return ((MemberExpression)expression);
}
if (expression.NodeType == ExpressionType.Convert)
{
var operande = ((UnaryExpression)expression).Operand;
return ExtraireMemberExpression(operande);
}
return null;
}
}
}
<file_sep>/UI/Console.Saisie.cs
using System;
namespace LocaMat.UI
{
public static class ConsoleSaisie
{
private const string MessagePourValeurObligatoire = "Valeur obligatoire. Veuillez recommencer: ";
private const string MessagePourValeurInvalide = "Valeur invalide. Veuillez recommencer: ";
public static string SaisirChaine(string libelle, bool autoriserAucuneValeur)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
var saisie = Console.ReadLine();
while (string.IsNullOrEmpty(saisie) && !autoriserAucuneValeur)
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurObligatoire);
saisie = Console.ReadLine();
}
return saisie;
}
public static DateTime SaisirDateObligatoire(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide = false;
DateTime date = default(DateTime);
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurObligatoire);
}
else
{
estSaisieValide = DateTime.TryParse(saisie, out date);
if (!estSaisieValide)
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
}
} while (!estSaisieValide);
return date;
}
public static DateTime? SaisirDateOptionnelle(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide;
DateTime? valeur = null;
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
valeur = null;
break;
}
estSaisieValide = DateTime.TryParse(saisie, out DateTime date);
if (estSaisieValide)
{
valeur = date;
}
else
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
} while (!estSaisieValide);
return valeur;
}
public static int SaisirEntierObligatoire(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide = false;
int valeur = default(int);
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurObligatoire);
}
else
{
estSaisieValide = int.TryParse(saisie, out valeur);
if (!estSaisieValide)
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
}
} while (!estSaisieValide);
return valeur;
}
public static int? SaisirEntierOptionnel(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide;
int? valeur = null;
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
valeur = null;
break;
}
estSaisieValide = int.TryParse(saisie, out int integer);
if (estSaisieValide)
{
valeur = integer;
}
else
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
} while (!estSaisieValide);
return valeur;
}
public static decimal SaisirDecimalObligatoire(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide = false;
decimal valeur = default(decimal);
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurObligatoire);
}
else
{
estSaisieValide = decimal.TryParse(saisie.Replace(".", ","), out valeur);
if (!estSaisieValide)
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
}
} while (!estSaisieValide);
return valeur;
}
public static decimal? SaisirDecimalOptionnel(string libelle)
{
ConsoleHelper.AfficherLibelleSaisie(libelle);
bool estSaisieValide;
decimal? valeur = null;
do
{
var saisie = Console.ReadLine();
if (string.IsNullOrEmpty(saisie))
{
valeur = null;
break;
}
estSaisieValide = decimal.TryParse(saisie.Replace(".", ","), out decimal number);
if (estSaisieValide)
{
valeur = number;
}
else
{
ConsoleHelper.AfficherMessageErreur(MessagePourValeurInvalide);
}
} while (!estSaisieValide);
return valeur;
}
}
}
<file_sep>/UI/Framework/ElementMenu.cs
using System;
namespace LocaMat.UI.Framework
{
public class ElementMenu
{
public ElementMenu(string commande, string libelle)
{
this.Commande = commande ?? throw new ArgumentNullException(nameof(commande));
this.Libelle = libelle ?? throw new ArgumentNullException(nameof(libelle));
}
public string Libelle { get; }
public string Commande { get; }
public Action FonctionAExecuter { get; set; }
public bool AfficherLigneRetourMenuApresExecution { get; set; } = true;
public bool Correspondre(string valeur)
{
return this.Commande.Equals(valeur, StringComparison.OrdinalIgnoreCase);
}
public virtual void Afficher()
{
Console.WriteLine($"{this.Commande} - {this.Libelle}");
}
public virtual void Executer()
{
ConsoleHelper.AfficherEntete(this.Libelle);
this.FonctionAExecuter();
if (this.AfficherLigneRetourMenuApresExecution)
{
ConsoleHelper.AfficherLignePourRetournerAuMenu();
}
}
}
public sealed class ElementMenuQuitterMenu : ElementMenu
{
public ElementMenuQuitterMenu(string commande, string libelle)
: base(commande, libelle)
{
this.AfficherLigneRetourMenuApresExecution = false;
}
public override void Afficher()
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine();
Console.WriteLine($"Tapez {this.Commande} pour {this.Libelle}");
Console.ForegroundColor = ConsoleColor.Gray;
}
public override void Executer()
{
// On ne veut ni d'en-tête ni de ligne de retour
this.FonctionAExecuter?.Invoke();
}
}
}
<file_sep>/Metier/Location.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
using LocaMat.UI.Framework;
namespace LocaMat.Metier
{
public class Location
{
[InformationAffichage(Entete = "Id", NombreCaracteres = 3)]
public int Id { get; set; }
[InformationAffichage(Entete = "Produit", NombreCaracteres = 30)]
[ForeignKey("IdProduit")]
public virtual Produit Produit { get; set; }
public int IdProduit { get; set; }
[InformationAffichage(Entete = "Client", NombreCaracteres = 40)]
[ForeignKey("IdClient")]
public virtual Client Client { get; set; }
public int IdClient { get; set; }
[InformationAffichage(Entete = "Agence", NombreCaracteres = 15)]
[ForeignKey("IdAgence")]
public virtual Agence Agence { get; set; }
public int IdAgence { get; set; }
[InformationAffichage(Entete = "Du", NombreCaracteres = 10)]
public DateTime DateDebut { get; set; }
[InformationAffichage(Entete = "Au", NombreCaracteres = 10)]
public DateTime DateFin { get; set; }
[InformationAffichage(Entete = "Qté", NombreCaracteres = 3)]
public int Quantite { get; set; }
[InformationAffichage(Entete = "Total", NombreCaracteres = 7)]
public decimal TotalFacture { get; set; }
}
}
<file_sep>/Dal/BaseDonnees.cs
using LocaMat.Metier;
using System.Data.Entity;
namespace LocaMat.Dal
{
public class BaseDonnees : DbContext
{
public BaseDonnees(string connectionString = "Connexion")
: base(connectionString)
{
}
public DbSet<Agence> Agences { get; set; }
public DbSet<CategorieProduit> CategoriesProduits { get; set; }
public DbSet<Produit> Produits { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<OffreProduit> OffresProduits { get; set; }
public DbSet<Client> Clients { get; set; }
}
}
<file_sep>/UI/Framework/InformationAffichageAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocaMat.UI.Framework
{
public sealed class InformationAffichageAttribute : Attribute
{
public int NombreCaracteres { get; set; }
public string Entete { get; set; }
}
}
<file_sep>/UI/ModuleGestionAgences.cs
using System;
using System.Collections.Generic;
using System.Linq;
using LocaMat.Metier;
using LocaMat.UI.Framework;
using LocaMat.Dal;
namespace LocaMat.UI
{
public class ModuleGestionAgences
{
private Menu menu;
private void InitialiserMenu()
{
this.menu = new Menu("Gestion des agences");
this.menu.AjouterElement(new ElementMenu("1", "Afficher les agences")
{
FonctionAExecuter = this.AfficherAgences
});
this.menu.AjouterElement(new ElementMenu("2", "Ajouter une agence")
{
FonctionAExecuter = this.AjouterAgence
});
this.menu.AjouterElement(new ElementMenu("3", "Supprimer une agence")
{
FonctionAExecuter = this.SupprimerAgence
});
this.menu.AjouterElement(new ElementMenu("4", "Rechercher une agence")
{
FonctionAExecuter = this.RechercherAgence
});
this.menu.AjouterElement(new ElementMenuQuitterMenu("R", "Revenir au menu principal..."));
}
public void Demarrer()
{
if (this.menu == null)
{
this.InitialiserMenu();
}
this.menu.Afficher();
}
private void AfficherAgences()
{
ConsoleHelper.AfficherEntete("Agences");
var liste = AgenceDal.RecupererListeAgences();
ConsoleHelper.AfficherListe(liste);
}
private void AjouterAgence()
{
ConsoleHelper.AfficherEntete("Nouvelle agence");
var agence = new Agence
{
Ville = ConsoleSaisie.SaisirChaine("Ville : ", false),
Adresse = ConsoleSaisie.SaisirChaine("Adresse : ", false)
};
//AgenceDal.Ajouter(agence);
agence.Ajouter();
}
private void SupprimerAgence()
{
ConsoleHelper.AfficherEntete("Supprimer une agence");
var liste = Application.GetBaseDonnees().Agences.ToList();
ConsoleHelper.AfficherListe(liste);
var id = ConsoleSaisie.SaisirEntierObligatoire("Id à supprimer : ");
AgenceDal.Supprimer(id);
}
private void RechercherAgence()
{
ConsoleHelper.AfficherEntete("Rechercher un Produit");
var ville = ConsoleSaisie.SaisirChaine("Saisir un nom de ville (ou en partie) : ", true);
var adresse = ConsoleSaisie.SaisirChaine("Saisir une adresse (ou en partie) : ", true);
var liste = AgenceDal.Rechercher(ville, adresse);
ConsoleHelper.AfficherListe(liste);
}
}
}
<file_sep>/UI/Application.cs
using System;
using System.Configuration;
using System.Data.SqlClient;
using LocaMat.Dal;
using LocaMat.UI.Framework;
namespace LocaMat.UI
{
public class Application
{
private Menu menuPrincipal;
private ModuleGestionAgences moduleGestionAgences;
private ModuleGestionProduits moduleGestionProduits;
private ModuleGestionClients moduleGestionClients;
private ModuleGestionLocations moduleGestionLocations;
private void InitialiserModules()
{
this.moduleGestionAgences = new ModuleGestionAgences();
this.moduleGestionProduits = new ModuleGestionProduits();
this.moduleGestionClients = new ModuleGestionClients();
this.moduleGestionLocations = new ModuleGestionLocations();
}
private void InitialiserMenuPrincipal()
{
this.menuPrincipal = new Menu("Menu principal");
this.menuPrincipal.AjouterElement(new ElementMenu("1", "Gestion des produits")
{
AfficherLigneRetourMenuApresExecution = false,
FonctionAExecuter = this.moduleGestionProduits.Demarrer
});
this.menuPrincipal.AjouterElement(new ElementMenu("2", "Gestion des agences")
{
AfficherLigneRetourMenuApresExecution = false,
FonctionAExecuter = this.moduleGestionAgences.Demarrer
});
this.menuPrincipal.AjouterElement(new ElementMenu("3", "Gestion des clients")
{
AfficherLigneRetourMenuApresExecution = false,
FonctionAExecuter = this.moduleGestionClients.Demarrer
});
this.menuPrincipal.AjouterElement(new ElementMenu("4", "Gestion des locations")
{
AfficherLigneRetourMenuApresExecution = false,
FonctionAExecuter = this.moduleGestionLocations.Demarrer
});
this.menuPrincipal.AjouterElement(new ElementMenuQuitterMenu("Q", "Quitter")
{
FonctionAExecuter = () => Environment.Exit(1)
});
}
public void Demarrer()
{
this.InitialiserModules();
this.InitialiserMenuPrincipal();
this.menuPrincipal.Afficher();
}
public static SqlConnection GetConnexion()
{
var connectionString = ConfigurationManager.ConnectionStrings["Connexion"].ConnectionString;
return new SqlConnection(connectionString);
}
public static BaseDonnees GetBaseDonnees()
{
return new BaseDonnees();
}
}
}
<file_sep>/Metier/CategorieProduit.cs
using LocaMat.UI.Framework;
using System.ComponentModel.DataAnnotations.Schema;
namespace LocaMat.Metier
{
[Table("CategoriesProduits")]
public class CategorieProduit
{
[InformationAffichage(Entete = "Id", NombreCaracteres = 2)]
public int Id { get; set; }
[InformationAffichage(Entete = "Libelle", NombreCaracteres = 20)]
[Column("Nom")]
public string Libelle { get; set; }
public override string ToString()
{
return this.Libelle;
}
}
}
<file_sep>/UI/Framework/InformationAffichage.cs
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace LocaMat.UI.Framework
{
/// <summary>
/// Cette classe permet de gérer comment afficher une propriété.
/// </summary>
public class InformationAffichage
{
private InformationAffichage(PropertyInfo propriete,string entete, int nombreCaracteres)
{
Propriete = propriete;
Entete = entete;
NombreCaracteres = nombreCaracteres;
}
private PropertyInfo Propriete { get; }
public string Entete { get; }
public int NombreCaracteres { get; }
public string GetEntete()
{
return Entete.ToUpper().PadRight(NombreCaracteres);
}
public string GetValeur(object element)
{
string renduValeur = string.Empty;
var valeur = Propriete.GetValue(element);
if (valeur != null)
{
if (valeur is DateTime date)
{
renduValeur = date.ToShortDateString();
}
else
{
renduValeur = valeur.ToString().Replace(Environment.NewLine, " ").Tronquer(NombreCaracteres);
}
}
return renduValeur.PadRight(NombreCaracteres);
}
public static InformationAffichage Creer<T>(
Expression<Func<T, object>> propriete,
string entete,
int nombreCaracteres)
{
var informationPropriete = OutilsReflection.GetInformationPropriete(propriete);
return new InformationAffichage(informationPropriete, entete, nombreCaracteres);
}
}
}
<file_sep>/UI/ModuleGestionClients.cs
using System;
using System.Linq;
using LocaMat.Metier;
using LocaMat.UI.Framework;
namespace LocaMat.UI
{
public class ModuleGestionClients
{
private Menu menu;
private void InitialiserMenu()
{
this.menu = new Menu("Gestion des clients");
this.menu.AjouterElement(new ElementMenu("1", "Afficher les clients")
{
FonctionAExecuter = this.AfficherClients
});
this.menu.AjouterElement(new ElementMenu("2", "Ajouter un client")
{
FonctionAExecuter = this.AjouterClient
});
this.menu.AjouterElement(new ElementMenu("3", "Supprimer un client")
{
FonctionAExecuter = this.SupprimerClient
});
this.menu.AjouterElement(new ElementMenuQuitterMenu("R", "Revenir au menu principal..."));
}
public void Demarrer()
{
if (this.menu == null)
{
this.InitialiserMenu();
}
this.menu.Afficher();
}
private void AfficherClients()
{
ConsoleHelper.AfficherEntete("Clients");
var liste = Application.GetBaseDonnees().Clients.ToList();
ConsoleHelper.AfficherListe(liste);
}
private void AjouterClient()
{
ConsoleHelper.AfficherEntete("Nouveau client");
var client = new Client
{
Nom = ConsoleSaisie.SaisirChaine("Nom : ", false),
Prenom = ConsoleSaisie.SaisirChaine("Prénom : ", false),
Adresse = ConsoleSaisie.SaisirChaine("Adresse : ", false)
};
using (var bd = Application.GetBaseDonnees())
{
bd.Clients.Add(client);
bd.SaveChanges();
}
}
private void SupprimerClient()
{
ConsoleHelper.AfficherEntete("Supprimer un client");
var liste = Application.GetBaseDonnees().Clients.ToList();
ConsoleHelper.AfficherListe(liste);
var id = ConsoleSaisie.SaisirEntierObligatoire("Id à supprimer : ");
using (var bd = Application.GetBaseDonnees())
{
var client = bd.Clients.Single(x => x.Id == id);
bd.Clients.Remove(client);
bd.SaveChanges();
}
}
}
}
| ad833bbb9bd7f30cc10de468b2f9ecdbd2412db3 | [
"C#"
] | 22 | C# | Lapinte/LocaMat1 | 44f8997bff7d67f985bf8c3c7799d5f092208c71 | a427f05ca3903fe552d72f87bca33b158b3b1409 |
refs/heads/master | <file_sep>//
// TableViewController.swift
// OnTheMap
//
// Created by <NAME> on 5/5/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import UIKit
class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var Locations = [StudentLocation]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var addPinButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getStudentLocations()
tableView.reloadData()
}
@IBAction func logout(_ sender: Any) {
UdacityClient.logout(completioHandler: handleLogoutResponse(success:error:))
}
@IBAction func addLocation(_ sender: Any) {
performSegue(withIdentifier: "segueToAdd", sender: nil)
}
@IBAction func reloadData(_ sender: Any) {
getStudentLocations()
}
func getStudentLocations() {
ParseClient.getStudentLocation { (studentLocation, error) in
if error != nil {
self.getStudentLocationError()
} else {
self.Locations = studentLocation
self.tableView.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
Locations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "LocationCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as UITableViewCell
let locations = Locations[indexPath.row]
cell.textLabel?.text = "\(locations.firstName) \(locations.lastName)"
cell.detailTextLabel?.text = "\(locations.mediaURL)"
cell.imageView?.image = UIImage(named: "mapPin")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIApplication.shared.open(ParseClient.Endpoint.udacityURL.url, options: [:], completionHandler: nil)
}
func handleLogoutResponse(success: Bool, error: Error?) {
if success {
alertView()
} else {
errorView()
}
}
func alertView() {
let alertVC = UIAlertController(title: "You are about to log out", message: "Confirm Log Out", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Log Out", style: .default, handler: { (_) in
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}))
alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertVC, animated: true)
}
func errorView() {
let alert = UIAlertController(title: "Error", message: "Application Error", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
func getStudentLocationError() {
let alert = UIAlertController(title: "Error", message: "Error getting student locations", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
<file_sep># OnTheMap
This app allows users view their friends locations, drop pins on the map and add a url for friends to view.
<file_sep>//
// MapViewController.swift
// OnTheMap
//
// Created by <NAME> on 5/5/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var addPinButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
var location = [StudentLocation]()
var annotations = [MKPointAnnotation]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getStudentPins()
}
@IBAction func addLocation(_ sender: Any) {
performSegue(withIdentifier: "addSegue", sender: nil)
}
@IBAction func logout(_ sender: Any) {
logoutView()
}
@IBAction func mapRefreshButton(_ sender: Any) {
getStudentPins()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.tintColor = .red
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let app = UIApplication.shared
if let toOpen = view.annotation?.subtitle! {
app.open(URL(string: toOpen)!, options: [:], completionHandler: nil)
}
}
}
func getStudentPins() {
ParseClient.getStudentLocation { (studentLocation, error) in
if error != nil {
self.getStudentLocationError()
}else{
self.location = studentLocation
DispatchQueue.main.async {
self.placeStudentPins()
}
}
}
}
func placeStudentPins() {
for dictionary in location {
let lat = CLLocationDegrees(dictionary.latitude)
let lon = CLLocationDegrees(dictionary.longitude)
let cordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let first = dictionary.firstName
let last = dictionary.lastName
let mediaURL = dictionary.mediaURL
let annotation = MKPointAnnotation()
annotation.coordinate = cordinate
annotation.title = "\(first) \(last)"
annotation.subtitle = "\(mediaURL)"
annotations.append(annotation)
mapView.addAnnotations(annotations)
mapView.addAnnotation(annotation)
}
}
func handleLogOut(success: Bool, error: Error?) {
if success == false{
logoutError()
}
}
func logoutView() {
let alertVC = UIAlertController(title: "You are about to log out", message: "Confirm Log Out", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Log Out", style: .default, handler: { (_) in
UdacityClient.logout(completioHandler:self.handleLogOut(success:error:))
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}))
alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertVC, animated: true)
}
func logoutError() {
let alert = UIAlertController(title: "Error", message: "Error logging out", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
func getStudentLocationError() {
let alert = UIAlertController(title: "Error", message: "Error getting student locations", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
<file_sep>//
// UdacityLoginRequest.swift
// OnTheMap
//
// Created by <NAME> on 5/7/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct UdacityLoginRequest: Codable {
let username: String
let password: String
}
<file_sep>//
// StudentClient.swift
// OnTheMap
//
// Created by <NAME> on 5/5/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
class ParseClient {
static var postLocation: StudentLocation!
struct Auth{
static var objectId = ""
static var sessionId = ""
static var createdAt = ""
}
enum Endpoint {
static let getLocation = "https://onthemap-api.udacity.com/v1/StudentLocation?order=-updatedAt&limit=100"
static let postLocation = "https://onthemap-api.udacity.com/v1/StudentLocation"
static let putLocation = "https://onthemap-api.udacity.com/v1/StudentLocation/" + "\(Auth.objectId)"
static let udacity = "https://www.udacity.com"
case getLocationURL
case postLocationURL
case putLocationURL
case udacityURL
var urlValue: String {
switch self {
case .getLocationURL: return Endpoint.getLocation
case .postLocationURL: return Endpoint.postLocation
case .putLocationURL: return Endpoint.putLocation
case .udacityURL: return Endpoint.udacity
}
}
var url: URL {
return URL(string: urlValue)!
}
}
class func getStudentLocation(completionHandler: @escaping([StudentLocation], Error?) -> Void) {
taskGETRequest(url: Endpoint.getLocationURL.url, response: Results.self) { (response, error) in
if let response = response {
completionHandler(response.results, nil)
} else {
completionHandler([], error)
}
}
}
class func postStudentLocation(uniquekey: String, firstName: String, lastName: String, mapString: String, mediaURL: String, latitude: Double, longitude: Double, completionHandler: @escaping (Bool, Error?) -> Void){
taskPOSTRequest(url: Endpoint.postLocationURL.url, body: LocationRequest(uniqueKey: uniquekey, firstName: firstName, lastName: lastName, mapString: mapString, mediaURL: mediaURL, latitude: latitude, longitude: longitude), response: LocationResponse.self) { (response, error) in
if let response = response {
Auth.objectId = response.objectId
Auth.createdAt = response.createdAt
print("\(Auth.objectId) ,\(Auth.createdAt)")
completionHandler(true, nil)
}else {
completionHandler(false, error)
}
}
}
class func overwriteStudentLocation(completionHandler: @escaping (Bool, Error?) -> Void) {
taskPUTRequest(url: Endpoint.putLocationURL.url, body: LocationRequest(uniqueKey: postLocation.uniqueKey , firstName: postLocation.firstName, lastName: postLocation.lastName, mapString: postLocation.mapString, mediaURL: postLocation.mediaURL, latitude: postLocation.latitude, longitude: postLocation.longitude), response: PutResponse.self) { (response, error) in
if let response = response {
print(response)
completionHandler(true, nil)
} else {
completionHandler(false, error)
}
}
}
class func taskGETRequest<Response: Decodable>(url: URL, response: Response.Type, completionHandler: @escaping (Response?, Error?) -> Void) {
let task = URLSession.shared.dataTask(with: url) { (data, _, error) in
guard let data = data else {
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let object = try decoder.decode(Response.self, from: data)
DispatchQueue.main.async {
completionHandler(object, nil)
}
} catch {
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
task.resume()
}
class func taskPOSTRequest<Request: Encodable, Response: Decodable>(url: URL, body:Request, response: Response.Type, completionHandler: @escaping (Response?, Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let enconder = JSONEncoder()
do {
request.httpBody = try enconder.encode(body)
} catch {
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
guard let data = data else {
DispatchQueue.main.async {
completionHandler(nil, error)
}
return
}
let decoder = JSONDecoder()
do {
let object = try decoder.decode(response.self, from: data)
DispatchQueue.main.async {
completionHandler(object, nil)
}
} catch {
print(error.localizedDescription)
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
task.resume()
}
class func taskPUTRequest<Request: Encodable, Response: Decodable>(url: URL, body:Request, response: Response.Type, completionHandler: @escaping (Response?, Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let enconder = JSONEncoder()
do {
request.httpBody = try enconder.encode(body)
} catch {
completionHandler(nil, error)
}
let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
guard let data = data else {
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let object = try decoder.decode(Response.self, from: data)
DispatchQueue.main.async {
completionHandler(object, nil)
}
} catch {
print(error.localizedDescription)
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
task.resume()
}
}
<file_sep>//
// AddMapLocationViewController.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class AddMapLocationViewController: UIViewController, MKMapViewDelegate, UITextFieldDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var cityTextField: UITextField!
@IBOutlet weak var stateTextField: UITextField!
@IBOutlet weak var linkTextField: UITextField!
@IBOutlet weak var dropPinButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var uniqueKey = ""
var firstName = ""
var lastName = ""
var mediaURL = ""
var location = CLLocation()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
cityTextField.delegate = self
stateTextField.delegate = self
linkTextField.delegate = self
locationManager.delegate = self
loadingIndicator.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotification()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeToKeyboardNotification()
}
@IBAction func dropPin(_ sender: Any) {
enableLoading(Bool: true)
stateTextField.resignFirstResponder()
getCoordinate(addressString: "\(cityTextField.text!), \(stateTextField.text!)") { (location, error) in
if error == nil {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
self.mapView.addAnnotation(annotation)
self.enableLoading(Bool: false)
}
}
}
@IBAction func shareLocation(_ sender: Any) {
getUserData(completionHandler: handleGetUserData(success:error:))
}
@IBAction func cancelButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
func getCoordinate(addressString : String, completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
self.location = location
let span = MKCoordinateSpan(latitudeDelta: 0.50, longitudeDelta: 0.50)
let cordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: cordinate, span: span)
self.mapView.setRegion(region, animated: true)
completionHandler(location.coordinate, nil)
return
}
}
self.geocodingError()
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
func getUserData(completionHandler: @escaping(Bool, Error?) -> Void) {
UdacityClient.getUserData { (userData, error) in
if let userData = userData {
self.uniqueKey = userData.key
self.firstName = userData.firstName
self.lastName = userData.lastName
print(self.uniqueKey, self.firstName, self.lastName)
completionHandler(true, nil)
} else {
print("error in getting user data")
completionHandler(false, error)
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if stateTextField.isEditing {
linkTextField.isHidden = false
shareButton.isHidden = false
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func subscribeToKeyboardNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardNotification() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillHide(_ notification: Notification) {
view.frame.origin.y = 0
}
@objc func keyboardWillShow(_ notification: Notification) {
view.frame.origin.y = 50 - getKeyboardHeight(notification)
}
func handleGetUserData(success: Bool, error: Error?) {
if success {
ParseClient.postStudentLocation(uniquekey: uniqueKey, firstName: firstName, lastName: lastName, mapString: "\(cityTextField.text!), \(stateTextField.text!)", mediaURL: "\(linkTextField.text!)", latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, completionHandler: handlePostLocation(success:error:))
print(location.coordinate.latitude , location.coordinate.longitude)
} else {
postLocationError()
print(error!.localizedDescription)
}
}
func handlePostLocation(success: Bool, error: Error?) {
if success {
self.dismiss(animated: true, completion: nil)
} else {
print(error?.localizedDescription ?? "")
print("Error in posting location")
}
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func alertView() {
let alertVC = UIAlertController(title: "Error", message: "Error Finding Location, try another location", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertVC, animated: true, completion: nil)
}
func postLocationError() {
let alertVC = UIAlertController(title: "Error", message: "Error posting location", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertVC, animated: true, completion: nil)
}
func geocodingError() {
let alertVC = UIAlertController(title: "Error", message: "Error finding location", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertVC, animated: true, completion: nil)
}
func enableLoading(Bool: Bool) {
if Bool {
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
} else {
loadingIndicator.stopAnimating()
loadingIndicator.isHidden = true
}
}
}
<file_sep>//
// LoginViewController.swift
// OnTheMap
//
// Created by <NAME> on 5/5/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passowrdField: UITextField!
@IBOutlet weak var LoginButton: UIButton!
@IBOutlet weak var LoadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var acccountLabel: UILabel!
@IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
usernameField.delegate = self
passowrdField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
usernameField.text = ""
passowrdField.text = ""
subscribeToKeyboardNotification()
enableButton(Bool: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeToKeyboardNotification()
}
@IBAction func loginTapped(_ sender: Any) {
if usernameField.text == nil && passowrdField.text == nil {
alertView()
} else {
setLoggingIn(true)
UdacityClient.login(username: usernameField.text ?? "", password: <PASSWORD>Field.text ?? "", completionHandler: handleLoginResponse(success:error:))
}
}
@IBAction func signUpButton(_ sender: Any) {
setLoggingIn(true)
UIApplication.shared.open(ParseClient.Endpoint.udacityURL.url, options: [:], completionHandler: nil)
enableButton(Bool: true)
}
func setLoggingIn(_ loggingIn: Bool) {
if loggingIn {
LoadingIndicator.startAnimating()
} else {
LoadingIndicator.stopAnimating()
}
enableButton(Bool: !loggingIn)
}
func handleLoginResponse(success: Bool, error: Error?) {
if success {
performSegue(withIdentifier: "LoginSegue", sender: nil)
} else {
alertView()
print(error?.localizedDescription ?? "Something is wrong in the Login View Controller")
}
}
func alertView() {
let alertVC = UIAlertController(title: "Login Failed", message: "", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertVC, animated: true, completion: nil)
LoadingIndicator.stopAnimating()
enableButton(Bool: true)
}
func enableButton(Bool: Bool) {
usernameField.isEnabled = Bool
passowrdField.isEnabled = Bool
signUpButton.isEnabled = Bool
LoginButton.isEnabled = Bool
if Bool == true {
LoadingIndicator.stopAnimating()
}
}
func subscribeToKeyboardNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardNotification() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillHide(_ notification: Notification) {
view.frame.origin.y = 0
}
@objc func keyboardWillShow(_ notification: Notification) {
view.frame.origin.y = 50 - getKeyboardHeight(notification)
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
<file_sep>//
// UdacityAccountResponse.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct Account: Codable {
let registered: Bool
let key: String
}
<file_sep>//
// UdacityLoginRespone.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct UdacityLoginResponse: Codable {
let account: Account
let session: Session
enum CodingKeys:String, CodingKey {
case account
case session
}
}
<file_sep>//
// StudentLocationModel.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
class StudentLocationModel {
static var studentLocation = [StudentLocation]()
}
<file_sep>//
// UdacitySessionResponse.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct Session: Codable {
let id: String
let expiration: String
}
<file_sep>//
// StudentPutResponse.swift
// OnTheMap
//
// Created by <NAME> on 5/7/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct PutResponse: Codable {
let updatedAt: String
}
<file_sep>//
// LoginRequest.swift
// OnTheMap
//
// Created by <NAME> on 5/7/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct Login: Codable {
let udacity: UdacityLoginRequest
}
<file_sep>//
// UdacityClient.swift
// OnTheMap
//
// Created by <NAME> on 5/7/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
class UdacityClient {
struct Auth {
static var sessionId = ""
static var userId = ""
static var expiration = ""
}
enum Endpoint {
static let sessionURL = "https://onthemap-api.udacity.com/v1/session"
static let studentLocationURL = "https://onthemap-api.udacity.com/v1/StudentLocation"
static let userdataURL = "https://onthemap-api.udacity.com/v1/users/\(Auth.userId)"
case getSessionIdURL
case getStudentLocationURL
case getUserDataURL
var urlValue: String{
switch self {
case .getSessionIdURL: return Endpoint.sessionURL
case .getStudentLocationURL: return Endpoint.studentLocationURL
case .getUserDataURL: return Endpoint.userdataURL
}
}
var url: URL {
return URL(string: urlValue)!
}
}
class func login(username: String, password: String, completionHandler: @escaping (Bool, Error?) -> Void) {
taskPOSTRequest(url: Endpoint.getSessionIdURL.url, body: Login(udacity: UdacityLoginRequest(username: username, password: <PASSWORD>)), response: UdacityLoginResponse.self) { (response, error) in
if let response = response {
Auth.sessionId = response.session.id
Auth.userId = response.account.key
Auth.expiration = response.session.expiration
print(Auth.userId)
DispatchQueue.main.async {
completionHandler(true, nil)
}
} else {
DispatchQueue.main.async {
completionHandler(false, error)
}
}
}
}
class func logout(completioHandler: @escaping (Bool, Error?) -> Void) {
var request = URLRequest(url: Endpoint.getSessionIdURL.url)
request.httpMethod = "DELETE"
var xsrfCookie: HTTPCookie? = nil
let sharedCookieStorage = HTTPCookieStorage.shared
for cookie in sharedCookieStorage.cookies! {
if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie }
}
if let xsrfCookie = xsrfCookie {
request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN")
}
let body = Session(id: "\(Auth.sessionId)", expiration: "\(Auth.expiration)")
do {
request.httpBody = try JSONEncoder().encode(body)
DispatchQueue.main.async {
completioHandler(true, nil)
}
} catch {
DispatchQueue.main.async {
print(false, error)
}
}
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if error != nil {
return
}
do {
let range = (5..<data!.count)
let newData = data!.subdata(in: range)
_ = try JSONDecoder().decode(Session.self, from: newData)
DispatchQueue.main.async {
completioHandler(true, nil)
}
Auth.sessionId = ""
} catch {
DispatchQueue.main.async {
completioHandler(false, error)
}
}
}
task.resume()
}
class func getUserData(completionHandler: @escaping (UserData?, Error?) -> Void) {
taskGETRequest(url: Endpoint.getUserDataURL.url, response: UserData.self) { (response, error) in
if let response = response {
DispatchQueue.main.async {
completionHandler(response, nil)
}
print(response)
} else {
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
}
class func taskGETRequest<Response: Decodable>(url: URL, response: Response.Type, completionHandler: @escaping (Response?, Error?) -> Void) {
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let range = (5..<data.count)
let newData = data.subdata(in: range)
let object = try decoder.decode(Response.self, from: newData)
DispatchQueue.main.async {
completionHandler(object, nil)
}
} catch {
do {
let errorResponse = try JSONDecoder().decode(UdacityError.self, from: data)
DispatchQueue.main.async {
completionHandler(nil, errorResponse as? Error)
}
}catch {
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
}
task.resume()
}
class func taskPOSTRequest<Request: Encodable, Response: Decodable>(url: URL, body:Request, response: Response.Type, completionHandler: @escaping (Response?, Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let enconder = JSONEncoder()
do {
request.httpBody = try enconder.encode(body)
} catch {
completionHandler(nil, error)
print(error)
}
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
guard let data = data else {
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let range = (5..<data.count)
let newData = data.subdata(in: range)
let object = try decoder.decode(Response.self, from: newData)
DispatchQueue.main.async {
completionHandler(object, nil)
}
} catch {
do {
let errorResponse = try JSONDecoder().decode(UdacityError.self, from: data)
DispatchQueue.main.async {
completionHandler(nil, errorResponse as? Error)
}
} catch {
DispatchQueue.main.async {
completionHandler(nil, error)
}
}
}
}
task.resume()
}
}
<file_sep>//
// StudentLocationResponse.swift
// OnTheMap
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct LocationResponse: Codable {
let createdAt: String
let objectId: String
}
<file_sep>//
// UdacityErrorResponse.swift
// OnTheMap
//
// Created by <NAME> on 5/12/20.
// Copyright © 2020 DoyinOsanyintolu. All rights reserved.
//
import Foundation
struct UdacityError: Codable {
let status: Int
let error: String
}
| c1acda2f26e8b33f76a8afbb958480143153b9d2 | [
"Swift",
"Markdown"
] | 16 | Swift | Dosanyintolu/OnTheMap | 8685d5988b34cccb1705c171baaa3123c3a2fb18 | 50f48d0a7525205f120aa6fd34a9d68737f0dd1b |
refs/heads/master | <file_sep>//////////////////////////////////////////////////////////////////////////
//技能cd
//技能时间
//技能背景图
//
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "cocos2d.h"
//#include "cocos-ext.h"
#include "ui/CocosGUI.h"
using namespace cocos2d;
using namespace ui;
class SkillCD : public Layer
{
DECLARE_CLASS_GUI_INFO
public:
SkillCD();
virtual ~SkillCD();
CREATE_FUNC(SkillCD);
void setSkillCDFile(std::string strFileName);
void setSkillStart();
void setSkillCD(int cd);
bool getTouch(){return m_bTouch; }
private:
void updateCD(float dt);
float m_nSkillCDTime;//cd时间
float m_nSkillCDTimeMax;
ProgressTimer *m_pProgressTimer;
bool m_bStartCD;
bool m_bTouch;
};
<file_sep>#include "skillcd.h"
SkillCD::SkillCD()
{
m_nSkillCDTime = 0.f;
m_nSkillCDTimeMax = 0.f;
m_pProgressTimer = NULL;
m_bStartCD = false;
m_bTouch = false;
}
SkillCD::~SkillCD()
{
m_pProgressTimer = NULL;
this->unscheduleUpdate();
}
void SkillCD::setSkillCDFile(std::string strFileName)
{
//设置第三章图片为cd旋转图片
Sprite *pSprite = Sprite::create(strFileName.c_str());
m_pProgressTimer = ProgressTimer::create(pSprite);
m_pProgressTimer->setType(ProgressTimer::Type::RADIAL);
m_pProgressTimer->setReverseProgress(true);
m_pProgressTimer->setPercentage(100.f);
m_pProgressTimer->setVisible(false);
this->addChild(m_pProgressTimer);
Button *pButton = dynamic_cast<Button*>(this->getParent());
if (pButton)
{
m_pProgressTimer->setPosition(Vec2(pButton->getContentSize().width / 2, pButton->getContentSize().height/ 2));
}
//m_pProgressTimer->setAnchorPoint(Vec2::ZERO);
}
void SkillCD::setSkillCD(int cd)
{
m_nSkillCDTime = cd;//cd时间
m_nSkillCDTimeMax = cd;
}
void SkillCD::setSkillStart()
{
if (!m_bStartCD)
{
m_bTouch = true;
m_bStartCD = true;
Button *pButton = dynamic_cast<Button*>(this->getParent());
if (pButton)
{
pButton->setTouchEnabled(false);
}
if (m_pProgressTimer)
{
m_pProgressTimer->setVisible(true);
}
schedule(schedule_selector(SkillCD::updateCD));
}
}
void SkillCD::updateCD(float dt)
{
if (m_bStartCD)
{
if (m_pProgressTimer)
{
float fPercentage = m_pProgressTimer->getPercentage();
m_nSkillCDTime -= dt;
//CCLOG("%d", m_nSkillCDTime );
m_pProgressTimer->setPercentage(m_nSkillCDTime * 100 / m_nSkillCDTimeMax);
if (m_nSkillCDTime < 0)
{
Button *pButton = dynamic_cast<Button*>(this->getParent());
if (pButton)
{
pButton->setTouchEnabled(true);
}
m_bStartCD = false;
m_bTouch = false;
m_nSkillCDTime = m_nSkillCDTimeMax;
unschedule(schedule_selector(SkillCD::updateCD));
m_pProgressTimer->setVisible(false);
m_pProgressTimer->setPercentage(100.f);
}
}
}
}
<file_sep>#include "HelloWorldScene.h"
//#include "cocos-ext.h"
#include "skillcd.h"
using namespace cocostudio::timeline;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
/** you can create scene with following comment code instead of using csb file.
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
**/
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto rootNode = CSLoader::createNode("MainScene.csb");
Size size = Director::getInstance()->getWinSize();
addChild(rootNode);
Button *pButton = dynamic_cast<Button*>(rootNode->getChildByName("Button_1"));
if (pButton)
{
pButton->addTouchEventListener(CC_CALLBACK_2(HelloWorld::SkillCDCallBack,this));
SkillCD *pSkillCD = SkillCD::create();
if (pSkillCD)
{
pSkillCD->setTag(1000);
pButton->addChild(pSkillCD);
pSkillCD->setSkillCD(10);
pSkillCD->setSkillCDFile(pButton->getDisabledFile().file);
}
}
pButton = dynamic_cast<Button*>(rootNode->getChildByName("Button_2"));
if (pButton)
{
pButton->addTouchEventListener(CC_CALLBACK_2(HelloWorld::SkillCDCallBack, this));
SkillCD *pSkillCD = SkillCD::create();
if (pSkillCD)
{
pSkillCD->setTag(1000);
pButton->addChild(pSkillCD);
pSkillCD->setSkillCD(10);
pSkillCD->setSkillCDFile(pButton->getDisabledFile().file);
}
}
pButton = dynamic_cast<Button*>(rootNode->getChildByName("Button_3"));
if (pButton)
{
pButton->addTouchEventListener(CC_CALLBACK_2(HelloWorld::SkillCDCallBack, this));
SkillCD *pSkillCD = SkillCD::create();
if (pSkillCD)
{
pSkillCD->setTag(1000);
pButton->addChild(pSkillCD);
pSkillCD->setSkillCD(10);
pSkillCD->setSkillCDFile(pButton->getDisabledFile().file);
}
}
return true;
}
void HelloWorld::SkillCDCallBack(Ref *pSender, Widget::TouchEventType type)
{
Button *pButton = (Button*)pSender;
if (pButton)
{
if (type == Widget::TouchEventType::ENDED)
{
if (pButton->isTouchEnabled())
{
pButton->setTouchEnabled(false);
SkillCD* pSkillCD = dynamic_cast<SkillCD*>(pButton->getChildByTag(1000));
if (pSkillCD)
{
pSkillCD->setSkillStart();
}
//Êͷż¼ÄÜ
}
}
}
} | 7835ff236937818dae9309facfceed9826379d69 | [
"C++"
] | 3 | C++ | zhuiyiyyh/yyh | 749a95ca8f1249efad9a2b855da78451a1c08920 | cc1ee28770b5c005a86f1496ad2f607475fa0761 |
refs/heads/main | <repo_name>ianhi/matplotlib-extension-cookiecutter<file_sep>/{{cookiecutter.github_project_name}}/examples/example.py
"""
------------
Example Name
------------
A short example showcasing how to use the library. The docstrings will be
turns in REST by sphinx-gallery.
"""
import numpy as np
import matplotlib.pyplot as plt
from {{ cookiecutter.python_package_name }} import example_function
# make some fake data
rng = np.random.default_rng(0)
data = rng.standard_normal((1000, 2))
fig, ax = plt.subplots()
scatter = example_function(ax, data, above_color='b')
plt.show()
<file_sep>/{{cookiecutter.github_project_name}}/{{cookiecutter.python_package_name}}/example.py
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) {{ cookiecutter.author_name }}.
# Distributed under the terms of the Modified BSD License.
__all__ = [
"example_function",
]
import numpy as np
def example_function(ax, data, above_color="r", below_color="k", **kwargs):
"""
An example function that makes a scatter plot with points colored differently
depending on if they are above or below `y=0`.
Parameters
----------
ax : matplotlib axis
The axis to plot on.
data : (N, 2) array-like
The data to make a plot from
above_color : color-like, default: 'r'
The color of points with `y>0`
below_color : color-like, default: 'k'
The color of points with `y<0`
kwargs :
Passed through to `ax.scatter`
Returns
-------
MarkerCollection
"""
colors = np.array([above_color] * data.shape[0])
colors[data[:, 1] < 0] = below_color
return ax.scatter(data[:, 0], data[:, 1], c=colors, **kwargs)
<file_sep>/{{cookiecutter.github_project_name}}/docs/API.rst
===
API
===
Example Module
---------------
The example module just contains one function - which is just an example
function to extend matplotlib functionality.
.. currentmodule:: {{ cookiecutter.python_package_name}}.example
.. autosummary::
:toctree: autoapi
:nosignatures:
:recursive:
example_function
<file_sep>/{{cookiecutter.github_project_name}}/pyproject.toml
[tool.black]
skip-string-normalization = true
[tool.pytest.ini_options]
testpaths = [
"{{ cookiecutter.python_package_name }}/tests"
]
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
<file_sep>/{{cookiecutter.github_project_name}}/README.md
# {{ cookiecutter.github_project_name }}
{{ cookiecutter.project_short_description }}
## Installation
You can install using `pip`:
```bash
pip install {{ cookiecutter.python_package_name }}
```
## Development Installation
```bash
pip install -e ".[dev]"
```
<file_sep>/README.md
# Matplotlib 3rd Party Package Cookiecutter
Turn your matplotlib scripts into a sharable python package using this
[cookiecutter](https://cookiecutter.readthedocs.io/en/1.7.2/) recipe:
```
pip install cookiecutter
cookiecutter gh:matplotlib/matplotlib-extension-cookiecutter
```
Add your code to `yourname/yourname/yourcode.py` and you can do
```python
from yourname import yourcode
```
## But why?
Sharing your code on public distribution channels like PyPi requires some infrastructure in terms of setup files that take time and can be annoying to get right. The cookiecutter takes care of this for you, and alos sets up a testing and documentation building environment:
- Github actions work
- Issue templates
- Properly set up packaging
- A setup for docs with:
- `sphinx-gallery`
- `autodoc`
- The set up for `pytest-mpl`
## Building docs
```
cd docs
make watch
```
## Setting up readthedocs
Readthedocs is a website that hosts the docs for many projects in the Python ecosystem. You can integrate them with your repo by following the instructions here: https://docs.readthedocs.io/en/stable/webhooks.html
You can also have readthedocs make test builds on PRs by following the instructions here: https://docs.readthedocs.io/en/latest/pull-requests.html
## Setting up tests
The best way to do testing for a Matplotlib extension is to use [pytest-mpl](https://github.com/matplotlib/pytest-mpl#about). This project inclues a basic test, but does not pregenerate any baselines images. To make the example test work you first need to generate the baseline with:
```
pytest --mpl-generate-path=<package-name>/tests/baseline
```
For full instructions see: https://github.com/matplotlib/pytest-mpl#using
## Publicizing your package
Once you've made your package other people will likely want to use your hard work, and maybe even contribute to it! But for this to happen they need to know about it. The Matplotlib devs also want you to share your package and like to amplify your advertising. So some great steps to take in order to share your package are:
1. Make a PR to add it to Matplotlib's 3rd party packages page:
- https://matplotlib.org/mpl-third-party/
2. Tweet about your pacakge and and mention `@matplotlib` for a retweet.
## Miscellaneous Advice
Do not use Matplotlib private methods. If you really need the functionality then consider opening a feature request to have Matplotlib provide a public API for what you want.
There is some discussion of how to use Matplotlib docstrings on discourse: https://discourse.matplotlib.org/t/docs-for-a-method-wrapping-a-matplotlib-method/21055
https://colcarroll.github.io/yourplotlib/ is a great read for how to make an extension to Matplotlib.
## LICENSE Advice
You may end up using portions of Matplotlib's code or copying docstrings when making a Matplotlib extension.
As a practical rule: If you end up copying a non-trivial amount of code or docs the safest course of action is to add the Matplotlib license to your project as a derived work. For example see how Matplotlib does it https://github.com/matplotlib/matplotlib/tree/master/LICENSE.
> But what counts as non-trivial?
A good rule of thumb is to ask yourself:
If it were homework and you didn't acknowledge would it be cheating?
If the answer is yes, then you should leave a comment in the code and include a license file in a top level `LICENSE` folder.
## Releasing to PyPi
### Manually
First set ensure you have the right packages installed:
```
pip install build twine
```
Then generate an `sdist` and a `wheel`:
1. bump version in `_version.py`
2. `git add <...>/_version.py`
3. `commit -m 'version bump'`
4. `git tag <version number>`
5. `git push --tags`
6. `python -m build -sdist -wheel`
7. `twine upload dist/*`
### Using Github Actions
If you use Github as your Git repository then you can also automate steps 4-7 by using the Github action included in the cookiecutter.
To do this you will need to generate a PyPI api token and add it to your repository's secrets.
**Generating an api token**
Go to you [PyPI account setttings](https://pypi.org/manage/account/), scroll down to the API tokens section and select "Add API token".
**Adding api token to Github Secrets**
Once you've have copied the token from PyPI go the `Secrets` section of your Github repo's settings and add the token with the name `PYPI_API_TOKEN`
With that set up all you need to do to create a release is:
1. bump version in `_version.py`
2. `git add <...>/_version.py`
3. `git commit -m 'version bump' && git push`
4. Make a release using the github release tool.
To make the release go the the `Releases` section in the repo sidebar:

then draft a new release:

After you fill out the information the Github action will create a new tag for you, build the wheel, and upload it to PyPI.
## Credit
This cookiecutter is partially based on the following cookiecutters
- https://github.com/jupyter-widgets/widget-ts-cookiecutter
- The `setup.cfg` from https://github.com/napari/napari
----
Happy Plotting!
<file_sep>/{{cookiecutter.github_project_name}}/docs/index.rst
Welcome to {{ cookiecutter.python_package_name }}'s documentation!
===================================================================
A library makes for making awesome plots like this one:
.. image:: _static/images/front-page-image.png
Installation
^^^^^^^^^^^^^
.. code-block:: bash
pip install {{ cookiecutter.python_package_name }}
Getting Help
^^^^^^^^^^^^
If you have a question on how to do something with ``{{ cookiecutter.python_package_name }}`` a great place
to ask it is: https://discourse.matplotlib.org/c/3rdparty/18.
.. toctree::
:maxdepth: 3
examples/index
API
Contributing
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>/{{cookiecutter.github_project_name}}/examples/README.rst
---------------
Example Gallery
---------------
Some explanatory text. See https://sphinx-gallery.github.io/stable/index.html for how to configure this page.
<file_sep>/{{cookiecutter.github_project_name}}/{{cookiecutter.python_package_name}}/tests/test_example.py
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) {{ cookiecutter.author_name }}.
# Distributed under the terms of the Modified BSD License.
from ..example import example_function
import pytest
import matplotlib.pyplot as plt
import numpy as np
@pytest.mark.mpl_image_compare(filename="test_example.png")
def test_example():
fig, ax = plt.subplots()
# data = np.hstack([np.linspace(-10, 10)[:, None], np.linspace(10, -10)[:, None]])
example_function(ax, data, above_color='b', below_color='g')
return fig
| ea74b7b1ea3076770cc0c3b569e84a8d6e2466b2 | [
"TOML",
"Python",
"Markdown",
"reStructuredText"
] | 9 | Python | ianhi/matplotlib-extension-cookiecutter | 29b9b3f62bfc1b24a27711e5b956a389c5933cbc | 881da5b59370d6b697e9035e01dc41883713e2e5 |
refs/heads/master | <file_sep>const express = require('express')
const router = express.Router()
const City = require('../modules/city')
const request = require(`request`)
router.get('/city/:cityname', function (req, response) {
const city = req.params.cityname
const url = "http://api.apixu.com/v1/current.json?key=257a9899d5134554979111522191007&q=" + city
request(url, function (err, res) {
const weather = JSON.parse(res.body)
response.send(weather)
})
})
router.get(`/cities`,function(req,res){
City.find({},function(err,doc){
res.send(doc)
})
})
router.post(`/city`,function(req,res){
let wheather = req.body
const c = new City(wheather)
c.save()
res.end()
})
//expects an object {city: "cityname"}
router.delete(`/city`, function(req,res) {
let city = req.body.city
City.remove({name:city},function(err,data){
res.send(city + " is removed from the DB")
})
})
module.exports = router<file_sep>const mongoose = require('mongoose')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const api = require(`./routes/api`)
const City = require(`../server/modules/city`)
const path = require('path')
app.use(express.static(path.join(__dirname,"..", 'dist')))
app.use(express.static(path.join(__dirname,"..", 'node_modules')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/', api)
app.listen(3000, function() {
console.log("Server up and running on port 3000")
})<file_sep>class Controller {
constructor(render,tmpManeger){
this.render = render
this.tmpManeger =tmpManeger
}
async loadPage(){
let data = await this.tmpManeger.getDataFromDB()
this.render.renderData(data)
const tmp = this.tmpManeger
const cont = this
$(`.delete`).on(`click`,function(){
let city = $(this).closest("span").find(".name").html()
console.log(city)
tmp.removeCity(city)
location.reload()
})
}
async handleSearch (){
let cityInput = $(`#citySerch`).val()
let waether = await this.tmpManeger.getCityData(cityInput)
this.render.renderData([waether])
const tmp = this.tmpManeger
const save = $(`#button`)
save.html('Save')
save.on(`click`,function(){
tmp.saveCity(waether)
location.reload()
})
}
}
const tmpManeger = new TempManager()
const render = new Render()
const controller = new Controller(render,tmpManeger)
window.onload = controller.loadPage()
$(`#search`).on(`click`,function(){
controller.handleSearch()
})<file_sep>class TempManager {
constructor() {
this.cityData = []
}
async getDataFromDB() {
const cities = await $.get(`/cities`)
for (let city of cities) {
this.cityData.push(city)
}
return this.cityData
}
async getCityData(cityName) {
const data = await $.get(`/city/${cityName}`)
const realdata = {
name: cityName,
temperature: data.current.temp_c,
condition: data.current.condition.text,
conditionPic: data.current.condition.icon,
updatedAt: data.current.last_updated
}
return realdata
}
saveCity(data) {
$.ajax({
type: "POST",
url: `/city`,
data: data,
success: function (data) {
}
})
}
removeCity(cityname) {
$.ajax({
type: "DELETE",
url: `/city`,
data: { city: cityname },
success: function (data) {
}
})
}
}
| f6f2501c77302a8fc0367d0f5204b6ff5383a8e2 | [
"JavaScript"
] | 4 | JavaScript | davidbool/WeatherApp | 4a23fa43a781138554b318842eab5f14815aeb9c | f427327b3ec15bee72b6595732ad0d91b3a7d281 |
refs/heads/master | <repo_name>WabbyWabbo/DataStructure<file_sep>/SqList/2.2.3_9/2.2.3_9.cpp
#include "/Users/fisher/Desktop/ds/SqList/SqList.h"
void Function(SqList &L, int x)
{
int start = 0;
int end = L.length - 1;
int mid;
while (start <= end)
{
mid = (start + end) / 2;
if (x == L.data[mid])
{
if (mid < L.length - 1)
{
int temp = L.data[mid];
L.data[mid] = L.data[mid + 1];
L.data[mid + 1] = temp;
return;
}
else
{
cout << x << " 没有后继元素" << endl;
return;
}
}
else if (x < L.data[mid])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
//下标end的后一个是插入位置下标,即L中的第(end+2)个数
ListInsert(L, end + 2, x);
}
int main(void)
{
SqList L;
InitList(L);
ListInsert(L, 1, 1);
ListInsert(L, 2, 2);
ListInsert(L, 3, 3);
ListInsert(L, 4, 4);
ListInsert(L, 5, 5);
ListInsert(L, 6, 6);
ListInsert(L, 7, 7);
ListInsert(L, 8, 8);
ListInsert(L, 9, 9);
ListInsert(L, 10, 10);
Function(L,-1);
PrintList(L);
}<file_sep>/SqList/SqList.h
#include <iostream>
#define MaxSize 50
using namespace std;
//顺序表定义
typedef struct {
int data[MaxSize];
int length;
}SqList;
//初始化
void InitList(SqList &L) {
for (int i = 0; i < MaxSize; i++) {
L.data[i] = 0;
}
L.length = 0;
}
//求长度
int Length(SqList L) {
return L.length;
}
//插入
bool ListInsert(SqList& L, int i, int e) {
if (i < 1 || i > L.length + 1) {
return false;
}
if (L.length >= MaxSize) {
return false;
}
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
//删除
bool ListDelete(SqList& L, int i, int &e) {
if (i < 1 || i > L.length) {
return false;
}
if (L.length == 0) {
return false;
}
e = L.data[i - 1];
for (int j = i; j < L.length; j++) {
L.data[j - 1] = L.data[j];
}
L.length--;
return true;
}
//查找
int LocateElem(SqList L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i + 1;
}
}
return 0;//查找失败
}
//输出
void PrintList(SqList L) {
for (int i = 0; i < L.length - 1; i++) {
cout << L.data[i]<< " ";
}
cout << L.data[L.length - 1]<< endl;
}
//逆置
void Reverse(SqList& L) {
int temp;
int i, j;
for (i = 0,j = L.length - 1; i < j; i++, j--) {
temp = L.data[i];
L.data[i] = L.data[j];
L.data[j] = temp;
}
}
bool Delete_Same(SqList& L) {
if (L.length == 0)
return false;
int k = 0;
for (int i = 0; i < L.length; i++) {
if (L.data[i] == L.data[i + 1])
k++;
else
L.data[i + 1 - k] = L.data[i + 1];
}
L.length -= k;
return true;
}<file_sep>/SqList/2.2.3_10/2.2.3_10.cpp
#include <iostream>
#define N 5
using namespace std;
void Reverse(int R[], int l, int r)
{
int i, j, temp;
for (i = l, j = r; i < j; i++, j--)
{
temp = R[i];
R[i] = R[j];
R[j] = temp;
}
}
void RCR(int R[], int n, int p)
{
if (p <= 0 || p >= n)
{
cout << "ERROR" << endl;
}
else
{
Reverse(R, 0, p - 1);
Reverse(R, p, n - 1);
Reverse(R, 0, n - 1);
}
}
int main(void)
{
int p, i;
int R[N] = {1, 2, 3, 4, 5};
cout << "enter p:" << endl;
cin >> p;
RCR(R, N, p);
cout << "----------" << endl;
for (i = 0; i < N; i++)
{
cout << R[i];
cout << " ";
}
return 0;
}<file_sep>/LinkList/13.cpp
#include "/Users/fisher/Desktop/ds/LinkList/LinkList.h"
LinkList Merge_List_Dec(LinkList &L1, LinkList &L2)
{
}<file_sep>/SqList/2.2.3_8/2.2.3_8.cpp
#include "/Users/fisher/Desktop/ds/SqList/SqList.h"
void Reverse(int R[], int l, int r)
{
int i, j, temp;
for (i = l, j = r; i < j; i++, j--)
{
temp = R[i];
R[i] = R[j];
R[j] = temp;
}
}
void Exchange(int A[], int m, int n){
Reverse(A,0,m+n-1);
Reverse(A,0,n-1);
Reverse(A,n,m+n-1);
}
//main method for test
int main(void){
int A[] = {1,2,3,4,5,111,222,333};
Exchange(A,5,3);
for(int i = 0; i < 8; i++){
cout<<A[i]<<endl;
}
return 0;
}<file_sep>/SqList/2.2.3_7/2.2.3_7.cpp
#include "/Users/fisher/Desktop/ds/SqList/SqList.h"
bool Merge(SqList A, SqList B, SqList &C)
{
// if(A.length + B.length > C.maxSize)
// return false;
int i = 0, j = 0, k = 0;
while (i < A.length && j < B.length)
{
if (A.data[i] < B.data[j])
{
C.data[k++] = A.data[i++];
}
else
{
C.data[k++] = B.data[j++];
}
}
while (i < A.length)
{
C.data[k++] = A.data[i++];
}
while (j < B.length)
{
C.data[k++] = B.data[j++];
}
C.length = k;
return true;
}
/*test method*/
int main()
{
SqList L;
InitList(L);
ListInsert(L, 1, 1);
ListInsert(L, 2, 3);
ListInsert(L, 3, 5);
ListInsert(L, 4, 7);
ListInsert(L, 5, 9);
ListInsert(L, 6, 11);
ListInsert(L, 7, 13);
PrintList(L);
SqList L2;
InitList(L2);
ListInsert(L2, 1, 2);
ListInsert(L2, 2, 4);
ListInsert(L2, 3, 6);
ListInsert(L2, 4, 8);
ListInsert(L2, 5, 10);
ListInsert(L2, 6, 12);
ListInsert(L2, 7, 14);
PrintList(L2);
SqList C;
InitList(C);
Merge(L,L2,C);
PrintList(C);
return 0;
} | 75932f427a83b02c68d2032e6e2e50bf72d76c6d | [
"C++"
] | 6 | C++ | WabbyWabbo/DataStructure | dc5dadaa067b808930352396e94209540c56bd1b | 9e8f211bf9d64f5c74ba5f5d5b91f099e17c4bee |
refs/heads/master | <file_sep>require('sinatra')
require('sinatra/reloader')
require('./lib/queen')
get('/') do
erb(:index)
end
post('/results') do
queenA = params.fetch('queenA').split(',').map(&:to_i)
queenB = params.fetch('queenB').split(',').map(&:to_i)
@display = queenA.attack(queenB)
erb(:results)
end
<file_sep>require('rspec')
require('queen')
describe("Array#attack") do
it('checks if the queen can attack') do
expect(([1,2]).attack([2,4])).to(eq(false))
end
end
<file_sep>class Array
define_method(:attack) do |queenB|
if self[0] == queenB[0]
true
elsif self[1] == queenB[1]
true
elsif (self[0]-queenB[0]).abs == (self[1]-queenB[1]).abs
true
else
false
end
end
end
| 9c69067a290b6b6c7d92bc928910078bc4e8aed7 | [
"Ruby"
] | 3 | Ruby | LorenGlenn/ruby_queen_attack | 8273f0ebdc1f7328718cd778f8b1ec9e59afe0ff | 98bbbfc4b98aa3e23f47a9c11a4130a69b7abd22 |
refs/heads/master | <repo_name>jeremyeng/MusicEditor<file_sep>/src/cs3500/music/view/GuiViewFrame.java
package cs3500.music.view;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.util.*;
import java.util.List;
import javax.imageio.plugins.jpeg.JPEGHuffmanTable;
import javax.sound.midi.InvalidMidiDataException;
import javax.swing.*;
import cs3500.music.model.IMusicEditor;
import cs3500.music.model.MusicEditorModel;
import cs3500.music.model.IMusicEditor;
import cs3500.music.model.Note;
/**
* A skeleton Frame (i.e., a window) in Swing
*/
public class GuiViewFrame extends javax.swing.JFrame implements IMusicEditorView<Note> {
private final JPanel musicEditorPanel;
private final ScorePanel scorePanel; // You may want to refine this to a subtype of JPanel
private final PianoPanel pianoPanel;
private IMusicEditor model;
/**
* Creates new GuiView
*/
public GuiViewFrame() {
super();
this.setTitle("Music Editor");
this.musicEditorPanel = new JPanel();
this.musicEditorPanel.setLayout(new BoxLayout(this.musicEditorPanel, BoxLayout.Y_AXIS));
this.scorePanel = new ScorePanel();
this.pianoPanel = new PianoPanel();
scorePanel.setPreferredSize(scorePanel.getPreferredSize());
pianoPanel.setPreferredSize(new Dimension(1500,1200));
this.setSize(1600, 2000);
JScrollPane scrollFrame = new JScrollPane(scorePanel);
this.musicEditorPanel.add(scrollFrame);
this.musicEditorPanel.add(pianoPanel);
this.setContentPane(this.musicEditorPanel);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// this.pack();
}
@Override
public void makeVisible() {
this.setVisible(true);
}
@Override
public void playNote(List<List<List<Integer>>> info, long tempo) throws InvalidMidiDataException {
}
@Override
public void setListener(ActionListener action, KeyListener key) {
this.addKeyListener(key);
this.scorePanel.addKeyListener(key);
this.pianoPanel.addKeyListener(key);
}
// @Override
// public void resetFocus() {
// this.setFocusable(true);
// this.requestFocus();
// }
@Override
public void updateCurrentBeat(int beat) {
this.scorePanel.updateCurrentBeat(beat);
this.pianoPanel.updateCurrentBeat(beat);
}
@Override
public void showErrorMessage() {
}
@Override
public void refresh() {
}
@Override
public void setNoteRange(List noteRange) {
this.scorePanel.setNoteRange(noteRange);
this.pianoPanel.setNoteRange(noteRange);
}
@Override
public void setDuration(int duration) {
this.scorePanel.setDuration(duration);
this.pianoPanel.setDuration(duration);
}
@Override
public void setNoteMap(Map<Note, List<String>> notes) {
this.scorePanel.setNoteMap(notes);
}
@Override
public void update(IMusicEditor model) {
this.model = model;
}
@Override
public void setCombineNoteMap(Map <Integer, List<String>> notes) {
this.pianoPanel.setCombineNoteMap(notes);
this.scorePanel.setCombineNoteMap(notes);
}
@Override
public Dimension getPreferredSize(){
return new Dimension(100, 100);
}
}
<file_sep>/src/cs3500/music/view/MidiViewImpl.java
package cs3500.music.view;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.Map;
import javax.sound.midi.*;
import cs3500.music.model.IMusicEditor;
import cs3500.music.model.MusicEditorModel;
import cs3500.music.model.Note;
/**
* A skeleton for MIDI playback
*/
public class MidiViewImpl implements IMusicEditorView<Note> {
private final Synthesizer synth;
private final Receiver receiver;
private IMusicEditor model;
public MidiViewImpl() throws MidiUnavailableException {
this.synth = MidiSystem.getSynthesizer();
this.receiver = synth.getReceiver();
this.synth.open();
}
/**
* Relevant classes and methods from the javax.sound.midi library:
* <ul>
* <li>{@link MidiSystem#getSynthesizer()}</li>
* <li>{@link Synthesizer}
* <ul>
* <li>{@link Synthesizer#open()}</li>
* <li>{@link Synthesizer#getReceiver()}</li>
* <li>{@link Synthesizer#getChannels()}</li>
* </ul>
* </li>
* <li>{@link Receiver}
* <ul>
* <li>{@link Receiver#send(MidiMessage, long)}</li>
* <li>{@link Receiver#close()}</li>
* </ul>
* </li>
* <li>{@link MidiMessage}</li>
* <li>{@link ShortMessage}</li>
* <li>{@link MidiChannel}
* <ul>
* <li>{@link MidiChannel#getProgram()}</li>
* <li>{@link MidiChannel#programChange(int)}</li>
* </ul>
* </li>
* </ul>
* @see <a href="https://en.wikipedia.org/wiki/General_MIDI">
* https://en.wikipedia.org/wiki/General_MIDI
* </a>
*/
@Override
public void makeVisible() throws InvalidMidiDataException {
this.playNote(this.model.getMidiInfo(), this.model.getTempo());
}
@Override
public void playNote(List<List<List<Integer>>> info, long tempo) throws InvalidMidiDataException {
for (int beat = 0; beat < info.size(); beat++) {
for (List<Integer> l: info.get(beat)) {
this.receiver.send(new ShortMessage(ShortMessage.PROGRAM_CHANGE, l.get(1), l.get(1), l.get(1)), -1);
this.receiver.send(new ShortMessage(ShortMessage.NOTE_ON, l.get(1), l.get(2), l.get(3)), this.synth.getMicrosecondPosition());
this.receiver.send(new ShortMessage(ShortMessage.NOTE_OFF, l.get(1), l.get(2), l.get(3)), this.synth.getMicrosecondPosition() + l.get(4) * tempo);
}
try {
Thread.sleep(tempo / 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void setNoteRange(List noteRange) {
}
@Override
public void setDuration(int duration) {
}
@Override
public void update(IMusicEditor model) {
this.model = model;
}
@Override
public void setCombineNoteMap(Map<Integer, List<String>> notes) {
}
@Override
public void setNoteMap(Map notes) {
}
@Override
public void setListener(ActionListener action, KeyListener key) {
}
@Override
public void updateCurrentBeat(int beat) {
}
@Override
public void showErrorMessage() {
}
@Override
public void refresh() {
}
}
<file_sep>/test/MusicEditorModelTest.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import cs3500.music.model.MusicEditorModel;
import cs3500.music.model.Note;
import cs3500.music.model.Pitch;
import static junit.framework.TestCase.assertEquals;
/**
* Tests the methods implemented in the cs3500.music.model.MusicEditorModel class.
*/
public class MusicEditorModelTest {
private MusicEditorModel model;
/**
* Initializes the model to be tested.
*/
@Before
public void initialize() {
this.model = new MusicEditorModel(6);
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testInitialState() {
assertEquals(" \n" +
"0\n" +
"1\n" +
"2\n" +
"3\n" +
"4\n" +
"5\n", this.model.getState());
}
@Test
public void testAddNoteLongerThanDuration() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 10, 64);
assertEquals(" C0\n" +
"0 X\n" +
"1 |\n" +
"2 |\n" +
"3 |\n" +
"4 |\n" +
"5 |\n" +
"6 |\n" +
"7 |\n" +
"8 |\n" +
"9 |\n", this.model.getState());
}
@Test(expected = IllegalArgumentException.class)
public void testAddNoteInvalidLength() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, -1, 64);
}
@Test
public void testAddOneNote() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 60);
assertEquals(" C0\n" +
"0 X\n" +
"1 |\n" +
"2 |\n" +
"3 |\n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test
public void testAddTwoNotes() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 60);
this.model.addNote(new Note(Pitch.CSharp, 0, 0), 1, 4, 60);
assertEquals(" C0 C#0\n" +
"0 X \n" +
"1 | X\n" +
"2 | |\n" +
"3 | |\n" +
"4 |\n" +
"5 \n", this.model.getState());
}
@Test
public void testAddChord() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addNote(new Note(Pitch.E, 0, 0), 0, 4, 10);
this.model.addNote(new Note(Pitch.G, 0, 1), 0, 4, 10);
assertEquals(" C0 C#0 D0 D#0 E0 F0 F#0 G0\n" +
"0 X X X\n" +
"1 | | |\n" +
"2 | | |\n" +
"3 | | |\n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test
public void testAddOverlappingNotes() {
this.model.addNote(new Note(Pitch.C, 0, 1), 0, 4, 10);
this.model.addNote(new Note(Pitch.C, 0, 1), 1, 4, 10);
assertEquals(" C0\n" +
"0 X\n" +
"1 X\n" +
"2 |\n" +
"3 |\n" +
"4 |\n" +
"5 \n", this.model.getState());
}
@Test
public void testAddSameNoteDifferentInstrument() {
this.model.addNote(new Note(Pitch.C, 0, 1), 0, 4, 10);
this.model.addNote(new Note(Pitch.C, 0, 2), 0, 4, 10);
assertEquals(" C0\n" +
"0 X\n" +
"1 |\n" +
"2 |\n" +
"3 |\n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test
public void testRemoveBottomOverlappingNote() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addNote(new Note(Pitch.C, 0, 0), 1, 4, 10);
this.model.removeNote(new Note(Pitch.C, 0, 0), 1);
assertEquals(" C0\n" +
"0 X\n" +
"1 \n" +
"2 \n" +
"3 \n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test
public void testRemoveTopOverlappingNote() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addNote(new Note(Pitch.C, 0, 0), 1, 4, 10);
this.model.removeNote(new Note(Pitch.C, 0, 0), 0);
assertEquals(" C0\n" +
"0 \n" +
"1 X\n" +
"2 |\n" +
"3 |\n" +
"4 |\n" +
"5 \n", this.model.getState());
}
@Test(expected = IllegalArgumentException.class)
public void testRemoveNoteOutOfRange() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.removeNote(new Note(Pitch.C, 0, 0), 7);
}
@Test(expected = IllegalArgumentException.class)
public void testRemoveNoteDoesNotExist() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.removeNote(new Note(Pitch.C, 0, 0), 2);
}
@Test
public void testRemoveOneNote() {
this.model.addNote(new Note(Pitch.C, 0,0), 0, 4, 10);
this.model.addNote(new Note(Pitch.CSharp, 1, 0), 1, 4, 10);
this.model.removeNote(new Note(Pitch.CSharp, 1, 0), 1);
assertEquals(" C0\n" +
"0 X\n" +
"1 |\n" +
"2 |\n" +
"3 |\n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test
public void testRemoveAllNotes() {
this.model.addNote(new Note(Pitch.CSharp, 3, 0), 0, 4, 1);
this.model.addNote(new Note(Pitch.B, 10, 0), 0, 4, 10);
this.model.removeNote(new Note(Pitch.B, 10, 0), 0);
this.model.removeNote(new Note(Pitch.CSharp, 3, 0), 0);
assertEquals(" \n" +
"0\n" +
"1\n" +
"2\n" +
"3\n" +
"4\n" +
"5\n", this.model.getState());
}
@Test
public void testAddConsecutivePiece() {
this.model.addNote(new Note(Pitch.C, 0,0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addPieceConsecutively(model2);
assertEquals(" C0\n" +
" 0 X\n" +
" 1 |\n" +
" 2 |\n" +
" 3 |\n" +
" 4 \n" +
" 5 \n" +
" 6 X\n" +
" 7 |\n" +
" 8 |\n" +
" 9 |\n" +
"10 \n" +
"11 \n", this.model.getState());
}
@Test(expected = IllegalArgumentException.class)
public void testAddConsecutivePieceInvalid() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addPieceConsecutively(null);
}
@Test
public void testAddSameSimultaneousPiece() {
this.model.addNote(new Note(Pitch.C, 0,0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addPieceSimultaneously(model2);
assertEquals(" C0\n" +
"0 X\n" +
"1 |\n" +
"2 |\n" +
"3 |\n" +
"4 \n" +
"5 \n", this.model.getState());
}
@Test(expected = IllegalArgumentException.class)
public void testAddSimultaneousPieceInvalid() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.C, 0, 0), 1, 4, 10);
this.model.addPieceSimultaneously(null);
}
@Test(expected = IllegalArgumentException.class)
public void testAddSimultaneousPieceTooLong() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(10);
model2.addNote(new Note(Pitch.C, 0, 0), 1, 4, 10);
this.model.addPieceSimultaneously(model2);
}
@Test
public void testAddOverlappingSimultaneousPiece() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.C, 0, 0), 1, 4, 10);
this.model.addPieceSimultaneously(model2);
assertEquals(" C0\n" +
"0 X\n" +
"1 X\n" +
"2 |\n" +
"3 |\n" +
"4 |\n" +
"5 \n", this.model.getState());
}
@Test
public void testAddDifferentSimultaneousPiece() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
MusicEditorModel model2 = new MusicEditorModel(6);
model2.addNote(new Note(Pitch.CSharp, 0, 0), 1, 4, 10);
this.model.addPieceSimultaneously(model2);
assertEquals(" C0 C#0\n" +
"0 X \n" +
"1 | X\n" +
"2 | |\n" +
"3 | |\n" +
"4 |\n" +
"5 \n", this.model.getState());
}
@Test
public void testGetNoteState() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
assertEquals("start", this.model.getNoteState(new Note(Pitch.C, 0, 0), 0));
assertEquals("continue", this.model.getNoteState(new Note(Pitch.C, 0, 0), 1));
assertEquals("rest", this.model.getNoteState(new Note(Pitch.C, 0, 0), 5));
}
@Test
public void testGetCombinedNoteMap() {
this.model.addNote(new Note(Pitch.C, 0, 0), 0, 4, 10);
this.model.addNote(new Note(Pitch.C, 0, 1), 1, 4, 10);
assertEquals("[start, start, continue, continue, continue, rest]",
this.model.getCombinedNoteMap().get(12).toString());
}
}
<file_sep>/test/NoteTest.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import cs3500.music.model.Note;
import cs3500.music.model.Pitch;
import static junit.framework.TestCase.assertEquals;
/**
* Tests the methods implemented in the note class.
*/
public class NoteTest {
private Note c4_0;
private Note c4_1;
private Note cSharp4_0;
private Note b3_0;
/**
* Initializes the notes to be tested.
*/
@Before
public void initialize() {
this.c4_0 = new Note(Pitch.C, 4, 0);
this.c4_1 = new Note(Pitch.C, 4, 1);
this.cSharp4_0 = new Note(Pitch.CSharp, 4, 0);
this.b3_0 = new Note(Pitch.B, 3, 0);
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testNoteToString() {
assertEquals("C4(0)", this.c4_0.toString());
assertEquals("C#4(0)", this.cSharp4_0.toString());
assertEquals("B3(0)", this.b3_0.toString());
}
@Test (expected = IllegalArgumentException.class)
public void testCreateNoteOctaveTooLow() {
Note badNote = new Note(Pitch.C, 11, 0);
}
@Test (expected = IllegalArgumentException.class)
public void testCreateNoteOctaveTooHigh() {
Note badNote = new Note(Pitch.C, -1, 0);
}
@Test
public void testCompareTo() {
assertEquals(true, this.c4_0.compareTo(this.cSharp4_0) < 0);
assertEquals(true, this.c4_0.compareTo(this.c4_1) < 0);
assertEquals(true, this.c4_0.compareTo(this.c4_0) == 0);
assertEquals(true, this.c4_0.compareTo(this.b3_0) > 0);
}
@Test
public void testEquals() {
assertEquals(true, this.c4_0.equals(new Note(Pitch.C, 4, 0)));
assertEquals(false, this.c4_0.equals(this.cSharp4_0));
}
@Test
public void testHashCode() {
assertEquals(true, this.c4_0.hashCode() == new Note(Pitch.C, 4, 0).hashCode());
assertEquals(false, this.c4_0.hashCode() == this.cSharp4_0.hashCode());
}
@Test
public void testGetOctave() {
assertEquals(4, this.c4_0.getOctave());
assertEquals(4, this.cSharp4_0.getOctave());
assertEquals(3, this.b3_0.getOctave());
}
@Test
public void testGetPitch() {
assertEquals(Pitch.C, this.c4_0.getPitch());
assertEquals(Pitch.CSharp, this.cSharp4_0.getPitch());
assertEquals(Pitch.B, this.b3_0.getPitch());
}
}
<file_sep>/test/PitchTest.java
import org.junit.Test;
import cs3500.music.model.Pitch;
import static org.junit.Assert.assertEquals;
/**
* Tests methods in the cs3500.music.model.Pitch enum.
*/
public class PitchTest {
@Test
public void testToString() {
String allPitches = "";
for (Pitch p : Pitch.values()) {
allPitches += p.toString() + " ";
}
assertEquals("C C# D D# E F F# G G# A A# B", allPitches.trim());
}
@Test
public void testPitchNumber() {
String allPitchNumbers = "";
for (Pitch p : Pitch.values()) {
allPitchNumbers += p.getPitchNumber() + " ";
}
assertEquals("12 13 14 15 16 17 18 19 20 21 22 23", allPitchNumbers.trim());
}
}
| 759be5f0811aa702f8ad5175282f19b27703b780 | [
"Java"
] | 5 | Java | jeremyeng/MusicEditor | c7f8fb71b87c0a0bc3f3246cc2f909f6fb1061e1 | 8894d253b8407cdc2515ca879454cd2ba7972ae5 |
refs/heads/master | <repo_name>egorikem/TypeMaster<file_sep>/README.md
<b>Intro</b>
<br>
Started as a college project, typemaster has become my first app written in Java. The technology for GUI is Swing.
Goal of the project for to make a really simple product that estimates typing speed.
<b>What functions are avaliable?</b>
<ul>
<li>Loading and saving lessons as JSON files</li>
<li>Real time calculating of user's type speed</li>
<li>Graphical representation of keys being pressed, including different colors</li>
<li>Multithreading</li>
</ul>
<b>All code is 100% commented and may be used in any project</b>
<b><NAME> 2015</b>
<br>
<img width="150" src="https://pp.vk.me/c625431/v625431080/25015/UDU0haXt-HI.jpg">
<file_sep>/src/Lesson.java
/**
* Created by george on 15-09-29.
* Class, to store lessons
*/
public class Lesson {
// Text of lesson
private String Text;
// Readiness of lesson
private boolean IsReady;
/**
* Constructor
* @param text Lesson's text
*/
public Lesson(String text) {
Text = text;
IsReady = true;
}
/**
* Empty constructor for lazy initialization
*/
public Lesson() {
}
public boolean isReady() {
return IsReady;
}
public void setIsReady(boolean isReady) {
IsReady = isReady;
}
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
}
<file_sep>/src/Main.java
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
/**
* Created by george on 15-09-29.
*/
public class Main extends JFrame {
// worker instance
private static final Worker Worker = new Worker();
// current user's input
private String CurrentText = "";
/**
* TextArea
*/
// textarea for user's input
private JTextArea UserInputTextArea;
// textarea for lesson's text
private JTextArea LessonTextArea;
/**
* Labels
*/
// Label for errors
private JLabel MessageLabel;
// Label for type speed
private JLabel TypeSpeedLabel;
// Highlighter for user's input textbox
private Highlighter UserInputTextAreaHighlighter;
// Width of key button
private final int BUTTON_WIDTH = 30;
// Height of key button
private final int BUTTON_HEIGHT = 30;
// Margin left of key button
private final int BUTTON_MARGIN_LEFT = 30;
// Margin top of key button
private final int BUTTON_MARGIN_TOP = 30;
// Width of window
private final int SCREEN_WIDTH = 650;
// Height of window
private final int SCREEN_HEIGHT = 700;
// color of highlighter for wrong input
private final Color MISS_TYPE_HIGHLIGHT_COLOR = new Color(231, 76, 60);
// color of highlighter for correct input
private final Color CORRECT_TYPE_HIGHLIGHT_COLOR = new Color(46, 204, 113);
// color of highlighter for unused buttons
private final Color SHOULD_NOT_TYPE_HIGHLIGHT_COLOR = new Color(52, 73, 94);
// default font of app
private final Font DEFAULT_FONT = new Font("Helvetica", Font.PLAIN, 20);
// how long the onscreen key is being lighted up
// static due it has to called from closure that handles animation after key has been released
private static final int BUTTON_DELAY_TIME = 300;
// array with all buttons that are user in current charset
private List<JButton> ButtonsList = new ArrayList<>();
// keys' charset
private final String CHARSET = "qwertyuiopasdfghjklzxcvbnm,.?!'";
/**
* Function that setups UI
* @throws HeadlessException
*/
public Main() throws HeadlessException {
// default layput setup
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER));
/**
* Initializing UI
*/
// setting size of window
setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
// initialize user input and lesson text textboxes
InitInputs();
// initialize buttons
IntiButtons(BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_MARGIN_LEFT, BUTTON_MARGIN_TOP);
// initialize labels
InitLabels();
// initialize menu
InitMenu();
HandleInput();
}
/**
* Function that loads current lesson's text into UI
*/
private void StartLesson() {
LessonTextArea.setText(Worker.GetLessonText());
}
/**
* Function that setups input's textboxes
*/
private void InitInputs() {
// setting up the users input area
UserInputTextArea = new JTextArea();
// font
Font basicFont = new Font("Helvetica", Font.PLAIN, 30);
UserInputTextArea.setFont(basicFont);
// size
UserInputTextArea.setPreferredSize(new Dimension(600, 200));
// line wrap
UserInputTextArea.setLineWrap(true);
// adding highlighter
UserInputTextAreaHighlighter = UserInputTextArea.getHighlighter();
// adding onto the main JFrame
add(UserInputTextArea);
// setting up the lesson text area
LessonTextArea = new JTextArea();
// font
LessonTextArea.setFont(basicFont);
// disable ability to change value by user
LessonTextArea.setEnabled(false);
// size
LessonTextArea.setPreferredSize(new Dimension(600, 200));
// line wrap
LessonTextArea.setLineWrap(true);
// adding onto the main JFrame
add(LessonTextArea);
}
/**
* Function that setups and handles key presses
*/
private void HandleInput() {
/**
* Adding a KeyListener to catch moment when user presses the key and determine if the input was correct
*/
UserInputTextArea.addKeyListener(new KeyAdapter() {
// on key released
public void keyReleased(KeyEvent e) {
// update current text
CurrentText = UserInputTextArea.getText();
// handle analysis
HandleAnalysis(e);
// handle key press
HandleKeyPress(e);
}
});
}
private void HandleKeyPress(KeyEvent e) {
String keyPressedChar = "" + e.getKeyChar();
// set highlight range
int currentTextAreaIndex = UserInputTextArea.getText().length();
// find a button that has been pressed
JButton button = FindBtn(keyPressedChar);
//if button is not null
if (button != null) {
try {
// Check if it's the button that should be in lesson
boolean result = Worker.Analyse(CurrentText.length(), keyPressedChar);
// Set updateColor, depending of result
Color updateColor = result ? CORRECT_TYPE_HIGHLIGHT_COLOR : MISS_TYPE_HIGHLIGHT_COLOR;
// update button
// 1. Background
button.setBackground(updateColor);
// 2. Opaque (for mac only)
button.setOpaque(true);
// Update highlighter:
// 1. Remove all highlights
UserInputTextArea.getHighlighter().removeAllHighlights();
// 2. Add modified highlighter
// 2.1 Add highlighter in range from beginning of a textbox to current symbol with a color of updateColor
UserInputTextAreaHighlighter.addHighlight(0, currentTextAreaIndex, new DefaultHighlighter.DefaultHighlightPainter(updateColor));
}
// error handling
catch (Exception ex) {
System.out.println("Whoops, something happened! " + ex);
}
// Ease-out button fade animation
new java.util.Timer().schedule(
// create task with timeout
new java.util.TimerTask() {
@Override
public void run() {
// clear button's highlight
button.setBackground(null);
button.setOpaque(true);
}
},
Main.BUTTON_DELAY_TIME
);
}
}
private void HandleAnalysis(KeyEvent e) {
/**
* Check if this is the first key pressed and it's NOT Space. If so, start collecting statistics
*/
// if user's input is empty and key pressed is not space
if (CurrentText.length() < 1 && e.getKeyCode() != KeyEvent.VK_SPACE) {
// if statistics is running (happens when input has been erased)
if (Worker.isStatisticRunning()) {
// stop gathering data
Worker.StopStatistics();
}
// otherwise, it means that this is a first key typed ever, therefore start statistics
else {
// start gathering data
Worker.StartStatistics();
}
}
/**
* Otherwise, check if user hit SPACE key. If so, segment of text has ended, analyse everything
*/
else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
// clumsy access to worker instance as this code is located in closure
// getting last word from user's input
String lastWordBeforeSpace = Main.Worker.GetLastWord(CurrentText);
// if it is not empty
if(!lastWordBeforeSpace.equals(null)) {
// update statistics
Worker.UpdateStatistics(lastWordBeforeSpace);
// stop statistics
Worker.StopStatistics();
}
}
/**
* It is not first word and there is no space. Then it is a situation where space has been pressed
* and user's ready to write a new word. Therefore, start collecting statistics about it
*/
else {
// if statistics is not running
if(!Worker.isStatisticRunning()) {
// start statistics
Worker.StartStatistics();
}
}
// if statistics is ready to be published
if(Worker.isStatisticsReadyToBePublished()) {
// update labels
UpdateLabels();
}
}
private void InitLabels() {
/**
* Initialize error label
*/
// instantiate
MessageLabel = new JLabel("Status: OK");
// set font
MessageLabel.setFont(DEFAULT_FONT);
// add onto main JFrame
add(MessageLabel);
/**
* Initialize error label
*/
// instantiate
TypeSpeedLabel = new JLabel("Type Speed: 0");
// set font
TypeSpeedLabel.setFont(DEFAULT_FONT);
// add onto main JFrame
add(TypeSpeedLabel);
}
/**
* Initializing menu
*/
private void InitMenu() {
/**
* Initiating menu bar
*/
// Initiating variable
JMenuBar menuBar = new JMenuBar();
/**
* Adding main menu
*/
// Initiating and setting title
JMenu menu = new JMenu("File");
// Setting keystroke
menuBar.add(menu);
/**
* Setting load button
*/
// Initiating variable
JMenuItem menuItemLoad = new JMenuItem();
// set action to handle
menuItemLoad.setAction(loadAction);
// add onto main menu
menu.add(menuItemLoad);
/**
* Setting save button
*/
// Initiating variable
JMenuItem menuItemSave = new JMenuItem();
// set action to handle
menuItemSave.setAction(saveAction);
// add onto main menu
menu.add(menuItemSave);
// setting menuBar of JFrame
this.setJMenuBar(menuBar);
}
/**
* Actions of menu
*/
// Save action, triggered by menuItemSave
private final Action saveAction = new AbstractAction("Save") {
@Override
public void actionPerformed(ActionEvent e) {
try {
// instantiating JFileChooser
JFileChooser saveFile = new JFileChooser();
// showing the dialog
saveFile.showSaveDialog(null);
// save lesson
boolean result = Worker.Io.SaveLesson(Worker.GetLesson(), saveFile.getSelectedFile().getPath());
// if saving was not successful
if(!result) {
// show error message
ShowMessage("Save File", "Error: File can not be saved");
}
// otherwise
else {
// show success message
ShowMessage("Saved lesson");
}
}
// error handling
catch (Exception fileException) {
/**
* Set MessageLabel
*/
// foreground
MessageLabel.setForeground(MISS_TYPE_HIGHLIGHT_COLOR);
// text
MessageLabel.setText("Error: Can not save to null");
}
}
};
// Load action, triggered by menuItemLoad
private final Action loadAction = new AbstractAction("Load") {
@Override
public void actionPerformed(ActionEvent e) {
try {
// instantiating JFileChooser
JFileChooser openFile = new JFileChooser();
// showing the dialog
openFile.showOpenDialog(null);
// load lesson]
Lesson lesson = Worker.Io.LoadLesson(openFile.getSelectedFile().getPath());
// show error message
if(lesson == null) {
ShowMessage("Load file", "Error: File type is not supported");
}
// otherwise
else {
// load lesson to worker
Worker.SetLesson(lesson);
// show success message
ShowMessage("Loaded lesson");
// update ui
UpdateButtons();
// start lesson
StartLesson();
// reset inputs to default
ResetInputs();
}
}
// error handling
catch (Exception fileException) {
System.out.println("Was not able to perform a LoadAction!");
}
}
};
/**
* Function to indicate error with message
* @param title Header of error
* @param failureDescription Description of error
*/
private void ShowMessage(String title, String failureDescription) {
// show messageDialog
JOptionPane.showMessageDialog(null, failureDescription, title, JOptionPane.ERROR_MESSAGE);
// set font color of message label
MessageLabel.setForeground(MISS_TYPE_HIGHLIGHT_COLOR);
// set text of message label
MessageLabel.setText(failureDescription);
}
/**
* Function that indicated success with message
* @param successDescription Description of successful event
*/
private void ShowMessage(String successDescription) {
// set font color of message label
MessageLabel.setForeground(CORRECT_TYPE_HIGHLIGHT_COLOR);
// set text of error message
MessageLabel.setText(successDescription);
}
/**
* Function that finds button in ButtonList
* @param key Key of button to find
* @return
*/
private JButton FindBtn(String key) {
// loop through all ButtonsList
for (JButton aButton: ButtonsList) {
// if this is the button
if(aButton.getText().equals(key)) {
// return it
return aButton;
}
}
// return null as error
return null;
}
/**
* Function to initialize buttons from charset
* @param buttonWidth Width of buttons
* @param buttonHeight Height of buttons
* @param marginLeft Margin left
* @param marginTop Margin top
*/
private void IntiButtons(int buttonWidth, int buttonHeight, int marginLeft, int marginTop) {
// split charset into array of letters
String[] tmp = CHARSET.split("");
// loop through
for (int i = 0; i < tmp.length; i++) {
// text of a new button
String buttonText = tmp[i];
/**
* Initializing a button
*/
// 1. Initiate a variable
JButton button = new JButton();
// 2. Disable it for clicks
button.setEnabled(false);
// 3. Set its size
button.setBounds(buttonWidth*(i+marginLeft), buttonHeight*(i+marginTop), buttonWidth, buttonHeight);
// 4. Set its text
button.setText(buttonText);
// add button onto main JFrame
add(button);
// add button in ButtonsList
ButtonsList.add(button);
}
}
/**
* Function to erase user's input
*/
private void ResetInputs() {
// 1. Erase text
UserInputTextArea.setText("");
// 2. Remove highlighter
UserInputTextArea.getHighlighter().removeAllHighlights();
}
/**
* Function to set availability of buttons based on
*/
private void UpdateButtons() {
// loop through buttons
for(JButton aButton: ButtonsList) {
// if there is such a letter in lesson's text
if(Worker.GetLessonText().contains(aButton.getText())) {
// enable button
aButton.setEnabled(true);
}
// otherwise
else {
// disable button
aButton.setEnabled(false);
// set opaque
aButton.setOpaque(true);
}
}
}
/**
* Function to update labels
*/
private void UpdateLabels() {
TypeSpeedLabel.setText(String.format("Type speed: %d characters per minute", Worker.GetTypeSpeed()));
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
| e5f2607bb047265cb778e6fbf085e581b802f3d4 | [
"Markdown",
"Java"
] | 3 | Markdown | egorikem/TypeMaster | 37bcdde4de8a66b5b1e8f3dd3774bfbf224877dd | c14c96b10ed1bbcab28bd8355e6c5a8b87de2367 |
refs/heads/master | <file_sep>package net.sharksystem.sharknet.api;
import net.sharkfw.knowledgeBase.PeerSemanticTag;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* Created by timol on 16.05.2016.
*/
public class ImplProfile implements Profile {
Contact c;
String password ="";
Setting setting;
Blacklist blacklist;
/**
* Constructor for new Profiles which are going to be saved
* @param nickname
*/
public ImplProfile(String nickname, String deviceID){
c = new ImplContact(nickname, gernateUID(nickname, deviceID), "", this);
setting = new ImplSetting(this);
save();
}
/**
* Constructor for the Database
* @param c
* @param password
* @param setting
* @param blacklist
*/
public ImplProfile(Contact c, String password, Setting setting, Blacklist blacklist){
this.c = c;
this.password = <PASSWORD>;
this.setting = setting;
this.blacklist = blacklist;
}
@Override
public Contact getContact() {
return c;
}
@Override
public void setContact(Contact c) {
this.c = c;
}
@Override
public Setting getSettings() {
if(setting == null) setting = new ImplSetting(this);
return setting;
}
@Override
public PeerSemanticTag getPST() {
return null;
}
@Override
public String getNickname() {
return null;
}
@Override
public void setNickname(String nickname) {
}
@Override
public String getUID() {
return null;
}
@Override
public void setUID(String uid) {
}
@Override
public Content getPicture() {
return null;
}
@Override
public void setPicture(Content pic) {
}
@Override
public String getPublicKey() {
return null;
}
@Override
public void setPublicKey(String publicKey) {
}
@Override
public Timestamp getPublicKeyExpiration() {
return null;
}
@Override
public String getPublicKeyFingerprint() {
return null;
}
@Override
public void deleteKey() {
}
@Override
public void delete() {
//ToDo: Shark - delete the Profile in the KB
//Implementation of DummyDB
DummyDB.getInstance().removeProfile(this);
}
@Override
public void save() {
//ToDo: Shark - saveProfile in the KB
//Implementation of DummyDB
DummyDB.getInstance().addProfile(this);
}
@Override
public void update() {
//ToDo: Shark - update Profile in the KB
}
@Override
public Interest getInterests() {
return null;
}
@Override
public boolean isEqual(Contact c) {
return false;
}
@Override
public Profile getOwner() {
return null;
}
@Override
public void addName(String name) {
}
@Override
public String getName() {
return null;
}
@Override
public void addTelephonnumber(String telephonnumber) {
}
@Override
public List<String> getTelephonnumber() {
return null;
}
@Override
public void addNote(String note) {
}
@Override
public String getNote() {
return null;
}
@Override
public void setEmail(String email) {
}
@Override
public String getEmail() {
return null;
}
@Override
public Timestamp getLastWifiContact() {
return null;
}
@Override
public void setLastWifiContact(Timestamp lastWifiContact) {
}
@Override
public boolean login(String password) {
if(this.password.equals(password)){
return true;
}
else return false;
}
@Override
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@Override
public boolean isEqual(Profile p){
if(p.getContact().isEqual(c)) return true;
else return false;
}
@Override
public Blacklist getBlacklist() {
if(blacklist == null){
blacklist = new ImplBlacklist(this);
}
return blacklist;
}
@Override
public void renewKeys() {
// Generate a new dummy public key
if (getContact() instanceof ImplContact) {
DummyKeyPairHelper.createNewKeyForContact((ImplContact) getContact());
}
//ToDo: Shark - Renew the keypair
}
private String gernateUID(String nickname, String deviceID){
String newUID = "foo";
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss:SS");
Date now = new Date(System.currentTimeMillis());
String strDate = sdfDate.format(now);
newUID = nickname + "/" + deviceID + "/" + strDate;
return newUID;
}
}
<file_sep>package net.sharksystem.sharknet.api.impl;
import net.sharkfw.asip.ASIPInformation;
import net.sharkfw.asip.ASIPInformationSpace;
import net.sharkfw.asip.ASIPSpace;
import net.sharkfw.knowledgeBase.PeerSemanticTag;
import net.sharkfw.knowledgeBase.SemanticTag;
import net.sharkfw.knowledgeBase.SharkKB;
import net.sharkfw.knowledgeBase.SharkKBException;
import net.sharkfw.knowledgeBase.inmemory.InMemoSharkKB;
import net.sharksystem.sharknet.api.Contact;
import net.sharksystem.sharknet.api.Content;
import net.sharksystem.sharknet.api.Interest;
import net.sharksystem.sharknet.api.Profile;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by j4rvis on 01.08.16.
*/
public class ContactImpl implements Contact {
private SharkKB sharkKB;
private ASIPSpace asipSpace;
public final static String INFONAME_NAME = "INFONAME_NAME";
public final static String INFONAME_NICKNAME = "INFONAME_NICKNAME";
public final static String INFONAME_UID = "INFONAME_UID";
public final static String INFONAME_PICTURE = "INFONAME_PICTURE";
public final static String INFONAME_PUBLIC_KEY = "INFONAME_PUBLIC_KEY";
public final static String INFONAME_INTEREST = "INFONAME_INTEREST";
public final static String INFONAME_TELEPHONE = "INFONAME_TELEPHONE";
public final static String INFONAME_EMAIL = "INFONAME_EMAIL";
public final static String INFONAME_NOTE = "INFONAME_NOTE";
public ContactImpl(SharkKB sharkKB, PeerSemanticTag tag) throws SharkKBException {
this.sharkKB = sharkKB;
this.asipSpace = createASIPSpace(tag);
// SET FIRST INFO - NAME
this.setInfoWithName(INFONAME_NICKNAME, tag.getName());
}
public ContactImpl(SharkKB sharkKB, String nickname, String deviceId) throws SharkKBException {
this(sharkKB, ContactImpl.createPeerSemanticTag(nickname, deviceId));
}
public ContactImpl(SharkKB sharkKB, ASIPInformationSpace informationSpace) throws SharkKBException {
this.sharkKB = sharkKB;
this.asipSpace = informationSpace.getASIPSpace();
}
public static PeerSemanticTag createPeerSemanticTag(String nickname, String deviceId) {
String si = SharkNetEngine.SHARKNET_DOMAIN + deviceId + "." + System.currentTimeMillis();
return InMemoSharkKB.createInMemoPeerSemanticTag(nickname, si, null);
}
private ASIPSpace createASIPSpace(PeerSemanticTag tag) throws SharkKBException {
return this.sharkKB.createASIPSpace((SemanticTag) null, null, null, tag, null, null, null, ASIPSpace.DIRECTION_NOTHING);
}
private ASIPInformation getInfoByName(String name) throws SharkKBException {
Iterator<ASIPInformation> information = this.sharkKB.getInformation(this.asipSpace);
while (information.hasNext()) {
ASIPInformation next = information.next();
if (next.getName().equals(name)) {
return next;
}
}
return null;
}
private void setInfoWithName(String name, String content) throws SharkKBException {
ASIPInformation asipInformation = this.sharkKB.addInformation(content, this.asipSpace);
asipInformation.setName(name);
}
private void setInfoWithName(String name, InputStream content) throws SharkKBException, IOException {
ASIPInformation asipInformation = this.sharkKB.addInformation(content, content.available(), this.asipSpace);
asipInformation.setName(name);
}
@Override
public PeerSemanticTag getPST() throws SharkKBException {
return this.asipSpace.getSender();
}
@Override
public String getNickname() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_NICKNAME);
return information != null ? information.getContentAsString() : null;
}
@Override
public void setNickname(String nickname) throws SharkKBException {
this.setInfoWithName(INFONAME_NICKNAME, nickname);
}
@Override
public String getUID() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_UID);
return information != null ? information.getContentAsString() : null;
}
@Override
public void setUID(String uid) throws SharkKBException {
this.setInfoWithName(INFONAME_NICKNAME, uid);
}
@Override
public Content getPicture() throws SharkKBException {
// return getInfoByName(INFONAME_PICTURE); TODO IMPLEMENT CONTENT
return null;
}
@Override
public void setPicture(Content pic) throws IOException, SharkKBException {
this.setInfoWithName(INFONAME_PICTURE, pic.getInputstream());
}
@Override
public String getPublicKey() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_PUBLIC_KEY);
return information != null ? information.getContentAsString() : null;
}
@Override
public void setPublicKey(String publicKey) throws SharkKBException {
this.setInfoWithName(INFONAME_PUBLIC_KEY, publicKey);
}
@Override
public Timestamp getPublicKeyExpiration() {
return null;
}
@Override
public String getPublicKeyFingerprint() {
return null;
}
@Override
public void deleteKey() {
}
@Override
public void delete() {
}
@Override
public void update() {
}
@Override
public Interest getInterests() {
return null;
}
@Override
public boolean isEqual(Contact c) {
return false;
}
@Override
public Profile getOwner() {
return null;
}
@Override
public void addName(String name) throws SharkKBException {
this.setInfoWithName(INFONAME_NAME, name);
}
@Override
public String getName() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_NAME);
return information != null ? information.getContentAsString() : null;
}
// SEPERATED BY ';'
@Override
public void addTelephonnumber(String telephonnumber) throws SharkKBException {
if (getTelephonnumber().size() <= 0) {
setInfoWithName(INFONAME_TELEPHONE, telephonnumber);
} else {
ASIPInformation information = getInfoByName(INFONAME_TELEPHONE);
if (information != null) {
String content = information.getContentAsString();
information.setContent(content + ";" + telephonnumber);
}
}
}
@Override
public List<String> getTelephonnumber() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_TELEPHONE);
if (information != null) {
String contentAsString = information.getContentAsString();
String[] split = contentAsString.split(";");
return Arrays.asList(split);
}
return null;
}
@Override
public void addNote(String note) throws SharkKBException {
this.setInfoWithName(INFONAME_NOTE, note);
}
@Override
public String getNote() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_NOTE);
return information != null ? information.getContentAsString() : null;
}
@Override
public void setEmail(String email) throws SharkKBException {
this.setInfoWithName(INFONAME_EMAIL, email);
}
@Override
public String getEmail() throws SharkKBException {
ASIPInformation information = getInfoByName(INFONAME_EMAIL);
return information != null ? information.getContentAsString() : null;
}
@Override
public Timestamp getLastWifiContact() {
return null;
}
@Override
public void setLastWifiContact(Timestamp lastWifiContact) {
}
}
<file_sep>package net.sharksystem.sharknet.api.impl;
import net.sharkfw.asip.ASIPSpace;
import net.sharkfw.asip.engine.ASIPSerializer;
import net.sharkfw.knowledgeBase.*;
import net.sharkfw.knowledgeBase.PeerSTSet;
import net.sharkfw.knowledgeBase.PeerSemanticTag;
import net.sharkfw.knowledgeBase.SemanticTag;
import net.sharkfw.knowledgeBase.SharkKB;
import net.sharkfw.knowledgeBase.SharkKBException;
import net.sharkfw.knowledgeBase.inmemory.InMemoSharkKB;
import net.sharkfw.knowledgeBase.sync.SyncKB;
import net.sharksystem.sharknet.api.Chat;
import net.sharksystem.sharknet.api.Contact;
import net.sharksystem.sharknet.api.Content;
import net.sharksystem.sharknet.api.Message;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* Created by j4rvis on 01.08.16.
*/
public class ChatImpl implements Chat {
public static final String SHARKNET_CHAT_RECIPIENTS = "SHARKNET_CHAT_RECIPIENTS";
private SharkNetEngine sharkNetEngine;
private SyncKB chatKB;
private List<Contact> recipients;
public ChatImpl(SharkNetEngine sharkNetEngine, SharkKB sharkKB) throws SharkKBException {
this.chatKB = new SyncKB(sharkKB);
this.sharkNetEngine = sharkNetEngine;
String property = sharkKB.getProperty(SHARKNET_CHAT_RECIPIENTS);
PeerSTSet stSet = ASIPSerializer.deserializePeerSTSet(null, property);
Enumeration<PeerSemanticTag> enumeration = stSet.peerTags();
while (enumeration.hasMoreElements()){
PeerSemanticTag next = enumeration.nextElement();
recipients.add(this.sharkNetEngine.getContactByTag(next));
}
}
public ChatImpl(SharkKB sharkKB, List<Contact> recipients) throws SharkKBException {
this.chatKB = new SyncKB(sharkKB);
PeerSTSet peers = InMemoSharkKB.createInMemoPeerSTSet();
Iterator<Contact> iterator = recipients.iterator();
while (iterator.hasNext()){
Contact next = iterator.next();
peers.merge(next.getPST());
}
String serializedPeers = ""; // TODO ASIPSerializer.serializeSTSet(peers);
this.chatKB.setProperty(SHARKNET_CHAT_RECIPIENTS, serializedPeers);
this.recipients = recipients;
}
@Override
public void sendMessage(Content content) throws SharkKBException {
ASIPSpace space = createASIPSpace();
this.chatKB.addInformation(content.getInputstream(), content.getLength(), space);
}
private ASIPSpace createASIPSpace() throws SharkKBException {
net.sharkfw.knowledgeBase.TimeSemanticTag timeSemanticTag =
this.chatKB.getTimeSTSet().createTimeSemanticTag(System.currentTimeMillis(), 0);
return this.chatKB.createASIPSpace(null, null, null, null, null, timeSemanticTag, null, ASIPSpace.DIRECTION_OUT);
}
@Override
public void delete() {
}
@Override
public List<Message> getMessages(boolean descending) {
return null;
}
@Override
public List<Message> getMessages(int startIndex, int stopIndex, boolean descending) {
return null;
}
@Override
public List<Message> getMessages(Timestamp start, Timestamp stop, boolean descending) {
return null;
}
@Override
public List<Message> getMessages(Timestamp start, Timestamp stop, int startIndex, int stopIndex, boolean descending) {
return null;
}
@Override
public List<Message> getMessages(String search, int startIndex, int stopIndex, boolean descending) {
return null;
}
@Override
public void update() {
}
@Override
public List<Contact> getContacts() {
return null;
}
@Override
public void setPicture(Content picture) {
}
@Override
public Content getPicture() {
return null;
}
@Override
public void setTitle(String title) {
}
@Override
public String getTitle() {
return null;
}
@Override
public int getID() {
return 0;
}
@Override
public Contact getOwner() {
return null;
}
@Override
public Timestamp getTimestamp() {
return null;
}
@Override
public void addContact(List<Contact> cList) {
}
@Override
public void removeContact(List<Contact> cList) {
}
@Override
public void setAdmin(Contact admin) {
}
@Override
public Contact getAdmin() {
return null;
}
}
<file_sep>package net.sharksystem.sharknet.api;
import net.sharkfw.knowledgeBase.SharkKBException;
import net.sharkfw.knowledgeBase.Taxonomy;
import net.sharkfw.knowledgeBase.PeerSemanticTag;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
/**
* Created by timol on 12.05.2016.
*
* Interface represents a Contact (a Person) in SharkNet
*/
public interface Contact {
public PeerSemanticTag getPST() throws SharkKBException;
/**
* returns the Nickname of the contact
* @return
*/
public String getNickname() throws SharkKBException;
public void setNickname(String nickname) throws SharkKBException;
/**
* returns the UID of the contact
* @return
*/
public String getUID() throws SharkKBException;
public void setUID(String uid) throws SharkKBException;
/**
* Returns the profilepicture of a contact
* @return
*/
public Content getPicture() throws SharkKBException;
public void setPicture(Content pic) throws IOException, SharkKBException;
/**
* returns the PublicKey of the contact
* @return
*/
public String getPublicKey() throws SharkKBException;
public void setPublicKey(String publicKey) throws SharkKBException;
public Timestamp getPublicKeyExpiration();
public String getPublicKeyFingerprint();
public void deleteKey();
/**
* Deletes the Contact from the Database
*/
public void delete();
/**
* updates a Contact in the Database
*/
public void update();
/**
* returns a List of all Interests the profile is interested in
* @return
*/
public Interest getInterests();
/**
* Method to evaluate is a Contact is equal to another
* @return
*/
public boolean isEqual(Contact c);
/**
* Method returns the Owner of the Contact
*/
public Profile getOwner();
/**
* add a real name to the contact
* @param name
*/
public void addName(String name) throws SharkKBException;
/**
* Returns the real name of the contact
* @return
*/
public String getName() throws SharkKBException;
/**
* spelling suggestion- addTelephoneNumber()
* add a Telephonnumber to the Contact. The Contact has a List which can include more phone numbers (no validation included)
* @param telephonnumber
*/
public void addTelephonnumber(String telephonnumber) throws SharkKBException;
/**
* Returns the List of Phone Numbers
* @return
*/
public List<String> getTelephonnumber() throws SharkKBException;
/**
* Adds/Or overwrites the Note to a contact
* @param note
*/
public void addNote(String note) throws SharkKBException;
/**
* Returns Notes to a contact
* @return
*/
public String getNote() throws SharkKBException;
/**
* sets the e-mail of a contact (no validation included)
* @param email
*/
public void setEmail(String email) throws SharkKBException;
/**
* returns e-mail of the contact
* @return
*/
public String getEmail() throws SharkKBException;
/**
* Returns the timestamp of the last direct wifi connection with the contact
* @return
*/
public Timestamp getLastWifiContact();
/**
* Sets the timestamp of the last direct wifi connection with the contact
* @param lastWifiContact
*/
public void setLastWifiContact(Timestamp lastWifiContact);
}
<file_sep>package net.sharksystem.sharknet.api.shark;
import net.sharkfw.knowledgeBase.SharkKB;
import net.sharkfw.knowledgeBase.inmemory.InMemoSharkKB;
import net.sharksystem.sharknet.api.Chat;
import net.sharksystem.sharknet.api.Contact;
import java.util.List;
/**
* Created by msc on 20.07.16.
*/
public class ChatDB {
// Singleton
private static ChatDB instance = null;
private final Contact owner;
private ChatDB(Contact owner) {
this.chatKb = new InMemoSharkKB();
this.chatKb.setOwner(owner.getPST());
this.owner = owner;
}
public static ChatDB getInstance(Contact owner){
if(ChatDB.instance == null){
ChatDB.instance = new ChatDB(owner);
}
return ChatDB.instance;
}
// SharkKB
private SharkKB chatKb = null;
public List<Chat> getChats(){
// map all spaces to Chat objects.
return null;
}
public void newChat(List<Contact> recipients){
// TODO is List even with my own Peer?
// Create an InformationSpace
// And add the infos to the space
}
}
<file_sep>package net.sharksystem.sharknet.api;
import net.sharkfw.knowledgeBase.inmemory.InMemoSharkKB;
import java.sql.Timestamp;
import java.util.List;
/**
* Created by msc on 30.06.16.
*/
public class MessageImpl implements Message {
private InMemoSharkKB kb;
private Contact sender;
public MessageImpl(InMemoSharkKB kb, Contact sender, List<Contact> recipients) {
this.kb = kb;
this.sender = sender;
}
@Override
public Timestamp getTimestamp() {
return null;
}
@Override
public Contact getSender() {
return null;
}
@Override
public List<Contact> getRecipients() {
return null;
}
@Override
public Content getContent() {
return null;
}
@Override
public boolean isSigned() {
return false;
}
@Override
public boolean isEncrypted() {
return false;
}
@Override
public void deleteMessage() {
}
@Override
public void setDisliked(boolean isDisliked) {
}
@Override
public boolean isdisliked() {
return false;
}
@Override
public boolean isMine() {
return false;
}
@Override
public boolean isVerified() {
return false;
}
@Override
public void setVerified(boolean verified) {
}
@Override
public Chat getChat() {
return null;
}
@Override
public boolean isRead() {
return false;
}
@Override
public void setRead(boolean read) {
}
@Override
public void setSigned(boolean signed) {
}
@Override
public void setEncrypted(boolean encrypted) {
}
@Override
public boolean isDierectRecived() {
return false;
}
@Override
public void setDierectRecived(boolean dierectRecived) {
}
}
<file_sep>package net.sharksystem.sharknet.api.impl;
import net.sharkfw.knowledgeBase.inmemory.InMemoInformation;
import net.sharksystem.sharknet.api.Content;
import net.sharksystem.sharknet.api.ImplVoting;
import net.sharksystem.sharknet.api.Reminder;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by j4rvis on 02.08.16.
*/
public class ContentImpl implements Content {
@Override
public boolean setFile(File f) {
return false;
}
@Override
public boolean setInputstream(InputStream is) {
return false;
}
@Override
public OutputStream getOutputstream() {
return null;
}
@Override
public String getMimeType() {
return null;
}
@Override
public void setMimeType(String mimeType) {
}
@Override
public InputStream getInputstream() {
return null;
}
@Override
public String getMessage() {
return null;
}
@Override
public String getFileName() {
return null;
}
@Override
public void setFilename(String filename) {
}
@Override
public void setMessage(String message) {
}
@Override
public ImplVoting addVoting(String question, boolean singleqoice) {
return null;
}
@Override
public ImplVoting getVoting() {
return null;
}
@Override
public InMemoInformation getInformationFile() {
return null;
}
@Override
public void setInformationFile(InMemoInformation file) {
}
@Override
public Reminder getReminder() {
return null;
}
@Override
public void setReminder(Reminder reminder) {
}
@Override
public int getLength() {
return 0;
}
}
| 4a68bc8746a9b158db87e999517b20220a73f360 | [
"Java"
] | 7 | Java | SharedKnowledge/SharkNet-API | b0a58e1bceef1e1e96aeaae1cd7d65534459e72d | 976e1f739d6f7c0861c2fefae5d7698fffc5a184 |
refs/heads/master | <repo_name>MarMP/APPDenunciasMovil<file_sep>/app/src/main/java/com/example/appdenuncias/AnadirComunicacionFragment.java
package com.example.appdenuncias;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.widget.SwitchCompat;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.textfield.TextInputLayout;
import java.util.HashMap;
import java.util.Map;
public class AnadirComunicacionFragment extends Fragment {
private TextInputLayout textInputAnadirComunicacion, textInputAnadirEmpleado;
private SwitchCompat switchComunicacionAnonima;
private Spinner spinnerDepartamentos, spinnerTipoComunicacion;
private Button enviar, cancelar;
private static String idUsuario;
RequestQueue requestQueue;
private static final String URL = GlobalIp.IP+"appdenunciasphp/insertar.php";
public AnadirComunicacionFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_anadir_comunicacion, container, false);
textInputAnadirComunicacion = v.findViewById(R.id.text_input_anadir);
textInputAnadirEmpleado = v.findViewById(R.id.text_input_empleado);
switchComunicacionAnonima = v.findViewById(R.id.switch_anonimo);
spinnerDepartamentos = v.findViewById(R.id.spinner_departamento);
spinnerTipoComunicacion = v.findViewById(R.id.spinner_tipo_comunucacion);
enviar = v.findViewById(R.id.btnAnadirComunicacion);
cancelar = v.findViewById(R.id.btnCancelarComunicacion);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("preferencias", Context.MODE_PRIVATE);
idUsuario = sharedPreferences.getString("id", "16");
Log.i("idUsuario", idUsuario);
switchComunicacionAnonima.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
textInputAnadirEmpleado.getEditText().setText("Anónimo");
Toast.makeText(getContext(),"El mensaje se enviará de forma anónima", Toast.LENGTH_LONG).show();
} else {
String texto = textInputAnadirEmpleado.getEditText().getText().toString().trim();
if (texto.isEmpty()) {
textInputAnadirEmpleado.setError("El campo no puede estar vacío");
} else if (!texto.equals("Anónimo")){
Toast.makeText(getContext(),"El mensaje no será anónimo", Toast.LENGTH_LONG).show();
}
}
}
});
enviar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (noActivo() | !validarComunicacion()) {
Toast.makeText(getContext(),"El mensaje no será anónimo", Toast.LENGTH_LONG).show();
}
String empleado = textInputAnadirEmpleado.getEditText().getText().toString().trim();
String tipoComunicacion = spinnerTipoComunicacion.getSelectedItem().toString();
String departamento = spinnerDepartamentos.getSelectedItem().toString();
String comunicacion = textInputAnadirComunicacion.getEditText().getText().toString().trim();
insertarComunicacion(empleado, tipoComunicacion, departamento,comunicacion);
}
});
cancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textInputAnadirComunicacion.getEditText().setText("");
textInputAnadirEmpleado.getEditText().setText("");
switchComunicacionAnonima.setChecked(false);
}
});
requestQueue = Volley.newRequestQueue(getContext());
return v;
}
private void insertarComunicacion(final String empleado, final String tipoComunicacion, final String departamento, final String comunicacion) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getContext(), "Comunicación enviada", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "La comunicación no se ha podido enviar", Toast.LENGTH_SHORT).show();
}
}
){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap();
params.put("empleado", empleado);
params.put("tipo_comunicacion", tipoComunicacion);
params.put("departamento", departamento );
params.put("mensaje_comunicacion", comunicacion);
params.put("id", idUsuario);
return params;
}
};
requestQueue.add(stringRequest);
}
//Validaciones de los campos
private boolean validarComunicacion() {
String texto = textInputAnadirComunicacion.getEditText().getText().toString().trim();
if (texto.isEmpty()) {
textInputAnadirComunicacion.setError("El campo no puede estar vacío");
return false;
} else {
textInputAnadirComunicacion.setError(null);
return true;
}
}
//Cuando el switch no esté activo debe tener un empleado ya que la comunicación no será anónima
public boolean noActivo(){
if (!switchComunicacionAnonima.isChecked()){
textInputAnadirEmpleado.setError("El campo no puede estar vacío");
}
return true;
}
}<file_sep>/app/src/main/java/com/example/appdenuncias/InfoFragment.java
package com.example.appdenuncias;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class InfoFragment extends Fragment {
ImageView iv;
Button btn;
int position = 1;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.info_fragment, container, false);
iv = v.findViewById(R.id.ivInfo);
//btn = (Button) v.findViewById(R.id.btnBottonInfo);
//Vistas que se irán viendo cuando pase de página
switch (position) {
case 1:
iv.setImageResource(R.drawable.welcome);
//btn.setText("Siguiente");
break;
case 2:
iv.setImageResource(R.drawable.welcome_dos);
//btn.setText("Siguiente");
break;
case 3:
iv.setImageResource(R.drawable.welcome_tres);
btn = (Button) v.findViewById(R.id.btnBottonInfo);
btn.setText("Comienza");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//llamar a menu lateral
Intent i = new Intent(getActivity(), MenuLateral.class);
startActivity(i);
}
});
break;
}
return v;
}
public void setPosition(int position) {
this.position = position;
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/MisComunicacionesFragment.java
package com.example.appdenuncias;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.appdenuncias.retrofit_data.RetrofitApiService;
import com.example.appdenuncias.retrofit_data.RetrofitClient;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MisComunicacionesFragment extends Fragment implements RecyclerAdapter.RecyclerItemClick, SearchView.OnQueryTextListener{
private RecyclerView rvLista;
private RecyclerAdapter adapter;
private List<ItemListComunicaciones> items;
private SearchView buscador;
private String idUsuario;
private RetrofitApiService retrofitApiService;
View v;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_mis_comunicaciones, container, false);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("preferencias", Context.MODE_PRIVATE);
idUsuario = sharedPreferences.getString("id", "16");
initViews();
initValues();
initListener();
return v;
}
//Inicializa el recycler y el searchview
private void initViews(){
rvLista = (RecyclerView)v.findViewById(R.id.rvLista);
buscador = v.findViewById(R.id.svSearch);
}
private void initValues() {
retrofitApiService = RetrofitClient.getApiService();
//Para mostrarlo en listas (se puede mostrar en Grid también)
LinearLayoutManager manager = new LinearLayoutManager(getContext());
rvLista.setLayoutManager(manager);
getItemsComunicaciones();
}
private void initListener() {
buscador.setOnQueryTextListener(this);
}
private void getItemsComunicaciones() {
retrofitApiService.getItemsComunicaciones(idUsuario).enqueue(new Callback<List<ItemListComunicaciones>>() {
@Override
public void onResponse(Call<List<ItemListComunicaciones>> call, Response<List<ItemListComunicaciones>> response) {
items = response.body();
adapter = new RecyclerAdapter(items, MisComunicacionesFragment.this::itemClick);
rvLista.setAdapter(adapter);
}
@Override
public void onFailure(Call<List<ItemListComunicaciones>> call, Throwable t) {
Toast.makeText(getContext(), "Error: " +t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void itemClick(ItemListComunicaciones item) {
Intent i = new Intent(getContext(), DetailsActivity.class);
i.putExtra("itemDetalles", item);
startActivity(i);
}
//Se ejecutará cuando pulsemos enter en nuestro móvil en la barra de búsqueda
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
//Escuchará lo que escribamos en la barra de búsqueda
@Override
public boolean onQueryTextChange(String newText) {
adapter.buscar(newText);
return false;
}
}<file_sep>/app/src/main/java/com/example/appdenuncias/ItemListComunicaciones.java
package com.example.appdenuncias;
import java.io.Serializable;
public class ItemListComunicaciones implements Serializable {
private String tipo_comunicacion;
private String mensaje_comunicacion;
private String estado;
private String id;
private String id_empleado;
// private String estadoEs = "Estado: ";
public ItemListComunicaciones(String tipo_comunicacion, String mensaje_comunicacion, String estado, String id) {
this.tipo_comunicacion = tipo_comunicacion;
this.mensaje_comunicacion = mensaje_comunicacion;
this.estado = estado;
this.id = id;
}
public String getTipo_comunicacion() {
return tipo_comunicacion;
}
public String getMensaje_comunicacion() {
return mensaje_comunicacion;
}
public String getEstado() {
return estado;
}
public String getId() {
return id;
}
public String getId_empleado() {
return id_empleado;
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/InfoPageActivity.java
package com.example.appdenuncias;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class InfoPageActivity extends AppCompatActivity {
ViewPager pager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_pag_inicio);
pager = findViewById(R.id.view_page_main);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/MyPagerAdapter.java
package com.example.appdenuncias;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class MyPagerAdapter extends FragmentPagerAdapter {
InfoFragment page1, page2, page3;
public MyPagerAdapter(@NonNull FragmentManager fm) {
super(fm);
page1 = new InfoFragment();
page1.setPosition(1);
page2 = new InfoFragment();
page2.setPosition(2);
page3 = new InfoFragment();
page3.setPosition(3);
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return page1;
case 1:
return page2;
case 2:
return page3;
}
return null;
}
@Override
public int getCount() {
//devuelve el número de fragmentos que tendremos
return 3;
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/AlertasItem.java
package com.example.appdenuncias;
import java.io.Serializable;
public class AlertasItem implements Serializable {
private int imagen;
private String titulo;
private String mensaje;
public AlertasItem(int imagen, String titulo, String mensaje) {
this.imagen = imagen;
this.titulo = titulo;
this.mensaje = mensaje;
}
public int getImagen() {
return imagen;
}
public String getTitulo() {
return titulo;
}
public String getMensaje() {
return mensaje;
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/RecyclerAdapterAlertas.java
package com.example.appdenuncias;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class RecyclerAdapterAlertas extends RecyclerView.Adapter<RecyclerAdapterAlertas.RecyclerHolder> {
//Una lista para poblar el recycler
private List<AlertasItem> items;
//Para gestionar el onClick
//Lista para el search del estado original que no cambiará, el que cambiará será items
private List<AlertasItem>estadoOriginal;
public RecyclerAdapterAlertas(List<AlertasItem> items) {
this.items = items;
this.estadoOriginal = new ArrayList<>();
estadoOriginal.addAll(items);
}
public static class RecyclerHolder extends RecyclerView.ViewHolder {
private ImageView imagen;
private TextView titulo;
private TextView mensaje;
public RecyclerHolder(@NonNull View itemView){
super(itemView);
imagen = itemView.findViewById(R.id.imgItem);
titulo = itemView.findViewById(R.id.tvTituloAlerta);
mensaje = itemView.findViewById(R.id.tvMensajeAlerta);
}
}
@NonNull
@Override
public RecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_view_alertas, parent, false);
return new RecyclerHolder(v);
}
//Se ejecutará tantas veces como elementos haya en la lista (según getItemCount)
@Override
public void onBindViewHolder(@NonNull RecyclerHolder holder, int position) {
AlertasItem item = items.get(position);
//rellenar cada item
holder.imagen.setImageResource(item.getImagen());
holder.titulo.setText(item.getTitulo());
holder.mensaje.setText(item.getMensaje());
}
//Tamaño de la lista
@Override
public int getItemCount() {
return items.size();
}
}<file_sep>/app/src/main/java/com/example/appdenuncias/LeerComunicaciones.java
package com.example.appdenuncias;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.appdenuncias.retrofit_data.RetrofitApiService;
import com.example.appdenuncias.retrofit_data.RetrofitClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LeerComunicaciones extends AppCompatActivity implements RecyclerAdapter.RecyclerItemClick, SearchView.OnQueryTextListener {
private RecyclerView rvLista;
private RecyclerAdapter adapter;
private List<ItemListComunicaciones> items;
private SearchView buscador;
private String idUsuario;
private RetrofitApiService retrofitApiService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leer_comunicaciones);
SharedPreferences sharedPreferences = this.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
idUsuario = sharedPreferences.getString("id", "16");
initViews();
initValues();
initListener();
}
//Inicializa el recycler y el searchview
private void initViews(){
rvLista = (RecyclerView)findViewById(R.id.rvLista);
buscador = findViewById(R.id.svSearch);
}
private void initValues() {
retrofitApiService = RetrofitClient.getApiService();
//Para mostrarlo en listas (se puede mostrar en Grid también)
LinearLayoutManager manager = new LinearLayoutManager(this);
rvLista.setLayoutManager(manager);
getItemsComunicaciones();
}
private void initListener() {
buscador.setOnQueryTextListener(this);
}
private void getItemsComunicaciones() {
retrofitApiService.getItemsComunicaciones(idUsuario).enqueue(new Callback<List<ItemListComunicaciones>>() {
@Override
public void onResponse(Call<List<ItemListComunicaciones>> call, Response<List<ItemListComunicaciones>> response) {
items = response.body();
adapter = new RecyclerAdapter(items,LeerComunicaciones.this);
rvLista.setAdapter(adapter);
}
@Override
public void onFailure(Call<List<ItemListComunicaciones>> call, Throwable t) {
Toast.makeText(LeerComunicaciones.this, "Error: " +t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void itemClick(ItemListComunicaciones item) {
Intent i = new Intent(this, DetailsActivity.class);
i.putExtra("itemDetalles", item);
startActivity(i);
}
//Se ejecutará cuando pulsemos enter en nuestro móvil en la barra de búsqueda
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
//Escuchará lo que escribamos en la barra de búsqueda
@Override
public boolean onQueryTextChange(String newText) {
adapter.buscar(newText);
return false;
}
}<file_sep>/app/src/main/java/com/example/appdenuncias/NuevaComunicacion.java
package com.example.appdenuncias;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.textfield.TextInputLayout;
import java.util.HashMap;
import java.util.Map;
public class NuevaComunicacion extends AppCompatActivity {
private TextInputLayout textInputAnadirComunicacion, textInputAnadirEmpleado;
private SwitchCompat switchComunicacionAnonima;
private Spinner spinnerDepartamentos, spinnerTipoComunicacion;
private Button enviar, cancelar;
private static String idUsuario;
RequestQueue requestQueue;
private static final String URL = GlobalIp.IP+"appdenunciasphp/insertar.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nueva_comunicacion);
textInputAnadirComunicacion = findViewById(R.id.text_input_anadir);
textInputAnadirEmpleado = findViewById(R.id.text_input_empleado);
switchComunicacionAnonima = findViewById(R.id.switch_anonimo);
spinnerDepartamentos = findViewById(R.id.spinner_departamento);
spinnerTipoComunicacion = findViewById(R.id.spinner_tipo_comunucacion);
enviar = findViewById(R.id.btnAnadirComunicacion);
cancelar = findViewById(R.id.btnCancelarComunicacion);
SharedPreferences sharedPreferences = this.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
idUsuario = sharedPreferences.getString("id", "16");
Log.i("idUsuario", idUsuario);
switchComunicacionAnonima.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
textInputAnadirEmpleado.getEditText().setText("Anónimo");
Toast.makeText(getApplicationContext(),"El mensaje se enviará de forma anónima", Toast.LENGTH_LONG).show();
} else {
String texto = textInputAnadirEmpleado.getEditText().getText().toString().trim();
if (texto.isEmpty()) {
textInputAnadirEmpleado.setError("El campo no puede estar vacío");
} else if (!texto.equals("Anónimo")){
Toast.makeText(getApplicationContext(),"El mensaje no será anónimo", Toast.LENGTH_LONG).show();
}
}
}
});
requestQueue = Volley.newRequestQueue(this);
}
//Botón aceptar
public void aceptar (View v) {
if (noActivo() | !validarComunicacion()) {
Toast.makeText(getApplicationContext(),"El mensaje no será anónimo", Toast.LENGTH_LONG).show();
}
String empleado = textInputAnadirEmpleado.getEditText().getText().toString().trim();
String tipoComunicacion = spinnerTipoComunicacion.getSelectedItem().toString();
String departamento = spinnerDepartamentos.getSelectedItem().toString();
String comunicacion = textInputAnadirComunicacion.getEditText().getText().toString().trim();
insertarComunicacion(empleado, tipoComunicacion, departamento,comunicacion);
}
private void insertarComunicacion(final String empleado, final String tipoComunicacion, final String departamento, final String comunicacion) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(NuevaComunicacion.this, "Comunicación enviada", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(NuevaComunicacion.this, "La comunicación no se ha podido enviar", Toast.LENGTH_SHORT).show();
}
}
){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap();
params.put("empleado", empleado);
params.put("tipo_comunicacion", tipoComunicacion);
params.put("departamento", departamento );
params.put("mensaje_comunicacion", comunicacion);
params.put("id", idUsuario);
return params;
}
};
requestQueue.add(stringRequest);
}
public void cancelar (View v) {
textInputAnadirComunicacion.getEditText().setText("");
textInputAnadirEmpleado.getEditText().setText("");
switchComunicacionAnonima.setChecked(false);
}
//Validaciones de los campos
private boolean validarComunicacion() {
String texto = textInputAnadirComunicacion.getEditText().getText().toString().trim();
if (texto.isEmpty()) {
textInputAnadirComunicacion.setError("El campo no puede estar vacío");
return false;
} else {
textInputAnadirComunicacion.setError(null);
return true;
}
}
//Cuando el switch no esté activo debe tener un empleado ya que la comunicación no será anónima
public boolean noActivo(){
if (!switchComunicacionAnonima.isChecked()){
textInputAnadirEmpleado.setError("El campo no puede estar vacío");
}
return true;
}
}
<file_sep>/app/src/main/java/com/example/appdenuncias/Alertas.java
package com.example.appdenuncias;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
public class Alertas extends AppCompatActivity {
private RecyclerView rvListaAlertas;
private RecyclerAdapterAlertas adapter;
private List<AlertasItem> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alertas);
initViews();
initValues();
}
//Inicializa el recycler
private void initViews(){
rvListaAlertas = findViewById(R.id.rvListaAlertas);
}
private void initValues() {
//Para mostrarlo en listas (se puede mostrar en Grid también)
LinearLayoutManager manager = new LinearLayoutManager(this);
rvListaAlertas.setLayoutManager(manager);
items = getItems();
adapter = new RecyclerAdapterAlertas(items);
rvListaAlertas.setAdapter(adapter);
}
//Muestra los datos de las alertas en el recycler
private List<AlertasItem> getItems() {
List<AlertasItem> itemLists = new ArrayList<>();
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 28 ha cambiado.", "Estado: Cerrada"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 28 ha cambiado.", "Estado: En proceso"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 28 ha cambiado.", "Estado: Abierta"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 17 ha cambiado.", "Estado: Cerrada"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 17 ha cambiado.", "Estado: En proceso"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 17 ha cambiado.", "Estado: Abierta"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 3 ha cambiado.", "Estado: Cerrada"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 3 ha cambiado.", "Estado: En proceso"));
itemLists.add(new AlertasItem(R.drawable.campana_notificacion, "El estado de su comunicación con Nº 3 ha cambiado.", "Estado: Abierta"));
return itemLists;
}
}<file_sep>/app/src/main/java/com/example/appdenuncias/GlobalIp.java
package com.example.appdenuncias;
public class GlobalIp {
public static final String IP = "http://192.168.1.103/";
}
<file_sep>/app/src/main/java/com/example/appdenuncias/ProfileFragment.java
package com.example.appdenuncias;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class ProfileFragment extends Fragment {
private TextView nombreTextView, ocupacionTextView, emailTextView, telefonoTextView, departamentoTextView;
private ImageView usuarioImageView, emailImageView, telefonoImageView, departamentoImageView;
private Button btnSubirImagen;
private static String idUsuario;
private static final int REQUEST_PERMISSION_CODE = 100;
private static final int REQUEST_IMAGE_GALLERY = 101;
RequestQueue requestQueue;
private static final String URL = GlobalIp.IP+"appdenunciasphp/perfil.php?id=" ;
//private static final String URL = "http://192.168.1.103/appdenunciasphp/listar.php?id=" + 16;
public ProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
nombreTextView = v.findViewById(R.id.nombre_textview);
ocupacionTextView = v.findViewById(R.id.ocupacion_textview);
emailTextView = v.findViewById(R.id.email_textview);
telefonoTextView = v.findViewById(R.id.phone_textview);
departamentoTextView = v.findViewById(R.id.departamento_textview);
usuarioImageView = v.findViewById(R.id.user_imageview);
emailImageView = v.findViewById(R.id.email_imageview);
telefonoImageView = v.findViewById(R.id.phone_imageview);
departamentoImageView = v.findViewById(R.id.departamento_imageview);
btnSubirImagen = v.findViewById(R.id.btnSubirImagen);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("preferencias", Context.MODE_PRIVATE);
idUsuario = sharedPreferences.getString("id", "16");
btnSubirImagen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//permisos para el uso de la galería
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//si están habilitados o no los permisos
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
abrirGaleria();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
}
} else {
abrirGaleria();
}
}
});
requestQueue = Volley.newRequestQueue(getActivity());
mostrarDatosPerfil(idUsuario);
return v;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_IMAGE_GALLERY) {
//Para verificar si la activity es vacía o no, si se recuperó la imagen o no
if (resultCode == Activity.RESULT_OK && data != null) {
Uri foto = data.getData();
usuarioImageView.setImageURI(foto);
} else {
//si no se presiona nada
Toast.makeText(getActivity(), "No ha seleccionado ninguna imagen", Toast.LENGTH_SHORT);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void abrirGaleria() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE_GALLERY);
}
//Si el usuario acepta o rechaza los permisos
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_CODE) {
if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
abrirGaleria();
} else {
Toast.makeText(getActivity(), "Necesitas habilitar los permisos", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void mostrarDatosPerfil(String id) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL+id,
null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String nombre, apellidos, puesto, email, telefono, departamento;
try {
nombre = response.getString("nombre");
apellidos = response.getString("apellidos");
puesto = response.getString("puesto");
email = response.getString("email");
telefono = response.getString("telefono");
departamento = response.getString("departamento");
nombreTextView.setText(nombre +" "+ apellidos);
ocupacionTextView.setText(puesto);
emailTextView.setText(email);
telefonoTextView.setText(telefono);
departamentoTextView.setText(departamento);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
} | 6d3637b921c5487161ba57838db75eb7bc545294 | [
"Java"
] | 13 | Java | MarMP/APPDenunciasMovil | bf50e856500475d499c7d7ce03ce6158b4febff7 | 834789305f7a371a082862aa680660131f8a37ca |
refs/heads/master | <file_sep># Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# :equilateral if all sides are equal
# :isosceles if exactly 2 sides are equal
# :scalene if no sides are equal
#
# The tests for this method can be found in
# about_triangle_project.rb
# and
# about_triangle_project_2.rb
#
def triangle(a, b, c)
#TODO: Are the incoming values > 0 ?
raise TriangleError, "Sides must be greater than 0." if [a,b,c].min <= 0
raise TriangleError, "Summ of 2 sides can't be less or equal to 3th side" if a+b <= c || a+c <= b || b+c <= a
if a == b && a == c
return :equilateral
elsif a == b || a == c || c == b
:isosceles
else
:scalene
end
end
# Error class used in part 2. No need to change this code.
class TriangleError < StandardError
end
#For a test purposes only
#puts triangle(2, 4, 2) | 19455d77bad215e159288ca58db68c44d1f589f9 | [
"Ruby"
] | 1 | Ruby | maldoniy/Ruby-Koans-Answers | 4f7859f10607ae1da16c909d9ea64ea56ee3e81a | 3783752f1b2dd6546533dd74dfecb33ac8abf9ac |
refs/heads/master | <file_sep>package gr.cs.uoi.daintiness.servlets;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import gr.cs.uoi.daintiness.core.ProjectServer;
import gr.cs.uoi.daintiness.core.ProjectServerFactory;
import gr.cs.uoi.daintiness.core.StatisticsServer;
import gr.cs.uoi.daintiness.core.StatisticsServerFactory;
/**
* Receives requests for loading a parmenidian project sending back responses
* related to this project.
* @author KD
* @since 2018-12-12
* @version 1.0
*/
@WebServlet(name="ProjectLoader",
urlPatterns= {"/loader"})
@MultipartConfig
public class ProjectLoaderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PROJECT_FOLDER = "resources/projects";
private ProjectServer prjServer;
private ProjectServerFactory prjServerFactory;
private StatisticsServer stServer;
private StatisticsServerFactory stFactory;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = PROJECT_FOLDER;
File dir = null;
List<String> projectsNames = new ArrayList<String>();
this.prjServerFactory = new ProjectServerFactory();
this.prjServer = prjServerFactory.createProjectServer();
String projectId = null;
stFactory = new StatisticsServerFactory();
this.stServer = this.stFactory.createStatisticsServer();
if (!new File(path).exists()) {
new File(path).mkdirs();
}
dir = new File(path) ;
File[] fileList = dir.listFiles();
for(File f:fileList)
if (f.isDirectory())
projectsNames.add(f.getName());
//redirecting to upload page when the user load a project from server
if (request.getParameterMap().containsKey("optradio")) {
if (!request.getParameter("optradio").equals(null) &&
!request.getParameter("optradio").isEmpty()) {
projectId = request.getParameter("optradio");
String projectName = projectsNames.get(Integer.valueOf(projectId));
//Parse xml and load data
this.prjServer.parseXmlDoc(new File(PROJECT_FOLDER.concat("/").concat(projectName)));
request.setAttribute("stats",stServer.createOverallStats(
this.prjServer.getOverallStats()));
request.setAttribute("statsOver",this.stServer.createBirthVersionStats(
this.prjServer.getBirthVersionStats()));
request.setAttribute("schemas",prjServer.getVersionsInJson());
request.setAttribute("hideAttr",'1');
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
//redirecting to upload page when user selects different stats
}else if(request.getParameterMap().containsKey("statsId")) {
String statsId = request.getParameter("statsId");
if (statsId.equals("1"))
request.setAttribute("statsOver",this.stServer.createBirthVersionStats(
this.prjServer.getBirthVersionStats()));
else if (statsId.equals("2"))
request.setAttribute("statsOver",this.stServer.createSurvivalStats(
this.prjServer.getSurvivalStats()));
else if (statsId.equals("3"))
request.setAttribute("statsOver",this.stServer.createDurationStats(
this.prjServer.getDurationStats()));
else if (statsId.equals("4"))
request.setAttribute("statsOver",this.stServer.createActivityStats(
this.prjServer.getActivityStats()));
request.setAttribute("stats",stServer.createOverallStats(
this.prjServer.getOverallStats()));
request.setAttribute("schemas",prjServer.getVersionsInJson());
request.setAttribute("hideAttr",'1');
request.getRequestDispatcher("/upload.jsp").forward(request, response);
//redirecting to load page
}else {
request.setAttribute("projects",projectsNames);
request.getRequestDispatcher("/load.jsp").forward(request, response);
}
}
// Redirect POST request to GET request.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
}<file_sep># WebParmenidianTruth
A web application that can be used to visualize the schema evolution of relational databases. We should mention that this application as well as the [ParmenidianTruth-API] are submodules of the [WebSchemaVisualizer] project\*.
The main functionalities of the application can be summarized as follows:
* **Visualize** DB's schemata as graphs with nodes and edges representing the including tables and foreign keys, respectively.\**
* **Visualize** several evolution-related patterns
* **Compute** evolution-related statistics
The data required from the application are provided by the ParmenidianTruth-API, a refactored version of the ParmenidianTruth tool. We make use of this data to create a new project that offers the aforementioned functionalities.
The visualization part of the application is implemented via [D3] , a javascript library that enables the visual representation of the data related to the schema evolution.
For more information on how to run web application, please refer to the [README] file of the parent project WebSchemaVisualizer.
[D3]: https://github.com/d3
[ParmenidianTruth-API]:https://github.com/kdimolikas/ParmenidianTruth-API
[WebSchemaVisualizer]:https://github.com/kdimolikas/WebSchemaVisualizer
[README]: https://github.com/kdimolikas/WebSchemaVisualizer/blob/master/README.md
\*: *created in the context of my MSc thesis at the department of Computer Science & Engineering of the University of Ioannina, under the supervision of associate professor <NAME>*.
\**The schema of BioSQL database in version 30.
<file_sep>$(document).ready(function(){
$("#btn1").click(function(){
var data ={};
data = $("#gamma").val();
drawGammaPattern(data);
$(this).prop('disabled', true);
});
$("#btn2").click(function(){
var data ={};
data = $("#invGamma").val();
drawInvGammaPattern(data);
$(this).prop('disabled', true);
});
$("#btn3").click(function(){
var data ={};
data = $("#commet").val();
drawCommetPattern(data);
$(this).prop('disabled', true);
});
$("#btn4").click(function(){
var data ={};
data = $("#eTriangle").val();
drawEmptyTrianglePattern(data);
$(this).prop('disabled', true);
});
});
function getActivityClass(d){
if (d==0)
return "RIGID";
else if (d==1)
return "QUIET";
else if (d==2)
return "ACTIVE";
}
//Draws the Gamma pattern
function drawGammaPattern(data){
try{
//alert(data);
var arr = JSON.parse(data);
console.log(arr);
}catch (e){
alert(e);
}
var margin = {top:30, right:30, bottom:50, left:70},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
//add graph canvas to the jsp
var svg = d3.select('#scatter1')
.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 + ')');
//setup radius
var radius = d3.scaleSqrt().range([2,5]);
//add domain to avoid overlapping
var xMax = d3.max(arr,(d)=>d.xValue);
var xScale = d3.scaleLinear().range([0,width-margin.right])
.domain([1,xMax])
.nice();
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(4);
var yScale = d3.scaleLinear().range([height,0])
.domain([1,d3.max(arr, (d)=>d.yValue)])
.nice();
var yAxis = d3.axisLeft().scale(yScale);
radius.domain(d3.extent(arr,function(d){
return d.rad;
})).nice();
//setup fill color
// var activity = [];
// arr.forEach(function(d,i){
//
// activity[i] = getActivityClass(d.col);
//
// });
// var colors = [];
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(arr.map(function(d){return getActivityClass(d.col);}));
svg.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'x axis')
.call(xAxis);
// y-axis is translated to (0,0)
svg.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'y axis')
.call(yAxis);
//draw bubbles
var bubble = svg.selectAll('.bubble')
.data(arr)
.enter().append('circle')
.attr('class', 'bubble')
.attr('cx', function(d){return xScale(d.xValue);})
.attr('cy', function(d){ return yScale(d.yValue);})
.attr('r', function(d){ return radius(d.rad);})
.style('fill', function(d,i){ return color(getActivityClass(d.col));});
bubble.append('title')
.attr('x', function(d){ return radius(d.rad); })
.text(function(d){
return d.name+ " ("+d.xValue+","+d.yValue+")";
});
// label for x-axis
svg.append('text')
.attr("transform","translate("+
(width/2)+","+(height+margin.top+10)+")")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Size @ Birth');
svg.append('text')
.attr("transform","rotate(-90)")
.attr("y",0-margin.left)
.attr("x",0-(height/2))
.attr("dy","1em")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Duration');
//draw legend
var legend = svg.selectAll('legend')
.data(color.domain())
.enter().append('g')
.attr('class', 'legend')
.attr('transform', function(d,i){ return 'translate(0,' + i * 20 + ')'; });
//draw legend colored rects
legend.append('rect')
.attr('x', width)
.attr('width', 18)
.attr('height', 18)
.style('fill', function(d){return color(d)});
//add text to legend
legend.append('text')
.attr('x', width - 6)
.attr('y', 9)
.attr('dy', '.35em')
.style('text-anchor', 'end')
.text(function(d){
return d;
});
legend.on('click', function(type){
d3.selectAll('.bubble')
.style('opacity', 0.15)
.filter(function(d){
return getActivityClass(d.col) == type;
})
.style('opacity', 1);
});
}
//Draws the Inverse Gamma pattern
function drawInvGammaPattern(data){
try{
//alert(data);
var arr2 = JSON.parse(data);
console.log(arr2);
}catch (e){
alert(e);
}
var margin = {top:30, right:30, bottom:50, left:70},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
//add graph canvas to the jsp
var svg2 = d3.select('#scatter2')
.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 + ')');
//setup radius
var radius = d3.scaleSqrt().range([2,5]);
//add domain to avoid overlapping
var xMax = d3.max(arr2,(d)=>d.xValue);
var xScale = d3.scaleLinear().range([0,width-margin.right])
.domain([1,xMax])
.nice();
var xAxis = d3.axisBottom().scale(xScale).ticks(2);
var yScale = d3.scaleLinear().range([height,0])
.domain([0,d3.max(arr2, (d)=>d.yValue)])
.nice();
var yAxis = d3.axisLeft().scale(yScale);
radius.domain(d3.extent(arr2,function(d){
return d.rad;
})).nice();
//setup fill color
// var activity = [];
//
// arr2.forEach(function(d,i){
//
// activity[i] = getActivityClass(d.col);
//
//
// });
//var colors = ["rgb(0,0,255)","rgb(0,255,0)","rgb(255,0,0)"];
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(arr2.map(function(d){return getActivityClass(d.col);}));
// adding axes is also simpler now, just translate x-axis to (0,height) and it's already defined to be a bottom axis.
svg2.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'x axis')
.call(xAxis);
// y-axis is translated to (0,0)
svg2.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'y axis')
.call(yAxis);
//draw bubbles
var bubble = svg2.selectAll('.bubble2')
.data(arr2)
.enter().append('circle')
.attr('class', 'bubble2')
.attr('cx', function(d){return xScale(d.xValue);})
.attr('cy', function(d){ return yScale(d.yValue);})
.attr('r', function(d){ return radius(d.rad);})
.style('fill', function(d,i){ return color(getActivityClass(d.col));});
bubble.append('title')
.attr('x', function(d){ return radius(d.rad); })
.text(function(d){
return d.name+ " ("+d.xValue+","+d.yValue+")";
});
//Labels for x and y axes
svg2.append('text')
.attr("transform","translate("+
(width/2)+","+(height+margin.top+10)+")")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Duration');
svg2.append('text')
.attr("transform","rotate(-90)")
.attr("y",0-margin.left)
.attr("x",0-(height/2))
.attr("dy","1em")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Sum(updates)');
//draw legend
var legend = svg2.selectAll('legend')
.data(color.domain())
.enter().append('g')
.attr('class', 'legend')
.attr('transform', function(d,i){ return 'translate(0,' + i * 20 + ')'; });
//draw legend colored rects
legend.append('rect')
.attr('x', width)
.attr('width', 18)
.attr('height', 18)
.style('fill', function(d){return color(d)});
// add text to the legend elements.
legend.append('text')
.attr('x', width - 6)
.attr('y', 9)
.attr('dy', '.35em')
.style('text-anchor', 'end')
.text(function(d){
return d;
});
legend.on('click', function(type){
d3.selectAll('.bubble2')
.style('opacity', 0.15)
.filter(function(d){
return getActivityClass(d.col) == type;
})
.style('opacity', 1);
});
}
//Draws the Commet pattern
function drawCommetPattern(data){
try{
//alert(data);
var arr3 = JSON.parse(data);
console.log(arr3);
}catch (e){
alert(e);
}
var margin = {top:30, right:30, bottom:50, left:70},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
//add graph canvas to the jsp
var svg3 = d3.select('#scatter3')
.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 + ')');
//setup radius
var radius = d3.scaleSqrt().range([2,5]);
//add domain to avoid overlapping
var xMax = d3.max(arr3,(d)=>d.xValue);
var xScale = d3.scaleLinear().range([0,width-margin.right])
.domain([1,xMax])
.nice();
var xAxis = d3.axisBottom().scale(xScale).ticks(4);
var yScale = d3.scaleLinear().range([height,0])
.domain([0,d3.max(arr3, (d)=>d.yValue)])
.nice();
var yAxis = d3.axisLeft().scale(yScale);
radius.domain(d3.extent(arr3,function(d){
return d.rad;
})).nice();
//setup fill color
// var activity = [];
// arr3.forEach(function(d,i){
//
// activity[i] = getActivityClass(d.col);
//
// });
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(arr3.map(function(d){return getActivityClass(d.col);}));
svg3.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'x axis')
.call(xAxis);
// y-axis is translated to (0,0)
svg3.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'y axis')
.call(yAxis);
//draw bubbles
var bubble = svg3.selectAll('.bubble3')
.data(arr3)
.enter().append('circle')
.attr('class', 'bubble3')
.attr('cx', function(d){return xScale(d.xValue);})
.attr('cy', function(d){ return yScale(d.yValue);})
.attr('r', function(d){ return radius(d.rad);})
.style('fill', function(d,i){ return color(getActivityClass(d.col));});
bubble.append('title')
.attr('x', function(d){ return radius(d.rad); })
.text(function(d){
return d.name+ " ("+d.xValue+","+d.yValue+")";
});
//Labels for x and y axes
svg3.append('text')
.attr("transform","translate("+
(width/2)+","+(height+margin.top+10)+")")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Size@Birth');
svg3.append('text')
.attr("transform","rotate(-90)")
.attr("y",0-margin.left)
.attr("x",0-(height/2))
.attr("dy","1em")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Sum(updates)');
//draw legend
var legend = svg3.selectAll('legend')
.data(color.domain())
.enter().append('g')
.attr('class', 'legend')
.attr('transform', function(d,i){ return 'translate(0,' + i * 20 + ')'; });
//draw legend colored rects
legend.append('rect')
.attr('x', width)
.attr('width', 18)
.attr('height', 18)
.style('fill', function(d){return color(d)});
// add text to the legend elements.
legend.append('text')
.attr('x', width - 6)
.attr('y', 9)
.attr('dy', '.35em')
.style('text-anchor', 'end')
.text(function(d){
return d;
});
// d3 has a filter fnction similar to filter function in JS. Here it is used to filter d3 components.
legend.on('click', function(type){
d3.selectAll('.bubble3')
.style('opacity', 0.15)
.filter(function(d){
return getActivityClass(d.col) == type;
})
.style('opacity', 1);
});
}
//Draws the Empty Triangle pattern
function drawEmptyTrianglePattern(data){
try{
//alert(data);
var arr4 = JSON.parse(data);
console.log(arr4);
}catch (e){
alert(e);
}
var margin = {top:30, right:30, bottom:50, left:70},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
//add graph canvas to the jsp
var svg4 = d3.select('#scatter4')
.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 + ')');
//setup radius
var radius = d3.scaleSqrt().range([2,5]);
//add domain to avoid overlapping
var xMax = d3.max(arr4,(d)=>d.xValue);
var xScale = d3.scaleLinear().range([0,width-margin.right])
.domain([1,xMax])
.nice();
var xAxis = d3.axisBottom().scale(xScale).ticks(4);
var yScale = d3.scaleLinear().range([height,0])
.domain([0,d3.max(arr4, (d)=>d.yValue)])
.nice();
var yAxis = d3.axisLeft().scale(yScale);
radius.domain(d3.extent(arr4,function(d){
return d.rad;
})).nice();
//setup fill color
//setup fill color
// var activity = [];
// arr4.forEach(function(d,i){
//
// activity[i] = getActivityClass(d.col);
//
// });
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(arr4.map(function(d){return getActivityClass(d.col);}));
svg4.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'x axis')
.call(xAxis);
// y-axis is translated to (0,0)
svg4.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'y axis')
.call(yAxis);
//draw bubbles
var bubble = svg4.selectAll('.bubble4')
.data(arr4)
.enter().append('circle')
.attr('class', 'bubble4')
.attr('cx', function(d){return xScale(d.xValue);})
.attr('cy', function(d){ return yScale(d.yValue);})
.attr('r', function(d){ return radius(d.rad);})
.style('fill', function(d,i){ return color(getActivityClass(d.col));});
bubble.append('title')
.attr('x', function(d){ return radius(d.rad); })
.text(function(d){
return d.name+ " ("+d.xValue+","+d.yValue+")";
});
//Labels for x and y axes
svg4.append('text')
.attr("transform","translate("+
(width/2)+","+(height+margin.top+10)+")")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Birth Version');
svg4.append('text')
.attr("transform","rotate(-90)")
.attr("y",0-margin.left)
.attr("x",0-(height/2))
.attr("dy","1em")
.attr('text-anchor', 'middle')
.attr('class', 'label')
.text('Duration');
//draw legend
var legend = svg4.selectAll('legend')
.data(color.domain())
.enter().append('g')
.attr('class', 'legend')
.attr('transform', function(d,i){ return 'translate(0,' + i * 20 + ')'; });
//draw legend colored rects
legend.append('rect')
.attr('x', width)
.attr('width', 18)
.attr('height', 18)
.style('fill', function(d){return color(d)});
// add text to the legend elements.
legend.append('text')
.attr('x', width - 6)
.attr('y', 9)
.attr('dy', '.35em')
.style('text-anchor', 'end')
.text(function(d){
return d;
});
legend.on('click', function(type){
d3.selectAll('.bubble4')
.style('opacity', 0.15)
.filter(function(d){
return getActivityClass(d.col) == type;
})
.style('opacity', 1);
});
}
<file_sep>package gr.cs.uoi.daintiness.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Represents the set of versions along with the including nodes and links
* that are used to load projects.
* @author KD
* @since 2018-12-14
* @version 1.0
*/
@XmlRootElement
public class Model {
@XmlElementWrapper(name="versions")
@XmlElement(name="version")
private List<Version> versions = new ArrayList<Version>();
public Model() {
this.versions = new ArrayList<Version>();
}
public Model(List<Version> v) {
this.versions = v;
}
public List<Version> getVersions(){
return this.versions;
}
}
<file_sep>package gr.cs.uoi.daintiness.core;
/**
* Simulates the visualized nodes of the Diachronic Graph.
* @author KD
* @since 2018-11
*/
public class Bubble {
@SuppressWarnings("unused")
private String name;
@SuppressWarnings("unused")
private int xValue;
@SuppressWarnings("unused")
private int yValue;
@SuppressWarnings("unused")
private double rad;
@SuppressWarnings("unused")
private double col;
public Bubble(String n, int x, int y, double r, double c) {
this.name = n;
this.xValue = x;
this.yValue = y;
this.rad = r;
this.col = c;
}
}
<file_sep>package gr.cs.uoi.daintiness.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import model.ForeignKey;
import model.Table;
public class Version {
@XmlAttribute(name="versionName")
private String name;
@XmlAttribute(name="versionId")
private int id;
@SuppressWarnings("unused")
private int tables;
@SuppressWarnings("unused")
private int keys;
@XmlElementWrapper(name="nodes")
@XmlElement(name="node")
private List<Node> versionNodes;
@XmlElementWrapper(name="links")
@XmlElement(name="link")
private List<Link> versionLinks;
public Version() {
versionNodes = new ArrayList<Node>();
versionLinks = new ArrayList<Link>();
}
public Version(String aName,int anId) {
this.name = aName;
this.id = anId;
versionNodes = new ArrayList<Node>();
versionLinks = new ArrayList<Link>();
}
/**
*
* @param tables
*/
public void setVersionNodes(List<Table> tables) {
for (Table t:tables) {
Node n = new Node(t.getTableName(),t.getDuration());
this.versionNodes.add(n);
}
this.tables = this.versionNodes.size();
}
public void setNodes(List<Node> nodes) {
this.versionNodes = nodes;
}
/**
*
* @param keys
*/
public void setVersionLinks(List<ForeignKey> keys) {
for (ForeignKey fk:keys) {
Link l = new Link(fk.getSourceTable(),fk.getTargetTable());
this.versionLinks.add(l);
}
this.keys = this.versionLinks.size();
}
@XmlAttribute(name="keysNum")
public int getKeysNum() {
return this.keys;
}
public void setKeysNum(int size) {
this.keys = size;
}
@XmlAttribute(name="tablesNum")
public int getTablesNum() {
return this.tables;
}
public void setTablesNum(int size) {
this.tables = size;
}
public List<Node> getVersionNodes(){
return this.versionNodes;
}
public List<Link> getVersionLinks(){
return this.versionLinks;
}
public int getVersionId() {
return this.id;
}
}
<file_sep>package gr.cs.uoi.daintiness.core;
import java.io.File;
import java.util.List;
import java.util.Map;
import gr.cs.uoi.daintiness.enums.ActivityStatus;
import gr.cs.uoi.daintiness.enums.BirthVersionLabel;
import gr.cs.uoi.daintiness.enums.DurationLabel;
import gr.cs.uoi.daintiness.enums.Labels;
import gr.cs.uoi.daintiness.enums.SurvivalStatus;
import gr.cs.uoi.daintiness.model.Link;
import gr.cs.uoi.daintiness.model.Node;
/**
* Defines methods requested by {@link gr.cs.uoi.daintiness.servlets.ProjectCreatorServlet} and
* {@link gr.cs.uoi.daintiness.servlets.ProjectLoaderServlet} classes.
* @author KD
* @since 2018-12-15
* @version 1.0
*/
public interface ProjectServer {
//Project Creator
public List<Link> getLinks();
public void createNodes();
public void createVersions();
public Map<Labels, Integer> getOverallStats();
public Map<BirthVersionLabel, Integer> getBirthVersionStats();
public void createLinks();
public void createXmlWithVersions(File dir);
public void parseXmlDoc(File dir);
public Map<SurvivalStatus, Integer> getSurvivalStats();
public Map<DurationLabel, Integer> getDurationStats();
public Map<ActivityStatus, Integer> getActivityStats();
//Common
public List<Bubble> setBubblesValues(Map<String,int[]> map);
public void setNodes(String groupId,String radiusId);
//Visualization
public List<Node> getNodes();
public String convertToJson(List<?> list);
public String getVersionsInJson();
public String getNodesInJson();
public String getLinksInJson();
public int getVersionsNum();
public void setVersionNodes(String gId, String rId, String vId);
public void setLinks();
public void setVersionLinks(String vId);
}
<file_sep>window.onload=function() {
var url = window.location.pathname;
$('#nav').find('li .active').removeClass('active');
if (url=="/upload.jsp" || url=="/loader"){
$("#nav").find("#l2").addClass("active");
}else if (url=="/index.jsp" || url==""){
$("#nav").find("#l1").addClass("active");
}else{
$("#nav").find("#l3").addClass("active");
}
};
<file_sep>package tests;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import gr.cs.uoi.daintiness.core.ParmenidianProvider;
/**
* Testing {@link gr.cs.uoi.daintiness.core.ParmenidianProvider} class.
* @author KD
* @since 2018-12-21
* @version 1.0
*/
public class ParmenidianProviderTest {
private static ParmenidianProvider prmProv;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
prmProv = ParmenidianProvider.getInstance();
}
@Test
public void testGetInstance() {
assertNotNull("Instance of ParmenidianProvider is not null",prmProv);
}
@Test
public void testGetTables() {
assertNotNull("List of tables is not null",prmProv.getTables());
}
@Test
public void testGetForeignKeys() {
assertNotNull("List of foreign keys is not null",prmProv.getForeignKeys());
}
}
<file_sep>package gr.cs.uoi.daintiness.core;
import java.util.List;
import model.DBVersion;
import model.ForeignKey;
import model.Table;
/**
* The interface of the parmenidian project.
* @author KD
* @since 2018-11-08
* @version 1.0
*/
public interface ParmenidianServer {
public void createProject (String sqlFolder);
public List<DBVersion> getVersions();
public int getVersionsNum();
public List<Table> getTables();
public DBVersion getVersionWithId(int id);
public List<ForeignKey> getForeignKeys();
}<file_sep>package tests;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import gr.cs.uoi.daintiness.model.Node;
/**
* Testing {@link gr.cs.uoi.daintiness.model.Node} class.
* @author KD
* @since 2018-12-21
* @version 1.0
*
*/
public class NodeTest {
private static Node testNode;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
testNode = new Node("node1",1);
}
@Test
public void testNodeStringInt() {
assertNotNull("Node object is not null",testNode);
}
@Test
public void testGetNodeName() {
assertEquals("Node name is node1","node1",testNode.getNodeName());
}
@Test
public void testGetNodeGroup() {
assertEquals("Node group is equal to 1",1,testNode.getNodeGroup());
}
}
<file_sep>package gr.cs.uoi.daintiness.core;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import gr.cs.uoi.daintiness.enums.ActivityStatus;
import gr.cs.uoi.daintiness.enums.BirthVersionLabel;
import gr.cs.uoi.daintiness.enums.DurationLabel;
import gr.cs.uoi.daintiness.enums.Labels;
import gr.cs.uoi.daintiness.enums.SurvivalStatus;
import gr.cs.uoi.daintiness.model.Link;
import gr.cs.uoi.daintiness.model.Model;
import gr.cs.uoi.daintiness.model.Node;
import gr.cs.uoi.daintiness.model.Version;
import gr.cs.uoi.daintiness.model.XmlProvider;
import model.DBVersion;
import model.ForeignKey;
import model.Table;
/**
* Implements the methods provided by the {@link gr.cs.uoi.daintiness.core.ProjectServer} interface.
* @author KD
* @since 2018-12-14
* @version 1.0
*/
public class ProjectProvider implements ProjectServer {
private static ProjectProvider instance = null;
private List<Node> nodes;
private List<Node> groupedNodes;
private List<Link> links;
private List<Link> groupedLinks;
private List<Version> versions;
private ParmenidianServer parmServer;
private ParmenidianServerFactory parmFactory;
private Model model;
private XmlProvider xmlManager;
private StatisticsServer stServer;
private StatisticsServerFactory stFactory;
protected ProjectProvider() {
nodes = new ArrayList<Node>();
groupedNodes = new ArrayList<Node>();
links = new ArrayList<Link>();
groupedLinks = new ArrayList<Link>();
versions = new ArrayList<Version>();
this.parmFactory = new ParmenidianServerFactory();
this.stFactory = new StatisticsServerFactory();
this.stServer = this.stFactory.createStatisticsServer();
this.xmlManager = new XmlProvider();
}
public static ProjectProvider getInstance() {
if (instance==null)
instance = new ProjectProvider();
return instance;
}
public void createLinks() {
for (ForeignKey f:parmServer.getForeignKeys()) {
Link l = new Link(f.getSourceTable(),f.getTargetTable());
links.add(l);
}
}
public void createNodes() {
this.clear();
parmServer = parmFactory.createParmenidianServer();
for (Table t:parmServer.getTables()) {
Node n = null;
n = new Node(t.getTableName(),0);
n.setDuration(t.getDuration());
n.setBirthVersion(t.getBirthVersion());
n.setSurvivorStatus(t.getSurvivorStatus());
n.setChangesNum(t.getSumUpdates());
n.setActivityStatus(stServer.getActivityLabel(t.getSumUpdates(), t.getATU()));
n.setSizeAtBirth(t.getAttrsNumAtBirth());
n.setATU();
nodes.add(n);
}
}
/**
* Load links from xml file.
*/
private void loadLinks() {
this.links = xmlManager.getLinks();
}
public void setLinks() {
for (Link l:this.links) {
Link lk = new Link(l.getSourceNode(),l.getTargetNode());
groupedLinks.add(lk);
}
}
/**
* Created only for test purposes.
* @param lk - a list of links
*/
public void setGroupedLinks(List<Link> lk) {
this.clearGroupedData();
for (Link l:lk)
this.groupedLinks.add(l);
}
public void setVersionLinks(String vId) {
Version version = versions.get(Integer.valueOf(vId));
for (Link fk:version.getVersionLinks()) {
Link l = new Link(fk.getSourceNode(),fk.getTargetNode());
this.groupedLinks.add(l);
}
}
public List<Node> getNodes(){
return this.nodes;
}
public List<Version> getVersions(){
return this.versions;
}
public int getVersionsNum() {
return this.versions.size();
}
public String convertToJson(List<?> list) {
JsonConverter converter = new JsonConverter();
return converter.convertListToJsonString(list);
}
@Override
public Map<Labels, Integer> getOverallStats() {
Map<Labels,Integer> stats = new TreeMap<Labels,Integer>();
stats.put(Labels.TABLES, nodes.size());
stats.put(Labels.KEYS, links.size());
stats.put(Labels.VERSIONS, versions.size());
return stats;
}
/**
*
*/
@Override
public Map<BirthVersionLabel, Integer> getBirthVersionStats() {
Map<BirthVersionLabel,Integer> stats = new TreeMap<BirthVersionLabel,Integer>();
double versionsNum = this.versions.size();
stats.put(BirthVersionLabel.EARLY_BORN, 0);
stats.put(BirthVersionLabel.MEDIUM_BORN, 0);
stats.put(BirthVersionLabel.LATE_BORN, 0);
for (Node n:nodes) {
if((n.getBirthVersion()/versionsNum) < 0.33)
stats.put(BirthVersionLabel.EARLY_BORN,stats.get(BirthVersionLabel.EARLY_BORN) + 1);
else if(((n.getBirthVersion()/versionsNum) >= 0.33) &&
((n.getBirthVersion()/versionsNum) <= 0.77))
stats.put(BirthVersionLabel.MEDIUM_BORN,stats.get(BirthVersionLabel.MEDIUM_BORN) + 1);
else
stats.put(BirthVersionLabel.LATE_BORN,stats.get(BirthVersionLabel.LATE_BORN) + 1);
}
return stats;
}
@Override
public Map<SurvivalStatus, Integer> getSurvivalStats() {
Map<SurvivalStatus,Integer> stats = new TreeMap<SurvivalStatus,Integer>();
stats.put(SurvivalStatus.SURVIVOR, 0);
stats.put(SurvivalStatus.NON_SURVIVOR, 0);
for (Node n:nodes) {
if(n.getSurvivorStatus() == SurvivalStatus.SURVIVOR.getValue())
stats.put(SurvivalStatus.SURVIVOR,stats.get(SurvivalStatus.SURVIVOR) + 1);
else
stats.put(SurvivalStatus.NON_SURVIVOR,stats.get(SurvivalStatus.NON_SURVIVOR) + 1);
}
return stats;
}
@Override
public Map<DurationLabel, Integer> getDurationStats() {
Map<DurationLabel,Integer> stats = new TreeMap<DurationLabel,Integer>();
stats.put(DurationLabel.SHORT_LIVED, 0);
stats.put(DurationLabel.MEDIUM_LIVED, 0);
stats.put(DurationLabel.LONG_LIVED, 0);
int versionsNum = versions.size();
for (Node n:nodes) {
if(stServer.getTableNormCategory(n.getDuration(), versionsNum) == 1)
stats.put(DurationLabel.SHORT_LIVED,stats.get(DurationLabel.SHORT_LIVED) + 1);
else if (stServer.getTableNormCategory(n.getDuration(), versionsNum) == 2)
stats.put(DurationLabel.MEDIUM_LIVED,stats.get(DurationLabel.MEDIUM_LIVED) + 1);
else
stats.put(DurationLabel.LONG_LIVED,stats.get(DurationLabel.LONG_LIVED) + 1);
}
return stats;
}
@Override
public Map<ActivityStatus, Integer> getActivityStats() {
Map<ActivityStatus,Integer> stats = new TreeMap<ActivityStatus,Integer>();
stats.put(ActivityStatus.RIGID, 0);
stats.put(ActivityStatus.QUIET, 0);
stats.put(ActivityStatus.ACTIVE, 0);
for (Node n:nodes) {
if(stServer.getActivityLabel(n.getChangesNum(), n.getATU()).equals(
ActivityStatus.RIGID.toString()) )
stats.put(ActivityStatus.RIGID,stats.get(ActivityStatus.RIGID) + 1);
else if (stServer.getActivityLabel(n.getChangesNum(), n.getATU()).equals(
ActivityStatus.QUIET.toString()))
stats.put(ActivityStatus.QUIET,stats.get(ActivityStatus.QUIET) + 1);
else
stats.put(ActivityStatus.ACTIVE,stats.get(ActivityStatus.ACTIVE) + 1);
}
return stats;
}
/**
* Load nodes from xl file.
*/
private void loadNodes() {
this.nodes = xmlManager.getNodes();
}
/**
*
* @param groupId
* @param radiusId
* @since 2018-12-03
*/
public void setNodes(String groupId,String radiusId) {
this.clearGroupedData();
for (Node nd:this.nodes) {
Node n = null;
if (groupId.equals("0")) {
n = new Node(nd.getNodeName(),nd.getBirthVersion());
n.setLabel(stServer.getBirthVersionLabel(nd.getBirthVersion(),this.versions.size()));
}else if (groupId.equals("1")) {
n = new Node(nd.getNodeName(),stServer.getTableUpdateClass(nd.getChangesNum(),nd.getATU()));
n.setLabel(stServer.getActivityLabel(nd.getChangesNum(), nd.getATU()));
}else if (groupId.equals("2")) {
n = new Node(nd.getNodeName(),nd.getSurvivorStatus());
n.setLabel(stServer.getSurvivalLabel(nd.getSurvivorStatus()));
}
if (radiusId.equals("0"))
n.setRadius(nd.getSizeAtBirth());
else if (radiusId.equals("1"))
n.setRadius(nd.getDuration());
this.groupedNodes.add(n);
}
}
public void setVersionNodes(String gId, String rId, String vId) {
this.clearGroupedData();
Version version = versions.get(Integer.valueOf(vId));
for (Node nd:version.getVersionNodes()) {
Node n = null;
if (gId.equals("0")) {
n = new Node(nd.getNodeName(),nd.getBirthVersion());
n.setLabel(stServer.getBirthVersionLabel(nd.getBirthVersion(),this.versions.size()));
}else if (gId.equals("1")) {
n = new Node(nd.getNodeName(),stServer.getTableUpdateClass(nd.getChangesNum(), nd.getATU()));
n.setLabel(stServer.getActivityLabel(nd.getChangesNum(), nd.getATU()));
}else if (gId.equals("2")) {
n = new Node(nd.getNodeName(),nd.getSurvivorStatus());
n.setLabel(stServer.getSurvivalLabel(nd.getSurvivorStatus()));
}
//Set radius
if (rId.equals("0"))
n.setRadius(nd.getSizeAtBirth());
else if (rId.equals("1"))
n.setRadius(nd.getDuration());
groupedNodes.add(n);
}
}
public String getVersionsInJson() {
return this.convertToJson(this.versions);
}
public String getLinksInJson() {
return this.convertToJson(this.groupedLinks);
}
public void createXmlWithVersions(File dir) {
model = new Model(this.versions);
xmlManager.createXmlDoc(model, dir);
}
public void parseXmlDoc(File dir) {
this.clear();
xmlManager.parseXmlDoc(dir);
this.loadNodes();
this.loadLinks();
this.loadVersions();
updateNodes();
this.updateVersionNodes();
}
private void updateNodes() {
for (Node n:nodes)
stServer.getActivityLabel(n.getChangesNum(),n.getATU());
}
/**
* Creates the objects used for creating scatter plots.
* @param map - data used to create the list of Bubble objects.
* @return a list with the values that we use to create scatter plots
* @author KD
* @since 2018-11-28
*/
public List<Bubble> setBubblesValues(Map<String,int[]> map) {
List<Bubble> bubbles = new ArrayList<Bubble>();
for (Map.Entry<String, int[]> entry: map.entrySet()) {
bubbles.add(new Bubble(entry.getKey(),entry.getValue()[0],entry.getValue()[1],
entry.getValue()[2],entry.getValue()[3]));
}
return bubbles;
}
private void clear() {
this.nodes.clear();
this.links.clear();
this.versions.clear();
}
private void clearGroupedData() {
this.groupedNodes.clear();
this.groupedLinks.clear();
}
@Override
public List<Link> getLinks() {
return this.links;
}
/**
* Created only for test purposes.
* @return a list of links.
*/
public List<Link> getGroupedLinks(){
return this.groupedLinks;
}
public void createVersions() {
for (DBVersion v:parmServer.getVersions()) {
Version vr = new Version(v.getVersion(),v.getVersionId());
vr.setVersionNodes(v.getTables());
vr.setVersionLinks(v.getVersionForeignKeys());
versions.add(vr);
}
updateVersionNodes();
}
private Node getNodeWithName(String name) {
for (Node n:nodes)
if (name.equals(n.getNodeName()))
return n;
return null;
}
/**
* Updates the attrs of each version's nodes.
*/
private void updateVersionNodes() {
for (Version v:versions) {
for (Node n:v.getVersionNodes()) {
Node nd = this.getNodeWithName(n.getNodeName());
n.setBirthVersion(nd.getBirthVersion());
n.setDuration(nd.getDuration());
n.setSizeAtBirth(nd.getSizeAtBirth());
n.setChangesNum(nd.getChangesNum());
n.setSurvivorStatus(nd.getSurvivorStatus());
n.setATU();
}
}
}
/**
* Load versions from xml file.
*/
private void loadVersions() {
this.versions = xmlManager.getVersions();
}
@Override
public String getNodesInJson() {
return convertToJson(this.groupedNodes);
}
}
<file_sep>package tests;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import gr.cs.uoi.daintiness.core.ProjectProvider;
import gr.cs.uoi.daintiness.model.Link;
/**
* Testing {@link gr.cs.uoi.daintiness.core.ProjectProvider} class.
* @author KD
* @since 2018-12-04
*
*/
public class ProjectProviderTest {
private static ProjectProvider projectProv;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
List<Link> links = new ArrayList<Link>();
Link l1 = new Link("table1","table2");
Link l2 = new Link("table3","table2");
links.addAll(Arrays.asList(l1,l2));
projectProv = ProjectProvider.getInstance();
projectProv.setGroupedLinks(links);
}
@Test
public void testGetInstance() {
assertNotNull("Instance of ProjectProvider is not null",projectProv);
}
@Test
public void testGetVersions() {
assertNotNull("List of versions is not null",projectProv.getVersions());
}
@Test
public void testGetNodes() {
assertNotNull("List of nodes is not null",projectProv.getNodes());
}
@Test
public void testGetLinks() {
assertNotNull("List of links is not null",projectProv.getLinks());
}
@Test
public void testConvertToJson() {
assertEquals("List has 2 elements",2,projectProv.getGroupedLinks().size());
System.out.println(projectProv.getLinksInJson());
assertNotNull(projectProv.getLinksInJson());
}
@Test
public void testGetLinksInJson() {
assertFalse("List of links is not empty",projectProv.getLinksInJson().isEmpty());
}
}
| b4364dc6726a26b0ac252bc7e72cfffc7e5d7482 | [
"Markdown",
"Java",
"JavaScript"
] | 13 | Java | kdimolikas/WebParmenidianTruth | 5af6174287f48663e3b7156fe90a3beeb61b783a | b801366a9cd255bcab3f890010a67ca9b31588b0 |
refs/heads/master | <file_sep>namespace Book_Store
{
//
// Filename: Login.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for Login.
/// </summary>
public partial class Login : System.Web.UI.Page
{
//Login CustomIncludes begin
protected CCUtility Utility;
//Login form Login variables and controls declarations
protected System.Web.UI.HtmlControls.HtmlInputHidden Login_querystring;
protected System.Web.UI.HtmlControls.HtmlInputHidden Login_ret_page;
// For each Login form hiddens for PK's,List of Values and Actions
protected string Login_FormAction="ShoppingCart.aspx?";
public Login()
{
this.Init += new System.EventHandler(Page_Init);
}
// Login CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// Login Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// Login Open Event begin
// Login Open Event end
//===============================
//===============================
// Login OpenAnyPage Event begin
// Login OpenAnyPage Event end
//===============================
//
//===============================
// Login PageSecurity begin
// Login PageSecurity end
//===============================
if (Session["UserID"] != null && Int16.Parse(Session["UserID"].ToString()) > 0)
Login_logged = true;
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Login_login.Click += new System.EventHandler (this.Login_login_Click);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Login_Show();
}
// Login Show end
/*===============================
Display Login Form
-------------------------------*/
protected bool Login_logged = false;
void Login_Show() {
// Login Show begin
// Login Open Event begin
// Login Open Event end
// Login BeforeShow Event begin
// Login BeforeShow Event end
if (Login_logged) {
// User logged in
Login_login.Text = "Logout";
Login_trpassword.Visible = false;
Login_trname.Visible = false;
Login_labelname.Visible = true;
Login_labelname.Text = Utility.Dlookup("members", "member_login", "member_id=" + Session["UserID"]) + " ";
} else {
// User is not logged in
Login_login.Text = "Login";
Login_trpassword.Visible = true;
Login_trname.Visible = true;
Login_labelname.Visible = false;
}
// Login Close Event begin
// Login Close Event end
// Login Show end
}
void Login_login_Click(Object Src, EventArgs E) {
if (Login_logged) {
// Login Logout begin
// Login OnLogout Event begin
// Login OnLogout Event end
Login_logged = false;
Session["UserID"] = 0;
Session["UserRights"] = 0;
Login_Show();
// Login Logout end
} else {
// Login Login begin
int iPassed = Convert.ToInt32(Utility.Dlookup("members", "count(*)", "member_login ='" + Login_name.Text + "' and member_password='" + CCUtility.Quote(Login_password.Text) + "'"));
if (iPassed > 0) {
// Login OnLogin Event begin
// Login OnLogin Event end
Login_message.Visible = false;
Session["UserID"] = Convert.ToInt32(Utility.Dlookup("members", "member_id", "member_login ='" + Login_name.Text + "' and member_password='" + CCUtility.Quote(Login_password.Text) +"'"));
Login_logged = true;
Session["UserRights"] = Convert.ToInt32(Utility.Dlookup("members", "member_level", "member_login ='" + Login_name.Text + "' and member_password='" + CCUtility.Quote(Login_password.Text) + "'"));
string sQueryString = Utility.GetParam("querystring");
string sPage = Utility.GetParam("ret_page");
if (! sPage.Equals(Request.ServerVariables["SCRIPT_NAME"]) && sPage.Length > 0) {
Response.Redirect(sPage + "?" + sQueryString);
} else {
Response.Redirect(Login_FormAction);
}
} else {
Login_message.Visible = true;
}
// Login Login end
}
}
// End of Login form
}
}<file_sep># Bookstore.Net
* Author: <NAME>
* Updated: 29 Sept 2018
This project is downloaded from Checkmarx knowledge center [[2]], and the repository includes several branches to illustrate incremental scanning with Checkmarx CxSAST.
***
## Git repository branch
- [Master](tree/master)
Original version
- [Fix_1](tree/Fix_1)
Version with some XSS vulnerabilities resolved
- [Fix_2](tree/Fix_2)
Version with XSS and SQLi vulnerabilities resolved
## Pre-requsites
- CxSAST 8.9: port 80
- Java 1.8
- Chrome browser
## Lab Objectives
1. Create first project interfacing with GIT SCM using source pulling
2. Execute incremental scan with a GIT branch
3. Compare scans
4. Experience incremental scan fail due to exceeding threshold.
## References
CxSAST Quick Start [[1]]
BookStore_NET [[2]]
[1]:https://checkmarx.atlassian.net/wiki/spaces/KC/pages/1170279316/CxSAST+Quick+Start "CxSAST Quick Start"
[2]:http://download.checkmarx.com/CXPS/SourceSamples/BookStore_NET.zip "Bookstore.Net"
<file_sep>namespace Book_Store
{
//
// Filename: CardTypesGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for CardTypesGrid.
/// </summary>
public partial class CardTypesGrid : System.Web.UI.Page
{
//CardTypesGrid CustomIncludes begin
protected CCUtility Utility;
//Grid form CardTypes variables and controls declarations
protected string CardTypes_sSQL;
protected string CardTypes_sCountSQL;
protected int CardTypes_CountPage;
protected int i_CardTypes_curpage=1;
// For each CardTypes form hiddens for PK's,List of Values and Actions
protected string CardTypes_FormAction="CardTypesRecord.aspx?";
public CardTypesGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// CardTypesGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// CardTypesGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// CardTypesGrid Open Event begin
// CardTypesGrid Open Event end
//===============================
//===============================
// CardTypesGrid OpenAnyPage Event begin
// CardTypesGrid OpenAnyPage Event end
//===============================
//
//===============================
// CardTypesGrid PageSecurity begin
Utility.CheckSecurity(2);
// CardTypesGrid PageSecurity end
//===============================
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
CardTypes_insert.Click += new System.EventHandler (this.CardTypes_insert_Click);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
CardTypes_Bind();
}
// CardTypesGrid Show end
// End of Login form
const int CardTypes_PAGENUM = 20;
public void CardTypes_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// CardTypes Show Event begin
// CardTypes Show Event end
}
ICollection CardTypes_CreateDataSource() {
// CardTypes Show begin
CardTypes_sSQL = "";
CardTypes_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by c.name Asc";
if(Utility.GetParam("FormCardTypes_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("FormCardTypes_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
//-------------------------------
// Build base SQL statement
//-------------------------------
CardTypes_sSQL = "select [c].[card_type_id] as c_card_type_id, " +
"[c].[name] as c_name " +
" from [card_types] c ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
CardTypes_sSQL = CardTypes_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(CardTypes_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, CardTypes_PAGENUM, "CardTypes");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
CardTypes_no_records.Visible = true;
}
else
{CardTypes_no_records.Visible = false;
}
return Source;
// CardTypes Show end
}
void CardTypes_Bind() {
CardTypes_Repeater.DataSource = CardTypes_CreateDataSource();
CardTypes_Repeater.DataBind();
}
void CardTypes_insert_Click(Object Src, EventArgs E) {
string sURL = CardTypes_FormAction+"";
Response.Redirect(sURL);
}
protected void CardTypes_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
CardTypes_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: MembersGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for MembersGrid.
/// </summary>
public partial class MembersGrid : System.Web.UI.Page
{
//MembersGrid CustomIncludes begin
protected CCUtility Utility;
//Search form Search variables and controls declarations
//Grid form Members variables and controls declarations
protected string Members_sSQL;
protected string Members_sCountSQL;
protected int Members_CountPage;
//protected System.Web.UI.WebControls.LinkButton Members_insert;
protected int i_Members_curpage=1;
// For each Search form hiddens for PK's,List of Values and Actions
protected string Search_FormAction="MembersGrid.aspx?";
// For each Members form hiddens for PK's,List of Values and Actions
protected string Members_FormAction="MembersRecord.aspx?";
protected String[] Members_member_level_lov = "1;Member;2;Administrator".Split(new Char[] {';'});
public MembersGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// MembersGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// MembersGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// MembersGrid Open Event begin
// MembersGrid Open Event end
//===============================
//===============================
// MembersGrid OpenAnyPage Event begin
// MembersGrid OpenAnyPage Event end
//===============================
//
//===============================
// MembersGrid PageSecurity begin
Utility.CheckSecurity(2);
// MembersGrid PageSecurity end
//===============================
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Search_search_button.Click += new System.EventHandler (this.Search_search_Click);
Members_insert.Click += new System.EventHandler (this.Members_insert_Click);
Members_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.Members_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Search_Show();
Members_Bind();
}
// MembersGrid Show end
// End of Login form
void Search_Show() {
// Search Open Event begin
// Search Open Event end
// Search Show begin
string s;
s=Utility.GetParam("name");
Search_name.Text = s;
// Search Show Event begin
// Search Show Event end
// Search Show end
// Search Close Event begin
// Search Close Event end
}
void Search_search_Click(Object Src, EventArgs E) {
string sURL = Search_FormAction + "name="+Search_name.Text+"&"
;
// Transit
sURL += "";
Response.Redirect(sURL);
}
// End of Login form
const int Members_PAGENUM = 20;
public void Members_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Members Show Event begin
// Members Show Event end
}
ICollection Members_CreateDataSource() {
// Members Show begin
Members_sSQL = "";
Members_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by m.member_login Asc";
if(Utility.GetParam("FormMembers_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("FormMembers_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
//-------------------------------
// Build WHERE statement
//-------------------------------
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
if(!Params.ContainsKey("name")){
string temp=Utility.GetParam("name");
Params.Add("name",temp);}
if(!Params.ContainsKey("name")){
string temp=Utility.GetParam("name");
Params.Add("name",temp);}
if(!Params.ContainsKey("name")){
string temp=Utility.GetParam("name");
Params.Add("name",temp);}
if (Params["name"].Length>0) {
HasParam = true;
sWhere = "m.[member_login] like '%" + Params["name"].Replace( "'", "''") + "%'" + " or " + "m.[first_name] like '%" + Params["name"].Replace( "'", "''") + "%'" + " or " + "m.[last_name] like '%" + Params["name"].Replace( "'", "''") + "%'";
}
if(HasParam)
sWhere = " WHERE (" + sWhere + ")";
//-------------------------------
// Build base SQL statement
//-------------------------------
Members_sSQL = "select [m].[first_name] as m_first_name, " +
"[m].[last_name] as m_last_name, " +
"[m].[member_id] as m_member_id, " +
"[m].[member_level] as m_member_level, " +
"[m].[member_login] as m_member_login " +
" from [members] m ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Members_sSQL = Members_sSQL + sWhere + sOrder;
if (Members_sCountSQL.Length== 0) {
int iTmpI = Members_sSQL.ToLower().IndexOf("select ");
int iTmpJ = Members_sSQL.ToLower().LastIndexOf(" from ")-1;
Members_sCountSQL = Members_sSQL.Replace(Members_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = Members_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) Members_sCountSQL = Members_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Members_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_Members_curpage - 1) * Members_PAGENUM, Members_PAGENUM,"Members");
OleDbCommand ccommand = new OleDbCommand(Members_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
Members_Pager.MaxPage=(PageTemp%Members_PAGENUM)>0?(int)(PageTemp/Members_PAGENUM)+1:(int)(PageTemp/Members_PAGENUM);
bool AllowScroller=Members_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Members_no_records.Visible = true;
AllowScroller=false;}
else
{Members_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
Members_Pager.Visible=AllowScroller;
return Source;
// Members Show end
}
protected void Members_pager_navigate_completed(Object Src, int CurrPage)
{
i_Members_curpage=CurrPage;
// Members CustomNavigation Event begin
// Members CustomNavigation Event end
Members_Bind();
}
void Members_Bind() {
Members_Repeater.DataSource = Members_CreateDataSource();
Members_Repeater.DataBind();
}
void Members_insert_Click(Object Src, EventArgs E) {
string sURL = Members_FormAction+"name=" + Server.UrlEncode(Utility.GetParam("name")) + "&";
Response.Redirect(sURL);
}
protected void Members_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
Members_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: EditorialsGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for EditorialsGrid.
/// </summary>
public partial class EditorialsGrid : System.Web.UI.Page
{
//EditorialsGrid CustomIncludes begin
protected CCUtility Utility;
//Grid form editorials variables and controls declarations
protected string editorials_sSQL;
protected string editorials_sCountSQL;
protected int editorials_CountPage;
//protected System.Web.UI.WebControls.LinkButton editorials_insert;
protected int i_editorials_curpage=1;
// For each editorials form hiddens for PK's,List of Values and Actions
protected string editorials_FormAction="EditorialsRecord.aspx?";
public EditorialsGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// EditorialsGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// EditorialsGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// EditorialsGrid Open Event begin
// EditorialsGrid Open Event end
//===============================
//===============================
// EditorialsGrid OpenAnyPage Event begin
// EditorialsGrid OpenAnyPage Event end
//===============================
//
//===============================
// EditorialsGrid PageSecurity begin
Utility.CheckSecurity(2);
// EditorialsGrid PageSecurity end
//===============================
if (!IsPostBack){
p_editorials_article_id.Value = Utility.GetParam("article_id");Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
editorials_insert.Click += new System.EventHandler (this.editorials_insert_Click);
editorials_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.editorials_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
editorials_Bind();
}
// EditorialsGrid Show end
// End of Login form
const int editorials_PAGENUM = 20;
public void editorials_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// editorials Show Event begin
// editorials Show Event end
}
ICollection editorials_CreateDataSource() {
// editorials Show begin
editorials_sSQL = "";
editorials_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by e.article_title Asc";
if(Utility.GetParam("Formeditorials_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("Formeditorials_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
//-------------------------------
// Build base SQL statement
//-------------------------------
editorials_sSQL = "select [e].[article_id] as e_article_id, " +
"[e].[article_title] as e_article_title, " +
"[e].[editorial_cat_id] as e_editorial_cat_id, " +
"[e].[item_id] as e_item_id, " +
"[e1].[editorial_cat_id] as e1_editorial_cat_id, " +
"[e1].[editorial_cat_name] as e1_editorial_cat_name, " +
"[i].[item_id] as i_item_id, " +
"[i].[name] as i_name " +
" from [editorials] e, [editorial_categories] e1, [items] i" +
" where [e1].[editorial_cat_id]=e.[editorial_cat_id] and [i].[item_id]=e.[item_id] ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
editorials_sSQL = editorials_sSQL + sWhere + sOrder;
if (editorials_sCountSQL.Length== 0) {
int iTmpI = editorials_sSQL.ToLower().IndexOf("select ");
int iTmpJ = editorials_sSQL.ToLower().LastIndexOf(" from ")-1;
editorials_sCountSQL = editorials_sSQL.Replace(editorials_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = editorials_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) editorials_sCountSQL = editorials_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(editorials_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_editorials_curpage - 1) * editorials_PAGENUM, editorials_PAGENUM,"editorials");
OleDbCommand ccommand = new OleDbCommand(editorials_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
editorials_Pager.MaxPage=(PageTemp%editorials_PAGENUM)>0?(int)(PageTemp/editorials_PAGENUM)+1:(int)(PageTemp/editorials_PAGENUM);
bool AllowScroller=editorials_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
editorials_no_records.Visible = true;
AllowScroller=false;}
else
{editorials_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
editorials_Pager.Visible=AllowScroller;
return Source;
// editorials Show end
}
protected void editorials_pager_navigate_completed(Object Src, int CurrPage)
{
i_editorials_curpage=CurrPage;
// editorials CustomNavigation Event begin
// editorials CustomNavigation Event end
editorials_Bind();
}
void editorials_Bind() {
editorials_Repeater.DataSource = editorials_CreateDataSource();
editorials_Repeater.DataBind();
}
void editorials_insert_Click(Object Src, EventArgs E) {
string sURL = editorials_FormAction+"";
Response.Redirect(sURL);
}
protected void editorials_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
editorials_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: OrdersGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for OrdersGrid.
/// </summary>
public partial class OrdersGrid : System.Web.UI.Page
{
//OrdersGrid CustomIncludes begin
protected CCUtility Utility;
//Search form Search variables and controls declarations
//Grid form Orders variables and controls declarations
protected string Orders_sSQL;
protected string Orders_sCountSQL;
protected int Orders_CountPage;
//protected System.Web.UI.WebControls.LinkButton Orders_insert;
protected int i_Orders_curpage=1;
// For each Search form hiddens for PK's,List of Values and Actions
protected string Search_FormAction="OrdersGrid.aspx?";
// For each Orders form hiddens for PK's,List of Values and Actions
protected string Orders_FormAction="OrdersRecord.aspx?";
public OrdersGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// OrdersGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// OrdersGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// OrdersGrid Open Event begin
// OrdersGrid Open Event end
//===============================
//===============================
// OrdersGrid OpenAnyPage Event begin
// OrdersGrid OpenAnyPage Event end
//===============================
//
//===============================
// OrdersGrid PageSecurity begin
Utility.CheckSecurity(2);
// OrdersGrid PageSecurity end
//===============================
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Search_search_button.Click += new System.EventHandler (this.Search_search_Click);
Orders_insert.Click += new System.EventHandler (this.Orders_insert_Click);
Orders_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.Orders_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Search_Show();
Orders_Bind();
}
// OrdersGrid Show end
// End of Login form
void Search_Show() {
// Search Open Event begin
// Search Open Event end
// Search Show begin
Utility.buildListBox(Search_item_id.Items,"select item_id,name from items order by 2","item_id","name","All","");
Utility.buildListBox(Search_member_id.Items,"select member_id,member_login from members order by 2","member_id","member_login","All","");
string s;
s=Utility.GetParam("item_id");
try {Search_item_id.SelectedIndex=Search_item_id.Items.IndexOf(Search_item_id.Items.FindByValue(s));
}catch{}
s=Utility.GetParam("member_id");
try {Search_member_id.SelectedIndex=Search_member_id.Items.IndexOf(Search_member_id.Items.FindByValue(s));
}catch{}
// Search Show Event begin
// Search Show Event end
// Search Show end
// Search Close Event begin
// Search Close Event end
}
void Search_search_Click(Object Src, EventArgs E) {
string sURL = Search_FormAction + "item_id="+Search_item_id.SelectedItem.Value+"&"
+ "member_id="+Search_member_id.SelectedItem.Value+"&"
;
// Transit
sURL += "";
Response.Redirect(sURL);
}
// End of Login form
const int Orders_PAGENUM = 20;
public void Orders_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Orders Show Event begin
// Orders Show Event end
}
ICollection Orders_CreateDataSource() {
// Orders Show begin
Orders_sSQL = "";
Orders_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by o.order_id Asc";
if(Utility.GetParam("FormOrders_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("FormOrders_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
//-------------------------------
// Build WHERE statement
//-------------------------------
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
if(!Params.ContainsKey("item_id")){
string temp=Utility.GetParam("item_id");
if (Utility.IsNumeric(null,temp) && temp.Length>0) { temp = CCUtility.ToSQL(temp, FieldTypes.Number);} else {temp = "";}
Params.Add("item_id",temp);}
if(!Params.ContainsKey("member_id")){
string temp=Utility.GetParam("member_id");
if (Utility.IsNumeric(null,temp) && temp.Length>0) { temp = CCUtility.ToSQL(temp, FieldTypes.Number);} else {temp = "";}
Params.Add("member_id",temp);}
if (Params["item_id"].Length>0) {
HasParam = true;
sWhere +="o.[item_id]=" + Params["item_id"];
}
if (Params["member_id"].Length>0) {
if (sWhere.Length >0) sWhere +=" and ";
HasParam = true;
sWhere +="o.[member_id]=" + Params["member_id"];
}
if(HasParam)
sWhere = " AND (" + sWhere + ")";
//-------------------------------
// Build base SQL statement
//-------------------------------
Orders_sSQL = "select [o].[item_id] as o_item_id, " +
"[o].[member_id] as o_member_id, " +
"[o].[order_id] as o_order_id, " +
"[o].[quantity] as o_quantity, " +
"[i].[item_id] as i_item_id, " +
"[i].[name] as i_name, " +
"[m].[member_id] as m_member_id, " +
"[m].[member_login] as m_member_login " +
" from [orders] o, [items] i, [members] m" +
" where [i].[item_id]=o.[item_id] and [m].[member_id]=o.[member_id] ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Orders_sSQL = Orders_sSQL + sWhere + sOrder;
if (Orders_sCountSQL.Length== 0) {
int iTmpI = Orders_sSQL.ToLower().IndexOf("select ");
int iTmpJ = Orders_sSQL.ToLower().LastIndexOf(" from ")-1;
Orders_sCountSQL = Orders_sSQL.Replace(Orders_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = Orders_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) Orders_sCountSQL = Orders_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Orders_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_Orders_curpage - 1) * Orders_PAGENUM, Orders_PAGENUM,"Orders");
OleDbCommand ccommand = new OleDbCommand(Orders_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
Orders_Pager.MaxPage=(PageTemp%Orders_PAGENUM)>0?(int)(PageTemp/Orders_PAGENUM)+1:(int)(PageTemp/Orders_PAGENUM);
bool AllowScroller=Orders_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Orders_no_records.Visible = true;
AllowScroller=false;}
else
{Orders_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
Orders_Pager.Visible=AllowScroller;
return Source;
// Orders Show end
}
protected void Orders_pager_navigate_completed(Object Src, int CurrPage)
{
i_Orders_curpage=CurrPage;
// Orders CustomNavigation Event begin
// Orders CustomNavigation Event end
Orders_Bind();
}
void Orders_Bind() {
Orders_Repeater.DataSource = Orders_CreateDataSource();
Orders_Repeater.DataBind();
}
void Orders_insert_Click(Object Src, EventArgs E) {
string sURL = Orders_FormAction+"item_id=" + Server.UrlEncode(Utility.GetParam("item_id")) + "&member_id=" + Server.UrlEncode(Utility.GetParam("member_id")) + "&";
Response.Redirect(sURL);
}
protected void Orders_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
Orders_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: EditorialCatGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for EditorialCatGrid.
/// </summary>
public partial class EditorialCatGrid : System.Web.UI.Page
{
//EditorialCatGrid CustomIncludes begin
protected CCUtility Utility;
//Grid form editorial_categories variables and controls declarations
protected string editorial_categories_sSQL;
protected string editorial_categories_sCountSQL;
protected int editorial_categories_CountPage;
//protected System.Web.UI.WebControls.LinkButton editorial_categories_insert;
protected int i_editorial_categories_curpage=1;
// For each editorial_categories form hiddens for PK's,List of Values and Actions
protected string editorial_categories_FormAction="EditorialCatRecord.aspx?";
public EditorialCatGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// EditorialCatGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// EditorialCatGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// EditorialCatGrid Open Event begin
// EditorialCatGrid Open Event end
//===============================
//===============================
// EditorialCatGrid OpenAnyPage Event begin
// EditorialCatGrid OpenAnyPage Event end
//===============================
//
//===============================
// EditorialCatGrid PageSecurity begin
Utility.CheckSecurity(2);
// EditorialCatGrid PageSecurity end
//===============================
if (!IsPostBack){
p_editorial_categories_editorial_cat_id.Value = Utility.GetParam("editorial_cat_id");Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
editorial_categories_insert.Click += new System.EventHandler (this.editorial_categories_insert_Click);
editorial_categories_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.editorial_categories_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
editorial_categories_Bind();
}
// EditorialCatGrid Show end
// End of Login form
const int editorial_categories_PAGENUM = 20;
public void editorial_categories_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// editorial_categories Show Event begin
// editorial_categories Show Event end
}
ICollection editorial_categories_CreateDataSource() {
// editorial_categories Show begin
editorial_categories_sSQL = "";
editorial_categories_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by e.editorial_cat_name Asc";
if(Utility.GetParam("Formeditorial_categories_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("Formeditorial_categories_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
//-------------------------------
// Build base SQL statement
//-------------------------------
editorial_categories_sSQL = "select [e].[editorial_cat_id] as e_editorial_cat_id, " +
"[e].[editorial_cat_name] as e_editorial_cat_name " +
" from [editorial_categories] e ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
editorial_categories_sSQL = editorial_categories_sSQL + sWhere + sOrder;
if (editorial_categories_sCountSQL.Length== 0) {
int iTmpI = editorial_categories_sSQL.ToLower().IndexOf("select ");
int iTmpJ = editorial_categories_sSQL.ToLower().LastIndexOf(" from ")-1;
editorial_categories_sCountSQL = editorial_categories_sSQL.Replace(editorial_categories_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = editorial_categories_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) editorial_categories_sCountSQL = editorial_categories_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(editorial_categories_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_editorial_categories_curpage - 1) * editorial_categories_PAGENUM, editorial_categories_PAGENUM,"editorial_categories");
OleDbCommand ccommand = new OleDbCommand(editorial_categories_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
editorial_categories_Pager.MaxPage=(PageTemp%editorial_categories_PAGENUM)>0?(int)(PageTemp/editorial_categories_PAGENUM)+1:(int)(PageTemp/editorial_categories_PAGENUM);
bool AllowScroller=editorial_categories_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
editorial_categories_no_records.Visible = true;
AllowScroller=false;}
else
{editorial_categories_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
editorial_categories_Pager.Visible=AllowScroller;
return Source;
// editorial_categories Show end
}
protected void editorial_categories_pager_navigate_completed(Object Src, int CurrPage)
{
i_editorial_categories_curpage=CurrPage;
// editorial_categories CustomNavigation Event begin
// editorial_categories CustomNavigation Event end
editorial_categories_Bind();
}
void editorial_categories_Bind() {
editorial_categories_Repeater.DataSource = editorial_categories_CreateDataSource();
editorial_categories_Repeater.DataBind();
}
void editorial_categories_insert_Click(Object Src, EventArgs E) {
string sURL = editorial_categories_FormAction+"";
Response.Redirect(sURL);
}
protected void editorial_categories_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
editorial_categories_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: Default.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for Default.
/// </summary>
public partial class Default : System.Web.UI.Page
{
//Default CustomIncludes begin
protected CCUtility Utility;
//Search form Search variables and controls declarations
//Grid form Recommended variables and controls declarations
protected string Recommended_sSQL;
protected string Recommended_sCountSQL;
protected int Recommended_CountPage;
protected int i_Recommended_curpage=1;
//Grid form What variables and controls declarations
protected string What_sSQL;
protected string What_sCountSQL;
protected int What_CountPage;
protected int i_What_curpage=1;
//Grid form Categories variables and controls declarations
protected string Categories_sSQL;
protected string Categories_sCountSQL;
protected int Categories_CountPage;
protected int i_Categories_curpage=1;
//Grid form New variables and controls declarations
protected string New_sSQL;
protected string New_sCountSQL;
protected int New_CountPage;
protected int i_New_curpage=1;
//Grid form Weekly variables and controls declarations
protected string Weekly_sSQL;
protected string Weekly_sCountSQL;
protected int Weekly_CountPage;
protected int i_Weekly_curpage=1;
//Grid form Specials variables and controls declarations
protected string Specials_sSQL;
protected string Specials_sCountSQL;
protected int Specials_CountPage;
protected int i_Specials_curpage=1;
// For each Search form hiddens for PK's,List of Values and Actions
protected string Search_FormAction="Books.aspx?";
// For each AdvMenu form hiddens for PK's,List of Values and Actions
protected string AdvMenu_FormAction=".aspx?";
// For each Recommended form hiddens for PK's,List of Values and Actions
protected string Recommended_FormAction=".aspx?";
// For each What form hiddens for PK's,List of Values and Actions
protected string What_FormAction=".aspx?";
// For each Categories form hiddens for PK's,List of Values and Actions
protected string Categories_FormAction=".aspx?";
// For each New form hiddens for PK's,List of Values and Actions
protected string New_FormAction=".aspx?";
// For each Weekly form hiddens for PK's,List of Values and Actions
protected string Weekly_FormAction=".aspx?";
// For each Specials form hiddens for PK's,List of Values and Actions
protected string Specials_FormAction=".aspx?";
public Default()
{
this.Init += new System.EventHandler(Page_Init);
}
// Default CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// Default Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// Default Open Event begin
// Default Open Event end
//===============================
//===============================
// Default OpenAnyPage Event begin
// Default OpenAnyPage Event end
//===============================
//
//===============================
// Default PageSecurity begin
// Default PageSecurity end
//===============================
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Search_search_button.Click += new System.EventHandler (this.Search_search_Click);
Recommended_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.Recommended_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Search_Show();
AdvMenu_Show();
Recommended_Bind();
What_Bind();
Categories_Bind();
New_Bind();
Weekly_Bind();
Specials_Bind();
}
// Default Show end
// End of Login form
void Search_Show() {
// Search Open Event begin
// Search Open Event end
// Search Show begin
Utility.buildListBox(Search_category_id.Items,"select category_id,name from categories order by 2","category_id","name","All","");
string s;
s=Utility.GetParam("category_id");
try {Search_category_id.SelectedIndex=Search_category_id.Items.IndexOf(Search_category_id.Items.FindByValue(s));
}catch{}
s=Utility.GetParam("name");
Search_name.Text = s;
// Search Show Event begin
// Search Show Event end
// Search Show end
// Search Close Event begin
// Search Close Event end
}
void Search_search_Click(Object Src, EventArgs E) {
string sURL = Search_FormAction + "category_id="+Search_category_id.SelectedItem.Value+"&"
+ "name="+Search_name.Text+"&"
;
// Transit
sURL += "";
Response.Redirect(sURL);
}
// End of Login form
protected void AdvMenu_Show(){
// AdvMenu Open Event begin
// AdvMenu Open Event end
// AdvMenu Show begin
// AdvMenu BeforeShow Event begin
// AdvMenu BeforeShow Event end
// AdvMenu Show end
}
// End of Login form
const int Recommended_PAGENUM = 5;
public void Recommended_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Recommended Show Event begin
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((HyperLink)e.Item.FindControl("Recommended_name")).Text ="<img border=\"0\" src=\"" + ((DataRowView)e.Item.DataItem )["i_image_url"].ToString() + "\"></td><td valign=\"top\"><table width=\"100%\" style=\"width:100%\"><tr><td style=\"background-color: #FFFFFF; border-style: inset; border-width: 0\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\"><b>" + ((DataRowView)e.Item.DataItem )["i_name"].ToString() + "</b>";
}
// Recommended Show Event end
}
ICollection Recommended_CreateDataSource() {
// Recommended Show begin
Recommended_sSQL = "";
Recommended_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
sWhere = " WHERE is_recommended=1";
//-------------------------------
// Build base SQL statement
//-------------------------------
Recommended_sSQL = "select [i].[author] as i_author, " +
"[i].[image_url] as i_image_url, " +
"[i].[item_id] as i_item_id, " +
"[i].[name] as i_name, " +
"[i].[price] as i_price " +
" from [items] i ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Recommended_sSQL = Recommended_sSQL + sWhere + sOrder;
if (Recommended_sCountSQL.Length== 0) {
int iTmpI = Recommended_sSQL.ToLower().IndexOf("select ");
int iTmpJ = Recommended_sSQL.ToLower().LastIndexOf(" from ")-1;
Recommended_sCountSQL = Recommended_sSQL.Replace(Recommended_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = Recommended_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) Recommended_sCountSQL = Recommended_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Recommended_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_Recommended_curpage - 1) * Recommended_PAGENUM, Recommended_PAGENUM,"Recommended");
OleDbCommand ccommand = new OleDbCommand(Recommended_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
Recommended_Pager.MaxPage=(PageTemp%Recommended_PAGENUM)>0?(int)(PageTemp/Recommended_PAGENUM)+1:(int)(PageTemp/Recommended_PAGENUM);
bool AllowScroller=Recommended_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Recommended_no_records.Visible = true;
AllowScroller=false;}
else
{Recommended_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
Recommended_Pager.Visible=AllowScroller;
return Source;
// Recommended Show end
}
protected void Recommended_pager_navigate_completed(Object Src, int CurrPage)
{
i_Recommended_curpage=CurrPage;
// Recommended CustomNavigation Event begin
// Recommended CustomNavigation Event end
Recommended_Bind();
}
void Recommended_Bind() {
Recommended_Repeater.DataSource = Recommended_CreateDataSource();
Recommended_Repeater.DataBind();
}
// End of Login form
const int What_PAGENUM = 20;
public void What_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// What Show Event begin
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((HyperLink)e.Item.FindControl("What_article_title")).Text ="<b>"+((DataRowView)e.Item.DataItem )["e_article_title"].ToString()+"<b>";
((Label)e.Item.FindControl("What_article_desc")).Text="<img align=\"left\" border=\"0\" src=\"" + Utility.Dlookup("items","image_url","item_id=" + ((DataRowView)e.Item.DataItem )["e_item_id"].ToString()) + "\">" + ((DataRowView)e.Item.DataItem )["e_article_desc"].ToString();
}
// What Show Event end
}
ICollection What_CreateDataSource() {
// What Show begin
What_sSQL = "";
What_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
sWhere = " WHERE editorial_cat_id=1";
//-------------------------------
// Build base SQL statement
//-------------------------------
What_sSQL = "select [e].[article_desc] as e_article_desc, " +
"[e].[article_title] as e_article_title, " +
"[e].[item_id] as e_item_id " +
" from [editorials] e ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
What_sSQL = What_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(What_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, What_PAGENUM, "What");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
What_no_records.Visible = true;
}
else
{What_no_records.Visible = false;
}
return Source;
// What Show end
}
void What_Bind() {
What_Repeater.DataSource = What_CreateDataSource();
What_Repeater.DataBind();
}
// End of Login form
const int Categories_PAGENUM = 20;
public void Categories_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Categories Show Event begin
// Categories Show Event end
}
ICollection Categories_CreateDataSource() {
// Categories Show begin
Categories_sSQL = "";
Categories_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
//-------------------------------
// Build base SQL statement
//-------------------------------
Categories_sSQL = "select [c].[category_id] as c_category_id, " +
"[c].[name] as c_name " +
" from [categories] c ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Categories_sSQL = Categories_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Categories_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, Categories_PAGENUM, "Categories");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Categories_no_records.Visible = true;
}
else
{Categories_no_records.Visible = false;
}
return Source;
// Categories Show end
}
void Categories_Bind() {
Categories_Repeater.DataSource = Categories_CreateDataSource();
Categories_Repeater.DataBind();
}
// End of Login form
const int New_PAGENUM = 20;
public void New_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// New Show Event begin
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((HyperLink)e.Item.FindControl("New_article_title")).Text ="<b>"+((DataRowView)e.Item.DataItem )["e_article_title"].ToString()+"<b>";
((Label)e.Item.FindControl("New_article_desc")).Text="<img align=\"left\" border=\"0\" src=\"" + Utility.Dlookup("items","image_url","item_id=" + ((DataRowView)e.Item.DataItem )["e_item_id"].ToString()) + "\">" + ((DataRowView)e.Item.DataItem )["e_article_desc"].ToString();
}
// New Show Event end
}
ICollection New_CreateDataSource() {
// New Show begin
New_sSQL = "";
New_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
sWhere = " WHERE editorial_cat_id=2";
//-------------------------------
// Build base SQL statement
//-------------------------------
New_sSQL = "select [e].[article_desc] as e_article_desc, " +
"[e].[article_title] as e_article_title, " +
"[e].[item_id] as e_item_id " +
" from [editorials] e ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
New_sSQL = New_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(New_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, New_PAGENUM, "New");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
New_no_records.Visible = true;
}
else
{New_no_records.Visible = false;
}
return Source;
// New Show end
}
void New_Bind() {
New_Repeater.DataSource = New_CreateDataSource();
New_Repeater.DataBind();
}
// End of Login form
const int Weekly_PAGENUM = 20;
public void Weekly_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Weekly Show Event begin
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((HyperLink)e.Item.FindControl("Weekly_article_title")).Text ="<b>"+((DataRowView)e.Item.DataItem )["e_article_title"].ToString()+"<b>";
((Label)e.Item.FindControl("Weekly_article_desc")).Text="<img align=\"left\" border=\"0\" src=\"" + Utility.Dlookup("items","image_url","item_id=" + ((DataRowView)e.Item.DataItem )["e_item_id"].ToString()) + "\">" + ((DataRowView)e.Item.DataItem )["e_article_desc"].ToString();
}
// Weekly Show Event end
}
ICollection Weekly_CreateDataSource() {
// Weekly Show begin
Weekly_sSQL = "";
Weekly_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
sWhere = " WHERE editorial_cat_id=3";
//-------------------------------
// Build base SQL statement
//-------------------------------
Weekly_sSQL = "select [e].[article_desc] as e_article_desc, " +
"[e].[article_title] as e_article_title, " +
"[e].[item_id] as e_item_id " +
" from [editorials] e ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Weekly_sSQL = Weekly_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Weekly_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, Weekly_PAGENUM, "Weekly");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Weekly_no_records.Visible = true;
}
else
{Weekly_no_records.Visible = false;
}
return Source;
// Weekly Show end
}
void Weekly_Bind() {
Weekly_Repeater.DataSource = Weekly_CreateDataSource();
Weekly_Repeater.DataBind();
}
// End of Login form
const int Specials_PAGENUM = 20;
public void Specials_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Specials Show Event begin
// Specials Show Event end
}
ICollection Specials_CreateDataSource() {
// Specials Show begin
Specials_sSQL = "";
Specials_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
sWhere = " WHERE editorial_cat_id=4";
//-------------------------------
// Build base SQL statement
//-------------------------------
Specials_sSQL = "select [e].[article_desc] as e_article_desc, " +
"[e].[article_title] as e_article_title " +
" from [editorials] e ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Specials_sSQL = Specials_sSQL + sWhere + sOrder;
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Specials_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, 0, Specials_PAGENUM, "Specials");
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Specials_no_records.Visible = true;
}
else
{Specials_no_records.Visible = false;
}
return Source;
// Specials Show end
}
void Specials_Bind() {
Specials_Repeater.DataSource = Specials_CreateDataSource();
Specials_Repeater.DataBind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: CategoriesGrid.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for CategoriesGrid.
/// </summary>
public partial class CategoriesGrid : System.Web.UI.Page
{
//CategoriesGrid CustomIncludes begin
protected CCUtility Utility;
//Grid form Categories variables and controls declarations
protected string Categories_sSQL;
protected string Categories_sCountSQL;
protected int Categories_CountPage;
//protected System.Web.UI.WebControls.LinkButton Categories_insert;
protected int i_Categories_curpage=1;
// For each Categories form hiddens for PK's,List of Values and Actions
protected string Categories_FormAction="CategoriesRecord.aspx?";
public CategoriesGrid()
{
this.Init += new System.EventHandler(Page_Init);
}
// CategoriesGrid CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// CategoriesGrid Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// CategoriesGrid Open Event begin
// CategoriesGrid Open Event end
//===============================
//===============================
// CategoriesGrid OpenAnyPage Event begin
// CategoriesGrid OpenAnyPage Event end
//===============================
//
//===============================
// CategoriesGrid PageSecurity begin
Utility.CheckSecurity(2);
// CategoriesGrid PageSecurity end
//===============================
if (!IsPostBack){
Page_Show(sender, e);
}
}
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Categories_insert.Click += new System.EventHandler (this.Categories_insert_Click);
Categories_Pager.NavigateCompleted+=new NavigateCompletedHandler(this.Categories_pager_navigate_completed);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Categories_Bind();
}
// CategoriesGrid Show end
// End of Login form
const int Categories_PAGENUM = 20;
public void Categories_Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e){
// Categories Show Event begin
// Categories Show Event end
}
ICollection Categories_CreateDataSource() {
// Categories Show begin
Categories_sSQL = "";
Categories_sCountSQL = "";
string sWhere = "", sOrder = "";
bool HasParam = false;
//-------------------------------
// Build ORDER BY statement
//-------------------------------
sOrder = " order by c.name Asc";
if(Utility.GetParam("FormCategories_Sorting").Length>0&&!IsPostBack)
{ViewState["SortColumn"]=Utility.GetParam("FormCategories_Sorting");
ViewState["SortDir"]="ASC";}
if(ViewState["SortColumn"]!=null) sOrder = " ORDER BY " + ViewState["SortColumn"].ToString()+" "+ViewState["SortDir"].ToString();
System.Collections.Specialized.StringDictionary Params =new System.Collections.Specialized.StringDictionary();
//-------------------------------
// Build base SQL statement
//-------------------------------
Categories_sSQL = "select [c].[category_id] as c_category_id, " +
"[c].[name] as c_name " +
" from [categories] c ";
//-------------------------------
//-------------------------------
//-------------------------------
//-------------------------------
// Assemble full SQL statement
//-------------------------------
Categories_sSQL = Categories_sSQL + sWhere + sOrder;
if (Categories_sCountSQL.Length== 0) {
int iTmpI = Categories_sSQL.ToLower().IndexOf("select ");
int iTmpJ = Categories_sSQL.ToLower().LastIndexOf(" from ")-1;
Categories_sCountSQL = Categories_sSQL.Replace(Categories_sSQL.Substring(iTmpI + 7, iTmpJ-6), " count(*) ");
iTmpI = Categories_sCountSQL.ToLower().IndexOf(" order by");
if (iTmpI > 1) Categories_sCountSQL = Categories_sCountSQL.Substring(0, iTmpI);
}
//-------------------------------
OleDbDataAdapter command = new OleDbDataAdapter(Categories_sSQL, Utility.Connection);
DataSet ds = new DataSet();
command.Fill(ds, (i_Categories_curpage - 1) * Categories_PAGENUM, Categories_PAGENUM,"Categories");
OleDbCommand ccommand = new OleDbCommand(Categories_sCountSQL, Utility.Connection);
int PageTemp=(int)ccommand.ExecuteScalar();
Categories_Pager.MaxPage=(PageTemp%Categories_PAGENUM)>0?(int)(PageTemp/Categories_PAGENUM)+1:(int)(PageTemp/Categories_PAGENUM);
bool AllowScroller=Categories_Pager.MaxPage==1?false:true;
DataView Source;
Source = new DataView(ds.Tables[0]);
if (ds.Tables[0].Rows.Count == 0){
Categories_no_records.Visible = true;
AllowScroller=false;}
else
{Categories_no_records.Visible = false;
AllowScroller=AllowScroller&&true;}
Categories_Pager.Visible=AllowScroller;
return Source;
// Categories Show end
}
protected void Categories_pager_navigate_completed(Object Src, int CurrPage)
{
i_Categories_curpage=CurrPage;
// Categories CustomNavigation Event begin
// Categories CustomNavigation Event end
Categories_Bind();
}
void Categories_Bind() {
Categories_Repeater.DataSource = Categories_CreateDataSource();
Categories_Repeater.DataBind();
}
void Categories_insert_Click(Object Src, EventArgs E) {
string sURL = Categories_FormAction+"";
Response.Redirect(sURL);
}
protected void Categories_SortChange(Object Src, EventArgs E) {
if(ViewState["SortColumn"]==null || ViewState["SortColumn"].ToString()!=((LinkButton)Src).CommandArgument){
ViewState["SortColumn"]=((LinkButton)Src).CommandArgument;
ViewState["SortDir"]="ASC";
}else{
ViewState["SortDir"]=ViewState["SortDir"].ToString()=="ASC"?"DESC":"ASC";
}
Categories_Bind();
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: CCUtility.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public class PositionData {
private string name;
private string CatID;
public PositionData(string Name, string CategoryID) {
this.name = Name;
this.CatID = CategoryID;
}
public string Name {
get {
return name;
}
}
public string CategoryID {
get {
return CatID;
}
}
}
public enum FieldTypes{Text,Number,Date,Memo}
public class CCUtility
{
protected HttpSessionState Session;
protected HttpServerUtility Server;
protected HttpRequest Request;
protected HttpResponse Response;
// GlobalFuncs Event begin
// GlobalFuncs Event end
public static string ToSQL(string Param, FieldTypes Type) {
if (Param == null || Param.Length == 0) {
return "Null";
} else {
string str = Quote(Param);
if (Type == FieldTypes.Number) {
return str.Replace(',','.');
} else {
return "\'" + str + "\'";
}
}
}
public CCUtility(object parent){
Session=HttpContext.Current.Session;
Server=HttpContext.Current.Server;
Request=HttpContext.Current.Request;
Response=HttpContext.Current.Response;
DBOpen();
}
public static String GetValFromLOV(String val, String[] arr) {
String ret = "";
if (arr.Length % 2 == 0) {
int temp=Array.IndexOf(arr,val);
ret=temp==-1?"":arr[temp+1];}
return ret;
}
public bool IsNumeric(object source, string value) {
try{
Decimal temp=Convert.ToDecimal(value);
return true;
}catch {
return false;
}
}
public static string Quote(string Param) {
if (Param == null || Param.Length == 0) {
return "";
} else {
return Param.Replace("'","''");
}
}
public static string GetValue(DataRow row, string field) {
if (row[field].ToString() == null)
return "";
else
return row[field].ToString();
}
public OleDbConnection Connection;
public DataSet FillDataSet(string sSQL)
{
DataSet ds = new DataSet();
OleDbDataAdapter command = new OleDbDataAdapter(sSQL, Connection);
return ds;
}
public int FillDataSet(string sSQL,ref DataSet ds)
{
OleDbDataAdapter command = new OleDbDataAdapter(sSQL, Connection);
return command.Fill(ds, "Table");
}
public int FillDataSet(string sSQL,ref DataSet ds,int start, int count)
{
OleDbDataAdapter command = new OleDbDataAdapter(sSQL, Connection);
return command.Fill(ds, start, count, "Table");
}
public void DBOpen()
{
// get Connection string from Config.web
string sConnectionString=System.Configuration.ConfigurationSettings.AppSettings["sBook_StoreDBConnectionString"];
// open DB Connection via OleDb
Connection = new OleDbConnection(sConnectionString);
Connection.Open();
}
public void DBClose(){
Connection.Close();
}
public string GetParam(string ParamName) {
string Param = Request.QueryString[ParamName];
if (Param == null)
Param = Request.Form[ParamName];
if (Param == null)
return "";
else
return Quote(Param);
}
public string Dlookup(string table, string field, string sWhere)
{
string sSQL = "SELECT " + field + " FROM " + table + " WHERE " + sWhere;
OleDbCommand command = new OleDbCommand(sSQL, Connection);
OleDbDataReader reader=command.ExecuteReader(CommandBehavior.SingleRow);
string sReturn;
if (reader.Read()) {
sReturn = reader[0].ToString();
if (sReturn == null)
sReturn = "";
} else {
sReturn = "";
}
reader.Close();
return sReturn;
}
public int DlookupInt(string table, string field, string sWhere)
{
string sSQL = "SELECT " + field + " FROM " + table + " WHERE " + sWhere;
OleDbCommand command = new OleDbCommand(sSQL, Connection);
OleDbDataReader reader=command.ExecuteReader(CommandBehavior.SingleRow);
int iReturn = -1;
if (reader.Read()) {
iReturn = reader.GetInt32(0);
}
reader.Close();
return iReturn;
}
public void Execute(string sSQL){
OleDbCommand cmd = new OleDbCommand(sSQL, Connection);
cmd.ExecuteNonQuery();
}
public void buildListBox(ListItemCollection Items,string sSQL, string sId, string sTitle, string CustomInitialDisplayValue,string CustomInitialSubmitValue)
{
Items.Clear();
OleDbCommand command = new OleDbCommand(sSQL, Connection);
OleDbDataReader reader = command.ExecuteReader();
if(CustomInitialDisplayValue!=null) Items.Add(new ListItem(CustomInitialDisplayValue,CustomInitialSubmitValue));
while(reader.Read()) {
if(sId==""&&sTitle=="") {
Items.Add(new ListItem(reader[1].ToString(),reader[0].ToString()));
}else{
Items.Add(new ListItem(reader[sTitle].ToString(),reader[sId].ToString()));
}
}
reader.Close();
}
public void buildListBox(ListItemCollection Items,string[] values, string CustomInitialDisplayValue,string CustomInitialSubmitValue)
{
Items.Clear();
if(CustomInitialDisplayValue!=null) Items.Add(new ListItem(CustomInitialDisplayValue,CustomInitialSubmitValue));
for(int i=0;i<values.Length;i+=2)Items.Add(new ListItem(values[i+1],values[i]));
}
public ICollection buildListBox(string sSQL, string sId, string sTitle, string CustomInitialDisplayValue,string CustomInitialSubmitValue)
{
DataRow row;
OleDbDataAdapter command = new OleDbDataAdapter(sSQL, Connection);
DataSet ds = new DataSet();
ds.Tables.Add("lookup");
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = sId;
ds.Tables[0].Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = sTitle;
ds.Tables[0].Columns.Add(column);
if (CustomInitialDisplayValue!=null) {
row = ds.Tables[0].NewRow();
row[0] = CustomInitialSubmitValue;
row[1] = CustomInitialDisplayValue;
ds.Tables[0].Rows.Add(row);}
command.Fill(ds, "lookup");
return new DataView(ds.Tables[0]);
}
public static string getCheckBoxValue(string sVal, string CheckedValue, string UnCheckedValue, FieldTypes Type)
{
if (sVal.Length == 0) {
return ToSQL(UnCheckedValue, Type);
} else {
return ToSQL(CheckedValue, Type);
}
}
public void CheckSecurity(int iLevel) {
if (Session["UserID"] == null || Session["UserID"].ToString().Length == 0) {
Response.Redirect("Login.aspx?QueryString=" + Server.UrlEncode(Request.ServerVariables["QUERY_STRING"]) + "&ret_page=" + Server.UrlEncode(Request.ServerVariables["SCRIPT_NAME"]));
} else {
if (Int16.Parse(Session["UserRights"].ToString()) < iLevel)
Response.Redirect("Login.aspx?QueryString=" + Server.UrlEncode(Request.ServerVariables["QUERY_STRING"]) + "&ret_page=" + Server.UrlEncode(Request.ServerVariables["SCRIPT_NAME"])) ;
}
}
}
}<file_sep>namespace Book_Store
{
//
// Filename: BookDetail.cs
// Generated with CodeCharge 2.0.5
// ASP.NET C#.ccp build 03/07/2002
//
//-------------------------------
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for BookDetail.
/// </summary>
public partial class BookDetail : System.Web.UI.Page
{
//BookDetail CustomIncludes begin
protected CCUtility Utility;
//Record form Detail variables and controls declarations
//Record form Order variables and controls declarations
//Record form Rating variables and controls declarations
// For each Detail form hiddens for PK's,List of Values and Actions
protected string Detail_FormAction="ShoppingCart.aspx?";
// For each Order form hiddens for PK's,List of Values and Actions
protected string Order_FormAction="ShoppingCart.aspx?";
// For each Rating form hiddens for PK's,List of Values and Actions
protected string Rating_FormAction="BookDetail.aspx?";
protected String[] Rating_rating_lov = "1;Deficient;2;Regular;3;Good;4;Very Good;5;Excellent".Split(new Char[] {';'});
public BookDetail()
{
this.Init += new System.EventHandler(Page_Init);
}
// BookDetail CustomIncludes end
//-------------------------------
public void ValidateNumeric(object source, ServerValidateEventArgs args) {
try{
Decimal temp=Decimal.Parse(args.Value);
args.IsValid=true;
}catch{
args.IsValid=false; }
}
//===============================
// BookDetail Show begin
protected void Page_Load(object sender, EventArgs e)
{
Utility=new CCUtility(this);
//===============================
// BookDetail Open Event begin
// BookDetail Open Event end
//===============================
//===============================
// BookDetail OpenAnyPage Event begin
// BookDetail OpenAnyPage Event end
//===============================
//
//===============================
// BookDetail PageSecurity begin
Utility.CheckSecurity(1);
// BookDetail PageSecurity end
//===============================
if (!IsPostBack){
p_Detail_item_id.Value = Utility.GetParam("item_id");
p_Order_order_id.Value = Utility.GetParam("order_id");
p_Rating_item_id.Value = Utility.GetParam("item_id");Page_Show(sender, e);
}
}
/// <summary>
/// Page_Unload
/// </summary>
/// <param name="sender">the sender</param>
/// <param name="e">args</param>
protected void Page_Unload(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
if(Utility!=null) Utility.DBClose();
}
protected void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP+ Windows Form Designer.
//
InitializeComponent();
Order_insert.ServerClick += new System.EventHandler (this.Order_Action);
Rating_update.ServerClick += new System.EventHandler (this.Rating_Action);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
protected void Page_Show(object sender, EventArgs e)
{
Detail_Show();
Order_Show();
Rating_Show();
}
// BookDetail Show end
// End of Login form
private bool Detail_Validate(){
bool result=true;
Detail_ValidationSummary.Text="";
for(int i=0;i<Page.Validators.Count;i++){
if(((System.Web.UI.WebControls.BaseValidator)Page.Validators[i]).ID.ToString().StartsWith("Detail")){
if(!Page.Validators[i].IsValid){
Detail_ValidationSummary.Text+=Page.Validators[i].ErrorMessage+"<br>";
result=false;
}
}
}
Detail_ValidationSummary.Visible=(!result);
return result;
}
/*===============================
Display Record Form
-------------------------------*/
void Detail_Show() {
// Detail Show begin
bool ActionInsert=true;
if (p_Detail_item_id.Value.Length > 0 ) {
string sWhere = "";
sWhere += "item_id=" + CCUtility.ToSQL(p_Detail_item_id.Value, FieldTypes.Number);
// Detail Open Event begin
// Detail Open Event end
string sSQL = "select * from items where " + sWhere;
OleDbDataAdapter dsCommand = new OleDbDataAdapter(sSQL, Utility.Connection);
DataSet ds = new DataSet();
DataRow row;
if (dsCommand.Fill(ds, 0, 1, "Detail") > 0) {
row = ds.Tables[0].Rows[0];
Detail_item_id.Value = CCUtility.GetValue(row, "item_id");
Detail_name.Text =Server.HtmlEncode(CCUtility.GetValue(row, "name").ToString());
Detail_author.Text =Server.HtmlEncode(CCUtility.GetValue(row, "author").ToString());
Detail_category_id.Text =Server.HtmlEncode( Utility.Dlookup("categories", "name", "category_id=" + CCUtility.ToSQL(CCUtility.GetValue(row, "category_id"), FieldTypes.Number)).ToString());
Detail_price.Text =Server.HtmlEncode(CCUtility.GetValue(row, "price").ToString());
Detail_image_url.Text =CCUtility.GetValue(row, "image_url");
Detail_image_url.NavigateUrl=CCUtility.GetValue(row, "product_url")+"";
Detail_notes.Text =CCUtility.GetValue(row, "notes");
Detail_product_url.Text =Server.HtmlEncode(CCUtility.GetValue(row, "product_url").ToString());
Detail_product_url.NavigateUrl=CCUtility.GetValue(row, "product_url")+"";
ActionInsert=false;
// Detail ShowEdit Event begin
// Detail ShowEdit Event end
}}
if(ActionInsert){
String pValue;
pValue = Utility.GetParam("item_id");Detail_item_id.Value = pValue;
// Detail ShowInsert Event begin
// Detail ShowInsert Event end
}
// Detail Open Event begin
// Detail Open Event end
// Detail Show Event begin
Detail_image_url.ImageUrl=Detail_image_url.Text;
Detail_product_url.Text="Review this book on Amazon.com";
// Detail Show Event end
// Detail Show end
// Detail Close Event begin
// Detail Close Event end
}
// Detail Action begin
void Detail_BeforeSQLExecute(string SQL,String Action){
// Detail BeforeExecute Event begin
// Detail BeforeExecute Event end
}
// End of Login form
private bool Order_Validate(){
bool result=true;
Order_ValidationSummary.Text="";
for(int i=0;i<Page.Validators.Count;i++){
if(((System.Web.UI.WebControls.BaseValidator)Page.Validators[i]).ID.ToString().StartsWith("Order")){
if(!Page.Validators[i].IsValid){
Order_ValidationSummary.Text+=Page.Validators[i].ErrorMessage+"<br>";
result=false;
}
}
}
Order_ValidationSummary.Visible=(!result);
return result;
}
/*===============================
Display Record Form
-------------------------------*/
void Order_Show() {
// Order Show begin
bool ActionInsert=true;
if (p_Order_order_id.Value.Length > 0 ) {
string sWhere = "";
sWhere += "order_id=" + CCUtility.ToSQL(p_Order_order_id.Value, FieldTypes.Number);
// Order Open Event begin
// Order Open Event end
string sSQL = "select * from orders where " + sWhere;
OleDbDataAdapter dsCommand = new OleDbDataAdapter(sSQL, Utility.Connection);
DataSet ds = new DataSet();
DataRow row;
if (dsCommand.Fill(ds, 0, 1, "Order") > 0) {
row = ds.Tables[0].Rows[0];
Order_order_id.Value = CCUtility.GetValue(row, "order_id");
Order_quantity.Text = CCUtility.GetValue(row, "quantity");
Order_item_id.Value = CCUtility.GetValue(row, "item_id");
Order_insert.Visible=false;
ActionInsert=false;
// Order ShowEdit Event begin
// Order ShowEdit Event end
}}
if(ActionInsert){
String pValue;
pValue = Utility.GetParam("item_id");Order_item_id.Value = pValue;
// Order ShowInsert Event begin
// Order ShowInsert Event end
}
// Order Open Event begin
// Order Open Event end
// Order Show Event begin
// Order Show Event end
// Order Show end
// Order Close Event begin
// Order Close Event end
}
// Order Action begin
bool Order_insert_Click(Object Src, EventArgs E) {
string sSQL="";
bool bResult=Order_Validate();
// Order Check Event begin
// Order Check Event end
string s1_UserID=CCUtility.ToSQL(Session["UserID"].ToString(), FieldTypes.Number);
string p2_quantity=CCUtility.ToSQL(Utility.GetParam("Order_quantity"), FieldTypes.Number) ;
string p2_item_id=CCUtility.ToSQL(Utility.GetParam("Order_item_id"), FieldTypes.Number) ;
// Order Insert Event begin
// Order Insert Event end
if(bResult){
if(sSQL.Length==0){
sSQL = "insert into orders (" +
"[member_id]," +
"quantity," +
"item_id)" +
" values (" +
s1_UserID + "," +
p2_quantity + "," +
p2_item_id + ")";
}
Order_BeforeSQLExecute(sSQL,"Insert");
OleDbCommand cmd = new OleDbCommand(sSQL, Utility.Connection);
try {
cmd.ExecuteNonQuery();
} catch(Exception e) {
Order_ValidationSummary.Text += e.Message;
Order_ValidationSummary.Visible = true;
return false;
}
// Order AfterInsert Event begin
// Order AfterInsert Event end
}
return bResult;
}
void Order_BeforeSQLExecute(string SQL,String Action){
// Order BeforeExecute Event begin
// Order BeforeExecute Event end
}
void Order_Action(Object Src, EventArgs E) {
bool bResult=true;
if(((HtmlInputButton)Src).ID.IndexOf("insert")>0) bResult=Order_insert_Click(Src,E);
if(bResult)Response.Redirect(Order_FormAction+"");
}
// Order Action end
// End of Login form
private bool Rating_Validate(){
bool result=true;
Rating_ValidationSummary.Text="";
for(int i=0;i<Page.Validators.Count;i++){
if(((System.Web.UI.WebControls.BaseValidator)Page.Validators[i]).ID.ToString().StartsWith("Rating")){
if(!Page.Validators[i].IsValid){
Rating_ValidationSummary.Text+=Page.Validators[i].ErrorMessage+"<br>";
result=false;
}
}
}
Rating_ValidationSummary.Visible=(!result);
return result;
}
/*===============================
Display Record Form
-------------------------------*/
void Rating_Show() {
// Rating Show begin
Utility.buildListBox(Rating_rating.Items,Rating_rating_lov,null,"");
bool ActionInsert=true;
if (p_Rating_item_id.Value.Length > 0 ) {
string sWhere = "";
sWhere += "item_id=" + CCUtility.ToSQL(p_Rating_item_id.Value, FieldTypes.Number);
// Rating Open Event begin
// Rating Open Event end
string sSQL = "select * from items where " + sWhere;
OleDbDataAdapter dsCommand = new OleDbDataAdapter(sSQL, Utility.Connection);
DataSet ds = new DataSet();
DataRow row;
if (dsCommand.Fill(ds, 0, 1, "Rating") > 0) {
row = ds.Tables[0].Rows[0];
Rating_item_id.Value = CCUtility.GetValue(row, "item_id");
Rating_rating_view.Text =CCUtility.GetValue(row, "rating");
Rating_rating_count_view.Text =Server.HtmlEncode(CCUtility.GetValue(row, "rating_count").ToString());
{string s;
s=CCUtility.GetValue(row, "rating");
try {Rating_rating.SelectedIndex=Rating_rating.Items.IndexOf(Rating_rating.Items.FindByValue(s));
}catch{}}
Rating_rating_count.Value = CCUtility.GetValue(row, "rating_count");
ActionInsert=false;
// Rating ShowEdit Event begin
// Rating ShowEdit Event end
}}
if(ActionInsert){
String pValue;
pValue = Utility.GetParam("item_id");Rating_item_id.Value = pValue;Rating_update.Visible=false;
// Rating ShowInsert Event begin
// Rating ShowInsert Event end
}
// Rating Open Event begin
// Rating Open Event end
// Rating Show Event begin
if (Int16.Parse(Rating_rating_view.Text)==0){
Rating_rating_view.Text="Not rated yet";
Rating_rating_count_view.Text="";
}else{
Rating_rating_view.Text="<img src=images/" + System.Math.Round(Double.Parse(Rating_rating.SelectedItem.Value)/Double.Parse(Rating_rating_count.Value)) + "stars.gif>";
}
// Rating Show Event end
// Rating Show end
// Rating Close Event begin
// Rating Close Event end
}
// Rating Action begin
void Rating_BeforeSQLExecute(string SQL,String Action){
// Rating BeforeExecute Event begin
// Rating BeforeExecute Event end
}
bool Rating_update_Click(Object Src, EventArgs E) {
string sWhere = "";
string sSQL ="";
bool bResult=Rating_Validate();
if(bResult){
if (p_Rating_item_id.Value.Length > 0) {
sWhere = sWhere + "item_id=" + CCUtility.ToSQL(p_Rating_item_id.Value, FieldTypes.Number);
}
// Rating Check Event begin
// Rating Check Event end
if (bResult){
sSQL = "update items set " +
"[rating]=" +CCUtility.ToSQL(Utility.GetParam("Rating_rating"),FieldTypes.Number) +
",[rating_count]=" +CCUtility.ToSQL(Utility.GetParam("Rating_rating_count"),FieldTypes.Number) ;
sSQL = sSQL + " where " + sWhere;
// Rating Update Event begin
sSQL="update items set rating=rating+" + Rating_rating.SelectedItem.Value + ", rating_count=rating_count+1 where item_id=" + Rating_item_id.Value;
// Rating Update Event end
Rating_BeforeSQLExecute(sSQL,"Update");
OleDbCommand cmd = new OleDbCommand(sSQL, Utility.Connection);
try {
cmd.ExecuteNonQuery();
} catch(Exception e) {
Rating_ValidationSummary.Text += e.Message;
Rating_ValidationSummary.Visible = true;
return false;
}
}
if (bResult){
// Rating AfterUpdate Event begin
// Rating AfterUpdate Event end
}
}
return bResult;
}
void Rating_Action(Object Src, EventArgs E) {
bool bResult=true;
if(((HtmlInputButton)Src).ID.IndexOf("update")>0) bResult=Rating_update_Click(Src,E);
if(bResult)Response.Redirect(Rating_FormAction+"item_id=" + Server.UrlEncode(Utility.GetParam("item_id")) + "&");
}
// Rating Action end
}
} | 9d62d7410d8a312b66ddaf94ad31a22003fe8eb0 | [
"Markdown",
"C#"
] | 11 | C# | cx-demo/Bookstore.Net | 8ad8faf9d7da629828e776ea3e4f8a8eeae1a724 | e5eb8ab74728f074bf698e444fd479518ecd3a47 |
refs/heads/master | <file_sep>//
// ViewController.swift
// Cat Years
//
// Created by <NAME> on 2/21/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTextField: UITextField!
@IBOutlet weak var myCatLabel: UILabel!
@IBAction func doFindAge(sender: AnyObject) {
var enteredAge = myTextField.text.toInt()
if enteredAge != nil {
var catAge = enteredAge!*7;
myCatLabel.text = "Your cat is \(catAge)"
} else {
myCatLabel.text = "Please enter a number in the text box."
}
}
override func viewDidLoad() {
super.viewDidLoad()
myCatLabel.text = "";
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 372223f6eee85ad24500e0faeceb9bfafa491324 | [
"Swift"
] | 1 | Swift | RommelTJ/Cat-Years | 2cf776cc8ce5020244d43037694198eeffe96913 | 61b14e1ca408cc00c09b612d296145bccc718c85 |
refs/heads/master | <repo_name>miaoxinguo/grass<file_sep>/grass-test/build.gradle
dependencies {
compile files(project(':grass-core').buildDir.path + '/libs/grass-core-'+version+'.jar')
}<file_sep>/grass-core/src/test/java/org/miaoxg/grass/core/enhancer/DomainClassFileTransformerTest.java
package org.miaoxg.grass.core.enhancer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.lang.instrument.IllegalClassFormatException;
import org.junit.Before;
import org.junit.Test;
public class DomainClassFileTransformerTest {
private ModelClassEnhancer enhancer;
@Before
public void setup() {
enhancer = mock(ModelClassEnhancer.class);
}
@Test
public void shouldTransform() throws IllegalClassFormatException {
ClassLoader loader = mock(ClassLoader.class);
ModelClassFileTransformer transformer = new ModelClassFileTransformer(enhancer);
transformer.transform(loader, ModelClassEnhancer.class.getName(), null, null, null);
verify(enhancer).enhance(loader, ModelClassEnhancer.class.getName());
}
}
<file_sep>/settings.gradle
include "grass-core", "grass-test"<file_sep>/grass-core/build.gradle
dependencies {
//compile files(System.properties['java.home']+'/../lib/tools.jar')
compile "org.mockito:mockito-all:1.9.5"
compile "commons-beanutils:commons-beanutils:1.9.2"
}
task dist(type: Copy) {
from configurations.runtime
into 'dist' // 目标位置
}
jar {
manifest {
attributes("Permain-Class": "org.miaoxg.grass.core.enhancer.GrassAgent",
"Agent-Class": "org.miaoxg.grass.core.enhancer.GrassAgent",
"Can-Redefine-Classes": "true",
"Can-Retransform-Classes": "true")
}
}
<file_sep>/build.gradle
subprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
sourceCompatibility = 1.8
version = '1.0'
[compileJava, javadoc, compileTestJava]*.options*.encoding = 'UTF-8'
repositories {
mavenCentral()
}
dependencies {
compile files(System.properties['java.home']+'/../lib/tools.jar')
compile "org.springframework:spring-jdbc:$version_spring"
compile "org.slf4j:slf4j-api:$version_slf4j"
compile "org.javassist:javassist:$version_javassist"
compile "ch.qos.logback:logback-core:$version_logback"
compile "ch.qos.logback:logback-classic:$version_logback"
testCompile 'junit:junit:4.8.2'
testCompile "org.springframework:spring-context:$version_spring"
testCompile 'mysql:mysql-connector-java:5.1.18'
}
}
<file_sep>/gradle.properties
version_slf4j = 1.7.7
version_javassist = 3.18.1-GA
version_logback = 1.1.2
version_spring = 4.1.1.RELEASE | 1815db629aa470311ac6b48eb66d5addb1fd353d | [
"Java",
"INI",
"Gradle"
] | 6 | Gradle | miaoxinguo/grass | cb7d9327e200eb77253c25e4fa5f0afefd64481e | dd8b546f873903d937c1654b0fe4314e8f5c22a9 |
refs/heads/master | <file_sep>buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter()
}
dependencies {
classpath 'io.fabric.tools:gradle:1.28.1'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
static def getCurrentCommitMessage() {
def gitlog = 'git log origin/develop...HEAD --decorate'.execute().text
if (gitlog.trim().length()>0) return gitlog
return 'git log -n 1 --decorate'.execute().text
}
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
signingConfigs {
config {
storeFile file('ysato.jks')
storePassword properties.getProperty("storePassword", System.getenv("storePassword"))
keyAlias properties.getProperty("keyAlias", System.getenv("keyAlias"))
keyPassword properties.getProperty("keyPassword", System.getenv("keyPassword"))
}
}
compileSdkVersion 28
buildToolsVersion '28.0.3'
defaultConfig {
applicationId 'jp.mediba.seeksemicolon'
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName '1.0'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [
fabric_api_key:properties.getProperty("fabric_api_key", System.getenv("fabric_api_key")),
HOCKEYAPP_APP_ID: properties.getProperty("HOCKEYAPP_APP_ID", System.getenv("HOCKEYAPP_APP_ID"))
]
ext.betaDistributionNotifications=false
ext.betaDistributionReleaseNotes=getCurrentCommitMessage()
}
buildTypes {
debug {
applicationIdSuffix '.debug'
}
release {
debuggable false
signingConfig signingConfigs.config
}
}
productFlavors {
}
packagingOptions {
exclude 'LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:28.0.0'
androidTestCompile 'com.android.support.test:runner:1.0.2'
androidTestCompile 'com.android.support.test:rules:1.0.2'
androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.2'
compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
transitive = true;
}
compile 'net.hockeyapp.android:HockeySDK:4.0.0'
}
<file_sep># SeekSemicolon
せみころんをさがせ
です。
[](https://circleci.com/gh/medi-y-sato/SeekSemicolon-Android/tree/master)
<file_sep>package jp.mediba.seeksemicolon;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.UpdateManager;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Random;
import io.fabric.sdk.android.Fabric;
public class MyActivity extends AppCompatActivity {
private int score = 0;
private int maxPatternNum;
private Bitmap buttonImage1 , buttonImage2;
private TableLayout table;
private int colon_x , colon_y;
private int tableSize;
private int ChoiceCharTarget;
private String[][] ChoiceCharList;
private Handler TimeRefresh = new Handler();
private Handler TimeTimeOver = new Handler();
private long TimeupCount;
private double TimeRest , TimeStart;
private TextView TimeView;
private Boolean isTimeOver , isFailedTouch;
private int failed_x , failed_y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics()); Fabric.with(this, new Crashlytics());
maxPatternNum = getPatternCSV( "patterns.csv" );
titleScene();
checkForUpdates();
}
public void titleScene() {
setContentView(R.layout.activity_my);
LinearLayout parentLayout;
parentLayout = (LinearLayout)(findViewById(R.id.parentLinearLayout));
TextView titleView = new TextView(this);
titleView.setText(getString(R.string.game_title));
parentLayout.addView(titleView);
Button startButton = new Button(this);
startButton.setId(R.id.startButton);
startButton.setText(getString(R.string.title_start));
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimeupCount = 10 * 1000;
TimeStart = System.currentTimeMillis();
TimeRest = TimeupCount - (System.currentTimeMillis() - TimeStart);
isTimeOver = false;
isFailedTouch = false;
score = 0;
gameScene(2);
}
});
parentLayout.addView(startButton);
}
public void gameScene(int tableSizeRef){
setContentView(R.layout.activity_my);
tableSize = tableSizeRef;
LinearLayout parentLayout;
parentLayout = (LinearLayout)(findViewById(R.id.parentLinearLayout));
ChoiceCharTarget = (int) ( Math.random() * maxPatternNum );
table = makeColonTable( tableSize , ChoiceCharList[ChoiceCharTarget][0] , ChoiceCharList[ChoiceCharTarget][1] );
TextView scoreView = new TextView(this);
scoreView.setText(getString(R.string.gamescore) + score);
TextView titleView = new TextView(this);
titleView.setText( String.format( getString(R.string.gameseekcolon) , ChoiceCharList[ChoiceCharTarget][1] , ChoiceCharList[ChoiceCharTarget][0] ) );
titleView.setTextSize(18f);
TimeView = new TextView(this);
parentLayout.addView(table);
parentLayout.addView(scoreView);
parentLayout.addView(titleView);
parentLayout.addView(TimeView);
StartCount();
}
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public TableLayout makeColonTable(final int columns, final String ChoiceCharCorrect, final String ChoiceCharIncorrect) {
TableLayout table = new TableLayout(this);
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
TableRow tableRowArray[];
tableRowArray = new TableRow[columns];
if ( ! isFailedTouch && ! isTimeOver ) {
Random rnd = new Random();
colon_x = rnd.nextInt(columns);
colon_y = rnd.nextInt(columns);
}
int ButtonSize = (int)(size.x / columns * 0.9);
boolean setMissedButtonIdFlug = false;
for (int y = 0; y < columns; y++) {
tableRowArray[y] = new TableRow(this);
for(int x = 0 ; x < columns ; x++) {
Button button = new Button(this);
button.setPadding(0, 0, 0, 0);
button.setTextSize(ButtonSize / 4);
if ( x == colon_x && y == colon_y ) {
button.setText(ChoiceCharCorrect);
if ( ! isFailedTouch && ! isTimeOver ) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StopCount();
TimeupCount += 10 * 1000;
score += columns * (int) (TimeRest / 100);
if (columns < 10) {
gameScene(columns + 1);
} else {
gameScene(columns);
}
}
});
}else {
button.setBackgroundColor(Color.CYAN);
}
button.setId(R.id.correctButton);
}else{
button.setText(ChoiceCharIncorrect);
if ( ! isFailedTouch && ! isTimeOver ) {
final int finalX = x;
final int finalY = y;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StopCount();
failed_x = finalX;
failed_y = finalY;
gameOverScene();
}
});
}else{
if ( x == failed_x && y == failed_y && !isTimeOver ){
button.setBackgroundColor(Color.RED);
}
}
if ( ! setMissedButtonIdFlug ){
button.setId(R.id.missedButton);
setMissedButtonIdFlug = true;
}
}
tableRowArray[y].addView(button, new TableRow.LayoutParams(ButtonSize, ButtonSize));
}
table.addView(tableRowArray[y], new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
return table;
}
public void gameOverScene() {
setContentView(R.layout.activity_my);
StopCount();
LinearLayout parentLayout;
parentLayout = (LinearLayout)(findViewById(R.id.parentLinearLayout));
TextView titleView = new TextView(this);
if ( isTimeOver ) {
titleView.setText(getString(R.string.resulttimeover));
}else{
isFailedTouch = true;
titleView.setText(getString(R.string.resultgameover));
}
table = makeColonTable( tableSize , ChoiceCharList[ChoiceCharTarget][0] , ChoiceCharList[ChoiceCharTarget][1] );
TextView scoreView = new TextView(this);
scoreView.setText(getString(R.string.resultscore) + score);
Button startButton = new Button(this);
startButton.setId(R.id.backTitleButton);
startButton.setText(getString(R.string.resultback2title));
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
titleScene();
}
});
parentLayout.addView(table);
parentLayout.addView(titleView);
parentLayout.addView(scoreView);
parentLayout.addView(startButton);
}
public int getPatternCSV(String CSVFilename) {
int i = 0;
InputStreamReader isr;
try {
Log.d("INFO","CSV Read : " + CSVFilename);
isr = new InputStreamReader( getAssets().open(CSVFilename) );
// 行数数えて配列確保。
LineNumberReader lr = new LineNumberReader( isr );
while ( lr.readLine() != null ) ;
ChoiceCharList = new String[lr.getLineNumber()][2];
Log.d("INFO","CSV Line : " + lr.getLineNumber());
} catch (FileNotFoundException e) {
// Fileオブジェクト生成時の例外捕捉
e.printStackTrace();
} catch (IOException e) {
// BufferedReaderオブジェクトのクローズ時の例外捕捉
e.printStackTrace();
}
try {
isr = new InputStreamReader( getAssets().open(CSVFilename) );
// CSVとして読んで配列に投入。
BufferedReader br = new BufferedReader( isr );
String line;
while ( (line = br.readLine()) != null ) {
String[] result = line.split(",");
ChoiceCharList[i] = new String[]{result[0], result[1]};
Log.d( "INFO" , "add choice no " + i + " : " + ChoiceCharList[i][0] + " / " + ChoiceCharList[i][1] );
i++;
}
} catch (FileNotFoundException e) {
// Fileオブジェクト生成時の例外捕捉
e.printStackTrace();
} catch (IOException e) {
// BufferedReaderオブジェクトのクローズ時の例外捕捉
e.printStackTrace();
}
Log.d("INFO","return : " + i );
return i;
}
public void StartCount() {
TimeRefresh.postDelayed( RefreshTimeViewRunnable , 1 );
TimeRest = TimeupCount - (System.currentTimeMillis() - TimeStart);
TimeTimeOver.postDelayed( TimeOverRunnable , (long)(TimeRest) );
Log.d("INFO","Count Start : " + (long)(TimeRest) );
}
public void StopCount(){
TimeRefresh.removeCallbacks( RefreshTimeViewRunnable );
TimeTimeOver.removeCallbacks( TimeOverRunnable );
}
private final Runnable TimeOverRunnable = new Runnable(){
@Override
public void run(){
StopCount();
isTimeOver = true;
gameOverScene();
}
};
private final Runnable RefreshTimeViewRunnable = new Runnable(){
@Override
public void run() {
TimeRest = TimeupCount - (System.currentTimeMillis() - TimeStart);
TimeView.setText(String.format(getString(R.string.gameTimeString), (TimeRest / 1000)));
TimeRefresh.postDelayed( RefreshTimeViewRunnable, 1 );
}
};
@Override
public void onResume() {
super.onResume();
// ... your own onResume implementation
checkForCrashes();
}
@Override
public void onPause() {
super.onPause();
unregisterManagers();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterManagers();
}
private void checkForCrashes() {
CrashManager.register(this);
}
private void checkForUpdates() {
// Remove this for store builds!
UpdateManager.register(this);
}
private void unregisterManagers() {
UpdateManager.unregister();
}
}
<file_sep>
GIT_COMPARE_KEY=${CIRCLE_COMPARE_URL##*/}
GIT_PRETTY_COMMIT_LOG=$(echo "<ul>$(git log ${GIT_COMPARE_KEY} --pretty=format:'<li>[%ad] %s (%an)</li>' --date=short)</ul>" | tr -d '\n')
HOCKEYAPP_NOTES_HEADER="**Built on:** $(date +"%a %d-%b-%Y %I:%M %p")
**Branch:** $(git rev-parse --abbrev-ref HEAD)
**Commit:** $(git rev-parse --short HEAD)"
HOCKEYAPP_NOTES_HEADER_HTML=${HOCKEYAPP_NOTES_HEADER//$'\n'/<br>}
HOCKEYAPP_NOTES="${HOCKEYAPP_NOTES_HEADER_HTML} ${GIT_PRETTY_COMMIT_LOG}"
echo ${HOCKEYAPP_NOTES}
curl \
-F "status=2" \
-F "notify=0" \
-F "notes=${HOCKEYAPP_NOTES}" \
-F "ipa=@app/build/outputs/apk/app-debug.apk" \
-H "X-HockeyAppToken: $HockeyAppToken" \
https://rink.hockeyapp.net/api/2/apps/$HOCKEYAPP_APP_ID/app_versions/upload
| cfb988211e74aa67896e6d4f0c26aecaae070e68 | [
"Markdown",
"Java",
"Shell",
"Gradle"
] | 4 | Gradle | yoshiaki310/SeekSemicolon-Android | 61b5dbf15cd1c970d76307d92f762a39352bcd7a | 4aa5ac77e7786ab8aca20d6cb68194267fb7a85b |
refs/heads/master | <file_sep>package composite;
/**
* @author Schlipak
*/
public class AppComposite {
//calcul de l'expression arithmétique 2 + (3 * (5 -2)) * 6 / 6 + 7
public static void main(String[] args) {
CompositeOperand complete;
complete = new ExpressionPlus();
complete.addElement(new NumericOperand(2));
CompositeOperand milieu = new ExpressionDiv();
complete.addElement(milieu);
complete.addElement(new NumericOperand(7));
CompositeOperand droitediv = new ExpressionMult();
milieu.addElement(droitediv);
milieu.addElement(new NumericOperand(6));
droitediv.addElement(new NumericOperand(3));
CompositeOperand soustraction = new ExpressionMin();
droitediv.addElement(soustraction);
droitediv.addElement(new NumericOperand(6));
soustraction.addElement(new NumericOperand(5));
soustraction.addElement(new NumericOperand(2));
System.out.println("2 + (3 * (5 -2)) * 6 / 6 + 7 = " +
complete.evaluate());
}
}
<file_sep>package composite;
/**
* @author Schlipak
*/
public abstract class ArithmeticExpression {
public abstract int evaluate();
}
<file_sep>Design Pattern Composite
=========
IUT 'A' <NAME>, département Informatique<br />
InS3 M3105 - TPs 5 et 6
<file_sep>package composite;
import java.util.ArrayList;
import java.util.List;
/**
* @author Schlipak
*/
public abstract class CompositeOperand extends ArithmeticExpression {
private List<ArithmeticExpression> children;
public CompositeOperand() {
this.children = new ArrayList<ArithmeticExpression>();
}
public void addElement(ArithmeticExpression arithmeticExpression) {
this.children.add(arithmeticExpression);
}
public ArithmeticExpression getElement(int i) {
return this.children.get(i);
}
public List<ArithmeticExpression> getElements() {
return this.children;
}
public int getSize() {
return this.children.size();
}
}
<file_sep>package composite;
/**
* @author Schlipak
*/
public class ExpressionMult extends CompositeOperand {
@Override
public int evaluate() {
int ev = 1;
for(ArithmeticExpression a : this.getElements()) {
ev *= a.evaluate();
}
return ev;
}
}
<file_sep>package magasin;
/**
* @author Schlipak
*/
public class AppMagasin {
public static void main(String[] args) {
Barre maBarre = new Barre();
maBarre.setPrice(25f);
maBarre.setDescription("Barre d'haltérophilie");
maBarre.setBarcode("BA0001");
maBarre.setLength(150f);
Poids leger = new Poids();
leger.setPrice(15f);
leger.setDescription("Poids d'haltère");
leger.setBarcode("PA0001");
leger.setWeight(0.5f);
Poids moyen = new Poids();
moyen.setPrice(17f);
moyen.setDescription("Poids d'haltère");
moyen.setBarcode("PA0002");
moyen.setWeight(1f);
Poids lourd = new Poids();
lourd.setPrice(19f);
lourd.setDescription("Poids d'haltère");
lourd.setBarcode("PA0003");
lourd.setWeight(1.5f);
ProduitComposite haltere = new ProduitComposite();
haltere.add(maBarre);
haltere.add(leger);
haltere.add(moyen);
haltere.add(lourd);
System.out.println(haltere.toString());
}
}
| 42f88d22fe8c27edfce0140e878031744502d66d | [
"Markdown",
"Java"
] | 6 | Java | Schlipak/composite | 8ab27777e0d643cb657f7fa19c79b67ece4d7edf | 4acca4a388b5ea04219079f10a995c03e8450239 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from .ecoinvent_lcia import EcoinventLCIAImporter
from .ecospold1 import (
MultiOutputEcospold1Importer,
NoIntegerCodesEcospold1Importer,
SingleOutputEcospold1Importer,
)
from .ecospold1_lcia import Ecospold1LCIAImporter
from .ecospold2 import SingleOutputEcospold2Importer
from .ecospold2_biosphere import Ecospold2BiosphereImporter
from .excel import ExcelImporter, CSVImporter
from .simapro_csv import SimaProCSVImporter
from .simapro_lcia_csv import SimaProLCIACSVImporter
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
import os
import xlrd
class ExcelExtractor(object):
@classmethod
def extract(cls, filepath):
assert os.path.exists(filepath), "Can't file file at path {}".format(filepath)
wb = xlrd.open_workbook(filepath)
return [(name, cls.extract_sheet(wb, name)) for name in wb.sheet_names()]
@classmethod
def extract_sheet(cls, wb, name, strip=True):
ws = wb.sheet_by_name(name)
_ = lambda x: x.strip() if (strip and hasattr(x, "strip")) else x
return [[_(ws.cell(row, col).value) for col in range(ws.ncols)] for row in range(ws.nrows)]
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from .csv import write_lci_csv
from .excel import lci_matrices_to_excel, write_lci_excel
from .gexf import DatabaseSelectionToGEXF, DatabaseToGEXF, keyword_to_gephi_graph
from .matlab import lci_matrices_to_matlab
<file_sep>bw2calc>=1.3
bw2data>=3.3
bw_migrations
lxml
mrio_common_metadata
numpy
psutil
pyprind
pytest
pytest-cov
python-coveralls
scipy
stats_arrays
unidecode
voluptuous
xlrd
xlsxwriter
<file_sep>from bw2io.extractors.ecospold2 import Ecospold2DataExtractor
import os
FIXTURES = os.path.join(os.path.dirname(__file__), "..", "fixtures", "ecospold2")
def test_extraction():
data = Ecospold2DataExtractor.extract(FIXTURES, "ei")
expected = [{
'activity': 'c40e3c0a-292f-45a5-88cd-ed18265cb7d7',
'activity type': 'ordinary transforming activity',
'authors': {'data entry': {'email': '<EMAIL>',
'name': '<NAME>'},
'data generator': {'email': '<EMAIL>',
'name': '<NAME>'}},
'classifications': [('EcoSpold01Categories',
'construction materials/concrete'),
('ISIC rev.4 ecoinvent',
'2395:Manufacture of articles of concrete, cement and '
'plaster')],
'comment': 'Things and stuff and whatnot\n'
'Technology: typical technology for ze Germans!',
'database': 'ei',
'exchanges': [{'activity': '759fac54-b912-4781-9833-0ddd6e8cda24',
'amount': 9999.0,
'classifications': {'CPC': ['53269: Other constructions for '
'manufacturing']},
'comment': 'estimated',
'flow': '6fe4040b-39c7-4d58-b95b-6ee1de4aedb3',
'loc': 0.0,
'name': 'clay pit infrastructure',
'pedigree': {'completeness': 1,
'further technological correlation': 1,
'geographical correlation': 1,
'reliability': 1,
'temporal correlation': 5},
'production volume': 0.0,
'scale': 0.4472135954999579,
'scale without pedigree': 0.31622776601683794,
'type': 'technosphere',
'uncertainty type': 2,
'unit': 'unit'},
{'activity': None,
'amount': 1.0,
'classifications': {'CPC': ['37510: Non-refractory mortars '
'and concretes']},
'flow': 'd4ee8f39-342b-4443-bbb9-c49b6801b5d6',
'loc': 1.0,
'name': 'concrete block',
'production volume': 42.0,
'type': 'production',
'uncertainty type': 0,
'unit': 'kg'},
{'amount': 123456.0,
'classifications': {'CPC': []},
'comment': 'Calculated value based on literature values and, '
'like, experts, and stuff.',
'flow': '075e433b-4be4-448e-9510-9a5029c1ce94',
'loc': 8.0,
'name': 'Water',
'pedigree': {'completeness': 2,
'further technological correlation': 1,
'geographical correlation': 1,
'reliability': 2,
'temporal correlation': 5},
'production volume': 0.0,
'scale': 2.449489742783178,
'scale without pedigree': 2.6457513110645907,
'type': 'biosphere',
'uncertainty type': 2,
'unit': 'm3'}],
'filename': '00000_11111111-2222-3333-4444-555555555555_66666666-7777-8888-9999-000000000000.spold',
'location': 'DE',
'name': 'concrete block production',
'parameters': {'does_it_hurt_when_dropped_on_foot': {
'amount': 7777.0,
'comment': 'This is where the people type the words!!!',
'description': "How much owwies PLEASE DON'T TELL MOM",
'id': 'daadf2d4-7bbb-4f69-8ab5-58df4c1685eb',
'loc': 2.0,
'pedigree': {
'completeness': 4,
'further technological correlation': 4,
'geographical correlation': 2,
'reliability': 4,
'temporal correlation': 3
},
'scale': 2.0,
'scale without pedigree': 1.7320508075688772,
'uncertainty type': 2,
'unit': 'dimensionless'}},
'type': 'process'
}]
assert data == expected
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from .strategies import *
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from ..utils import activity_hash
from bw2data import Database, mapping, config, databases
import csv
import itertools
import os
import xlrd
class ExiobaseDataExtractor(object):
@classmethod
def _check_dir(cls, path):
# Note: this assumes industry by industry
assert os.path.isdir(path), "Must supply path to `mrIOT_IxI_fpa_coefficient_version2.2.2` folder"
assert 'mrIot_version2.2.2.txt' in os.listdir(path), "Directory path must include Exiobase files"
assert 'types_version2.2.2.xls' in os.listdir(path), "Directory path must include Exiobase files"
@classmethod
def _extract_metadata(cls, path):
wb = xlrd.open_workbook(os.path.join(path, 'types_version2.2.2.xls'))
ws = wb.sheet_by_name('compartments')
compartments = [(
int(ws.cell(row, 0).value), # ID number
ws.cell(row, 2).value, # Name
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('countries')
countries = [(
ws.cell(row, 0).value, # Code (2-letter ISO/other)
ws.cell(row, 1).value, # Name
ws.cell(row, 3).value, # Group code
ws.cell(row, 4).value, # Group name
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('industrytypes')
industries = [(
ws.cell(row, 0).value, # Code
ws.cell(row, 1).value, # Name
ws.cell(row, 2).value, # Synonym
ws.cell(row, 4).value, # Group code
ws.cell(row, 5).value, # Group name
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('producttypes')
products = [(
ws.cell(row, 0).value, # Code
ws.cell(row, 1).value, # Name
ws.cell(row, 3).value, # Synonym
ws.cell(row, 4).value, # Group code
ws.cell(row, 5).value, # Group name
ws.cell(row, 7).value, # Layer
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('units')
units = [(
ws.cell(row, 0).value, # Code
ws.cell(row, 1).value, # Name
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('substances')
substances = [(
ws.cell(row, 1).value, # Name
ws.cell(row, 2).value, # Code
ws.cell(row, 3).value, # Synonym
ws.cell(row, 4).value, # Description
) for row in range(1, ws.nrows)]
ws = wb.sheet_by_name('extractions')
extractions = [(
ws.cell(row, 0).value, # ID number
ws.cell(row, 2).value, # Name
ws.cell(row, 3).value, # Synonym
) for row in range(1, ws.nrows)]
return (
units,
compartments,
countries,
industries,
products,
substances,
extractions,
)
@classmethod
def _extract_csv(cls, path, filename, materials=False):
reader = csv.reader(open(os.path.join(
path, filename)
), delimiter="\t")
data = []
countries = next(reader)[3:]
industries = next(reader)[3:]
for line in reader:
for index, country, industry in zip(itertools.count(), countries,
industries):
value = (float(line[index + 2]) if materials
else float(line[index + 3]))
if not value:
continue
elif materials:
data.append((
country,
industry,
line[0],
"materials",
line[1],
value
))
else:
data.append((
country,
industry,
line[0],
line[1],
line[2],
value
))
return data
@classmethod
def _generate_csv(cls, path, filename):
reader = csv.reader(open(os.path.join(
path, filename)
), delimiter="\t")
countries = next(reader)[3:]
industries = next(reader)[3:]
for line_no, line in enumerate(reader):
for index, country, industry in zip(itertools.count(), countries,
industries):
value = float(line[index + 3])
if not value:
continue
yield (
country,
industry,
line[0], # country
line[1], # industry
line[2], # unit
value
)
@classmethod
def extract(cls, path):
cls._check_dir(path)
print("Extracting metadata")
units, compartments, countries, industries, products, substances, \
extractions = cls._extract_metadata(path)
print("Extracting emissions")
emissions = cls._extract_csv(path, "mrEmissions_version2.2.2.txt")
# print("Extracting materials")
# materials = cls._extract_csv(path, "mrMaterials_version2.2.2.txt", True)
print("Extracting resources")
resources = cls._extract_csv(path, "mrResources_version2.2.2.txt")
print("Extracting main IO table")
table = cls._generate_csv(path, "mrIot_version2.2.2.txt")
outputs = {
"compartments": compartments,
"countries": countries,
"emissions": emissions,
"extractions": extractions,
"industries": industries,
"products": products,
"resources": resources,
"substances": substances,
"table": table,
"units": units,
}
return outputs
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from bw2data.backends.iotable import IOTableBackend
from bw2data import Database
from ..extractors import ExiobaseDataExtractor
from ..strategies import (
migrate_datasets,
)
from ..utils import activity_hash
from bw2data import config
from time import time
import functools
import itertools
import pprint
class Exiobase22Importer(object):
format = u"Exiobase 2.2"
def __init__(self, filepath, db_name="EXIOBASE 2.2"):
self.strategies = []
self.db_name = db_name
print("Creating database {}".format(self.db_name))
start = time()
self.outputs = ExiobaseDataExtractor.extract(filepath)
print(u"Extracted {} datasets and many exchanges in {:.2f} seconds".format(
len(self.outputs['industries']),
time() - start
))
def apply_strategies(self, biosphere=None):
# Plus normalize units
self.biosphere_lookup = get_biosphere_lookup_dict(
self.outputs['substances'],
self.outputs['extractions'],
biosphere
)
print("Processing technosphere")
self.activities = extract_exiobase_technosphere(
self.outputs['industries'],
self.outputs['countries'],
self.db_name
)
print("Processing exchanges")
self.exchanges = itertools.chain(
relabel_exchanges(
self.outputs['table'],
self.db_name
),
relabel_emissions(
self.outputs['emissions'],
self.db_name,
self.biosphere_lookup
)
)
def write_database(self):
mrio = IOTableBackend(self.db_name)
mrio.write(self.activities, self.exchanges)
def get_biosphere_lookup_dict(substances, extractions, biosphere=None):
print("Aggregating `substances` and `extractions`")
lookup = [{
'name': obj[0],
'exiobase-code': obj[1],
'synonym': obj[2],
'description': obj[3] or None
} for obj in substances] + [{
'name': obj[1],
'synonym': obj[2]
} for obj in extractions]
for obj in lookup:
obj['old-name'] = obj['name'][:]
lookup = migrate_datasets(lookup, "exiobase-biosphere")
biosphere_hashes = {activity_hash(obj, fields=["name", "categories"]): obj.key
for obj in Database(biosphere or "biosphere3")}
return {
obj['old-name']: biosphere_hashes[activity_hash(obj, fields=["name", "categories"])]
for obj in lookup
}
def extract_exiobase_technosphere(industries, countries, db_name):
"""Create activity datasets for each combination of `industries` and `countries`."""
data = [{
'name': obj[1],
'code': obj[1],
'key': (db_name, "{}:{}".format(obj[1], country[0])),
'exiobase_code': obj[0],
'database': db_name,
'synonym': obj[2],
'location': country[1],
'group': obj[3],
'group_name': obj[4],
'unit': 'million €',
'type': 'process',
} for country in countries for obj in industries]
return {obj['key']: obj for obj in data}
def relabel_emissions(emissions_table, db_name, lookup):
"""Turn rows into a generator of (flow, process, type, amount) tuples.
Original data format:
(
'AT',
'Cultivation of wheat',
'CO2 - combustion',
'air',
'kg/M.EUR',
289687.6972210754
)
* `emissions_table` is the list of raw data lines.
* `db_name` is the string name of the database, 'Exiobase 2.2' by default.
* `lookup` is a dictionary from string flow names to biosphere keys.
Returns:
(
("biosphere3", "some-code"), # Looks up 'CO2 - combustion' in `lookup`
("Exiobase 2.2", "Cultivation of wheat:AT"),
289687.6972210754
)
"""
for row in emissions_table:
yield (
lookup[row[2]],
(db_name, "{}:{}".format(row[1], row[0])),
"biosphere",
row[5]
)
def relabel_exchanges(table, db_name):
for row in table:
yield (
(db_name, "{}:{}".format(row[1], row[0])), # Input
(db_name, "{}:{}".format(row[3], row[2])), # Output,
"technosphere",
row[5]
)
<file_sep># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from eight import *
from ..compatibility import (
SIMAPRO_BIO_SUBCATEGORIES,
SIMAPRO_BIOSPHERE,
SIMAPRO_SYSTEM_MODELS,
)
from ..data import get_valid_geonames
from ..errors import StrategyError
from .generic import (
link_iterable_by_fields,
link_technosphere_by_activity_hash,
)
from .locations import GEO_UPDATE
from ..utils import activity_hash, load_json_data_file, rescale_exchange
from ..units import normalize_units
from bw2data import databases, Database
import copy
import re
import numpy as np
from stats_arrays import LognormalUncertainty
# Pattern for SimaPro munging of ecoinvent names
detoxify_pattern = '^(?P<name>.+?)/(?P<geo>[A-Za-z]{2,10})(/I)? [SU]$'
detoxify_re = re.compile(detoxify_pattern)
def sp_allocate_products(db):
"""Create a dataset from each product in a raw SimaPro dataset"""
new_db = []
for ds in db:
products = [exc for exc in ds.get('exchanges', []) if exc['type'] == 'production']
if ds.get("reference product"):
new_db.append(ds)
elif not products:
ds["error"] = True
new_db.append(ds)
elif len(products) == 1:
# Waste treatment datasets only allowed one product
product = products[0]
ds['name'] = ds['reference product'] = product['name']
ds['unit'] = product['unit']
ds['production amount'] = product['amount']
new_db.append(ds)
else:
ds['exchanges'] = [exc for exc in ds['exchanges']
if exc['type'] != "production"]
for product in products:
product = copy.deepcopy(product)
if product['allocation']:
product['amount'] = (product['amount'] *
1 / (product['allocation'] / 100))
else:
product['amount'] = 0
copied = copy.deepcopy(ds)
copied['exchanges'].append(product)
copied['name'] = copied['reference product'] = product['name']
copied['unit'] = product['unit']
copied['production amount'] = product['amount']
new_db.append(copied)
return new_db
def fix_zero_allocation_products(db):
"""Drop all inputs from allocated products which had zero allocation factors.
The final production amount is the initial amount times the allocation factor. If this is zero, a singular technosphere matrix is created. We fix this by setting the production amount to one, and deleting all inputs.
Does not modify datasets with more than one production exchange."""
for ds in db:
if (
len([exc for exc in ds.get('exchanges', [])
if exc['type'] == 'production']) == 1
) and all(
exc['amount'] == 0 for exc in ds.get('exchanges', [])
if exc['type'] == 'production'
):
ds['exchanges'] = [exc for exc in ds['exchanges'] if exc['type'] == 'production']
exc = ds['exchanges'][0]
exc['amount'] = exc['loc'] = 1
exc['uncertainty type'] = 0
return db
def link_technosphere_based_on_name_unit_location(db, external_db_name=None):
"""Link technosphere exchanges based on name, unit, and location. Can't use categories because we can't reliably extract categories from SimaPro exports, only exchanges.
If ``external_db_name``, link against a different database; otherwise link internally."""
return link_technosphere_by_activity_hash(db,
external_db_name=external_db_name,
fields=('name', 'location', 'unit')
)
def split_simapro_name_geo(db):
"""Split a name like 'foo/CH U' into name and geo components.
Sets original name to ``simapro name``."""
for ds in db:
match = detoxify_re.match(ds['name'])
if match:
gd = match.groupdict()
ds['simapro name'] = ds['name']
ds['location'] = gd['geo']
ds['name'] = ds["reference product"] = gd['name']
for exc in ds.get('exchanges', []):
match = detoxify_re.match(exc['name'])
if match:
gd = match.groupdict()
exc['simapro name'] = exc['name']
exc['location'] = gd['geo']
exc['name'] = gd['name']
return db
def normalize_simapro_biosphere_categories(db):
"""Normalize biosphere categories to ecoinvent standard."""
for ds in db:
for exc in (exc for exc in ds.get('exchanges', [])
if exc['type'] == 'biosphere'):
cat = SIMAPRO_BIOSPHERE.get(
exc['categories'][0],
exc['categories'][0]
)
if len(exc['categories']) > 1:
subcat = SIMAPRO_BIO_SUBCATEGORIES.get(
exc['categories'][1],
exc['categories'][1]
)
exc['categories'] = (cat, subcat)
else:
exc['categories'] = (cat, )
return db
def normalize_simapro_biosphere_names(db):
"""Normalize biosphere flow names to ecoinvent standard"""
mapping = {tuple(x[:2]): x[2]
for x in load_json_data_file("simapro-biosphere")}
for ds in db:
for exc in (exc for exc in ds.get('exchanges', [])
if exc['type'] == 'biosphere'):
try:
exc['name'] = mapping[(exc['categories'][0], exc['name'])]
except KeyError:
pass
return db
def normalize_simapro_formulae(formula, settings):
"""Convert SimaPro formulae to Python"""
def replace_comma(match):
return match.group(0).replace(",", ".")
formula = formula.replace("^", "**")
if settings and settings.get('Decimal separator') == ',':
formula = re.sub('\d,\d', replace_comma, formula)
return formula
def change_electricity_unit_mj_to_kwh(db):
"""Change datasets with the string ``electricity`` in their name from units of MJ to kilowatt hour."""
for ds in db:
for exc in ds.get('exchanges', []):
if (
(exc.get('name', '').lower().startswith('electricity') or
exc.get('name', '').lower().startswith('market for electricity')
) and exc.get('unit') == 'megajoule'):
exc['unit'] = 'kilowatt hour'
rescale_exchange(exc, 1/3.6)
return db
def fix_localized_water_flows(db):
"""Change ``Water, BR`` to ``Water``.
Biosphere flows can't have locations - locations are defined by the activity dataset."""
locations = set(get_valid_geonames()).union(set(GEO_UPDATE.keys())).union(set(GEO_UPDATE.values()))
flows = [
"Water",
"Water, cooling, unspecified natural origin",
"Water, river",
"Water, turbine use, unspecified natural origin",
"Water, unspecified natural origin",
"Water, well, in ground",
]
mapping = {"{}, {}".format(flow, location): (flow, location)
for flow in flows
for location in locations}
for ds in db:
for exc in ds.get('exchanges', []):
if exc.get('input') or not exc['type'] == 'biosphere':
continue
try:
flow, location = mapping[exc['name']]
exc['name'] = flow
exc['simapro location'] = GEO_UPDATE.get(location, location)
except KeyError:
pass
return db
def set_lognormal_loc_value_uncertainty_safe(db):
"""Make sure ``loc`` value is correct for lognormal uncertainty distributions"""
for ds in db:
for exc in ds.get('exchanges', []):
if exc.get('uncertainty type') == LognormalUncertainty.id:
exc['loc'] = np.log(abs(exc['amount']))
return db | c64f865810c4b81cd4f95812d3ad9ea7798bf49d | [
"Python",
"Text"
] | 9 | Python | pjamesjoyce/brightway2-io | 142fc26e2ffc47d8ec474386ee93ab2737a089ce | e4fc4ec218143fa90b83f1b09fc0f1f27861a83f |
refs/heads/master | <repo_name>ChoSeoHwan/next-ts-template<file_sep>/src/modules/TestModule.ts
import { createActionCreators, ImmerReducer } from 'libs/immerReducer';
import ApiStatus from 'constants/ApiStatus';
interface TestModuleState {
status: ApiStatus;
data: string;
}
export class TestModule extends ImmerReducer<TestModuleState> {
public initialState = {
status: ApiStatus.CLEAR,
data: ''
};
public hydrate(payload: TestModuleState): void {
this.draftState = payload;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public fetchData(name: string): void {
this.draftState.status = ApiStatus.LOADING;
}
public fetchDataSuccess(data: string): void {
this.draftState.status = ApiStatus.SUCCESS;
this.draftState.data = data;
}
public fetchDataError(error: string): void {
this.draftState.status = ApiStatus.ERROR;
this.draftState.data = error;
}
}
export const TestAction = createActionCreators(TestModule);
<file_sep>/src/constants/ApiStatus.ts
enum ApiStatus {
CLEAR,
LOADING,
SUCCESS,
ERROR
}
export default ApiStatus;
<file_sep>/src/constants/Domain.ts
enum Domain {
API_URL = 'http://localhost:3000'
}
export default Domain;
<file_sep>/src/mocks/index.ts
import MockAdapter from 'axios-mock-adapter';
import test from 'mocks/test';
import { axiosMock } from 'libs/axios';
import { USE_API_MOCK } from 'constants/env';
export type ApiMock = (apiMock: MockAdapter) => void;
const mocks: ApiMock[] = [test];
type InitApiMock = (mock: ReturnType<typeof axiosMock>) => void;
export const initApiMock: InitApiMock = (axiosMock) => {
if (!USE_API_MOCK || axiosMock === null) {
return;
}
mocks.forEach((mock) => {
mock(axiosMock);
});
};
<file_sep>/src/sagas/TestSaga.ts
import { call, put, takeEvery } from '@redux-saga/core/effects';
import axios from 'libs/axios';
import { TestAction } from 'modules/TestModule';
export const fetchTestApi = (name: string): Promise<unknown> => {
const params = { name };
return axios.get('/api/test', { params });
};
function* fetchData(name: string) {
try {
const response = yield call(fetchTestApi, name);
yield put(TestAction.fetchDataSuccess(response.data));
} catch (error) {
yield put(
TestAction.fetchDataError(
typeof error === 'string' ? error : 'ERROR'
)
);
}
}
export function* TestSaga(): Generator {
yield takeEvery<ReturnType<typeof TestAction.fetchData>>(
TestAction.fetchData.type,
({ payload }) => fetchData(payload)
);
}
<file_sep>/src/mocks/test.ts
import { ApiMock } from 'mocks/index';
const test: ApiMock = (apiMock) => {
// 테스트 api 조회
apiMock.onGet('/api/test').reply((config) => {
const { name = '' } = config.params;
return [200, { data: `Test mock ${name}` }];
});
};
export default test;
<file_sep>/src/types/ErrorResponse.ts
interface ErrorResponse {
message: string;
}
export const isErrorResponse = (item: unknown): item is ErrorResponse => {
const errorItem = item as ErrorResponse;
return (
errorItem.message !== undefined && typeof errorItem.message === 'string'
);
};
export default ErrorResponse;
<file_sep>/.storybook/tsconfig.json
{
"extends": "../tsconfig",
"include": [
"../types.d.ts",
"../next-env.d.ts",
"../**/*.stories.ts",
"../**/*.stories.tsx"
]
}
<file_sep>/.jest/jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
rootDir: '../',
modulePaths: ['<rootDir>/src/'],
setupFilesAfterEnv: ['<rootDir>/.jest/jest.setup.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/.jest/tsconfig.json'
}
},
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
'^.+\\.[t|j]sx?$': 'babel-jest'
},
collectCoverage: true,
coverageReporters: ['json', 'html'],
collectCoverageFrom: [
'<rootDir>/src/components/**/*.{ts,tsx,js,jsx}',
'!<rootDir>/src/**/*.stories.{ts,tsx,js,jsx}'
],
testMatch: ['**/(*.)+(test).[jt]s?(x)'],
reporters: [
'default',
[
'jest-html-reporters',
{
publicPath: 'report',
filename: 'report.html',
expand: true
}
]
]
};
<file_sep>/README.md
# next-ts-template
[Next js](https://nextjs.org/) template with [Typescript](https://www.typescriptlang.org/).
[Learn how to use github template.](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-from-a-template)
# Scripts
Use `yarn` or `npm run`
- Run Next JS development server.
```
$ yarn dev [--hostname=test.choseohwan.com --port=80]
```
- Build Next JS application.
```
$ yarn build
```
- Run Next Js production server with built Next JS application.
```
$ yarn start
```
- Export Next JS application for production server.
```
$ yarn export
```
- Run Storybook development server
```
$ yarn storybook
```
- Build Storybook Application for production server.
```
$ yarn build-storybook
```
- Run [lint-staged](https://www.npmjs.com/package/lint-staged) to clean up code.
- need to "git add" the modified file.
- Recommend: Add 'git add' command to file watcher.
```
$ yarn lint-staged
```
- Test Next JS application using [Jest](https://jestjs.io/)
```
$ yarn test
```
- Run when husky's 'git hook' does not work.
```
$ yarn git-hook-reset
```
# Directory Structure
```bash
|-- .env
|-- .eslintrc : eslint configure file
|-- .gitignore : git ignore file
|-- .prettierrc : prettier configure file
|-- README.md : README file
|-- next-env.d.ts : next type declare file
|-- next.config.js : next configure file
|-- package.json
|-- tsconfig.json : typescript compiler configure file
|-- yarn.lock
|--[.storybook : directory for storybook settings
| |-- main.js
| |-- preview.js
| |-- tsconfig.json : typescript config for storybook
|--[.jest : directory for jest setting
| |-- jest.config.js
| |-- jest.setup.js
| |-- tsconfig.jest.json
|--[public : resource directory
|--[src : source root
|--[components : component directory (used atomic design)
| |--[atoms
| |--[molecules
| |--[organisms
| |--[layout : instead of template (component for layout style)
|--[constants : constant directory
|--[libs : internal library directory
|--[modules : reducer module directory (used immer-reducer)
| |-- index.ts
| |-- store.ts
|--[pages : Next JS pages directory
| |-- _app.tsx
| |-- index.tsx
|--[sagas : Redux-saga directory
| |-- index.ts
|--[styles : styles directory (used @emotion/core)
|--[types : user defined types directory
```
- [Atomic Design](https://bradfrost.com/blog/post/atomic-web-design/)
# Dependencies
## Main
### [Next JS](https://nextjs.org/)
- The React framework for SSR
### [Typescript](https://www.typescriptlang.org/)
- TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
### [Redux](https://redux.js.org/)
- A Predictable State Container for JS Apps
### [Redux Saga](https://redux-saga.js.org/)
- redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.
## Development
### [ESLint](https://eslint.org/)
- Find and fix problems in JavaScript code.
### [Prettier](https://prettier.io/)
- An opinionated code formatter
### [Storybook](https://storybook.js.org/)
- Storybook is a user interface development environment and playground for UI components.
### [Lint Staged](https://www.npmjs.com/package/lint-staged)
- Run linters against staged git files and don't let slip into your code base.
### [Husky](https://www.npmjs.com/package/husky)
- Husky can prevent bad git commit, git push and more.
## Test
### [Jest](https://jestjs.io/)
- JavaScript Testing Framework with a focus on simplicity.
### [React Testing Library](https://github.com/testing-library/react-testing-library)
- Simple and complete React DOM testing utilities that encourage good testing practices.
### [Axios Mock Adapter](https://www.npmjs.com/package/axios-mock-adapter)
- Axios adapter that allows to easily mock requests
## ETC..
### [Axios](https://github.com/axios/axios)
- Promise based HTTP client for the browser and node.js
### [Immer](https://immerjs.github.io/immer/docs/introduction)
- Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.
### [Immer Reducer](https://www.npmjs.com/package/immer-reducer)
- Type-safe and terse reducers with Typescript for React Hooks and Redux using Immer.
### [@emotion/core](https://emotion.sh/docs/introduction)
- Emotion is a library designed for writing css styles with JavaScript.
<file_sep>/src/modules/index.ts
import { combineModules } from 'libs/immerReducer';
import { TestModule } from 'modules/TestModule';
const rootReducer = combineModules({
TestReducer: TestModule
});
export type RootReducerState = ReturnType<typeof rootReducer>;
export default rootReducer;
<file_sep>/src/constants/env.ts
export const USE_API_MOCK = process.env.NEXT_PUBLIC_USE_API_MOCK === 'true';
<file_sep>/src/sagas/TestSaga.test.ts
import { expectSaga } from 'redux-saga-test-plan';
import { call } from 'redux-saga-test-plan/matchers';
import ApiStatus from 'constants/ApiStatus';
import rootReducer, { RootReducerState } from 'modules';
import { TestAction } from 'modules/TestModule';
import { fetchTestApi, TestSaga } from 'sagas/TestSaga';
describe('Sagas | TestSaga', () => {
it('should be executed test api', async () => {
const name = 'TestName';
const responseData = `Mocking call and name is : ${name}`;
const { storeState } = await expectSaga(TestSaga)
.withReducer(rootReducer) // reducer 등록
.provide([[call.fn(fetchTestApi), { data: responseData }]]) // api mocking
.put(TestAction.fetchDataSuccess(responseData)) // put matcher
.dispatch(TestAction.fetchData(name)) // dispatch action
.run({ timeout: 3000 });
const state = storeState as RootReducerState;
expect(state.TestReducer).toEqual({
status: ApiStatus.SUCCESS,
data: responseData
});
});
});
<file_sep>/src/modules/store.ts
import { createWrapper, MakeStore } from 'next-redux-wrapper';
import { applyMiddleware, createStore, Store } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware, { Task } from 'redux-saga';
import rootReducer, { RootReducerState } from 'modules/index';
import { rootSaga } from 'sagas';
export interface SagaStore extends Store {
sagaTask?: Task;
}
export const initStore = (): ReturnType<MakeStore<RootReducerState>> => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(sagaMiddleware))
);
(store as SagaStore).sagaTask = sagaMiddleware.run(rootSaga);
return store;
};
export const wrapper = createWrapper<RootReducerState>(initStore, {
debug: true
});
<file_sep>/src/styles/GlobalStyle.ts
import { css } from '@emotion/core';
import { Theme } from 'styles/Themes';
export const GlobalStyle = (theme: Theme): ReturnType<typeof css> => css`
@font-face {
font-family: 'Product Sans Regular';
font-style: normal;
font-weight: normal;
src: local('Product Sans Regular'),
url('/fonts/ProductSans-Regular.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Italic'),
url('/fonts/ProductSans-Italic.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Thin Regular';
font-style: normal;
font-weight: normal;
src: local('Product Sans Thin Regular'),
url('/fonts/ProductSans-Thin.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Light Regular';
font-style: normal;
font-weight: normal;
src: local('Product Sans Light Regular'),
url('/fonts/ProductSans-Light.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Medium Regular';
font-style: normal;
font-weight: normal;
src: local('Product Sans Medium Regular'),
url('/fonts/ProductSans-Medium.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Black Regular';
font-style: normal;
font-weight: normal;
src: local('Product Sans Black Regular'),
url('/fonts/ProductSans-Black.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Thin Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Thin Italic'),
url('/fonts/ProductSans-ThinItalic.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Light Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Light Italic'),
url('/fonts/ProductSans-LightItalic.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Medium Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Medium Italic'),
url('/fonts/ProductSans-MediumItalic.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Bold';
font-style: normal;
font-weight: normal;
src: local('Product Sans Bold'),
url('/fonts/ProductSans-Bold.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Bold Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Bold Italic'),
url('/fonts/ProductSans-BoldItalic.woff') format('woff');
}
@font-face {
font-family: 'Product Sans Black Italic';
font-style: normal;
font-weight: normal;
src: local('Product Sans Black Italic'),
url('/fonts/ProductSans-BlackItalic.woff') format('woff');
}
@font-face {
font-family: 'NanumGothic';
src: url('/fonts/NanumGothic.eot');
src: url('/fonts/NanumGothic.eot') format('embedded-opentype'),
url('/fonts/NanumGothic.woff') format('woff');
}
html {
font-size: 10px;
font-family: 'NanumGothic', 'Product Sans Regular', Roboto, Arial, serif;
}
body {
font-size: 1.4rem;
background: ${theme.colors.bodyBackground};
color: ${theme.colors.primaryText};
margin: 0;
padding: 0;
line-height: 1.34;
}
p,
a,
h1,
h2,
h3,
h4,
h5,
span,
button,
input,
ul,
li {
margin: 0;
padding: 0;
font: inherit;
color: inherit;
}
li {
list-style: none;
}
a {
color: inherit;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
button {
cursor: pointer;
background: inherit;
}
`;
<file_sep>/src/libs/axios.ts
import originalAxios, { AxiosError, AxiosResponse } from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
import { isErrorResponse } from 'types/ErrorResponse';
import Domain from 'constants/Domain';
import { USE_API_MOCK } from 'constants/env';
// check axios response type
const isAxiosResponse = (item: unknown): item is AxiosResponse => {
const response = item as AxiosResponse<typeof item>;
return (
typeof response === 'object' &&
response.data !== undefined &&
typeof response.status === 'number' &&
response.config !== undefined
);
};
// check axios error type
const isAxiosError = (item: unknown): item is AxiosError => {
const error = item as AxiosError<typeof item>;
return (
typeof error === 'object' &&
typeof error.name === 'string' &&
typeof error.message === 'string' &&
error.config !== undefined &&
(typeof error.code === 'undefined' || typeof error.code === 'string') &&
typeof error.isAxiosError === 'boolean'
);
};
const axios = originalAxios.create({
baseURL: Domain.API_URL,
timeout: 2500,
headers: {
'Access-Control-Allow-Origin': '*'
},
withCredentials: true
});
axios.interceptors.response.use(
// response 가공
(response) => (isAxiosResponse(response) ? response.data : response),
// error 데이터 가공
(error) => {
// axios 외부의 에러인 경우
if (!isAxiosError(error)) {
throw error;
}
// axios 내부 에러인 경우
if (!isAxiosResponse(error.response)) {
throw error.response;
}
// response 에러가 아닌경우
if (!isErrorResponse(error.response.data)) {
throw error.response.data;
}
// api response 에서 발생한 에러인 경우
throw error.response.data.message;
}
);
// axios-mock-adapter
export const axiosMock = (options = {}): AxiosMockAdapter | null =>
USE_API_MOCK ? new AxiosMockAdapter(axios, options) : null;
export default axios;
<file_sep>/src/styles/Themes.ts
import deepmerge from 'deepmerge';
export const theme = {
colors: {
bodyBackground: '#fff',
hoverBackground: 'rgba(32,33,36,0.039)',
primaryText: '#3c4043',
secondaryText: '#5f6368',
contentShadow: 'rgba(0, 0, 0, 0.2)'
},
size: {
headerHeight: '64px',
leftPanelWidth: '250px'
},
effect: {
contentLoadingOpacity: 0.25,
shadow: '0 0 0.7rem #dbdbdb'
}
};
export const darkTheme = deepmerge(theme, {
colors: {
bodyBackground: 'black'
}
});
export type Theme = typeof theme | typeof darkTheme;
<file_sep>/src/libs/immerReducer.ts
import {
createActionCreators,
createReducerFunction,
ImmerReducer as BaseImmerReducer,
ImmerReducerClass as BaseImmerReducerClass,
ImmerReducerFunction
} from 'immer-reducer';
import {
CombinedState,
combineReducers,
Reducer,
StateFromReducersMapObject
} from 'redux';
import { mapObject } from 'underscore';
import { hydrateActions } from 'sagas/HydrateSaga';
export abstract class ImmerReducer<T> extends BaseImmerReducer<T> {
public abstract initialState: T;
public abstract hydrate(payload: T): void;
}
interface ImmerReducerClass extends BaseImmerReducerClass {
new (...args: unknown[]): ImmerReducer<unknown>;
}
interface Modules<T extends ImmerReducerClass> {
[key: string]: T;
}
type ModulesMapObject<M extends Modules<ImmerReducerClass>> = {
[K in keyof M]: ImmerReducerFunction<M[K]>;
};
export function combineModules<T extends Modules<ImmerReducerClass>>(
modules: T
): Reducer<CombinedState<StateFromReducersMapObject<ModulesMapObject<T>>>> {
const map = (module, moduleName) => {
hydrateActions[moduleName] = createActionCreators(module);
const moduleObject = new module();
return createReducerFunction(module, moduleObject.initialState);
};
return combineReducers(mapObject<T, typeof map>(modules, map));
}
export * from 'immer-reducer';
<file_sep>/src/pages/api/test.ts
import { NextApiRequest, NextApiResponse } from 'next';
interface Data {
data?: string;
message?: string;
}
export default (req: NextApiRequest, res: NextApiResponse<Data>): void => {
const origin = req.headers['origin'] || '*';
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET');
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin'
);
if (req.method === 'GET') {
const { name = '' } = req.query;
res.status(200).json({ data: `Test Api ${name}` });
} else if (req.method === 'OPTIONS') {
res.status(200).end();
} else {
res.status(400).json({ message: 'ERROR' });
}
};
<file_sep>/src/sagas/index.ts
import { Store } from 'redux';
import { END } from 'redux-saga';
import { all, call } from 'redux-saga/effects';
import { SagaStore } from 'modules/store';
import { HydrateSaga } from 'sagas/HydrateSaga';
import { TestSaga } from 'sagas/TestSaga';
// root saga
export function* rootSaga(): Generator {
yield all([call(TestSaga), call(HydrateSaga)]);
}
/**
* end saga process when ssr
* @param store
*/
export const endServerSideSaga = async (store: Store): Promise<void> => {
const sagaStore = store as SagaStore;
if (sagaStore.sagaTask) {
sagaStore.dispatch(END);
await sagaStore.sagaTask.toPromise();
}
};
<file_sep>/src/sagas/HydrateSaga.ts
import { HYDRATE } from 'next-redux-wrapper';
import { all, put, take } from '@redux-saga/core/effects';
import { createActionCreators } from 'immer-reducer';
import { mapObject, values } from 'underscore';
import { RootReducerState } from 'modules';
interface HydrateActions {
[key: string]: ReturnType<typeof createActionCreators>;
}
// hydrate 발생 시 동기화 해줄 action 리스트
export const hydrateActions: HydrateActions = {};
interface HydrateAction {
type: typeof HYDRATE;
payload: RootReducerState;
}
/**
* hydrate 발생 시 각 reducer 와 동기화
* @constructor
*/
export function* HydrateSaga(): Generator {
const { payload } = (yield take(HYDRATE)) as HydrateAction;
const actions = values(
mapObject(hydrateActions, (action, name) =>
typeof action['hydrate'] === 'function'
? put(action['hydrate'](payload[name]))
: null
)
);
yield all(actions);
}
<file_sep>/.storybook/preview.js
import React from 'react';
import AppProvider from '../src/libs/AppProvider';
import { initStore } from '../src/modules/store';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' }
};
export const decorators = [
(Story) => (
<AppProvider store={initStore()}>
<Story />
</AppProvider>
)
];
<file_sep>/src/config/moment/locale.ts
import moment from 'moment';
moment.locale('ko');
moment.updateLocale('ko', {
// 시간 비교 텍스트
relativeTime: {
future: 'in %s',
past: '%s 전',
s: '몇초',
ss: '%d초',
m: '1분',
mm: '%d분',
h: '한시간',
hh: '%d시간',
d: '하루',
dd: '%d일',
w: '일주일',
M: '한달',
MM: '%d달',
y: '일년',
yy: '%d년'
},
// 요일 텍스트
weekdays: [
'일요일',
'월요일',
'화요일',
'수요일',
'목요일',
'금요일',
'토요일'
],
// 오전 / 오후 텍스트
meridiem: (hour) => (hour < 12 ? '오전' : '오후')
});
<file_sep>/.jest/jest.setup.ts
import path from 'path';
require('dotenv').config({ path: path.resolve(__dirname, '../.env.test') });
import '@testing-library/jest-dom/extend-expect';
// jest 타입아웃 30초로 설정
jest.setTimeout(30000);
<file_sep>/lint-staged.config.js
// eslint-disable-next-line @typescript-eslint/no-var-requires
const escape = require('shell-quote').quote;
const isWin = process.platform === 'win32';
module.exports = {
'**/*.{js,jsx,ts,tsx}': (filenames) => {
const escapedFileNames = filenames
.map(
(filename) =>
`"${
isWin
? filename.replace(/[[\]]/g, '[$&]')
: escape([filename])
}"`
)
.join(' ');
return [
`yarn format --with-node-modules ${escapedFileNames}`,
`yarn lint:fix ${filenames
.map((f) => `"${f.replace(/[[\]]/g, '[$&]')}"`)
.join(' ')}`,
`git add ${escapedFileNames}`
];
},
'**/*.{json,md,mdx,css,html,yml,yaml,scss}': (filenames) => {
const escapedFileNames = filenames
.map(
(filename) =>
`"${
isWin
? filename.replace(/[[\]]/g, '[$&]')
: escape([filename])
}"`
)
.join(' ');
return [
`yarn format ${escapedFileNames}`,
`git add ${escapedFileNames}`
];
}
};
| 80073680c92906266c697fdf91913b52254f2545 | [
"JavaScript",
"TypeScript",
"JSON with Comments",
"Markdown"
] | 25 | TypeScript | ChoSeoHwan/next-ts-template | 7b970b90a26851cd8d344b439dfec3ef9a6f1714 | 93adca113849807f0ea03d5ddc9981c045afe62d |
refs/heads/main | <repo_name>PetAdote/petAdote_MOBILE<file_sep>/src/component/CaixaPublicacoesPerfil.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
import PublicacoesDoPerfil from '../component/PubicacoesPerfil'
function CaixaPublicacoes() {
return (
<View style={styles.caixaPublicacoes}>
<ScrollView nestedScrollEnabled = {true}>
<View style={styles.flexBoxPosatagem}>
<View style={styles.alinharPubicacaoAEsquerda}>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
</View>
<Text> </Text>
<View style={styles.alinharPubicacaoADireita}>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
<PublicacoesDoPerfil/>
</View>
</View>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
caixaPublicacoes: {
backgroundColor: '#674ea7',
width: 300,
height: 500,
marginRight: 30,
marginLeft: 30,
bottom: 610,
},
alinharPubicacaoAEsquerda: {
marginLeft: 15,
marginTop: 40,
},
alinharPubicacaoADireita: {
marginLeft: 15,
marginTop: 40,
},
flexBoxPosatagem: {
flexDirection: 'row',
},
})
export default CaixaPublicacoes<file_sep>/src/component/PegarImagem.js
/*
import * as ImagePicker from 'expo-image-picker'
import React, { useState, useEffect } from 'react'
import Constants from 'expo-constants';
export function imagem() {
const [image, setImage] = useState(null);
useEffect(() => {
(async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
})();
}, []);
}
export default imagem
*/<file_sep>/src/pages/HomePage.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import BarraMomentos from '../component/BarraMomentos'
import FormRow from '../component/FormRow'
import BotaoPesquisar from '../component/BotaoPesquisar'
import CaixaDePostagem from '../component/CaixaDePostagem'
import AnuncioMomentos from '../component/BarraAnunciosMomentos'
export class Home extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<View style={styles.background}>
<ScrollView>
<View style={styles.flexBoxStoriesPesquisar}>
<BarraMomentos/>
<BotaoPesquisar/>
</View>
<AnuncioMomentos/>
<View style={styles.flexBoxCaixaDePostagem}>
<View style={styles.PostagensAEsquerda}>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
</View>
<Text> </Text>
<View style={styles.PostagensADireita}>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
<CaixaDePostagem/>
</View>
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
background:{
flex:1,
backgroundColor: '#93c47d',
},
flexBoxStoriesPesquisar: {
flexDirection: 'row',
},
flexBoxCaixaDePostagem: {
flexDirection: 'row',
},
PostagensAEsquerda: {
marginTop: 15,
marginLeft: 10,
},
PostagensADireita: {
marginTop: 15,
marginRight: 10,
},
})
export default Home
<file_sep>/src/pages/CadastroPage2.js
import React, { useState, useEffect } from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import {AutoGrowingTextInput} from 'react-native-autogrow-textinput';
import * as ImagePicker from 'expo-image-picker'
import Constants from 'expo-constants';
import FormRow from '../component/FormRow'
export class TelaCadastro2 extends React.Component {
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
this.setState({image: result.uri});
}
console.log(result);
}
_pickImage2 = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
this.setState({image2: result.uri});
}
console.log(result);
}
state = {
image: null,
image2: null,
}
constructor(props){
super(props)
}
render() {
let { image, image2 } = this.state;
return (
<View style={styles.background}>
<KeyboardAvoidingView>
<ScrollView>
<View style={styles.flexBoxCabecalho}>
<View style={styles.cabecalho}>
<Text style={styles.tituloCadastro}>Cadastro 2/3: </Text>
</View>
<Text> </Text>
<View style={styles.logo}>
<Image source={require('../../assets/logo.png')}/>
</View>
</View>
<View style={styles.container}>
<Text> </Text>
<Text style={styles.textCadastro}>Foto (opicional):</Text>
<Text> </Text>
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
<Text> </Text>
<View>
<TouchableOpacity style={styles.btnProximoEscolher} onPress={this._pickImage}>
<Text style={styles.submitTextProximoEscolher}>Escolher</Text>
</TouchableOpacity>
</View>
<Text> </Text>
<Text style={styles.textCadastro}>Capa (opicional):</Text>
<Text> </Text>
{image2 && <Image source={{ uri: image2 }} style={{ width: 200, height: 200 }} />}
<Text> </Text>
<View>
<TouchableOpacity style={styles.btnProximoEscolher} onPress={this._pickImage2}>
<Text style={styles.submitTextProximoEscolher}>Escolher</Text>
</TouchableOpacity>
</View>
<Text> </Text>
<FormRow>
<Text style={styles.textCadastro}>Bios/Detalhes (opicional):</Text>
<AutoGrowingTextInput style={styles.inputBiosDetalhes}/>
</FormRow>
</View>
<Text> </Text>
<View style={styles.loginProximoEscolher}>
<View>
<TouchableOpacity style={styles.btnLogin} onPress={() => {this.props.navigation.navigate('LoginPetAdote');}}>
<Text style={styles.submitLogin}>Login</Text>
</TouchableOpacity>
</View>
<Text> </Text>
<View>
<TouchableOpacity style={styles.btnProximoEscolher} onPress={() => {this.props.navigation.navigate('CadastroPetAdote3');}}>
<Text style={styles.submitTextProximoEscolher}>Proximo</Text>
</TouchableOpacity>
<Text> </Text>
</View>
</View>
</ScrollView>
</KeyboardAvoidingView>
</View>
)
}
}
const styles = StyleSheet.create({
background:{
flex:1,
backgroundColor: '#674ea7',
},
tituloCadastro: {
color: '#FFF',
fontSize: 25,
},
cabecalho: {
marginLeft: 12,
marginTop: 30,
},
logo: {
marginTop: 30,
},
flexBoxCabecalho: {
flexDirection: 'row',
},
textCadastro: {
color: '#FFF',
fontSize: 20,
},
container: {
margin: 12,
width: '100%',
},
textEspacos: {
fontSize: 5,
},
loginProximoEscolher: {
marginLeft: 12,
flexDirection: 'row',
},
btnProximoEscolher: {
backgroundColor: '#FFF',
height: 38,
width: 125,
alignItems: 'center',
justifyContent: 'center',
},
submitTextProximoEscolher: {
color: '#000000',
fontSize: 18,
},
btnLogin: {
color: '#ebbe4b',
fontSize: 18,
},
submitLogin: {
color: '#ebbe4b',
fontSize: 18,
},
inputBiosDetalhes: {
backgroundColor: '#FFF',
width: '49%',
color: '#222',
fontSize: 17,
},
})
export default TelaCadastro2
<file_sep>/README.md
# petAdote_MOBILE
Repositório do cliente Mobile do projeto PetAdote - Facilitará o uso da aplicação em smartphones.
<file_sep>/src/component/PubicacoesPerfil.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from './FormRow'
function PublicacoesDoPerfil() {
return (
<View>
<TouchableOpacity>
<Image source={require('../../assets/imagemPostagemX.png')} style={styles.alinharPubicacao}/>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
alinharPubicacao: {
width: 120,
height: 120,
marginBottom: 40,
},
})
export default PublicacoesDoPerfil<file_sep>/src/component/CaixaDePostagem.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
function CaixaDePostagem() {
return (
<View style={styles.estiloPostagem}>
<View style={styles.BarraMarrom}>
<TouchableOpacity>
<Text style={styles.pontoPontoPonto}>...</Text>
</TouchableOpacity>
</View>
<View style={styles.alinharImagem}>
<TouchableOpacity style={styles.TouchableimagemPostagem}>
<Image source={require('../../assets/imagemPostagemX.png')} style={styles.imagemPostagem}/>
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
BarraMarrom: {
backgroundColor: '#783f04',
width: 150,
height: 20,
//flexDirection: 'row',
justifyContent: 'center',
},
pontoPontoPonto: {
color: 'white',
fontSize: 30,
textAlign: 'right',
fontWeight: 'bold',
marginBottom: 15,
marginRight: 5,
},
imagemPostagem: {
maxWidth: 150,
maxHeight: 150,
},
alinharImagem: {
justifyContent: 'space-around',
},
TouchableimagemPostagem: {
maxWidth: 150,
maxHeight: 150,
marginBottom: 30,
},
})
export default CaixaDePostagem<file_sep>/src/component/BarraPublicacoesAnimaisPerfilUsuario.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
function PublicacoesAnimais() {
return (
<View style={styles.alinharAnuncioMomento}>
<View style={styles.BotaoAnuncio}>
<TouchableOpacity>
<Text style={styles.TextoAnuncioMomento}>Publicações</Text>
</TouchableOpacity>
</View>
<View style={styles.BotaoMomento}>
<TouchableOpacity>
<Text style={styles.TextoAnuncioMomento}>Animais</Text>
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
BotaoAnuncio: {
backgroundColor: '#6fa8dc',
width: 150,
height: 40,
justifyContent: 'center',
alignItems: 'center',
},
BotaoMomento: {
backgroundColor: '#6fa8dc',
width: 150,
height: 40,
justifyContent: 'center',
alignItems: 'center',
},
TextoAnuncioMomento: {
textAlign: 'center',
color: 'white',
fontSize: 20,
},
alinharAnuncioMomento: {
flexDirection: 'row',
marginRight: 30,
marginLeft: 30,
bottom: 610,
},
})
export default PublicacoesAnimais<file_sep>/src/component/ImagemBanner.js
import React from 'react'
import { render } from 'react-dom'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
function ImagemDoBanner() {
return (
<View>
<View style={styles.BannerStyle}>
<Image source={require('../../assets/banner.jpg')} style={styles.ImageBannerStyle}/>
</View>
</View>
)
}
const styles = StyleSheet.create({
BannerStyle: {
marginRight: 30,
marginLeft: 30,
},
ImageBannerStyle: {
width: 300,
height: 176,
},
})
export default ImagemDoBanner<file_sep>/src/component/BotaoPesquisar.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
function BotaoPesquisar() {
return (
<TouchableOpacity style={styles.botao}>
<Image source={require('../../assets/vetor-pesquisar.png')} style={styles.Icone}/>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
botao: {
backgroundColor: '#b6d7a8',
width: 130,
height: 55,
justifyContent: 'center',
alignItems: 'center',
},
Icone: {
height: 40,
width: 40,
},
})
export default BotaoPesquisar<file_sep>/src/component/FotoDePerfil.js
import React from 'react'
import { render } from 'react-dom'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
function FotoPerfil() {
return (
<View>
<Image source={require('../../assets/perfil-vetor2.png')} style={styles.PerfilVetor}/>
</View>
)
}
const styles = StyleSheet.create({
PerfilVetor: {
maxHeight: 49,
maxWidth: 49,
},
})
export default FotoPerfil<file_sep>/src/component/PerfilButton.js
import React from 'react'
import { render } from 'react-dom'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
import { useNavigation } from '@react-navigation/native';
import FotoPerfil from '../component/FotoDePerfil'
function BotaoPerfil() {
const navigation = useNavigation();
return (
<View style={styles.AlinharBotaoEsquerdo}>
<TouchableOpacity style={styles.BotaoMais} onPress={() => {navigation.navigate('PerfilDoUsuario');}}>
<FotoPerfil style={styles.PerfilVetor}/>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
BotaoMais:{
backgroundColor: '#b4a7d6',
borderRadius: 100,
alignItems: 'center',
justifyContent: 'center',
height: '90%',
width: 45,
},
Mais: {
color: 'black',
fontSize: 50,
textAlign: 'center',
fontWeight: 'bold',
justifyContent: 'center',
},
AlinharBotaoEsquerdo: {
marginRight: 13,
alignItems: 'center',
justifyContent: 'center',
},
PerfilVetor: {
maxHeight: 49,
maxWidth: 49,
},
})
export default BotaoPerfil<file_sep>/src/pages/CadastroPage3.js
import React from 'react'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
export class TelaCadastro3 extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<View style={styles.background}>
<KeyboardAvoidingView>
<ScrollView>
<View style={styles.flexBoxCabecalho}>
<View style={styles.cabecalho}>
<Text style={styles.tituloCadastro}>Cadastro 3/3: </Text>
<Text> </Text>
<Text> </Text>
</View>
<Text> </Text>
<View style={styles.logo}>
<Image source={require('../../assets/logo.png')}/>
</View>
</View>
<View style={styles.container}>
<Text style={styles.tituloEndereco}>Endereço: </Text>
<Text> </Text>
<View style={styles.estadoCepFlexBox}>
<FormRow>
<Text style={styles.textCadastro}>Estado:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputEstado}
></TextInput>
</FormRow>
<Text> </Text>
<FormRow>
<Text style={styles.textCadastro}>CEP:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputCep}
></TextInput>
</FormRow>
</View>
<Text style={styles.textEspacos}> </Text>
<FormRow>
<Text style={styles.textCadastro}>Cidade:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputCidadeBairroLogradouro}
></TextInput>
</FormRow>
<Text style={styles.textEspacos}> </Text>
<FormRow>
<Text style={styles.textCadastro}>Bairro:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputCidadeBairroLogradouro}
></TextInput>
</FormRow>
<Text style={styles.textEspacos}> </Text>
<FormRow>
<Text style={styles.textCadastro}>Logradouro:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputCidadeBairroLogradouro}
></TextInput>
</FormRow>
<Text style={styles.textEspacos}> </Text>
<FormRow>
<Text style={styles.textCadastro}>Número:</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputNumero}
></TextInput>
</FormRow>
<Text style={styles.textEspacos}> </Text>
<FormRow>
<Text style={styles.textCadastro}>Complemento: (opcional)</Text>
<TextInput
autoCorrect={false}
onChangeText={()=>{}}
style={styles.inputComplemento}
></TextInput>
</FormRow>
</View>
<Text> </Text>
<Text style={styles.textEspacos}> </Text>
<View style={styles.loginProximo}>
<View>
<TouchableOpacity style={styles.btnLogin} onPress={() => {this.props.navigation.navigate('LoginPetAdote');}}>
<Text style={styles.submitLogin}>Login</Text>
</TouchableOpacity>
</View>
<Text> </Text>
<View>
<TouchableOpacity style={styles.btnProximo}>
<Text style={styles.submitTextProximo} onPress={() => {this.props.navigation.navigate('HomePage');}}>Finalizar</Text>
</TouchableOpacity>
</View>
</View>
</ScrollView>
</KeyboardAvoidingView>
</View>
)
}
}
const styles = StyleSheet.create({
background:{
flex:1,
backgroundColor: '#674ea7',
},
tituloCadastro: {
color: '#FFF',
fontSize: 25,
},
cabecalho: {
marginLeft: 12,
marginTop: 30,
},
logo: {
marginTop: 30,
},
flexBoxCabecalho: {
flexDirection: 'row',
},
textCadastro: {
color: '#FFF',
fontSize: 20,
},
inputCidadeBairroLogradouro: {
backgroundColor: '#FFF',
width: '50%',
color: '#222',
fontSize: 17,
padding: 1,
},
container: {
margin: 12,
width: '100%',
},
inputComplemento: {
backgroundColor: '#FFF',
width: 130,
color: '#222',
fontSize: 17,
padding: 1,
},
inputNumero: {
backgroundColor: '#FFF',
width: 102,
color: '#222',
fontSize: 17,
padding: 1,
},
inputEstado: {
backgroundColor: '#FFF',
color: '#222',
width: 120,
fontSize: 17,
padding: 1,
},
inputCep: {
backgroundColor: '#FFF',
width: 75,
color: '#222',
fontSize: 17,
padding: 1,
},
textEspacos: {
fontSize: 5,
},
loginProximo: {
marginLeft: 12,
flexDirection: 'row',
},
btnProximo: {
backgroundColor: '#FFF',
height: 38,
width: 125,
alignItems: 'center',
justifyContent: 'center',
},
submitTextProximo: {
color: '#000000',
fontSize: 18,
},
btnLogin: {
color: '#ebbe4b',
fontSize: 18,
},
submitLogin: {
color: '#ebbe4b',
fontSize: 18,
},
estadoCepFlexBox: {
flexDirection: 'row',
},
tituloEndereco: {
color: '#FFF',
fontSize: 23,
},
})
export default TelaCadastro3
<file_sep>/src/component/BiosEDetalhes.js
import React from 'react'
import { render } from 'react-dom'
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, Button, ScrollView} from 'react-native'
import FormRow from '../component/FormRow'
function BiosDetalhesUsuario() {
return (
<View>
<View style={styles.EstiloDetalhes}>
<Text style={styles.EstiloTextoDetalhes}>Bios e detalhes</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
EstiloDetalhes: {
backgroundColor: '#8e7cc3',
justifyContent: 'center',
alignItems: 'center',
width: 300,
height: 130,
marginRight: 30,
marginLeft: 30,
bottom: 609,
},
EstiloTextoDetalhes: {
fontSize: 20,
},
})
export default BiosDetalhesUsuario<file_sep>/src/component/FormRow.js
import React from 'react'
import { StyleSheet, View } from 'react-native'
const FormRow = props => {
const { children } = props
return (
<View>
{ children }
</View>
)
}
export default FormRow; | f3ea95b72623588034c6469c087bb61f24963568 | [
"JavaScript",
"Markdown"
] | 15 | JavaScript | PetAdote/petAdote_MOBILE | e59b8e294b619bf917be27e33423fb631d3671f5 | 83e1ebea5c39218cb66a535b92776cb205b54cfc |
refs/heads/master | <repo_name>xiepf1101/python_study<file_sep>/workspaceDemo/request_http.py
#coding=utf-8
import requests
import os
import time
url = 'http://www.baidu.com'
while True:
try:
data = requests.get(url).text
print("connection success")
time.sleep(300)
except:
print('connection failed')
b = os.popen('sayHelloBat.bat')
b.read()
time.sleep(60)<file_sep>/workspaceDemo/helloBat.py
#Coding=utf-8
#.bat文件运行此文件
import time
if __name__ == "__main__" :
print("Hello Bat")
time.sleep(5)
print("孙红平长得好看")<file_sep>/workspaceDemo/QuoteEmp.py
#coding=utf-8
#引用class Employee
<file_sep>/workspaceDemo/number.py
#coding=utf-8
import math
import random
#数字
var1 = 1
var2 = 10
print(var1)
print(var2)
#del var1 删除对数字对象的引用
#int 无限大 (python2中有 long 类型)
int1 = 100
print(int1)
#float 浮点数
float1 = 0.012
print("float1",float1)
float2 = 2.5e2 #=2.5×10×10
print("float2",float2)
#complex 复数
complex1 = 3.14j
print(complex1)
#数字类型转换
x = 11.22
print(x) #float
x = int(x) #转为int
print(x)
x = float(x) #转为float
print(x)
#x = long(x) #转为long类型 python2.0
#print(x)
x = complex(x) #转为complex复数
print(x)
#数字函数
x = -11
print(x)
x = abs(x) #绝对值
print(x)
x = math.ceil(x) #返回不小于(大于等于)x的最小整数
print(x)
x = math.exp(x) #e的x次幂
print(x)
x = math.fabs(x) #x的绝对值
print(x)
x = math.floor(x) #返回不大于(小于等于)x的最大整数
print(x)
x = math.log(x) #返回x的自然对数(x > 0)。
print(x)
x = math.log10(x) #返回10的x的对数
print(x)
x,y,z = 1,2,3
a = max(x,y,z)
print(a) #返回给定参数中的最大值
a = min(x,y,z)
print(a) #返回给定参数中的最小值
a = math.modf(x) # 将x的分数和整数部分切成两项放入元组中,两个部分与x具有相同的符号。整数部分作为浮点数返回。
print(a)
a = pow(y,z) #返回y的z次方
print(a)
a = round(-0.5333) #四舍五入
print(a)
a = math.sqrt(4) #平方根
print(a)
#随机数函数
str1 = "hello"
a = random.choice(str1) #来自列表,元组或字符串的随机项目。
print(a)
a = random.randrange(1,100,2) # 从范围(start, stop, step)中随机选择的元素。 start - 范围的起始点,这将包括在范围内,默认值为0。stop - 范围的起终点,这将包括在范围内,默认值为1。step - 跳跃值,不包括在范围内。
print(a)
a = int(random.random()*10+1) #返回随机浮点数r(0 <= r < 1)
print(a)
list = [1,2,3,4]
print("list",list)
random.shuffle(list) #将列表的内容位置随机打乱
print(list)
a = random.uniform(1,2) #返回随机浮点数 r (x <= r < y)
print(a)
#三角函数
a = math.acos(1) #返回x的弧余弦值
print(a)
a = math.asin(1) #返回x的弧线正弦
print(a)
a = math.atan(1) #返回x的反正切
print(a)
a = math.atan2(-1,1) #返回atan(y/x)
print(a)
a = math.cos(1) #返回x弧度的余弦
print(a)
a = math.hypot(0,2) #返回欧几里得规范
print(a)
a = math.sin(1) #返回x弧度的正弦
print(a)
a = math.tan(1) #返回x弧度的正切值
print(a)
a = math.degrees(1) #将角度x从弧度转为度
print(a)
a = math.radians(30) #将角度转为弧度
print(a)
<file_sep>/workspaceDemo/file_rw.py
#coding=utf-8
#文件读写
#文件读取
try:
# r 表示读取UTF编码的文本文件
# rb 表示读取二进制文件,例如图片和视频
f = open('D:/Python/workspace/python_study_file/filerw.txt','r')
print(f.read())
except:
system.exit(0)
finally:
if f:
f.close()
# 用with更简单,不用写close
#with open('/path/to/file', 'r') as f:
# print(f.read())
#文件写入
with open('D:/Python/workspace/python_study_file/filerw.txt','w') as f:
f.write('python to write hello world')<file_sep>/DeepLearning/MultiRegreDeliveryExample.py
#coding=utf-8
#E:/Python/workspace/DeepLearning/NeuralNetworks/contact.csv
#多元线性回归
import sys
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
from numpy import genfromtxt
import numpy as np
from sklearn import datasets, linear_model
#英里数 次数 时间
dataPath = r"E:/Python/workspace/DeepLearning/NeuralNetworks/contact.csv"
deliveryData = genfromtxt(dataPath, delimiter=',')
print("data:\r",deliveryData)
X = deliveryData[:, :-1]
Y = deliveryData[:, -1]
print("X:\r",X)
print("Y:\r",Y)
regr = linear_model.LinearRegression()
regr.fit(X, Y)
print('coefficients:', regr.coef_)
print("intercept:",regr.intercept_)
xPred = [[102, 6]]
yPred = regr.predict(xPred)
print("predicted y:",yPred)<file_sep>/workspaceDemo/fastai_image.py
#coding=utf-8
#imageclassification
from fastai import *
from fastai.vision import *
folder = 'black'
file = 'urls_black.txt'
folder = 'teddys'
file = 'urls_teddys.txt'
folder = 'grizzly'
file = 'urls_grizzly.txt'
#download_images
path = Path('data/bears')
dest = path/folder
dest.mkdir(parents=True, exist_ok=True)
classes = ['teddys','grizzly','black']
download_images(path/file, dest, max_pics=200)
for c in classes:
print(c)
verify_images(path/c, delete=True, max_workers=8)
np.random.seed(42)
data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.2,
ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)
data.classes
data.show_batch(rows=3, figsize=(7,8))
data.classes, data.c, len(data.train_ds), len(data.valid_ds)
#Train Model
learn = create_cnn(data, models.resnet34, metrics=error_rate)
learn.fit_one_cycle(4)
learn.save('stage-1')
learn.unfreeze()
learn.lr_find()
learn.recorder.plot()
learn.fit_one_cycle(2, max_lr=slice(3e-5,3e-4))
learn.save('stage-2')
#interpretation
iterp.load('stage-2')
interp = ClassificationInterpretation.from_learner(learn)
interp.plot_confusion_matrix()
#cleaning up 干扰的数据或者无用的数据清理
from fastai.widgets import *
losses,idxs = interp.top_losses()
top_loss_paths = data.valid_ds.x[idxs]
fd = FileDeleter(file_paths=top_loss_paths)
#Putting your model in production 生产测试
data.classes
#如果不是使用GPU,则进行下面配置。反之则免之
fastai.defaults.device = torch.device('cpu')
img = open_image(path/'black'/'0000021.jpg')
img
classes = ['black', 'grizzly', 'teddys']
data2 = ImageDataBunch.single_from_classes(path, classes, tfms=get_transforms(), size=224).normalize(imagenet_stats)
learn = create_cnn(data2, models.resnet34)
learn.load('stage-2')
pred_class,pred_idx,outputs = learn.predict(img)
pred_class
learn = create_cnn(data, models.resnet34, metrics=error_rate)
learn.fit_one_cycle(1, max_lr=0.5)
learn = create_cnn(data, models.resnet34, metrics=error_rate0)
learn.fit_one_cycle(5, max_lr=1e-5)
learn.recorder.plot_losses()
learn = create_cnn(data, models.resnet34, metrics=error_rate)
learn.fit_one_cycle(1)
<file_sep>/workspaceDemo/simpleSpiderByCookie.py
#coding=utf-8
#爬去知乎 headers的应用
from http import cookiejar
from urllib import request
from bs4 import BeautifulSoup
# # cookie的测试
# # 声明一个CookieJar实例对象
cookie = cookiejar.CookieJar()
# # 创建cookie处理器
handle = request.HTTPCookieProcessor(cookie)
# # 通过cookie处理器创建opener实例
opener = request.build_opener(handle)
# # 通过opener实例打开网页
response = opener.open('https://www.zhihu.com/question/25313930')
# # 打印cookie
for item in cookie:
print('Name = %s' % item.name)
print('Value = %s' % item.value)
#命名保存cookie的文件和文件名
filename = 'D:\cookie.txt'
#保存cookie到文件
def saveCookie():
cookie = cookiejar.MozillaCookieJar(filename)
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler)
response = opener.open('https://www.zhihu.com/question/25313930')
# ignore_discard的意思是即使cookies将被丢弃也将它保存下来;
# ignore_expires的意思是如果在该文件中cookies已经存在,则覆盖原文件写入
cookie.save(ignore_discard=True, ignore_expires=True)
saveCookie()
#从文件中获取cookie并访问
#创建MozillaCookirjar实例
cookie = cookiejar.MozillaCookieJar()
#从文件中读取cookie内容到变量
cookie.load(filename,ignore_discard=True,ignore_expires=True)
#创建cookie处理器
handle = request.HTTPCookieProcessor(cookie)
#通过cookie处理器创建opener对象
opener = request.build_opener(handle)
#通过opener对象的open方法打开网页
response = opener.open('https://www.zhihu.com/question/25313930')
html = response.read()
#解析html
soup = BeautifulSoup(html, 'lxml')
storys = soup.find_all('div',class_="List-item")
print(len(storys))
for story in storys:
print(story)
nameLabel = story.find('meta', itemprop="name")
name = nameLabel["content"]
with open("D:/thisme_D/Python/workspace/python_study_file/"+str(name)+'.txt', 'w') as f:
storyText = story.find('span', class_="RichText ztext CopyrightRichText-richText")
#storyPages = storyText.find_all('p')
try:
#获取多个内容,不过需要遍历获取,比下:
for string in storyText.strings:
f.write(repr(string)+"\n")
print("D:\thisme_D\Python\workspace\python_study_file"+str(name)+' has been finished')
except Exception:
print('Something is wrong on writing to txt')
print('That is all')
soup = BeautifulSoup(html, 'lxml')
with open("D:/thisme_D/Python/workspace/python_study_file/html_.txt", 'w') as f:
try:
f.write(str(html)+"\n")
except Exception:
print('Something is wrong on writing to txt')
storys = soup.find_all('div',class_="ContentItem AnswerItem")
print(len(storys))
for story in storys:
print(story)
nameLabel = story.find('meta', itemprop="name")
name = nameLabel["content"]
with open("D:/thisme_D/Python/workspace/python_study_file/"+str(name)+'.txt', 'w') as f:
storyText = story.find('span', class_="RichText ztext CopyrightRichText-richText")
#storyPages = storyText.find_all('p')
try:
#获取多个内容,不过需要遍历获取,比下:
for string in storyText.strings:
f.write(repr(string)+"\n")
print("D:\thisme_D\Python\workspace\python_study_file"+str(name)+' has been finished')
except Exception:
print('Something is wrong on writing to txt')
print('That is all')<file_sep>/workspaceDemo/SimpleSpiderToImg.py
#coding=utf-8
#根据正则表达式匹配图片 图片文件保存
#以.asp、.jsp、.php 为扩展名,或者有"?"、"="、"%",以及"&"、"$"、"id"等乱七八糟的字符的网页,都是动态页面 。
#静态网站 .html、.htm、.shtml
import requests #cmd #pip install requests
import re
#url = 'http://www.nipic.com/photo/jingguan/ziran/index.html'
url = 'http://www.nipic.com/photo/renwu/nvxing/index.html'
#获取网页源码
data = requests.get(url).text
#图片正则表达式
regex = r'<img src="http://static.nipic.com/images/grey.gif" data-src="(.*?.jpg)"'
#re 是一个列表
pa = re.compile(regex) #创建一个pa模板,使其符合匹配的网址
ma = re.findall(pa,data) #findall方法 找到data中所有符合pa的对象,添加到re中并返回
#图片的名字
i=0
print('start downloading')
for image in ma :
i+=1
print(image)
image = requests.get(image).content
print(str(i)+'.jpg')
#\ 要用转义符号\\ 表示 要注意元图片的格式
with open('D:/Python/workspace/python_study_file/'+str(i)+'.jpg','wb') as f:
f.write(image)
print('finish downloading')
end = 2
url1 = 'http://www.nipic.com/photo/baike/yule/index.html'
for num in range(1,end+1):
url=url1+"?page="+str(num)
print(url)
data = requests.get(url).text
pa = re.compile(regex)
ma = re.findall(pa,data)
for image in ma :
i+=1
image = requests.get(image).content
#\ 要用转义符号\\ 表示 要注意元图片的格式
with open('D:/Python/workspace/python_study_file/'+str(i)+'.jpg','wb') as f:
f.write(image) <file_sep>/workspaceDemo/function.py
#coding=utf-8
#函数
#函数块以关键字def开头,后跟函数名和小括号(())。
#任何输入参数或参数应放置在这些小括号中。也可以在这些小括号内定义参数。
#每个函数中的代码块以冒号(:)开始,并缩进。
#函数内的第一个语句可以是可选语句 - 函数的文档或docstring字符串。
#语句return [expression]用于退出一个函数,可选地将一个表达式传回给调用者。如果没有使用参数的return语句,则它与return None相同。
def printFunction(str):
"字符串输出函数" #函数内的第一句(可选语句)
print("str:",str)
return None
#函数调用
printFunction("printFunction")
#参数引用与传递
#Python语言中的所有参数(参数)都将通过引用传递。如果在函数中更改参数所指的内容,则更改也会反映在调用函数的外部
def changeme(mylist):
mylist[0] = 100
return
mylist = [1,2,3]
changeme(mylist)
print("mylist : ",mylist)
#参数mylist是changeme1()函数的局部变量。在函数中更改mylist不影响mylist的值。函数执行完成后
def changeme1(mylist):
mylist = [100,200,300]
return
mylist = [1,2,3]
changeme1(mylist)
print("mylist : ",mylist)
#函数参数
#1.必需参数
def print_(str):
print(str)
return
print_("必须参数")
#2.关键词参数
def print1(name,age):
print("name : ",name,"age : ",age)
return
#调用函数是传参可无序,但需要将关键词和参数进行匹配
print1(age = 15,name = "张三")
#3.默认参数
def print2(name,age = 25):
print("name : ",name,"age : ",age)
return
print2("李四",17)
print2("王五")
#4.可变长度参数
def change_(arg1,*vartuple):
print("arg1 : ",arg1)
for var in vartuple:
print("vart : ",var)
return
change_(1)
change_(1,2,3)
#5.匿名函数 lambda函数
sum = lambda arg1,arg2 : arg1+arg2
print(sum(1,2))
#全局变量和局部变量
total = 100 #全局变量
def sum_():
total = 2+3 #局部变量
print(total)
return
sum_()
print("total : ",total)<file_sep>/DeepLearning/SkLearnExample.py
#coding=utf-8
#最邻近规则KNN分类算法 应用
#指定sklearn 文件路径
import sys
print(sys.path)
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
from sklearn import neighbors
from sklearn import datasets
knn = neighbors.KNeighborsClassifier()
#数据集
iris = datasets.load_iris()
#print(iris)
#模板训练
#iris.data 特征数据集 iris.target 特征对应类别
knn.fit(iris.data, iris.target)
#模板验证
predictedLabel = knn.predict([[0.1, 0.2, 0.3, 0.4]])
print(predictedLabel)
<file_sep>/workspaceDemo/Vector.py
#coding=utf-8
#重载运算符 数据隐藏
class Vector():
#在secretCount 前+__则 __secretCount被隐藏
__secretCount = 0
def count(self):
self.__secretCount+=1
print(self.__secretCount)
def __init__(self,a,b):
self.a = a
self.b = b
def __str__(self):
return "Vector(%d,%d)" % (self.a,self.b)
def __add__(self,other):
return Vector(self.a + other.a,self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(3,-1)
print(v1 + v2)
#数据隐藏
v3 = Vector(1,2)
v3.count()
v3.count()
#__secretCount 属性被隐藏 引用会报错
#print(v3.__secretCount)<file_sep>/workspaceDemo/date.py
#coding=utf-8
#日期与时间
import time
import datetime
#日历 calendar
import calendar
#当前时间
print(datetime.datetime.now())
#时间差
starttime = datetime.datetime.now()
#等待10s
time.sleep(1)
endtime = datetime.datetime.now()
#时间差 秒
print((endtime - starttime).seconds)
#计算十天后的时间
currentdate = datetime.datetime.now()
tendate = currentdate + datetime.timedelta(days = 10)
print(str(tendate))
print(tendate.ctime())
#获取两个时间的时间差
t = ( datetime.datetime(2018,11,8,12,0,0) - datetime.datetime.now() ).total_seconds()
print("t = ",t)
#时间间隔
ticks = time.time()
#当前时间与1970-01-01间隔多少秒
print("ticks = ",ticks)
#获取当前时间
print(time.localtime())
#格式化时间
curtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
print("curtime = ",curtime)
#获取格式化时间
localtime = time.asctime(time.localtime())
print(localtime)
#日历 calendar
cal = calendar.month(2017,11)
print(cal)<file_sep>/workspaceDemo/urllibDemo.py
#coding=utf-8
#urllib详细使用方法(header,代理,超时,认证,异常处理)
import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()
print(html)
#Request 的使用
req = urllib.request.Request('http://python.org/')
response = urllib.request.urlopen(req)
page = response.read()
print(page)
#http 错误
import urllib.request
req = urllib.request.Request('http://www.111cn.net ')
try:
e = urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
#异常处理
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://www.111cn.net /")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn’t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print("good!")
print(response.read().decode("utf8"))
#Http认证
import urllib.request
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "https://www.111cn.net /"
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)
# use the opener to fetch a URL
a_url = "https://www.111cn.net /"
x = opener.open(a_url)
print(x.read())
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
a = urllib.request.urlopen(a_url).read().decode('utf8')
print(a)
#使用代理
import urllib.request
proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
a = urllib.request.urlopen("http://www.111cn.net").read().decode("utf8")
print(a)
#超时
import socket
import urllib.request
# timeout in seconds
timeout = 2
socket.setdefaulttimeout(timeout)
# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.111cn.net /')
a = urllib.request.urlopen(req).read()
print(a)
#发送数据
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : '<EMAIL>',
'login[password]' : '<PASSWORD>'
}
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
req.add_header('Referer', 'http://python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))
#发送数据和header
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : '<EMAIL>',
'login[password]' : '<PASSWORD>'
}
headers = { 'User-Agent' : user_agent }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))<file_sep>/workspaceDemo/loop.py
#coding=utf-8
import sys
#循环
list = [1,2,3,4]
print(list)
it = iter(list)
#print("next = ",next(it))
for x in it : print(x)
#it = iter(list)
#while True:
#try:
#print("next = ",next(it))
#except StopIteration:
#print("没有东西可以输出了")
#sys.exit()
print("break : 终止循环语句转至执行循环外的后续操作")
it = iter(list)
for y in it :
if y <= 3 :
print(y)
else :
print("break")
break
print("success")
print("continue : 跳出本次循环执行下一次循环")
it = iter(list)
for y in it :
if y == 2 :
print("contiune")
continue
else :
print(y)
print("success")
print("pass : 在不需要执行的情况下 并要求保证语法")
it = iter(list)
for y in it :
if y == 2 :
print("pass")
pass
else :
print(y)
print("success")
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()<file_sep>/workspaceDemo/regex.py
#coding=utf-8
#正则表达式 re
import re
#re.match(regex,string,flags=0) 从句头开始匹配
#re.search(regex,string,flags=0) 检查字符串中任何位置的匹配
class regexDemo:
regex = r"\w" # r 声明正则表达式(应该是吧) 可省略
def regexMethod(self,string):
reMatch = re.match(self.regex,string,flags=0) #匹配不成功返回None 成功返回匹配对象
print(reMatch.group())
reg = regexDemo()
reg.regexMethod("1")
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")
#search 检查字符串中任何位置的匹配
searchObj = re.search( r'Dogs', line, re.M|re.I) #re.I 不区分大小写
if searchObj:
print("searchObj.group() : ",searchObj.group())
else:
print("no search")
#re.sub(pattern, repl, string, max=0) 根据正则表达式对原有字符串修改(截取)
phone = "2018-959-559 # This is Phone Number"
sub1 = re.sub(r"\D","",phone)
print("sub1 : ",sub1)
sub2 = re.sub(r"#.*$","",phone)
print("sub2 : ",sub2)
#http://www.yiibai.com/python/python_reg_expressions.html
<file_sep>/DeepLearning/MultipleRerDummy.py
#coding=utf-8
#多元线性回归
import sys
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
from numpy import genfromtxt
import numpy as np
from sklearn import datasets,linear_model
dataPath = r"E:/Python/workspace/DeepLearning/NeuralNetworks/contact - 副本.csv"
deliveryData = genfromtxt(dataPath, delimiter=',')
#print("data",deliveryData)
X = deliveryData[:, :-1]
Y = deliveryData[:, -1]
print("X:\n",X)
print("Y:\n",Y)
regr = linear_model.LinearRegression()
regr.fit(X, Y)
print("coefficients:\n", regr.coef_)
print("intercept:\n", regr.intercept_)
xPred = [[102, 6, 0, 1, 0]]
yPred = regr.predict(xPred)
print("predicted y:",yPred)<file_sep>/workspaceDemo/hello.py
#coding=utf-8
# -*- coding:utf-8 -*-
#两种预设编码格式
#python变量类型
a=123
print(a)
num=100
flo=99.99
name="zhangsan"
print(num)
print(flo)
print(name)
print(num+flo)
print(flo-num)
a=b=c=1
print(a)
print(b)
print(c)
x,y,z=21,"name",110
print(x)
print(y)
print(z)
#String字符串
str = "hellopython"
print("str[0]="+str[0])
print("str[5:11]="+str[5:11])
print("str[2:]="+str[2:])
print("str[-1]="+str[-1])
print("str*2="+str*2)
print("str+!!!="+str+'!!!')
#列表list
list=[110,120,"jc","yy",11.9,'hj','mszh']
print('list = ',list)
print("list[0]=",list[0])
print("list[2:5]=",list[2:5])
print("list[2:]=",list[2:])
print("list[-1]=",list[-1])
print("list[-3:-1]=",list[-3:-1])
linkList=['link','jia',666]
print('list + linkList =',list+linkList)
#元组
tuple = ("tuple","nolist",110,120,'gg',"qq",666)
print("tuple = ",tuple)
print("tuple[0] = ",tuple[0])
print("tuple[2:5] = ",tuple[2:5])
print("tuple[2:] = ",tuple[2:])
print("tuple[-1] = ",tuple[-1])
print("tuple[-3:-1] = ",tuple[-3:-1])
linktuple = ("link","ddd")
print("tuple + linktuple = ",tuple+linktuple)
list[0] = 1111111
print("list = ",list)
#tuple[0] = "tuple111" 错误,元组不可以更新
#print("tuple = ",tuple)
#字典
dict = {}
dict[110] = {"警察"}
dict["火警"] = {119}
print("dict = ",dict)
print("dict['火警'] = ", dict["火警"])
tinydict = {'110':'抓小偷','火警':119}
print("tinydict = ",tinydict)
print("tinydict[110] = ",tinydict["110"])
print("tinydict.keys() = ",tinydict.keys())
print("tinydict.values() = ",tinydict.values())<file_sep>/demo/ToWordCloud.py
#coding=gbk
#python 生成词云
#简单词云
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba
#加载文件内容
text_from_file_with_apath = open('D:/thisme_D/Python/python_study/demo/hello.txt',encoding='utf-8').read()
#结巴分词器分词
wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all=True)
wl_space_split = " ".join(wordlist_after_jieba)
#云图的生成
my_wordcloud = WordCloud(background_color="white",width=1000,height=860, font_path="C:\\Windows\\Fonts\\STFANGSO.ttf").generate(wl_space_split)
#显示
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
#词云Demo
import jieba.analyse
from PIL import Image,ImageSequence
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
article= open('D:/thisme_D/Python/python_study/demo/hello.txt',encoding='utf-8').read()
result=jieba.analyse.textrank(article,topK=50,withWeight=True)
keywords = dict()
for i in result:
keywords[i[0]]=i[1]
print(keywords)
#获取原型图片
image= Image.open('D:/thisme_D/Python/python_study/demo/timg.jpg')
graph = np.array(image)
wc = WordCloud(font_path='C:/Windows/fonts/simhei.ttf',background_color='white',max_words=50,mask=graph,width=700,height=1244)
wc.generate_from_frequencies(keywords)
image_color = ImageColorGenerator(graph)
plt.imshow(wc)
plt.imshow(wc.recolor(color_func=image_color))
plt.axis("off")
plt.show()<file_sep>/workspaceDemo/spider_selenium.py
#coding=utf-8
#selenium的简单使用
#用法教程#https://cuiqingcai.com/2599.html
#使用文档#https://selenium-python.readthedocs.io/navigating.html
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
#打开请求的url
driver.get('http://www.baidu.com/')
#通过name属性寻找网页元素,此处寻找输入框
elem = driver.find_element_by_name('wd')
#模拟输入Python
elem.send_keys('Python')
#模拟点击回车
elem.send_keys(Keys.RETURN)
#获取网页渲染后的源代码
print(driver.page_source)
# 对于动态加载的网页,例如知乎,需要使用Selenium+ChromeDriver(或PhantomJS)
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
#知乎
url = 'https://www.zhihu.com/question/45694301'
#知乎爬虫 https://blog.csdn.net/qq_28057541/article/details/61921632
#让界面滚动
def scroll(driver):
driver.execute_script("""
(function () {
var y = document.body.scrollTop;
var step = 100;
window.scroll(0, y);
function f() {
if (y < document.body.scrollHeight) {
y += step;
window.scroll(0, y);
setTimeout(f, 50);
}
else {
window.scroll(0, y);
document.title += "scroll-done";
}
}
setTimeout(f, 1000);
})();
""")
driver = webdriver.Chrome()
driver.get(url)
scroll(driver)
#等待滑到页面最下方
time.sleep(150)
html = driver.page_source
soup = BeautifulSoup(html,'lxml')
storys = soup.find_all('div',class_='List-item')
for story in storys:
nameLabel = story.find('meta',itemprop='name')
name = nameLabel["content"]
with open('D:/thisme_D/Python/workspace/python_study_file/有哪些关于刀的故事/By '+str(name)+'.txt','w',encoding = 'utf-8') as f:
storyText = story.find('span', class_="RichText ztext CopyrightRichText-richText")
#输出方式一: 会打印全文 包括图片链接地址
for string in storyText.strings:
f.write(repr(string) + '\n')
#方式一结束
#输出方式二: 会有none出现
#try:
# storyPages = storyText.find_all('p')
# for storyPage in storyPages:
# f.write(str(storyPage.string)+"\n")
# #输出方式二结束
# print('By '+str(name)+' has been finished')
#except Exception:
# print(storyText)
# print('===Something is wrong on writing to txt')
print('That is all')<file_sep>/workspaceDemo/mysql.py
#coding=utf-8
#操作mysql数据库
import pymysql
# mysql version
#打开数据库连接
#db = pymysql.connect("127.0.0.1","root","root")
#创建游标
#cursor = db.cursor()
#创建游标后 通过execute() 方法来执行sql语句 进行数据库的操作
#cursor.execute("SELECT VERSION()") #查询mysql的版本号
#使用fetchone()方法获取单挑数据
#date = cursor.fetchone()
#打印
#print("datebase version:",date)
#关闭数据库连接
#db.close()
# 删除/创建 表
db = pymysql.connect("127.0.0.1","root","root","mysql") #ip username password datebaseName
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS employee") #如果table存在则删除
sql = """CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`first_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
cursor.execute(sql)
print("create table successful")
db.close()
#增加数据
db = pymysql.connect("127.0.0.1","root","root","mysql")
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE (FIRST_NAME,LAST_NAME,AGE,SEX,INCOME) VALUES ('Li','Si',19,'M',95)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Kobe', 'Bryant', 40, 'M', 8000)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Max', 'Su', 25, 'F', 2800)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
db.close()
print(sql)
print("insert successful")
# 查询数据
db = pymysql.connect("127.0.0.1","root","root","mysql")
cursor = db.cursor()
cursor.execute("SELECT * FROM employee")
date = cursor.fetchall()
print("date :",date)
db.close()
#查询表中数据 按照字典形式返回
db = pymysql.connect("127.0.0.1","root","root","mysql")
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME <= %d" % (1000)
try:
cursor.execute(sql)
resultAll = cursor.fetchall()
for row in resultAll:
#print(row)
first_name = row[1]
last_name = row[2]
age = row[3]
sex = row[4]
income = row[5]
print("name = %s %s,age = %s,sex = %s,income = %s" % \
(first_name,last_name,age,sex,income))
except:
import traceback
traceback.print_exc() #打印异常数据
print("没有查询到数据")
db.close()
#更新 update
db = pymysql.connect("localhost","root","root","mysql")
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE + 100 WHERE SEX = '%c'" % ('M')
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
#删除 delete
db = pymysql.connect("localhost","root","root","mysql")
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE < '%d'" % (40)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()<file_sep>/DeepLearning/SKLearnExample_SVM_pl.py
#coding=utf-8
import sys
print(sys.path)
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
import numpy as np
import pylab as pl
from sklearn import svm
#创建40个点
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20
#训练model
clf = svm.SVC(kernel='linear')
clf.fit(X, Y)
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clf.intercept_[0]) / w[1]
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
print('w', w)
print('a', a)
print('support_vectors_', clf.support_vectors_)
print('clf.coef_',clf.coef_)
pl.plot(xx, yy, 'k-')
pl.plot(xx, yy_down, 'k--')
pl.plot(xx, yy_up, 'k--')
pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s = 80, facecolors='none')
pl.scatter(X[:, 0], X[:, 1], c = Y, cmap=pl.cm.Paired)
pl.axis('tight')
pl.show()<file_sep>/DeepLearning/KNN.py
#coding=utf-8
import math
#最邻近规则KNN分类算法
def ComputeEuclideanDistance(x1, y1, x2, y2):
#根号下(x1-x2)²+(y1-y2)²
d = math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2), 2))
return d
d_ag = ComputeEuclideanDistance(3, 104, 18, 90)
d_bg = ComputeEuclideanDistance(2, 100, 18, 90)
d_cg = ComputeEuclideanDistance(1, 81, 18, 90)
d_dg = ComputeEuclideanDistance(101, 10, 18, 90)
d_eg = ComputeEuclideanDistance(99, 5, 18, 90)
d_fg = ComputeEuclideanDistance(98, 2, 18, 90)
print("d_ag", d_ag)
print("d_bg", d_bg)
print("d_cg", d_cg)
print("d_dg", d_dg)
print("d_eg", d_eg)
print("d_fg", d_fg)
<file_sep>/workspaceDemo/simpleSpiderBeautifulSoup.py
#coding=utf-8
#print(soup.prettify()) # 格式化输出网址源码
# 打印title,用soup加标签名轻松获得标签内容,而不需要用正则表达式
#print(soup.title)
#print(soup.head)
#print(soup.p) #只打印第一个p的部分
#print(soup.div.attrs) # 打印div标签的所有属性,得到的类型是一个字典
#print(soup.div['class']) # 但单独打印div的某一个部分
#print(soup.title.string) # .string获得标签内部的文字
# 遍历文档树
# 直接子节点 .contents .children
#print('直接子节点')
#for child in soup.body.children :
# print(child)
# 用来遍历
# 所有子孙节点 .descendans 包括其内部所有内容
#print('所有子孙节点')
#for child in soup.body.descendants:
# print(child)
# 所有父节点 .parents
# 所有兄弟节点 .next_siblings .previous_siblings
# 所有前后节点 .next_elements .previous_elements
# 节点内容 .string (s)s
# 搜索文档树
# 注意:如果一个指定名字的参数不是搜索内置的参数名,
# 搜索时会把该参数当作指定名字tag的属性来搜索,
# 如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性
from bs4 import BeautifulSoup
import requests
url = 'http://m.ximalaya.com/news/2018-04-19/VUzfwQde.html'
#获取网址源码
html = requests.get(url).text
print(html)
soup = BeautifulSoup(html, 'lxml')
print('开始抓取')
title = soup.title.string
with open("D:/thisme_D/Python/workspace/python_study_file/"+title+'.txt', 'w') as f:
href = soup.find_all('p')
try:
f.write('\t%s\r\n' %str(title)) #前面%s 后面之间空格加%内容
for hre in href:
if(hre.string!=None): #未解决标签内容回车后打印none问题
f.write('\t%s\r\n' %str(hre.string))
except Exception:
print('发生错误')
print('抓取成功')
#爬取豆瓣河神演员照片列表
from bs4 import BeautifulSoup
import requests
import lxml
import re
url = 'https://movie.douban.com/subject/26776350/celebrities'
html = requests.get(url).content
soup = BeautifulSoup(html, 'lxml')
#用class搜索,由于是python的关键词, 所以用下划线
imgs = soup.find_all(class_="avatar")
names = soup.find_all('a',href=re.compile('celebrity'),class_="name")
i = 0
print("开始下载")
for img in imgs:
img_url = img['style']
#利用切片获取图片网址
img_content = img_url.split('(')[1].split(')')[0]
try:
print("下载第%s涨图片"%i)
with open("D:/thisme_D/Python/workspace/python_study_file/河神/"+str(names[i].string)+".jpg",'wb') as f:
#将获得图片网址转换成二进制编码
f.write(requests.get(img_content).content)
i+=1
except Exception:
print("出现错误")
print("下载完成")<file_sep>/workspaceDemo/compute.py
#coding=utf-8
#python 运算符
a = 10
b = 21
#计算运算符
print(a+b)
print(a-b)
print(a*b)
print(b/a)
print(b%a)
print(a**b)
print(b//a)
#关系运算符
print(a==b)
print(a!=b)
print(a<b)
print(a>b)
print(a<=b)
print(a>=b)
#赋值运算符
c=a+b
print(c)
c += a
print(c)
c -= a
print(c)
c *= b
print(c)
c /= a
print(c)
c %= a
print(c)
c **= a
print(c)
c //= a
print(c)
#逻辑运算符
a = True
b = False
print(a and b)
print(a or b)
print(not(b))
a = "string"
b = "str"
print(b in a)
print(b not in a)
c = tuple(a)
print(c)
d = tuple(b)
print(d)
print(d in c)
print(d not in c)
#身份运算符
a = 20
b = 20
print(a is b)
print(a == b)
print(a is not b)
#if...else...
var = 11
if var == 11 :
print("ok")
print("okk")
else : print("no")<file_sep>/workspaceDemo/dataTypeTransfor.py
#coding=utf-8
#数据类型转换
#转换为int
int_ = int("110")
print(int_)
#转换为float
float_ = float("11.12")
print(float_)
#转换为字符串
str_ = str(["110",120])
print(str_)
#转换为表达式字符串
repr_ = repr("xxx")
print(repr_)
#
eval_ = eval("str")
print(eval_)
#将字符串转换为元组 tuple
tuple_ = tuple("123")
print(tuple_)
#将字符串转换为列表list
list_ = list("123")
print(list_)
#将字符串转换为集合
set_ = set("123")
print(set_)
#dict
#将字符串转换为冻结集 frozenset
frozenset_ = frozenset("123")
print(frozenset_)
#将数字转换为字符(没看懂)
chr_ = chr(2)
print(chr_)
#将单个字符转换为整数值
ord_ = ord("a")
print(ord_)
#将整数转换为16进制字符串
hex_ = hex(123)
print(hex_)
#将整数转换为8进制字符串
oct_ = oct(123)
print(oct_)<file_sep>/DeepLearning/SKLearnSimple_SVM.py
#coding=utf-8
#svm 支持向量机
import sys
print(sys.path)
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
from sklearn import svm
x = [[2, 0], [1, 1], [2, 3]]
y = [0, 0, 1]
clf = svm.SVC(kernel = 'linear')
clf.fit(x, y)
print(clf)
print(clf.support_vectors_)
print(clf.support_)
print(clf.n_support_)
z = [[2, 0]]
print(clf.predict(z))<file_sep>/workspaceDemo/simpleSpiderToBaiduTB.py
#coding=utf-8
#简单爬取百度贴吧内容
from bs4 import BeautifulSoup
import requests
import lxml
#百度贴吧
url = "https://tieba.baidu.com/p/3572475102"
html = requests.get(url).content
soup = BeautifulSoup(html, 'lxml')
article = soup.find("div", class_="left_section")
#在正文标签里面找图片链接
article1 = article.find_all()
images = article.find_all('img', class_="BDE_Image")
#下载图片
i=0
print("start")
for image in images:
image_url = image["src"]
#获取图片url
with open("D:/thisme_D/Python/workspace/python_study_file/百度贴吧/"+str(i)+".jpg", 'wb') as f:
try:
re = requests.get(image_url).content
f.write(re)
print(str(i)+".jpg images is downloading")
i+=1
except Exception:
print("error")
print("image downloading finish")
#百度贴吧 发帖标题和内容
title = article.find('div',class_="core_title_wrap_bright clearfix")
#find_all搜索得到的是列表,不能直接用find查找其中的标签
endTitle = title.find('h3')
content = article.find_all('div',class_="d_post_content j_d_post_content ")
print("start")
user_card = article.find_all("a",class_="p_author_name j_user_card")
allContent = "";
#多行注释 """内容"""
#两种集合遍历的方式
"""
for cont in content:
try:
allContent += str(cont.get_text())+"\n"
except Exception:
print("error")
"""
for i in range(0,len(content)):
try:
allContent += str(user_card[i].get_text())+":\n"+str(content[i].get_text())+"\n"
except Exception:
print("error")
#创建文件写在循环内部会导致前面写入的被覆盖
with open("D:/thisme_D/Python/workspace/python_study_file/百度贴吧/"+str(endTitle["title"])+".txt", "w") as f:
f.write(allContent)
print("success")
#搜索百度贴吧 采集吧中内容
keyword = "秋"
url = "https://tieba.baidu.com/f?ie=utf-8&kw="+keyword
html = requests.get(url).content
soup = BeautifulSoup(html, "lxml")
#print(soup)
th_tit = soup.find_all("a", "j_th_tit")
href = "https://tieba.baidu.com"
for tit in th_tit:
print(href+tit["href"])
#print(str(th_tit))
<file_sep>/DeepLearning/DecisionTree.py
#coding=utf-8
#决策树
import sys
print(sys.path)
sys.path[0] = 'E:\Python\Anaconda\Lib\site-packages'
print(sys.path)
from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
header = []
featureList = []
labelList = []
i=0
with open(r'C:\Users\Administrator\Desktop\testData.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
if i==0:
header = row
i=1
else:
rowDict = {}
labelList.append(row[len(row)-1])
for j in range(1, len(row) - 1):
rowDict[header[j]] = row[j]
featureList.append(rowDict)
print(row)
print(row[0])
print(row[0],row[1])
print(header)
print(labelList)
print(featureList)
vec = DictVectorizer()
dummyX = vec.fit_transform(featureList).toarray()
print(dummyX)
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print("dummyY:" + str(dummyY))
clf = tree.DecisionTreeClassifier(criterion="entropy")
clf = clf.fit(dummyX, dummyY)
print("clf:" + str(clf))
with open(r"C:\Users\Administrator\Desktop\allElectronicInfomationGainOri.dot" ,"w") as f:
f = tree.export_graphviz(clf, feature_names=vec.get_feature_names(), out_file = f)
oneRowX = dummyX[0, :]
print("oneRowX: "+str(oneRowX))
newRowX = oneRowX
newRowX[0] = 1
newRowX[2] = 0
print("newRowX : "+str(newRowX))
newRowX = newRowX.reshape(1, -1) #重塑 reshape(1, -1) 一行n列
print ("newRowx:" + str(newRowX))
#预测
predictedY = clf.predict(newRowX)
print("predictedY: "+str(predictedY))<file_sep>/workspaceDemo/fastai_imageClassification.py
#coding=utf-8
#image
import sys
print(sys.path)
sys.path[0] = 'D:\thisme_D\Python\Anaconda3\Lib\site-packages'
from fastai import *
from fastai.vision import *
import matplotlib.pyplot as plt
from PIL import Image
a = 1
b = a + 1
c = b + a + 1
d = c + b + a +1
print(str(a)+", "+str(b)+", "+str(c)+", "+str(d))
#plt.plot([a,b,c,d])
#plt.show()
help(untar_data)
filepath = "D:/thisme_D/Python/python_study/workspaceDemo/oxford-iiit-pet"
print(URLs.PETS)
path = untar_data(URLs.PETS); path
path.ls()
path_anno = path/'annotations'
path_img = path/'images'
fnames = get_image_files(path_img)
fnames[:5]
pp.random.seed(2)
pat = r'/([^/]+)_\d+.jpg$'
data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transfroms(), size=224)
data.normalize(imagenet_stats)
data.show_batch(rows=3, figsize=(7,6))
print(data.classes)
len(data,classes),data.c
learn = ConvLearner(data, models.resnet34, metrics=error_rate)
learn.fit_one_cycle(4)
learn.save('stage-1')
interp = ClassificationInterpretation.from_learner(learn)
interp.plot_top_losses(9, figsize=(15,11))
doc(interp.plot_top_losses)
interp.plot_confusion_matrix(figsize=(12,12), dpi=60)
interp.most_confused(min_val=2)
learn.unfreeze()
learn.fit_one_cycle(1)
learn.load('stage-1')
learn.lr_find()
learn.recorder.plot()
learn.unfreeze()
learn.fit_one_cycle(2, max_lr=slice(1e-6,1e-4))
data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transfroms())
data.normalize(imagenet_stats)
learn = ConvLearner(data, models.resnet50, metrics=error_rate)
learn.fit_one_cycle(5)
learn.save('stage-1-50')
learn.unfreeze()
learn.fit_one_cycle(1, max_lr=silce(1e-6,1e-4))
learn.load('stage-1-50')
interp = ClassificationInterpretation.from_learner(learn)
interp.most_confused(min_val=2)
path = untar_data(URLs.MNIST_SAMPLE); path
tfms = get_transfroms(do_flip=False)
data = ImageDataBunch.from_folder(path, ds_tfms=tfms, size = 26)
data.show_batch(rows=3, figsize=(5,5))
learn = ConvLearner(data, models.resnet18, metrics=accuracy)
learn.fit(2)
df = pd.read_csv(path/'labels.csv')
df.head()
data = ImageDataBunch.from_csv(path, ds_tfms, size=28)
data.show_batch(rows=3, figsize=(5,5))
data.classes
data = ImageDataBunch.from_df(path, df, ds_tfms=tfms, size=24)
data.classes
fn_paths = [path/name for name in df['name']]; fn_paths[:2]
pat = r"/(\d)/\d+\.png$"
data = ImageDataBunch.from_name_re(path, fn_paths, pat=pat, ds_tfms=tfms, size=24)
data.classes
data = ImageDataBunch.from_name_func(path, fn_paths, ds_tfms=tfms, size=24,
label_func = lambda x: '3' if '/3/' in str(x) else '7')
data.classes
labels = [('3' if '/3/' in str(x) else '7') for x in fn_paths]
labels[:5]
data = ImageDataBunch.from_lists(path, fn_paths, labels=labels, ds_tfms=tfms, size=24)
data.classes<file_sep>/workspaceDemo/file.py
#coding=utf-8
import os
#文件读写
#获取用户输入 input()
x = input("input something:")
print(x)
#打开文件
file_open = open("F:/test.txt")
#文件路径
print(file_open.name)
#文件是否关闭状态 true or false
print(file_open.closed)
#打开文件的访问模式
print(file_open.mode)
#关闭文件
file_open.close()
#文件追加内容 a:访问模式,追加
file_append = open("F:/test.txt","a")
file_append.write("\n append.")
file_append.close()
#打开文件 r+:访问模式 打开读写文件。文件指针放在文件的开头。 encoding=“utf-8”文件编码格式
file_read = open("F:/test.txt","r+",encoding="utf-8")
#读取文件
str = file_read.read()
print(str)
#
file_read = open("F:/test.txt","r+",encoding="utf-8")
#指定字节长度10
str10 = file_read.read(10)
print(str10)
file_read.close()
#更改文件名称
os.rename("F:/test.txt","F:/test1.txt")
#删除指定文件
#os.remove("F:/test.txt")
#创建目录
os.mkdir("F:/test")
#使用当前目录
os.chdir("F:/test")
#获取当前目录
print(os.getcwd())
#删除指定目录
os.rmdir("F:/test")<file_sep>/workspaceDemo/if.py
#coding=utf-8
#if else
var = 10
if(var == 10) :
print("ok")
print("end")
else :
print("no")
<file_sep>/workspaceDemo/parentChild.py
#coding=utf-8
#类的继承
class Parent:
parentAttr = 100
def __init__(self):
print("i am parent")
def parentMethod(self):
print("parent method")
def myMethod(self):
print("parentMethod")
def setAttr(self,attr):
Parent.parentAttr = attr
def getAttr(self):
print("parentAttr:",Parent.parentAttr)
#继承 className(ParentClassName1,ParentClassName2,...)
class Child(Parent):
def __init__(self):
print("i am child")
def childMethod(self):
print("child method")
def myMethod(self):
print("childMethod")
c = Child()
c.childMethod()
#父类方法
c.parentMethod()
c.setAttr(123)
c.getAttr()
#重载父类myMethod方法
c.myMethod()
#issubclass(sub,sup) 判断sub类和sup类间的关系 sub继承sup则返回True
print(issubclass(Child,Parent))
<file_sep>/workspaceDemo/Employee.py
#coding=utf-8
#声明class
class Employee:
empCount = 0 #类变量 其值在此类中的所有实例之间共享。 这可以从类或类之外的Employee.empCount访问
#初始实例化方法 每个方法的第一个参数为self(调用方法是不需要传参)
def __init__(self,name,salary):
self.name = name #赋值
self.salary = salary
Employee.empCount += 1
def dispalyEmpCount(self):
print(Employee.empCount)
def dispalyEmp(self):
#异常处理
try:
print ("name:",self.name,"salary:",self.salary)
except Exception:
print ("name:",self.name,"salary:","未透露")
#实例化 相当于构造函数
emp1 = Employee("Maxsu", 2000)
#调用class中的方法
emp1.dispalyEmp()
emp2 = Employee("张三",3000)
#修改属性值
emp2.salary = 2300
emp2.name = "lisi"
emp2.dispalyEmp()
#删除属性
del emp2.salary
emp2.dispalyEmp()
emp2.dispalyEmpCount()
Employee.empCount = 20
emp2.dispalyEmpCount()
#检查属性是否存在
print("is exists:",hasattr(emp2,"salary"))
#返回name属性的值
print("name:",getattr(emp2,"name"))
#给salary属性赋值
setattr(emp2,"salary",5666)
emp2.dispalyEmp()
#删除属性salary值
delattr(emp2,"salary")
emp2.dispalyEmp()
#包含该类的命名空间的字典
print("dict",Employee.__dict__)
#类文档字符串或无
print("doc:",Employee.__doc__)
#类名
print("name:",Employee.__name__)
#定义类的模块名称。此属性在交互模式下的值为“main”
print("module:",Employee.__module__)
#一个包含基类的空元组,按照它们在基类列表中出现的顺序
print("bases:",Employee.__bases__)
| e41e2a4b05f92001b7c6edbc3080b5eb2bdb608b | [
"Python"
] | 34 | Python | xiepf1101/python_study | 4d825707821a3c435b5d5a87130a6c9f2f638c7e | 5ac840dd3ae9bb8f7bda1593e6ce13b1df6316e6 |
refs/heads/master | <file_sep>[ThridPlat]
KValue = 0.000000
BValue = 0.000000
Z1Pos = -10500
Z2Pos = -7200
Z3Pos = -3800
Z4Pos = -500
X1Pos = 1150
X2Pos = 4050
X3Pos = 7050
X4Pos = 9950
SelectPol = 2
MinSpeed = 1
MaxSpeed = 0
ComboPol = "1"
FirstPosX = 0
FirstPosZ = 0<file_sep>#pragma once
#include "CnComm.h"
class DyMechicalAPI
{
public:
DyMechicalAPI(void)
{
m_pCom=NULL;
m_AD = 0;
for (int i=0;i<48;i++)
m_Solen[i]=0;
for (int i=0;i<6;i++)
m_motorStatue[i]=0;
for (int i=0;i<8;i++)
{
m_platformStatue_IO1[i]=0;
m_platformStatue_IO2[i]=0;
m_platformStatue_IO3[i]=0;
m_sensorStatue[i]=0;
}
}
~DyMechicalAPI(void)
{
}
private:
//内部变量
CnComm* m_pCom;
int m_Solen[48];
int m_motorStatue[6];
int m_platformStatue_IO1[8];
int m_platformStatue_IO2[8];
int m_platformStatue_IO3[8];
int m_sensorStatue[8];
double m_AD;
private:
//内部函数
bool FindCard(CnComm* pCom)
{
for (int i=1;i<20;i++)
{
if (pCom->Open(i,57600))
{
unsigned char t_cmd[4];
t_cmd[0]=0x55;
t_cmd[1]=0x02;
t_cmd[2]=0xbb;
t_cmd[3]=0xaa;
pCom->WritePort(t_cmd,4);
Sleep(10);
unsigned char t_Rcv[9];
memset(t_Rcv,0,sizeof(unsigned char)*9);
pCom->ReadPort(t_Rcv,9);
if (t_Rcv[0]==0x48
&&t_Rcv[1]==0x65
&&t_Rcv[2]==0x6c
&&t_Rcv[3]==0x6c
&&t_Rcv[4]==0x6f
&&t_Rcv[5]==0x4a
&&t_Rcv[6]==0x49
&&t_Rcv[7]==0x41
&&t_Rcv[8]==0x21)
{
return true;
}
}
}
return false;
}
public:
//操作
//************************************
// Method: SysInit
// FullName: DyMechicalAPI::SysInit
// Access: public
// Returns: bool
// Qualifier: 系统初始化
// Parameter: void
//************************************
bool SysInit(void)
{
if (m_pCom!=NULL)
return false;
else
{
m_pCom=new CnComm;
if (FindCard(m_pCom))
return true;
else
return false;
}
}
//************************************
// Method: SysQuit
// FullName: DyMechicalAPI::SysQuit
// Access: public
// Returns: void
// Qualifier: 系统关闭
// Parameter: void
//************************************
void SysQuit(void)
{
m_pCom->Close();
m_pCom=NULL;
delete m_pCom;
}
//************************************
// Method: FeedMotor_Start
// FullName: DyMechicalAPI::FeedMotor_Start
// Access: public
// Returns: bool
// Qualifier: 进料电机持续转动
// Parameter: void
//************************************
bool FeedMotor_Start(void)
{
if (m_pCom==NULL)
return false;
unsigned char t_cmd[4];
t_cmd[0]=0x55;
t_cmd[1]=0x02;
t_cmd[2]=0xfb;
t_cmd[3]=0xaa;
m_pCom->Write(t_cmd,4);
return true;
}
//************************************
// Method: FeedMotor_Stop
// FullName: DyMechicalAPI::FeedMotor_Stop
// Access: public
// Returns: bool
// Qualifier: 进料电机停止转动
// Parameter: void
//************************************
bool FeedMotor_Stop(void)
{
if (m_pCom==NULL)
return false;
unsigned char t_cmd[4];
t_cmd[0]=0x55;
t_cmd[1]=0x02;
t_cmd[2]=0xbf;
t_cmd[3]=0xaa;
m_pCom->Write(t_cmd,4);
return true;
}
//************************************
// Method: MotorStart
// FullName: DyMechicalAPI::MotorStart
// Access: public
// Returns: bool
// Qualifier: 指定电机运动
// Parameter: int motorNum
// Parameter: int direction
// Parameter: int stepNum
//************************************
bool MotorStart(int motorNum,int direction,int stepNum)
{
if (m_pCom==NULL)
return false;
if (motorNum<1||motorNum>6)
{
return false;
}
if (direction<0||direction>1)
{
return false;
}
unsigned char t_cmd[8];
t_cmd[0]=0x55;
t_cmd[1]=0x06;
t_cmd[2]=0xfa;
t_cmd[3]=motorNum;
t_cmd[4]=direction;
int t_highNum=0;
int t_lowNum=0;
t_highNum=stepNum/256;
t_lowNum=stepNum%256;
t_cmd[5]=t_highNum;
t_cmd[6]=t_lowNum;
t_cmd[7]=0xaa;
m_pCom->Write(t_cmd,8);
return true;
}
//************************************
// Method: MotorStop
// FullName: DyMechicalAPI::MotorStop
// Access: public
// Returns: bool
// Qualifier: 指定电机停止
// Parameter: void
//************************************
bool MotorStop(int motorNum)
{
if (m_pCom==NULL)
return false;
if (motorNum<1||motorNum>6)
{
return false;
}
unsigned char t_cmd[5];
t_cmd[0]=0x55;
t_cmd[1]=0x03;
t_cmd[2]=0xfd;
t_cmd[3]=motorNum;
t_cmd[4]=0xaa;
m_pCom->Write(t_cmd,5);
return true;
}
//************************************
// Method: MotorReset
// FullName: DyMechicalAPI::MotorReset
// Access: public
// Returns: bool
// Qualifier: 指定电机复位
// Parameter: int motorNum
//************************************
bool MotorReset(int motorNum)
{
if (m_pCom==NULL)
return false;
if (motorNum<1||motorNum>6)
{
return false;
}
unsigned char t_cmd[5];
t_cmd[0]=0x55;
t_cmd[1]=0x03;
t_cmd[2]=0xfc;
t_cmd[3]=motorNum;
t_cmd[4]=0xaa;
m_pCom->Write(t_cmd,5);
return true;
}
//************************************
// Method: SetMotorSpeed
// FullName: DyMechicalAPI::SetMotorSpeed
// Access: public
// Returns: bool
// Qualifier: 指定电机速度
// Parameter: int motorNum
//************************************
bool SetMotorSpeed(int motorNum,int speed)
{
if (m_pCom==NULL)
return false;
if (motorNum<1||motorNum>6)
{
return false;
}
if (speed<0||speed>65535)
{
return false;
}
unsigned char t_cmd[7];
t_cmd[0]=0x55;
t_cmd[1]=0x05;
t_cmd[2]=0xed;
t_cmd[3]=motorNum;
t_cmd[4]=speed/256;
t_cmd[5]=speed%256;
t_cmd[6]=0xaa;
m_pCom->Write(t_cmd,7);
return true;
}
//************************************
// Method: solenAction
// FullName: DyMechicalAPI::solenAction
// Access: public
// Returns: bool
// Qualifier: 指定电磁阀动作
// Parameter: int solenNum
// Parameter: int statue
//************************************
bool solenAction(int solenNum,int statue)
{
if (m_pCom==NULL)
return false;
if (solenNum<0||solenNum>47)
{
return false;
}
if (statue<0||statue>1)
{
return false;
}
unsigned char t_cmd[6];
t_cmd[0]=0x55;
t_cmd[1]=0x04;
t_cmd[2]=0xfe;
t_cmd[3]=solenNum;
t_cmd[4]=statue;
t_cmd[5]=0xaa;
m_pCom->Write(t_cmd,6);
//m_Solen[solenNum]=statue;
return true;
}
//************************************
// Method: solenAdvace
// FullName: DyMechicalAPI::solenAdvace
// Access: public
// Returns: bool
// Qualifier: 指定工作台全部动作
// Parameter: int platformNum
// Parameter: int statue
//************************************
bool solenAdvace(int platformNum,int statue)
{
if (m_pCom==NULL)
return false;
if (platformNum<0||platformNum>2)
{
return false;
}
if (statue<0||statue>1)
{
return false;
}
unsigned char t_cmd[6];
t_cmd[0]=0x55;
t_cmd[1]=0x04;
t_cmd[2]=0xef;
t_cmd[3]=platformNum;
t_cmd[4]=statue;
t_cmd[5]=0xaa;
m_pCom->Write(t_cmd,6);
switch(platformNum)
{
case 0:
for (int i=0;i<16;i++)
{
//m_Solen[i]=statue;
}
break;
case 1:
for (int i=16;i<32;i++)
{
//m_Solen[i]=statue;
}
break;
case 2:
for (int i=32;i<48;i++)
{
//m_Solen[i]=statue;
}
break;
default:
break;
}
return true;
}
//查询
//************************************
// Method: getSolenStatue
// FullName: DyMechicalAPI::getSolenStatue
// Access: public
// Returns: void
// Qualifier: 查询继电器状态
// Parameter: int * SolenStatue
//************************************
void getSolenStatue(int* SolenStatue)
{
CopyMemory(SolenStatue,m_Solen,sizeof(int)*48);
}
//************************************
// Method: getMotorStatue
// FullName: DyMechicalAPI::getMotorStatue
// Access: public
// Returns: bool
// Qualifier: 获取电机运动状态
// Parameter: int * motorStatue
//************************************
bool getMotorStatue(int* motorStatue)
{
if (m_pCom==NULL)
return false;
CopyMemory(motorStatue,m_motorStatue,sizeof(int)*6);
return true;
}
//************************************
// Method: getPlatformStatue
// FullName: DyMechicalAPI::getPlatformStatue
// Access: public
// Returns: bool
// Qualifier: 查询指定工作台的输入口状态
// Parameter: int PlatformNum
// Parameter: int * platformStatue
//************************************
bool getPlatformStatue(int PlatformNum,int* platformStatue)
{
if (m_pCom==NULL)
return false;
switch(PlatformNum)
{
case 0:
{
CopyMemory(platformStatue,m_platformStatue_IO1,sizeof(int)*8);
break;
}
case 1:
{
CopyMemory(platformStatue,m_platformStatue_IO2,sizeof(int)*8);
break;
}
case 2:
{
CopyMemory(platformStatue,m_platformStatue_IO3,sizeof(int)*8);
break;
}
default:
break;
}
return true;
}
//************************************
// Method: getSensorStatue
// FullName: DyMechicalAPI::getSensorStatue
// Access: public
// Returns: bool
// Qualifier: 获取IO量传感器IO值
// Parameter: int * SensorStatue
//************************************
bool getSensorStatue(int* SensorStatue)
{
if (m_pCom==NULL)
return false;
CopyMemory(SensorStatue,m_sensorStatue,sizeof(int)*8);
return true;
}
//************************************
// Method: GetADSensor
// FullName: DyMechicalAPI::GetADSensor
// Access: public
// Returns: bool
// Qualifier: 获取AD量传感器AD值
// Parameter: double & value
//************************************
bool GetADSensor(double& value)
{
if (m_pCom==NULL)
return false;
value = m_AD;
return true;
}
//************************************
// Method: rcvInit
// FullName: DyMechicalAPI::rcvInit
// Access: public
// Returns: bool
// Qualifier: 初始化数据接收
// Parameter: void
//************************************
bool rcvInit(void)
{
if (m_pCom==NULL)
return false;
unsigned char t_cmd[4];
t_cmd[0] = 0x55;
t_cmd[1] = 0x02;
t_cmd[2] = 0xf6;
t_cmd[3] = 0xaa;
m_pCom->Write(t_cmd,4);
unsigned char t_rcv[16];
m_pCom->Read(t_rcv,16);
if (t_rcv[0] == 0x55
&&t_rcv[1] == 0x0e
&&t_rcv[15] == 0xaa){
//AD
m_AD = ((double)(t_rcv[2]*256+t_rcv[3]))*4096.0/3300.0;
//Sensor Statue
int t_Data_SensorStatue = 0;
t_Data_SensorStatue = t_rcv[4];
for (int i=0;i<8;i++)
m_sensorStatue[i]=(t_Data_SensorStatue>>i)&0x01;
//IO1|IO2|IO3
int t_Data_IO1 = 0;
int t_Data_IO2 = 0;
int t_Data_IO3 = 0;
t_Data_IO1 = t_rcv[5];
t_Data_IO2 = t_rcv[6];
t_Data_IO3 = t_rcv[7];
for (int i=0;i<8;i++)
m_platformStatue_IO1[i] = (t_Data_IO1>>i)&0x01;
for (int i=0;i<8;i++)
m_platformStatue_IO2[i] = (t_Data_IO2>>i)&0x01;
for (int i=0;i<8;i++)
m_platformStatue_IO3[i] = (t_Data_IO3>>i)&0x01;
//Motor Statue
int t_Data_MotorStatue = 0;
t_Data_MotorStatue = t_rcv[8];
for (int i=0;i<6;i++)
m_motorStatue[i] = (t_Data_MotorStatue>>i)&0x01;
//Solen Statue
for (int i=0;i<8;i++){
m_Solen[i] = (t_rcv[9]>>i)&0x01;
}
for(int i=8;i<16;i++){
m_Solen[i] = (t_rcv[10]>>(i-8))&0x01;
}
for (int i=16;i<24;i++){
m_Solen[i] = (t_rcv[11]>>(i-16))&0x01;
}
for (int i=24;i<32;i++){
m_Solen[i] = (t_rcv[12]>>(i-24))&0x01;
}
for (int i=32;i<40;i++){
m_Solen[i] = (t_rcv[13]>>(i-32))&0x01;
}
for (int i=40;i<48;i++){
m_Solen[i] = (t_rcv[14]>>(i-40))&0x01;
}
return true;
}
else
return false;
}
};
| f8734911fbb299a2effafa2b522e81da8f8708c2 | [
"C++",
"INI"
] | 2 | INI | suw0801/DYSYS | 4ce5d9eac3aeb780c0739310539a2706f743be60 | b0263a01392928f34d023df21cfc6f5c06394434 |
refs/heads/master | <file_sep>wasmBoolean(value) {
return value !== 0;
}
wasmToChar(value) {
return String.fromCodePoint(value);
}
charToWasm(value) {
return value.codePointAt(0);
}<file_sep>{
'env': {
'println': (arg) => console.log(arg)
}
}<file_sep>val input = CharStreams.fromStream(File("...").inputStream())
val lexer = MyLanguageLexer(input)
val tokens = CommonTokenStream(lexer)
val parser = MyLanguageParser(tokens)
val tree = parser.listOfNumbers()<file_sep>'+_String_String': (stringRef1, stringRef2) => {
const s1 = runtime.wasmDeref(stringRef1);
const s2 = runtime.wasmDeref(stringRef2);
return runtime.wasmRefType(s1.concat(s2), 'String');
}<file_sep>module.exports = runtime => {
return {
'Console.println#int': arg => {
console.log(arg);
},
'Console.println#String': arg => {
console.log(runtime.wasmDeref(arg));
}
};
};<file_sep>import * as wasm from "point-module";
let point = wasm.Point.new(3, 4);
wasm.alert_point(point);<file_sep>@Test
fun `simple test`() {
val output = """
public static void main() {
Console.println(123);
}
""".compileAndRunInMainClass()
assertThat(output.lines()).containsExactly("123", "")
}<file_sep>implementation-class=dev.ssch.minijava.plugin.MiniJavaPlugin<file_sep>findMethod(className, methodName, ...argumentTypes) {
const argumentTypeString = argumentTypes.map(s => '#' + s).join('');
return this.wasmModuleInstance
.exports[className + '.' + methodName + argumentTypeString];
}<file_sep>staticMethod(className, methodName, ...argumentTypes) {
return this.findMethod(className, methodName, ...argumentTypes);
}<file_sep>module.exports = runtime => {
return {
'Document.getElementById#String': elementIdRef => {
const elementId = runtime.wasmDeref(elementIdRef);
return runtime.wasmRef(document.getElementById(elementId),
'HTMLElement');
},
'HTMLElement.addClickEventListener#Object': (thisRef, handlerRef) => {
const element = runtime.wasmDeref(thisRef);
const handler = runtime.wasmDeref(handlerRef);
element.addEventListener('click', (event) => {
runtime.instanceMethod(handler, 'handleEvent', 'MouseEvent')(event);
})
}
};
};<file_sep>'+_String_numeric': (stringRef, value) => {
const s = runtime.wasmDeref(stringRef);
return runtime.wasmRefType(s.concat(value.toString()), 'String');
}
'+_numeric_String': (value, stringRef) => {
const s = runtime.wasmDeref(stringRef);
return runtime.wasmRefType(value.toString().concat(s), 'String');
}<file_sep>assertEquals(123, someNumber); // JUnit
assertThat(someNumber).isEqualTo(123); // AssertJ<file_sep>module.exports = [function (runtime) {
runtime.wasmRefType("Hello ", 'String');
runtime.wasmRefType("World", 'String');
return {};
}, require('./native/0.js'), ... /* require natives */ , function (runtime) {
return {
'new_MyClass': function() {
return runtime.wasmRefType({'value':0,'text':null}, 'MyClass');
},
'get_MyClass.value': function (ref) {
return runtime.wasmDeref(ref)['value'];
},
'set_MyClass.value': function (ref, val) {
runtime.wasmDeref(ref)['value'] = val;
},
'get_MyClass.text': function (ref) {
return runtime.wasmRefType(runtime.wasmDeref(ref)['text'], 'String');
},
'set_MyClass.text': function (ref, val) {
runtime.wasmDeref(ref)['text'] = runtime.wasmDeref(val);
},
...
};
}];<file_sep>#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
extern {
fn alert(s: &str);
}
#[wasm_bindgen]
pub struct Point {
x: u32,
y: u32,
}
#[wasm_bindgen]
impl Point {
pub fn new(x: u32, y: u32) -> Point {
Point { x, y }
}
}
#[wasm_bindgen]
pub fn alert_point(point: &Point) {
alert(&format!("Point({}|{})", point.x, point.y));
}<file_sep># Master's Thesis<file_sep>fun findPoint(): Point? { ... }
fun main() {
val point = findPoint()
println(point.x) // compile error
if (point != null) {
println(point.x) // OK
}
}<file_sep>constructor() {
this.nextFreeReference = 1;
this.objects = new Map();
this.references = new Map();
this.types = new Map();
this.objects.set(null, 0);
this.references.set(0, null);
this.wasmModuleInstance = null;
}<file_sep>'array_length': arrayRef => {
return runtime.wasmDeref(arrayRef).length;
}<file_sep>'set_array_reference': (arrayRef, index, valueRef) => {
const a = runtime.wasmDeref(arrayRef);
a[index] = runtime.wasmDeref(valueRef);
}<file_sep>module.exports = runtime => {
return {
'Integer.parseInt#String': stringRef => {
return parseInt(runtime.wasmDeref(stringRef));
},
'Integer.toString#int': i => {
return runtime.wasmRefType(i.toString(), 'String');
}
};
};<file_sep>wasmRef(obj) {
if (this.objects.has(obj)) {
return this.objects.get(obj);
} else {
const address = this.nextFreeReference++;
this.objects.set(obj, address);
this.references.set(address, obj);
return address;
}
}
wasmRefType(obj, type) {
if (obj !== null) {
this.types.set(obj, type);
}
return this.wasmRef(obj);
}
wasmDeref(address) {
return this.references.get(address);
} | 34ee3f492b9f980a0cfe50fc280abb251f40321f | [
"JavaScript",
"Markdown",
"INI",
"Java",
"Rust",
"Kotlin"
] | 22 | JavaScript | stefanschoeberl/masters-thesis | a2ae6d9d465415af9588d52ce17f1c40bde5be8c | 1708f5e3d492db48093ba93df60258016402c562 |
refs/heads/main | <file_sep>function Footer() {
return (
<div data-testid="copyright">
Data provided by Marvel. © 2014 Marvel
</div>
)
}
export default Footer
<file_sep>import React, { useEffect, useState } from "react";
import { useQuery } from "@apollo/client";
import { getCharactersName } from "../../queries/character";
import Character from "./Character";
import "./characters.css";
const Events = ({ name }) => {
const { data, loading, error } = useQuery(getCharactersName, {
variables: { name },
});
const [visibleCharacter1, setVisibleCharacter1] = useState(1);
const [visibleCharacter2, setVisibleCharacter2] = useState(2);
const [visibleCharacter3, setVisibleCharacter3] = useState(3);
const [blurCharacter1, setBlurCharacter1] = useState(0);
const [blurCharacter2, setBlurCharacter2] = useState(4);
useEffect(() => {
setVisibleCharacter1(1);
setVisibleCharacter2(2);
setVisibleCharacter3(3);
setBlurCharacter1(0);
setBlurCharacter2(4);
return () => {
setVisibleCharacter1(1);
setVisibleCharacter2(2);
setVisibleCharacter3(3);
setBlurCharacter1(0);
setBlurCharacter2(4);
};
}, [data]);
const prevCharacter = () => {
setVisibleCharacter1(visibleCharacter1 - 1);
setVisibleCharacter2(visibleCharacter2 - 1);
setVisibleCharacter3(visibleCharacter3 - 1);
setBlurCharacter1(blurCharacter1 - 1);
setBlurCharacter2(blurCharacter2 - 1);
};
const nextCharacter = () => {
setVisibleCharacter1(visibleCharacter1 + 1);
setVisibleCharacter2(visibleCharacter2 + 1);
setVisibleCharacter3(visibleCharacter3 + 1);
setBlurCharacter1(blurCharacter1 + 1);
setBlurCharacter2(blurCharacter2 + 1);
};
const displayYes = "inline";
const displayNo = "none";
if (loading) return "Loading...";
if (error) return <pre>{error.message}</pre>;
const prevStyle = {
display: `${blurCharacter1 !== 0 ? displayYes : displayNo}`,
};
const nextStyle = {
display: `${blurCharacter2 !== data.charactersName.data.results.length ? displayYes : displayNo}`,
};
return (
<div className="container">
<p className="count">
{data.charactersName.data.count} answers related to : "{name}"
</p>
<div className="wrapper">
<div style={prevStyle} className="prev" onClick={() => prevCharacter()}>
❮
</div>
<div className="characters-container">
{data.charactersName.data.results.map(({ id, name, thumbnail }, index) => (
<Character
id={id}
name={name}
thumbnail={thumbnail}
index={index}
visibleCharacter1={visibleCharacter1}
visibleCharacter2={visibleCharacter2}
visibleCharacter3={visibleCharacter3}
blurCharacter1={blurCharacter1}
blurCharacter2={blurCharacter2}
/>
))}
</div>
<div style={nextStyle} className="next" onClick={() => nextCharacter()}>
❯
</div>
</div>
</div>
);
};
export default Events;
<file_sep>import React from "react";
import SearchCharacter from "../SearchCharacter";
import { fireEvent, render } from "@testing-library/react";
import renderer from "react-test-renderer";
import "@testing-library/jest-dom";
import "@testing-library/jest-dom/extend-expect";
test("The form is displayed correctly", () => {
const component = renderer.create(<SearchCharacter />).toJSON();
expect(component).toMatchSnapshot();
});
test("Change value is working correctly", () => {
const { getByTestId } = render(<SearchCharacter />);
const inputElem = getByTestId("characterName");
expect(inputElem.value).toBe("");
fireEvent.change(inputElem, {
target: {
value: "test",
},
});
expect(inputElem.value).toBe("test");
});
<file_sep>import React, { useState } from "react";
import { useForm } from "react-hook-form";
import DisplayCharacters from "./DisplayCharacters";
import "./characters.css";
const SearchCharacter = () => {
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm();
const [character, setCharacter] = useState("");
const onSubmit = async ({ characterName }) => {
setCharacter(await characterName);
reset();
};
return (
<div className="container">
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="characterName">Character name :</label>
<input
data-testid="characterName"
id="characterName"
type="characterName"
{...register("characterName", {
required: true,
pattern: {
value: /[a-zA-Z]+/,
message: "Entered value must be a name",
},
})}
/>
{errors.characterName?.type === "pattern" && (
<span role="alert">{errors.characterName.message}</span>
)}
{errors.characterName?.type === "required" && <span role="alert">Field is required</span>}
<button data-testid="submitButton" type="submit">
Search
</button>
</form>
{character ? <DisplayCharacters name={character} /> : null}
</div>
);
};
export default SearchCharacter;
<file_sep># Marvel Wiki (React version)
Marvel wiki using the official Marvel API (https://developer.marvel.com/) made with React.
The REST API is wrapped with GraphQL. It makes easier using the API since the official API is so HUGE!
# Live
App is live here : https://marvelwiki-react.netlify.app/
Front part is deployed with Netlify
Back part is deployed with Heroku
# Tech
- Front End made with React and Apollo
- Back End made with Node.js & Express & GraphQL
# Infos
The project is made with the mobile first approach. I'll have to upgrade to desktop view.
App made to learn the GraphQL query language and Jest the testing Framework
Next step will be to build pretty much the same app but using Next.js and Typescript
<file_sep>import React from "react";
import Footer from "../Footer";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
test("Marvel's copyright is displayed correctly", () => {
const { getByTestId} = render(<Footer />);
const componenetElement = getByTestId("copyright");
expect(componenetElement.textContent).toBe("Data provided by Marvel. © 2014 Marvel");
});
<file_sep>import React from "react";
import NavBar from "./components/navBar/NavBar";
import Home from "./components/home/Home";
import SearchCharacter from "./components/characters/SearchCharacter";
import Events from "./components/events/Events";
import Footer from "./components/footer/Footer";
import "./App.css";
const App = () => {
return (
<div className="app">
<div className="navBar">
<NavBar />
</div>
<div id="home">
<Home />
</div>
<div id="searchCharacter">
<h1 className="title" data-testid="searchTitle">
Look for a character :
</h1>
<SearchCharacter />
</div>
<div id="events">
<h1 className="title" data-testid="eventsTitle">
Events list :
</h1>
<Events />
</div>
<div id="footer">
<Footer />
</div>
</div>
);
};
export default App;
<file_sep>import React from "react";
const Home = () => {
return (
<div>
<h1 data-testid="title">My home component</h1>
</div>
);
};
export default Home;
<file_sep>import React from "react";
import { useQuery } from "@apollo/client";
import { getEvents } from "../../queries/events";
import "./events.css";
const Events = () => {
const { data, loading, error } = useQuery(getEvents);
if (loading) return "Loading...";
if (error) return <pre>{error.message}</pre>;
return (
<div>
<p className="count">{data.eventsList.data.count} events</p>
<div className="events">
{data.eventsList.data.results.map(({id, title, thumbnail}) => (
<div key={id} className="event">
<img
src={thumbnail.path + "/portrait_small." + thumbnail.extension}
alt="event"
/>
{title}
</div>
))}
</div>
</div>
);
};
export default Events;
| 6f8f1c1810053d4b88791ad5649aa28ec51eea5b | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | BenjaminDexant/wikimarvel-react | 44ae3ee39bbcf8e96691ac6cf4063290c8819e97 | 73eea8cd14b293ff73ce6fa82530a20c8375bc78 |
refs/heads/master | <repo_name>link-coala/tv<file_sep>/app/controllers/singles_controller.rb
class SinglesController < ApplicationController
before_action :set_single, only: [:show, :edit, :update, :destroy]
# GET /singles
# GET /singles.json
def index
@singles = Single.all
end
# GET /singles/1
# GET /singles/1.json
def show
end
# GET /singles/new
def new
@single = Single.new
end
# GET /singles/1/edit
def edit
end
# POST /singles
# POST /singles.json
def create
@single = Single.new(single_params)
respond_to do |format|
if @single.save
format.html { redirect_to @single, notice: 'Single was successfully created.' }
format.json { render :show, status: :created, location: @single }
else
format.html { render :new }
format.json { render json: @single.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /singles/1
# PATCH/PUT /singles/1.json
def update
respond_to do |format|
if @single.update(single_params)
format.html { redirect_to @single, notice: 'Single was successfully updated.' }
format.json { render :show, status: :ok, location: @single }
else
format.html { render :edit }
format.json { render json: @single.errors, status: :unprocessable_entity }
end
end
end
# DELETE /singles/1
# DELETE /singles/1.json
def destroy
@single.destroy
respond_to do |format|
format.html { redirect_to singles_url, notice: 'Single was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_single
@single = Single.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def single_params
params.require(:single).permit(:picture, :name)
end
end
<file_sep>/test/controllers/singles_controller_test.rb
require 'test_helper'
class SinglesControllerTest < ActionController::TestCase
setup do
@single = singles(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:singles)
end
test "should get new" do
get :new
assert_response :success
end
test "should create single" do
assert_difference('Single.count') do
post :create, single: { name: @single.name, picture: @single.picture }
end
assert_redirected_to single_path(assigns(:single))
end
test "should show single" do
get :show, id: @single
assert_response :success
end
test "should get edit" do
get :edit, id: @single
assert_response :success
end
test "should update single" do
patch :update, id: @single, single: { name: @single.name, picture: @single.picture }
assert_redirected_to single_path(assigns(:single))
end
test "should destroy single" do
assert_difference('Single.count', -1) do
delete :destroy, id: @single
end
assert_redirected_to singles_path
end
end
<file_sep>/app/views/singles/show.json.jbuilder
json.extract! @single, :id, :picture, :name, :created_at, :updated_at
<file_sep>/README.rdoc
gem 'mini_magick', '3.8.0'
app/uploaders/picture_uploader.rb
# include CarrierWave::MiniMagick
+
version :thumb do
process :resize_to_fill => [50, 50]
end
app/views/ideas/index.html.erb
<td><%= idea.picture %></td>
<td><%= image_tag idea.picture_url(:thumb) if idea.picture? %></td>
sudo apt-get install imagemagick<file_sep>/app/views/singles/index.json.jbuilder
json.array!(@singles) do |single|
json.extract! single, :id, :picture, :name
json.url single_url(single, format: :json)
end
| 3a476b679758d718fe6615a407f15e982bd0dc58 | [
"RDoc",
"Ruby"
] | 5 | Ruby | link-coala/tv | fc360021a9a90c1fbbd769913dcbe7f239bb9f73 | e5ff7d0c62ec2e059f7c6956638302c757076216 |
refs/heads/master | <repo_name>willxj36/Reacting-to-React<file_sep>/src/components/app.jsx
import React, {Component} from 'react';
// let App = (props) => <h1>{props.title}</h1>;
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: ' and then some words n stuff',
input: '',
hasLoaded: false
}
this.handleType = this.handleType.bind(this);
}
handleType(value) {
this.setState({
input: value
})
}
handleBtnClick() {
if (this.state.hasLoaded) {
this.setState({
hasLoaded: false
})
} else {
this.setState({
hasLoaded: true
})
}
}
componentDidMount() {
this.setState({
hasLoaded: true
})
}
render() {
if(this.state.hasLoaded) {
return(
<React.Fragment>
<h1>{this.props.title} {this.state.text}</h1>
<input onChange={(event) => this.handleType(event.target.value)}
type="text"
placeholder={this.state.placeholder}
value={this.state.input} />
<button onClick={() => this.handleBtnClick()}>Click me</button>
</React.Fragment>
)
} else {
return(
<React.Fragment>
<h1>Loading...</h1>
<button onClick={() => this.handleBtnClick()}>Click me</button>
</React.Fragment>
)
}
}
}
export default App | 157097626c460eedd5f1a931039848b5a3fd70aa | [
"JavaScript"
] | 1 | JavaScript | willxj36/Reacting-to-React | 062dd7ed4f377fb12118220b5d3986c518ef1091 | c2813209d4e2f22a0a5258d673748497c1bc1c7b |
refs/heads/master | <file_sep>require("dotenv").config();
var keys = require("./keys.js");
var Spotify = require('node-spotify-api');
var axios = require("axios");
var moment = require("moment");
var fs = require("fs");
function main(selection, value) {
switch (selection) {
case "concert-this":
concert(value);
break;
case "spotify-this-song":
spotify(value);
break;
case "movie-this":
movie(value);
break;
case "do-what-it-says":
random();
break;
default:
console.log("Not Valid Operation");
}
}
function concert(name) {
var artist = name;
var artistForError = name;
if (!artist) {
console.log("Please enter a valid Artist");
} else {
var url = "https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp";
axios.get(url).then(
function (response) {
if (response.data.length > 0) {
console.log("\n\n\n\nSearch Events for " + artistForError);
writeLog("Search Events for " + artistForError + "\n")
console.log("\nVenue Name: " + response.data[0].venue.name);
writeLog("Venue Name: " + response.data[0].venue.name + "\n")
console.log("\nVenue Location: " + response.data[0].venue.city);
writeLog("Venue Location: " + response.data[0].venue.city + "\n")
console.log("\nDate of Event: " + moment(response.data[0].datetime).format("MM/DD/YYYY") + "\n\n\n\n");
writeLog("Date of Event: " + moment(response.data[0].datetime).format("MM/DD/YYYY") + "\n" +"====================================================" + "\n")
} else {
console.log("No upcoming events for " + artistForError);
}
}).catch(function (error) {
if (error.response) {
console.log("---------------Data---------------");
console.log(error.response.data);
console.log("---------------Status---------------");
console.log(error.response.status);
console.log("---------------Status---------------");
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log("Error", error.message);
}
console.log(error.config);
});
}
}
function movie(name) {
var movieUrl = name;
var movieforError = name;
if (!movieUrl) {
var movieUrl = "Mr. Nobody";
var movieforError = "Mr. Nobody";
console.log("If you haven't watched Mr. Nobody, then you should: It's on Netflix!");
}
axios.get("http://www.omdbapi.com/?t=" + movieUrl + "&y=&plot=short&apikey=trilogy").then(
function (response) {
if (response.data.Title != undefined) {
console.log("\n\n\nSearching info for " + movieforError);
writeLog("Searching info for " + movieforError + "\n")
console.log("Title: " + response.data.Title);
writeLog("Title: " + response.data.Title + "\n")
console.log("Year: " + response.data.Year);
writeLog("Year: " + response.data.Year + "\n")
console.log("Imdb Rating: " + response.data.imdbRating);
writeLog("Imdb Rating: " + response.data.imdbRating + "\n")
console.log("Rotten Tomatoes Rating: " + response.data.Ratings[1].Value);
writeLog("Rotten Tomatoes Rating: " + response.data.Ratings[1].Value + "\n")
console.log("Country: " + response.data.Country);
writeLog("Country: " + response.data.Country + "\n")
console.log("Language: " + response.data.Language);
writeLog("Language: " + response.data.Language + "\n")
console.log("Plot: " + response.data.Plot);
writeLog("Plot: " + response.data.Plot + "\n")
console.log("Actors: " + response.data.Actors + "\n\n\n");
writeLog("Actors: " + response.data.Actors + "\n" +"====================================================" + "\n")
} else {
console.log("No results for " + movieforError);
}
})
.catch(function (error) {
if (error.response) {
console.log("---------------Data---------------");
console.log(error.response.data);
console.log("---------------Status---------------");
console.log(error.response.status);
console.log("---------------Status---------------");
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log("Error", error.message);
}
console.log(error.config);
});
}
function spotify(name) {
var spotifyUrl = name;
var spotifyUrlError = name;
if (!spotifyUrl) {
spotifyUrl = "The Sign";
}
var spotify = new Spotify(keys.spotify);
spotify.search({ type: 'track', query: spotifyUrl }, function (err, data) {
if (err) {
return console.log('Error occurred: ' + err);
}
console.log("\n\nSearching info for song: " + spotifyUrl);
writeLog("Searching info for song: " + spotifyUrl + "\n")
console.log("\nArtist(s) Name: " + data.tracks.items[0].artists[0].name);
writeLog("Artist(s) Name: " + data.tracks.items[0].artists[0].name + "\n")
console.log("\nSong Name: " + data.tracks.items[0].name);
writeLog("Song Name: " + data.tracks.items[0].name + "\n")
console.log("\nSpotify Preview Link: " + data.tracks.items[0].external_urls.spotify);
writeLog("Spotify Preview Link: " + data.tracks.items[0].external_urls.spotify + "\n")
console.log("\nAlbum Name: " + data.tracks.items[0].album.name + "\n\n\n\n");
writeLog("Album Name: " + data.tracks.items[0].album.name + "\n" +"====================================================" + "\n")
});
}
function random() {
fs.readFile('random.txt', "utf8", function (error, res) {
if (error) {
return console.log(error);
}
var sel = res.split("%")
//console.log(sel);
var pos = Math.floor(Math.random() * sel.length)
var arr = sel[pos].split(",")
main(arr[0], arr[1]);
});
}
main(process.argv[2], process.argv.slice(3).join("+"));
function writeLog(data) {
fs.appendFile("log.txt", data, function (err) {
if (err) {
console.log(err);
}
});
}<file_sep>Liri Node App
Link to video demostration
https://drive.google.com/file/d/1Ow9PhCXQoW7GVthGInwexNwZ9XMBqs6z/view
LIRI is a Language Interpretation and Recognition Interface
LIRI perform searchs in Spotify for songs, Bands in Town for concerts, and OMDB for movies
To run the program the user must write in cosole node liri then any of the commands and then the info to search
For example:
node liri spotify-this-song 24K or node liri movie-this titanic
or node liri concert-this metallica or node liri do-what-it-says
The features for the program are:
Take the console user input validate and depending on the info do the following
Command movie-this: takes the movie name from the user input and make an call to the OMDB API and show the info from the response in the console.
Command concert-this: takes the band name from the user input and make an call to the bandsintown API and show the info from the response in the console.
Command spotify-this-song: takes the song name from the user input and make an call to the Spotify API and show the info from the response in the console.
Command do-what-it-says: read the file ramdon.txt and separe the commands and values intro an array and then choose randomly one of the commands and values and then with this information call the function depending the commands selected and sent the value and show the info in the console, so each time the action must be diferent
Every time that the user perform an action all the info is appended to the log.txt file
In the development of this system was used severals node packages like: axios, fs, moments, node-spotify-api
The system was developed by
<NAME>
| cc3c963f7badbb70a8a4c2d762c5fc999b7b22c8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | reynaldodominguez/liri-node-app | 876ca904ea45a429547cf80a5e080449942bdadb | b9a8a006ceda3788fc2c03a668580b2af1448f41 |
refs/heads/master | <file_sep>PLAN9=/usr/local/plan9 export PLAN9
PATH=$PATH:$PLAN9/bin export PATH
<file_sep>#!/bin/sh
cap="$(cat /sys/class/power_supply/BAT0/capacity)"
low="10"
if [ "$cap" -le "$low" ]; then
herbe "battery low"
fi
<file_sep>#!/bin/sh
user="$(whoami)"
host="$(hostname)"
os='void'
shell="$(basename "${SHELL}")"
uptime="$(uptime -p | sed 's/up //')"
wm="$(grep "/usr/" ~/.xinitrc | cut -d ' ' -f 1 | cut -d '/' -f 5)"
cat <<EOF
$user@$host
(\(\ -----------
j". .. os: $os
( . .) shell: $shell
| ° ¡ uptime: $uptime
¿ ; wm: $wm
c?".UJ
EOF
<file_sep> HISTFILE=$HOME/.ksh_history
HISTSIZE=20000
PROMPT="; "
PS1=$PROMPT
export EDITOR=$VIM
export FCEDIT=$EDITOR
export PAGER=less
export LANG=en_GB.UTF-8
export TZ=Europe/London
export PLAN9=/usr/local/plan9 export PLAN9
export PATH=$PATH:$PLAN9/bin export PATH
export NO_COLOR
export GCC_COLORS=
export SFEED_PLUMBER="firefox"
export SFEED_URL_FILE="$HOME/.config/sfeed/urls"
alias restart='doas shutdown -r now'
alias shutdown='doas shutdown -P now'
alias ls='ls -p'
alias sx='startx'
alias svup='doas sv status /var/service/*'
alias sfu='sfeed_update ~/.config/sfeed/sfeedrc'
alias sf='sfeed_curses ~/.sfeed/feeds/*'
alias sfc='rm ~/.sfeed/feeds/*'
| 2d3ed03a5a2ce46878933208baec5b5a19f0529b | [
"Shell"
] | 4 | Shell | Nitheren/Dotfiles | fb2d0688bd83ede96a551a39c71b202f14d4fb20 | ed3c45e9b042e4a0e9e55afd20a4e443520a4e72 |
refs/heads/master | <file_sep><h3>Товары</h3>
<h6>Найдено: <?= $products_count ?></h6>
<?php foreach ($products as $product): ?>
<div>
<h4><?= $product['title'] ?></h4>
<p><b>Цена: <?= $product['price'] ?>р.</b></p>
<p><b>На складе: <?= $product['quantity'] ?></b></p>
<p><?= $product['description'] ?></p>
<form action="./?action=add_to_cart" method="POST">
<input type="hidden" name="product_id" value="<?= $product['id'] ?> ">
<label for="quantity_<?= $product['id'] ?>">Количество</label>
<input id="quantity_<?= $product['id'] ?>" type="text" name="quantity" value="1">
<button type="submit">Добавить в корзину</button>
</form>
</div>
<hr>
<?php endforeach; ?>
<?php if ($has_next_page): ?>
<a href="./?action=products&page=<?= $page + 1 ?>">Вперёд →</a><br>
<?php endif; ?>
<?php if ($has_prev_page): ?>
<a href="./?action=products&page=<?= $page - 1 ?>">← Назад</a>
<?php endif; ?>
<file_sep><?php
/**
* Контроллер выхода с сайта.
*/
// Пользователь нажал кнопку "выйти"
if (isset($_POST['logout'])) {
// Очищаем данные о пользователе в сессии
$_SESSION['user_id'] = 0;
$_SESSION['user'] = [];
browser_redirect('homepage');
}<file_sep><?php
/**
* Эта функция отображает шаблон 404-й страницы с заданным текстом
*/
function not_found_404($message = 'Страница не найдена!')
{
display_template('404', array(
'message' => $message,
'page_title' => $message,
));
}
/**
* Эта функция отображает шаблон и передаёт в него переменные из массива
*/
function display_template($template_name, $variables = array())
{
if (empty($variables['page_title'])) {
$variables['page_title'] = 'Интернет-магазин';
}
$template_name = basename($template_name);
ob_start();
extract($variables);
unset($variables);
require_once HEADER_TEMPLATE_FILE;
require_once TEMPLATES_DIR . '/' . $template_name . '.php';
require_once FOOTER_TEMPLATE_FILE;
ob_end_flush();
}
/**
* Получение из БД и подсчёт данных, необходимых для отображения блока
* "Корзина" в шапке сайта.
*/
function get_cart_data()
{
// Получим из БД массив с информацией о товарах, находящихся в корзине
$products = get_product_data_from_cart();
// Общая стоимость товаров в корзине
$total_cost = 0;
// Общее количество товаров в корзине
$total_quantity = 0;
// В цикле обойдём массив с информацией о товарах
foreach ($products as $product) {
// и прибавим к суммарным переменным данные о каждом товаре
$total_quantity += $_SESSION['cart'][$product['id']];
$total_cost += $product['price'] * $_SESSION['cart'][$product['id']];
}
// Вернём массив данных, которые могут быть переданы в шаблон
return array(
'quantity' => $total_quantity,
'cost' => $total_cost,
);
}
/**
* Получение из БД и подсчёт данных, необходимых для отображения страницы с информацией о товарах в корзине/
*/
function get_full_cart_data()
{
$products = get_product_data_from_cart();
// Общая стоимость товаров в корзине
$total_cost = 0;
// Общее количество товаров в корзине
$total_quantity = 0;
// В цикле обойдём массив с информацией о товарах
foreach ($products as &$product) {
// Количество данного товара, находящееся в корзине
$product_quantity_at_cart = $_SESSION['cart'][$product['id']];
// Суммарная стоимость за всё количество данного товара в корзине
$product_price_at_cart = $product['price'] * $product_quantity_at_cart;
// Добавим два значения в массив с информацией о конкретном товаре:
// quantity_at_cart - общее количество единиц товара в корзине
// total_price_at_cart - суммарная стоимость за всё количество данного товара в корзине
$product['quantity_at_cart'] = $product_quantity_at_cart;
$product['total_price_at_cart'] = $product_price_at_cart;
// прибавим к суммарным переменным данные о каждом товаре
$total_quantity += $product_quantity_at_cart;
$total_cost += $product_price_at_cart;
}
// Вернём массив данных, которые могут быть переданы в шаблон
return array(
'products' => $products,
'total_quantity' => $total_quantity,
'total_cost' => $total_cost,
);
}
function get_product_data_from_cart()
{
// В эту переменную занесём строку, содержащую идентификаторы товаров,
// находящихся в корзине, перечисленные через запятую
$product_ids = array_keys($_SESSION['cart']);
$product_ids = implode(',', $product_ids);
$product_ids = empty($product_ids) ? '0' : $product_ids;
// Получим из БД массив с информацией о товарах, находящихся в корзине
$products = db_select("SELECT * FROM products WHERE id IN ({$product_ids})");
return $products;
}
/**
* Возвращает "action" - действие, которое нужно выполнить
* согласно этому действию будет выполнен файл с соответствующим именем из папки controllers.
* "Action" задаётся GET-параметром.
*/
function get_current_action()
{
static $action = null;
if ($action === null) {
// $action - действие, которое нужно выполнить
// согласно этому действию будет выполнен файл с соответствующим именем из папки controllers
$action = filter_input(INPUT_GET, 'action');
if ($action === null) {
// homepage - значение по-умолчанию для $action
$action = 'homepage';
} else {
// обезопасим $action, убрав все компоненты пути, кроме последнего, т.е.
// если $action = '../../hello', то $action станет 'hello'
$action = basename($action);
}
}
return $action;
}
/**
* Возвращает булево значение - авторизован ли пользователь на сайте.
*/
function is_logged_in()
{
return isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0;
}
/**
* Возвращает список элементов меню сайта.
*/
function get_menu_items()
{
$is_logged_in = is_logged_in();
$items = array(
array(
'title' => 'Домашняя страница',
'action' => 'homepage',
'visible' => true,
),
array(
'title' => 'Товары',
'action' => 'products',
'visible' => true,
),
array(
'title' => 'Регистрация',
'action' => 'signup',
'visible' => !$is_logged_in // элемент скрыт для авторизованных пользователей
),
array(
'title' => 'Авторизация',
'action' => 'login',
'visible' => !$is_logged_in // элемент скрыт для авторизованных пользователей
),
array(
'title' => 'Корзина',
'action' => 'cart',
'visible' => true,
),
);
$action = get_current_action();
// для каждого элемента меню в цикле определим
foreach ($items as &$item) {
// активен ли он
$item['is_active'] = ($action == $item['action']);
// и ссылку на раздел сайта, за который отвечает элемент меню
$item['url'] = './index.php?action=' . $item['action'];
}
unset($item);
// уберём из массива элементы, которые не должны отображаться
foreach ($items as $k => $item) {
if (!$item['visible']) {
unset($items[$k]);
}
}
return $items;
}
function browser_redirect($action, $params = array())
{
$query_parameters = array(
'action' => $action
);
$query_parameters = array_merge($params, $query_parameters);
$query_parameters = http_build_query($query_parameters);
header('Location: ./index.php?' . $query_parameters);
}
function add_notification($message)
{
if (empty($_SESSION['notifications'])) {
$_SESSION['notifications'] = array();
}
$_SESSION['notifications'][] = $message;
}
function get_and_delete_notifications()
{
$return = isset($_SESSION['notifications'])
? $_SESSION['notifications']
: array();
unset($_SESSION['notifications']);
return $return;
}<file_sep><h3>Регистрация</h3>
<form method="POST" action="./index.php?action=signup">
<?php require __DIR__ .'/_form-errors.php'; ?>
<p>
<label>E-mail: <input type="text" name="email"></label>
</p>
<p>
<label>Пароль: <input type="<PASSWORD>" name="password"></label>
</p>
<p>
<button type="submit">Зарегистрироваться</button>
</p>
</form><file_sep><h3>Товары в корзине</h3>
<h4>Всего товаров: <?= $total_quantity ?></h4>
<h4>На сумму: <?= $total_cost ?></h4>
<table>
<tr>
<th>Наименование</th>
<th>Стоимость за ед.</th>
<th>На складе</th>
<th>Кол-во в корзине</th>
<th>К оплате, руб.</th>
<th></th>
</tr>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['title'] ?></td>
<td><?= $product['price'] ?></td>
<td><?= $product['quantity'] ?></td>
<td><?= $product['quantity_at_cart'] ?></td>
<td><?= $product['total_price_at_cart'] ?></td>
<td>
<form action="./?action=cart" method="POST">
<input type="hidden" name="product_id" value="<?= $product['id'] ?>">
<input type="submit" name="delete" value="Удалить">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<form action="./index.php?action=checkout" method="POST">
<button type="submit">Оформить заказ</button>
</form>
<file_sep><?php
/**
* Контроллер отображения полного содержимого корзины
*/
// Нам передан параметр "delete" - значит пользователь нажал на кнопку "Удалить товар"
if (isset($_POST['delete'], $_POST['product_id'])) {
$product_id = (int) $_POST['product_id'];
// Собственно, удаляем из сессии информацию о товаре в корзине, если он там есть
if (isset($_SESSION['cart'][$product_id])) {
unset($_SESSION['cart'][$product_id]);
}
}
// Отобразим шаблон "cart", передав в него в качестве переменных
// результат вызова функции get_full_cart_data()
display_template('cart', get_full_cart_data());<file_sep><!DOCTYPE html>
<html>
<head>
<title><?= $page_title ?></title>
<meta charset="UTF-8">
</head>
<body>
<?php $cart = get_cart_data() ?>
<div>
<h4><a href="./?action=cart">Корзина</a></h4>
<?= $cart['quantity'] ?> товаров на сумму <?= $cart['cost'] ?>р.
</div>
<div>
<?php if (is_logged_in()): ?>
<p>Привет, <?= $_SESSION['user']['name'] ?>!</p>
<form action="./index.php?action=logout" method="POST">
<input type="submit" name="logout" value="Выйти">
</form>
<?php endif; ?>
</div>
<ul style="color: red;">
<?php foreach (get_and_delete_notifications() as $notification): ?>
<li><?=$notification ?></li>
<?php endforeach; ?>
</ul>
<ul>
<?php foreach (get_menu_items() as $menu_item): ?>
<?php if ($menu_item['is_active']): ?>
<li><b><?= $menu_item['title'] ?></b></li>
<?php else: ?>
<li>
<a href="<?= $menu_item['url'] ?>"><?= $menu_item['title'] ?></a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul><file_sep><?php
/**
* Скрипт-установщик интернет-магазина
*/
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';
$install = array();
$install['Create DB'] = 'CREATE DATABASE IF NOT EXISTS `itc_eshop` DEFAULT CHARACTER SET = `utf8`;';
$install['Use DB'] = 'USE `itc_eshop`;';
// HEREDOC-syntax
// Create users table
$install['Delete users table'] = 'DROP TABLE IF EXISTS `users`;';
$install['Create users table'] = <<<SQL
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(40) NOT NULL DEFAULT "",
`password_hash` varchar(70) NOT NULL DEFAULT "",
`last_logged_in` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
// Create products table
$install['Delete products table'] = 'DROP TABLE IF EXISTS `products`;';
$install['Create products table'] = <<<SQL
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`price` decimal(11,2) NOT NULL DEFAULT '0.00',
`quantity` int(11) NOT NULL DEFAULT '0',
`description` text,
`image_path` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
// Create carts table
$install['Delete carts table'] = 'DROP TABLE IF EXISTS `carts`;';
$install['Create carts table'] = <<<SQL
CREATE TABLE `carts` (
`user_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`,`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
// Create orders table
$install['Delete orders table'] = 'DROP TABLE IF EXISTS `orders`;';
$install['Create orders table'] = <<<SQL
CREATE TABLE `orders` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
// Связь между товарами и заказами
$install['Delete products_at_orders table'] = 'DROP TABLE IF EXISTS `products_at_orders`;';
$install['Create products_at_orders table'] = <<<SQL
CREATE TABLE `products_at_orders` (
`product_id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`product_id`,`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
foreach ($install as $query_description => $query_body)
{
echo $query_description . '<br>';
db_query($query_body);
}<file_sep><?php
/**
* Контроллер авторизации (входа на сайт).
* Отвечает за обработку данных, пришедших из формы авторизации.
*/
// Массив с ошибками заполнения формы
$errors = [];
// Нам переданы из формы email & password
if (isset($_POST['email'], $_POST['password'])) {
// Отсечём пустые символы (пробелы и переносы строк)
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// Найдём пользователя в БД с переданным нам email'ом
$user = db_select('SELECT * FROM `users` WHERE `email` = :email LIMIT 1;', [
':email' => $email
]);
$user = reset($user);
// Не нашли такого пользователя в БД
if (empty($user)) {
$errors[] = 'Пользователь не найден.';
} else {
// Нашли, проверим пришедший из формы пароль.
// Сравним хэш из БД с хэшем пароля, введённого в форму.
$password_is_valid = password_verify($password, $user['password_hash']);
if ($password_is_valid) {
// Хэши совпали, запишем ID пользователя в сессию.
$_SESSION['user_id'] = (int) $user['id'];
// ...и отправим на главную страницу
browser_redirect('homepage');
} else {
$errors[] = 'Введён неверный пароль.';
}
}
}
display_template('login', [
'errors' => $errors
]);<file_sep><?php if (!empty($errors)): ?>
<div style="color: red;">
<h4>Были допущены ошибки:</h4>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?><file_sep><?php
/**
* Контроллер регистрации.
* Отвечает за обработку данных, пришедших из формы регистрации.
*/
// Массив с ошибками заполнения формы
$errors = array();
// Нам переданы из формы email & password
if (isset($_POST['email'], $_POST['password'])) {
// Отсечём пустые символы (пробелы и переносы строк)
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// Проверим e-mail на корректность
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
$errors[] = 'Введён некорректный e-mail.';
}
// Проверим длину пароля
if (mb_strlen($password) < 6) {
$errors[] = 'Пароль не может быть менее 6 символов.';
}
// Найдём пользователя с таким же email в БД
$user_with_same_email = db_select(
'SELECT * FROM `users` WHERE `email` = :email LIMIT 1;', array(
':email' => $email
));
// Если нашли - добавляем ошибку
if (!empty($user_with_same_email)) {
$errors[] = 'Этот e-mail уже занят.';
}
// Если ошибок нет - добавим новую запись в таблицу users
if (empty($errors)) {
// Мы храним только хэш пароля
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$sql = 'INSERT INTO `users` (`email`, `password_hash`) VALUES (:email, :password_hash)';
// Выполним SQL-запрос вставки записи, используя именованные параметры
$affected_rows = db_query($sql, array(
':email' => $email,
':password_hash' => $password_hash
));
// Вызов db_query должен вернуть 1, потому что мы вставляем 1 запись
if ($affected_rows < 1) {
$errors[] = 'Не удалось завершить регистрацию.';
}
}
// Ошибок не произошло - отправляем пользователя на главную страницу
if (empty($errors)) {
browser_redirect('homepage');
}
}
// Отображаем шаблон в случае если нам не пришли никакие данные из формы,
// либо при обработке данных формы возникли ошибки.
display_template('signup', array(
'errors' => $errors
));<file_sep><?php
/**
* Файл controllers/homepage.php содержит PHP-код для главной страницы интернет-магазина
*/
// Отобразим шаблон главной страницы
display_template('homepage', array(
'page_title' => 'Главная страница',
));<file_sep><?php
// Отображать все ошибки
error_reporting(-1);
ini_set('display_errors', 'on');
define('CONTROLLERS_DIR', __DIR__ . '/controllers');
define('TEMPLATES_DIR', __DIR__ . '/templates');
define('HEADER_TEMPLATE_FILE', __DIR__ . '/layouts/header.php');
define('FOOTER_TEMPLATE_FILE', __DIR__ . '/layouts/footer.php');
// Подключение к БД
require_once __DIR__ . '/db.php';
// Загрузка функций
require_once __DIR__ . '/functions.php';
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (!isset($_SESSION['user_id'])) {
$_SESSION['user_id'] = 0;
}
// Загрузим из БД данные об авторизованном пользователе
if ($_SESSION['user_id'] > 0) {
$user = db_select('SELECT * FROM `users` WHERE `id` = :id', array(
':id' => $_SESSION['user_id']
));
$user = reset($user);
if ($user) {
$_SESSION['user'] = $user;
} else {
$_SESSION['user_id'] = 0;
$_SESSION['user'] = array();
}
} else {
$_SESSION['user'] = array();
}
$action = get_current_action();
$path_to_controller = CONTROLLERS_DIR . '/' . $action . '.php';
// подключим файл, которые содержит код для выбранного $action
if (file_exists($path_to_controller)) {
require_once $path_to_controller;
} else {
// если передан несуществующий action - покажем 404 страницу
not_found_404();
}
// запишем данные сессии в файл сессии
session_write_close();<file_sep><?php
/**
* Контроллер, отвечающий за отображение списка товаров магазина
*/
// Получаем значение параметра "page", определяющего номер текущей страницы
$page = (int) filter_input(INPUT_GET, 'page');
// По-умолчанию, если такой GET-параметр не передан или некорректен, установим значение 1
if ($page <= 0) {
$page = 1;
}
// Количество товаров на страницу
$products_per_page = 3;
// Общее количество товаров в базе
$products_count = db_select('SELECT COUNT(*) FROM products;');
$products_count = reset($products_count);
$products_count = (int) reset($products_count);
// Кол-во товаров, которые нужно выбрать
$limit = $products_per_page;
// Кол-во товаров, которые нужно пропустить с начала выборки (сдвиг)
$offset = $products_per_page * ($page - 1);
// Определим номер последней страницы
$last_page = $products_count / $products_per_page;
// Есть ли следующая страница
$has_next_page = $last_page > $page;
// Есть ли предыдущая страница
$has_prev_page = $page > 1;
// Получим из БД список товаров, ограниченный значениями limit и offset
$products = db_select("SELECT * FROM products LIMIT {$offset}, {$limit};");
// Отобразим шаблон, передав в него необходимые переменные
display_template('products', array(
'products' => $products,
'products_count' => $products_count,
'page' => $page,
'has_next_page' => $has_next_page,
'has_prev_page' => $has_prev_page,
));<file_sep><?php
/**
* Контроллер добавления товара в корзину
*/
// Переданы ID товара и его количество
if (isset($_POST['product_id'], $_POST['quantity'])) {
$product_id = (int) $_POST['product_id'];
$quantity = (int) $_POST['quantity'];
// Получаем из базы информацию о товаре
$product = db_select("SELECT * FROM products WHERE id = {$product_id}");
$product = reset($product);
// Товар не найден в базе
if (!$product) {
not_found_404('Запрашиваемый товар не найден!');
} else {
// Доступное количество товара из базы
$product_available_quantity = $product['quantity'];
// $quantity - количество товара, которое будет в корзине
// (уже имеющееся в корзине + то, что мы собираемся добавить)
$quantity = isset($_SESSION['cart'][$product_id])
? $quantity + $_SESSION['cart'][$product_id]
: $quantity;
// Если мы собираемся иметь в корзине больше единиц товара, чем доступно,
// то положим в корзину всё доступное количество
if ($quantity > $product_available_quantity) {
$quantity = $product_available_quantity;
}
// Собственно добавление товара в корзину
$_SESSION['cart'][$product_id] = (int) $quantity;
// Отправим браузеру заголовок "Location", чтобы браузер вернулся на предыдущую страницу
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
}<file_sep><?php
if (strtolower($_SERVER['REQUEST_METHOD']) !== 'post') {
exit;
}
if (!is_logged_in()) {
add_notification('Оформление заказа доступно только авторизованным пользователям.');
browser_redirect('signup');
exit;
}
if (empty($_SESSION['cart'])) {
add_notification('Ваша корзина пуста.');
browser_redirect('homepage');
exit;
}
$products = get_product_data_from_cart();
$overhead_quantity_products = array();
foreach ($products as &$product) {
$product['quantity_at_cart'] = $_SESSION['cart'][$product['id']];
if ($product['quantity_at_cart'] > $product['quantity']) {
$overhead_quantity_products[] = $product['title'];
}
}
unset($product);
if (!empty($overhead_quantity_products)) {
$overhead_quantity_products = array_map(function ($product_title) {
return '"' . $product_title . '"';
}, $overhead_quantity_products);
add_notification('Для товаров ' . implode(', ', $overhead_quantity_products) . ' недостаточен остаток.');
browser_redirect('cart');
exit;
}
$order = array(
':user_id' => $_SESSION['user_id']
);
db_query('INSERT INTO `orders` (`user_id`) VALUES (:user_id);', $order);
$order_id = db_select('SELECT LAST_INSERT_ID();');
$order_id = reset($order_id);
$order_id = reset($order_id);
$order_id = (int)$order_id;
$sql_add_product_to_order = <<<SQL
INSERT INTO `products_at_orders`
(`product_id`, `order_id`, `quantity`)
VALUES
(:product_id, :order_id, :quantity)
SQL;
$sql_decrease_product_quantity = <<<SQL
UPDATE `products`
SET `quantity` = :new_quantity
WHERE `id` = :product_id
SQL;
foreach ($products as $product) {
db_query($sql_add_product_to_order, array(
':product_id' => $product['id'],
':order_id' => $order_id,
':quantity' => $product['quantity_at_cart'],
));
db_query($sql_decrease_product_quantity, array(
':product_id' => $product['id'],
':new_quantity' => $product['quantity'] - $product['quantity_at_cart'],
));
}
$_SESSION['cart'] = array();
add_notification('Заказ успешно создан!');
browser_redirect('order', array(
'order_id' => $order_id
));
exit;
<file_sep><?php
$order_id = filter_input(INPUT_GET, 'order_id');
if ($order_id === null) {
not_found_404();
exit;
}
if (!is_logged_in()) {
not_found_404();
exit;
}
$order = db_select('SELECT * FROM `orders` WHERE `id` = :order_id LIMIT 1;', array(
':order_id' => $order_id
));
$order = reset($order);
if (!$order) {
not_found_404();
exit;
}
$user_owns_the_order = ($order['user_id'] == $_SESSION['user_id']);
if (!$user_owns_the_order) {
not_found_404();
exit;
}
$sql = <<<SQL
SELECT
products.*, products_at_orders.quantity AS quantity_at_order
FROM products_at_orders
LEFT JOIN products ON products.id = products_at_orders.product_id
WHERE products_at_orders.order_id = :order_id;
SQL;
$products = db_select($sql, array(
':order_id' => $order_id
));
display_template('order', array(
'order' => $order,
'products' => $products,
));<file_sep><h3>Заказ #<?= $order['id'] ?></h3>
<file_sep><h3>Авторизация</h3>
<form method="POST" action="./index.php?action=login">
<?php require __DIR__ . '/_form-errors.php'; ?>
<p>
<label>E-mail: <input type="text" name="email"></label>
</p>
<p>
<label>Пароль: <input type="<PASSWORD>" name="password"></label>
</p>
<p>
<button type="submit">Войти</button>
</p>
</form><file_sep><?php
// Подключение к БД
function get_connection()
{
static $pdo = null;
$database_user = 'root';
$database_password = '<PASSWORD>';
if ($pdo === null) {
$pdo = new PDO(
'mysql:host=127.0.0.1',
$database_user, $database_password
);
// Каждая ошибка при работе с БД вызовет выброс исключения
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES utf8;');
$pdo->exec('USE itc_eshop;');
}
return $pdo;
}
/**
* Выборка табличных данных из БД
*
* @param string $query SELECT SQL-запрос
* @param array $params Список именованных параметров и их значений, например: array(':email' => '<EMAIL>')
*
* @return array Строки таблицы БД
*/
function db_select($query, $params = array())
{
/** @var PDO $pdo */
$pdo = get_connection();
$statement = $pdo->prepare($query);
$statement->execute($params);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Выполняет SQL-запрос (INSERT/UPDATE/DELETE/REPLACE/ALTER/...).
*
* @param string $query SQL-запрос
* @param array $params Список именованных параметров и их значений, например: array(':email' => '<EMAIL>')
*
* @return int Количество затронутых строк (сколько строк было вставлено или изменено или удалено в таблице)
*/
function db_query($query, $params = array())
{
/** @var PDO $pdo */
$pdo = get_connection();
$statement = $pdo->prepare($query);
$statement->execute($params);
return $statement->rowCount();
}
// Пример использования статической переменной в функции
function sum($x)
{
static $y = 0;
$y += $x;
return $y;
}
| e36f5a51fc092a8aacd15209aee6c34fd047516e | [
"PHP"
] | 20 | PHP | alpharder/learn-ecommerce | 2151ee0fcd817aa2e583ce42ece33b692902b186 | 1843588492b37f3da9960b23bf42202031944913 |
refs/heads/master | <file_sep>
#include "AssetLoader.h"
//#include "editor-support/cocostudio/CSContentJsonDictionary.h"
#include "editor-support/cocostudio/DictionaryHelper.h"
#include "Resources.h"
using namespace cocostudio;
Sprite* AssetLoader::createSprite(const std::string& name){
if (AssetLoader::getInstance()->fileExists(name)){
return Sprite::create(name);
}
log("create sprite: %s", name.c_str());
std::string plistfile = AssetLoader::getInstance()->getTexturePlist(name);
std::string imagefile = AssetLoader::getInstance()->getTextureImage(name);
log("plist: %s, image: %s", plistfile.c_str(), imagefile.c_str());
if (plistfile != "" && imagefile != ""){
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistfile, imagefile);
return Sprite::createWithSpriteFrameName(name);
}
return nullptr;
}
AssetLoader* AssetLoader::getInstance(){
static AssetLoader* m_assetLoader = nullptr;
if (m_assetLoader == nullptr){
m_assetLoader = new AssetLoader();
m_assetLoader->init();
}
return m_assetLoader;
}
bool AssetLoader::init(){
// 初始化 文件字典
//JsonDictionary *jsonDict = new JsonDictionary();
String* fileContent = String::createWithContentsOfFile(sjs_file_list);
//jsonDict->initWithDescription(fileContent->getCString());
rapidjson::Document jsonDict;
jsonDict.Parse<0>(fileContent->getCString());
DictionaryHelper* dicHelper = DICTOOL;
_fileDict = Dictionary::create();
int file_idx = dicHelper->getArrayCount_json(jsonDict, file_name);
for (int i = 0; i < file_idx; i++){
std::string name = dicHelper->getStringValueFromArray_json(jsonDict, file_name, i);
std::string index = dicHelper->getStringValueFromArray_json(jsonDict, file_index, i);
_fileDict->setObject(String::create(index), name);
}
log("file count: %d", file_idx);
_texturePlistDict = Dictionary::create();
int texture_idx = dicHelper->getArrayCount_json(jsonDict, texture_name);
for (int i = 0; i < texture_idx; i++){
std::string name = dicHelper->getStringValueFromArray_json(jsonDict, texture_name, i);
std::string plist = dicHelper->getStringValueFromArray_json(jsonDict, texture_plist, i);
_texturePlistDict->setObject(String::create(plist), name);
}
log("texture count: %d", texture_idx);
_textureImageDict = Dictionary::create();
for (int i = 0; i < texture_idx; i++){
std::string name = dicHelper->getStringValueFromArray_json(jsonDict, texture_name, i);
std::string image = dicHelper->getStringValueFromArray_json(jsonDict, texture_image, i);
_textureImageDict->setObject(String::create(image), name);
}
//CC_SAFE_DELETE(jsonDict);
return true;
}
bool AssetLoader::fileExists(const std::string &filename){
return _fileDict->objectForKey(filename) != nullptr;
}
std::string AssetLoader::getTexturePlist(const std::string &name){
Object* objPd = _texturePlistDict->objectForKey(name);
if (objPd != nullptr){
std::string tt_idx = dynamic_cast<String*>(objPd)->getCString();
DictElement* de = nullptr;
CCDICT_FOREACH(_fileDict, de){
if (de != nullptr){
String* str = dynamic_cast<String*>(de->getObject());
if (str->getCString() == tt_idx){
return de->getStrKey();
}
}
}
}
return "";
}
std::string AssetLoader::getTextureImage(const std::string &name){
Object* obj = _textureImageDict->objectForKey(name);
if (obj != nullptr){
std::string image = dynamic_cast<String*>(obj)->getCString();
DictElement* de = nullptr;
CCDICT_FOREACH(_fileDict, de){
if (de != nullptr){
String* str = dynamic_cast<String*>(de->getObject());
if (str->getCString() == image){
return de->getStrKey();
}
}
}
}
return "";
}
<file_sep>ManageAssets
============
Lib
cocos2dx 3.2<file_sep>
#ifndef __ResMgr__AssetLoader__
#define __ResMgr__AssetLoader__
#include "cocos2d.h"
using namespace cocos2d;
class AssetLoader: public Object{
public:
static Sprite* createSprite(const std::string& name);
private:
static AssetLoader* getInstance();
bool init();
bool fileExists(const std::string& filename);
std::string getTexturePlist(const std::string& name);
std::string getTextureImage(const std::string& name);
private:
Dictionary* _fileDict; // 文件列表
Dictionary* _texturePlistDict; // 打包资源到文件的映射
Dictionary* _textureImageDict; // 打包资源plist 到图片的映射
};
#endif /* defined(__ResMgr__AssetLoader__) */
<file_sep>#ifndef _AUTO_RESOURCES_H_
#define _AUTO_RESOURCES_H_
// search paths
static const char* directorys[] = {
"fonts",
"images",
};
// files
static const char si_CloseNormal[] = "CloseNormal.png";
static const char si_CloseSelected[] = "CloseSelected.png";
static const char sjs_file_list[] = "file_list.json";
static const char si_HelloWorld[] = "HelloWorld.png";
static const char st_MarkerFelt[] = "Marker Felt.ttf";
static const char sp_ghosts[] = "ghosts.plist";
static const char si_ghosts[] = "ghosts.png";
static const char sp_grossini_family[] = "grossini_family.plist";
static const char si_grossini_family[] = "grossini_family.png";
static const char si_JungleLeft[] = "JungleLeft.png";
////// texture //////
// ghosts.plist
static const char si_child1[] = "child1.gif";
static const char si_father[] = "father.gif";
static const char si_sister1[] = "sister1.gif";
static const char si_sister2[] = "sister2.gif";
// grossini_family.plist
static const char si_grossini[] = "grossini.png";
static const char si_grossinis_sister1[] = "grossinis_sister1.png";
static const char si_grossinis_sister2[] = "grossinis_sister2.png";
// json key
static const char file_name[] = "file_name";
static const char file_index[] = "file_index";
static const char texture_name[] = "texture_name";
static const char texture_plist[] = "texture_plist";
static const char texture_image[] = "texture_image";
#endif // _AUTO_RESOURCES_H_
| 31a9ed56321b7d413c145a92bbe5828a150ecea0 | [
"Markdown",
"C",
"C++"
] | 4 | C++ | gumcstronger/ManageAssets | 8fc9ef74c47f3622ca317a7754252e18c11194b9 | b292b53ba7b6e69649f07557c51b22c6b052d45d |
refs/heads/master | <repo_name>npjava90/struts_jasper<file_sep>/StrutswithJasper/src/org/jasper/StudentJasperAction.java
package org.jasper;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
public class StudentJasperAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String, Object> param=null;
private String studId;
private String rptFmt;
public String getRptFmt() {
return rptFmt;
}
public void setRptFmt(String rptFmt) {
this.rptFmt = rptFmt;
}
public String getStudId() {
return studId;
}
public void setStudId(String studId) {
this.studId = studId;
}
public Map<String, Object> getParam() {
return param;
}
public void setParam(Map<String, Object> param) {
this.param = param;
}
public String execute() throws Exception {
try {
param = new HashMap<String,Object>();
param.put("id", new Integer(studId));
param.put("Title", "Student Details");
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
} | d2e8dff03375df19c5f0230e1b3b392cb5ea6bb2 | [
"Java"
] | 1 | Java | npjava90/struts_jasper | a96f350bda4e1be554abafe358381dc78df1919e | f1f7fd3c5a4791e6bcd42bfee13ba635c9cc02c9 |
refs/heads/master | <file_sep>var http = require('http');
var fs = require('fs');
var chat = require('./js/chat');
http.createServer(function (req,res) {
switch(req.url){
case '/':
fs.readFile("index.html", function (err, data) {
if (err) throw err;
res.end(data);
});
break;
case '/subscribe':
chat.subscribe(req,res);
break;
case '/publish':
var body = '';
req
.on('readable', function () {
body +=req.read();
if (body.length > 1e4) {
res.statusCode = 413;
res.end("Your message is too big");
};
})
.on('end', function () {
try{
body = JSON.parse(body);
}catch(e){
res.statusCode = 400;
res.end("Bad request");
return;
}
chat.publish(body.message);
res.end("ok");
});
break;
default:
res.statusCode = 404;
res.end("Not FOUND");
}
}).listen(3000);<file_sep>nodejs-long-polling
===================
Chat long-polling, read POST
## Getting started
```
node server
```
Open http://localhost:3000 on your browser.
| 60b417c575b81e52a2f6181661c665fa39749fd3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | AmilKey/nodejs-long-polling | eff31eb86e2253b670e1d8384d24254db11fff3e | 4a8e5c9749772040dd2ca7de8d7b0cb36b37420e |
refs/heads/master | <repo_name>KirioXX/ba_pres_nonprint<file_sep>/config/initializers/assets.rb
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.scss, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( examples.scss )
Rails.application.config.assets.precompile += %w( examples.css )
Rails.application.config.assets.precompile += %w( examples.js )
Rails.application.config.assets.precompile += %w( custom/main.js )
Rails.application.config.assets.precompile += %w( custom/view.js )
Rails.application.config.assets.precompile += %w( custom/show.js )
Rails.application.config.assets.precompile += %w( anijs/anijs-min.js )
Rails.application.config.assets.precompile += %w( anijs/anijs-helper-dom-min.js )
Rails.application.config.assets.precompile += %w( anijs/anijs-helper-scrollreveal-min.js )
Rails.application.config.assets.precompile += %w( anijs/anijs-jquery-event-system-min.js )
Rails.application.config.assets.precompile += %w( greensock/TweenMax.min.js )
Rails.application.config.assets.precompile += %w( greensock/DrawSVGPlugin.min.js )<file_sep>/app/views/pages/index.json.jbuilder
json.array!(@pages) do |page|
json.extract! page, :id, :title, :page_type, :body, :image, :html, :number, :custom_css, :custom_js
json.url page_url(page, format: :json)
end
<file_sep>/lib/assets/javascripts/custom/view.js
/**
* Created by Ben on 10.08.2015.
* View JS
*/
var changeProduct = function(){
$('.dropdown-menu a').on('click',function(){
var url = $(this).data('url');
$.ajax({
url: url,
}
).success(function(result){
$('h1, #main-price, #shortdesc, #description, #main-img').animate({opacity:0}, 2000, function(){
$('#model-container').html(result.hero);
$('.img-loader').fadeIn();
$('h1').html(result.name);
var price = parseInt(result.price);
$('#main-price').html(price.toFixed(2));
$('#shortdesc').html(result.shortdesc);
$('#description').html(result.description);
$('#addToCart-button').data('prod', result.id)
$('#main-img').attr('src',result.mainImage_url);
}).delay(3000).animate({opacity: 1},2000, function(){
$('.img-loader').fadeOut();
});
})
})
}
$(document).ready(function(){
changeProduct();
startLoder();
});
<file_sep>/app/views/reviews/show.json.jbuilder
json.extract! @review, :id, :name, :title, :text, :score, :product_id, :created_at, :updated_at
<file_sep>/lib/assets/javascripts/examples.js
/**
* Created by Ben on 29.07.2015.
*/
//= require jquery
//= require bootstrap-sprockets<file_sep>/db/migrate/20150717141335_create_pages.rb
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :title
t.integer :page_type
t.text :body
t.string :image
t.text :html
t.integer :number
t.string :custom_css
t.string :custom_js
t.timestamps null: false
end
end
end
<file_sep>/app/models/page.rb
class Page < ActiveRecord::Base
has_attached_file :image,
:styles => {
:thumb => '100x100#',
:small => '150x150>',
:medium => '200x200>',
:large => '1500x770>'
}
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
attr_accessor :delete_image
before_validation { self.image.clear if self.delete_image == '1' }
def page_type_enum
[['HTML',0], ['Text',1],['Image',2]]
end
end
<file_sep>/lib/assets/javascripts/custom/show.js
/**
* Created by Ben on 12.08.2015.
*/
function isScrolledIntoView(elem)
{
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
var startView = function(){
$('.thumb-element').each(function(){
if($(this).hasClass('disabled')){
if(isScrolledIntoView(this)){
// the animation starts
$(this).toggleClass('fadeInUp animated disabled');
// do something when animation ends
$(this).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(e){
// trick to execute the animation again
$(e.target).removeClass('fadeInUp animated');
});
}
}
});
}
var scrollFunction = function(){
$('.thumb-element.disabled').each(function(){
if(isScrolledIntoView(this)){
// the animation starts
$(this).toggleClass('fadeInUp animated disabled');
// do something when animation ends
$(this).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(e){
// trick to execute the animation again
$(e.target).removeClass('fadeInUp animated');
});
}
});
};
var getProduct = function(url){
$('#content-main').fadeOut(2000, function(){
$('.main-loader').fadeIn();
$.ajax({
url: url,
success: function(result){
$('#content-main').html(result)
}
});
}).delay(3000).fadeIn(2000, function(){
$('.main-loader').fadeOut();
});;
}
$(document).ready(function(){
startView();
scrollFunction();
});
$(window).scroll(function(){
scrollFunction();
})<file_sep>/app/controllers/examples_controller.rb
class ExamplesController < ApplicationController
layout 'examples'
def show
@category = Category.find(params[:id])
@products = @category.products.all
end
def view
@product = Product.find(params[:id])
@reviews = @product.reviews.all
@thumb = Product.find([3,4,5,6])
respond_to do |format|
format.html { render :layout => !request.xhr? }
# other formats
end
end
def svgpage
render :layout => false
end
def cssBMO
render :layout => false
end
def json
@product = Product.find(params[:id])
render :json => @product.to_json(:methods => [:mainImage_url])
end
end
<file_sep>/db/migrate/20150717143346_change_type_of_html.rb
class ChangeTypeOfHtml < ActiveRecord::Migration
def change
change_column :pages, :html, :string
end
end
<file_sep>/app/assets/javascripts/pages.js
var loadIfram = function(){
$('.reload-button').click(function(){
var elem = $(this).parent();
var url = elem.data('url');
elem.find('iframe').attr('src',url);
});
}
$(document).ready(function(){
loadIfram();
}); | 016356814f9a1adf8a2407f35554dad3096e66f0 | [
"JavaScript",
"Ruby"
] | 11 | Ruby | KirioXX/ba_pres_nonprint | bbd6f998712eeba9a20a034e3054025dd851f67a | ea6f8d09a75b19f284de0e32ed35331056f9b4c2 |
refs/heads/master | <file_sep>__author__ = 'spousty'
import psycopg2
from bottle import route, run, get, static_file, DEBUG
import os,json
@route('/')
def index():
return static_file("index.html", root='./')
@get('/ws/zips')
def getzips():
results = []
try:
conn = psycopg2.connect(database=os.environ.get('POSTGRES_DB'), user=os.environ.get('POSTGRES_USER'),
host=os.environ.get('POSTGRES_HOST'), password=os.environ.get('POSTGRES_PASSWORD'))
except:
print("couldn't make connection" + os.environ.get('POSTGRES_HOST'))
cur = conn.cursor()
cur.execute("""select zipcode, count, ST_AsText(the_geom) from zipcodes""")
rows = cur.fetchall()
for row in rows:
result = {}
result = {'zipcode': row[0], 'count': row[1]}
coords = []
temp_coords = row[2]
lon = temp_coords[temp_coords.find('(')+ 1:temp_coords.find(' ')]
lat = temp_coords[temp_coords.find(' '):temp_coords.find(')')]
coords = [lon, lat]
result['coords'] = coords
results.append(result)
return json.dumps({'results': list(results)})
@get('/ws/airports')
def getairports():
results = []
try:
conn = psycopg2.connect(database=os.environ.get('POSTGRES_DB'), user=os.environ.get('POSTGRES_USER'),
host=os.environ.get('POSTGRES_HOST'), password=os.environ.get('POSTGRES_PASSWORD'))
except:
print(os.environ.get('POSTGRES_HOST'))
cur = conn.cursor()
cur.execute("""select name, passengers, ST_AsText(the_geom) from airports""")
rows = cur.fetchall()
for row in rows:
result = {}
result = {'name': row[0], 'passengers': row[1]}
coords = []
temp_coords = row[2]
lon = temp_coords[temp_coords.find('(')+ 1:temp_coords.find(' ')]
lat = temp_coords[temp_coords.find(' '):temp_coords.find(')')]
coords = [lon, lat]
result['coords'] = coords
results.append(result)
return json.dumps({'results': list(results)})
#This is for the parkpoints data set which may or may not be there
@get('/db')
def dbexample():
try:
conn = psycopg2.connect(database=os.environ.get('POSTGRES_DB'), user=os.environ.get('POSTGRES_USER'),
host=os.environ.get('POSTGRES_HOST'), password=os.<PASSWORD>('POSTGRES_PASSWORD'))
except:
print(os.environ.get('POSTGRES_HOST'))
cur = conn.cursor()
# cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints limit 10""")
cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints ORDER by parkid DESC LIMIT 10""")
rows = cur.fetchall()
result_string = "<h2>Here are your results: </h2>"
for row in rows:
result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"
cur.close()
conn.close()
return result_string
#For Static files
@get("/static/css/<filename:re:.*\.css>")
def css(filename):
return static_file(filename, root="static/css")
@get("/static/font/<filename:re:.*\.(eot|otf|svg|ttf|woff|woff2?)>")
def font(filename):
return static_file(filename, root="static/font")
@get("/static/img/<filename:re:.*\.(jpg|png|gif|ico|svg)>")
def img(filename):
return static_file(filename, root="static/img")
@get("/static/js/<filename:re:.*\.js>")
def js(filename):
return static_file(filename, root="static/js")
if __name__ == '__main__':
run(host='0.0.0.0', port=8080, debug=True, reloader=True)
<file_sep>FROM python:3
EXPOSE 8080
ENV BASE_DIR=/usr/src/py-zip-demo
RUN mkdir -p ${BASE_DIR}
COPY ddl ${BASE_DIR}/ddl
COPY static ${BASE_DIR}/static
COPY app.py ${BASE_DIR}/app.py
COPY index.html ${BASE_DIR}/index.html
COPY requirements.txt ${BASE_DIR}/requirements.txt
COPY LICENSE ${BASE_DIR}/LICENSE
WORKDIR ${BASE_DIR}
RUN pip install -r requirements.txt
CMD python3 app.py
<file_sep>bottle==0.12.8
psycopg2==2.6.1
| e8cc52346e9aadba88654a727b5ef4b5ddfa195f | [
"Python",
"Text",
"Dockerfile"
] | 3 | Python | fusor/py-zip-demo | d7ef8c1a71825fae8bf0e274735a4a9bdd14b04e | eac658400973ed504dcb5c24a08f47fa5f530b94 |
refs/heads/master | <file_sep>package com.example.streuobstpfad;
public class Fragen {
public String mFragen[] = {
"Which is the first planet in the Solar system",
"Which is the second planet in the Solar system",
"Which is the third planet in the Solar system",
"Which is the fourth planet in the Solar system",
"Which is the fifth planet in the Solar system",
"Which is the sixth planet in the Solar system",
"Which is the seventh planet in the Solar system",
"Which is the eighth planet in the Solar system",
"Which is the ninth planet in the Solar system"
};
private String mAntworten[][] = {
{"Merkur", "Venus", "Mars", "Saturn"},
{"Jupiter", "Venus", "Erde", "Neptun"},
{"Erde", "Jupiter", "Pluto", "Venus"},
{"Jupiter", "Saturn", "Mars", "Erde"},
{"Jupiter", "Pluto", "Merkur", "Erde"},
{"UrAnus", "Venus", "Mars", "Saturn"},
{"Saturn", "Pluto", "UrAnus", "Erde"},
{"Venus", "Neptun", "Pluto", "Mars"},
{"Merkur", "Venus", "Mars", "Pluto"},
};
private String mRichtigeAntworten[] = {"Merkur","Venus","Erde","Mars","Jupiter","Saturn","UrAnus","Neptun","Pluto"};
public String getFrage(int a){
String tfrage = mFragen[a];
return tfrage;
}
public String getAntworten1(int a) {
String tant = mAntworten[a][0];
return tant;
}
public String getAntworten2(int a) {
String tant = mAntworten[a][1];
return tant;
}
public String getAntworten3(int a) {
String tant = mAntworten[a][2];
return tant;
}
public String getAntworten4(int a) {
String tant = mAntworten[a][3];
return tant;
}
public String getRichtigeAntwort(int a){
String trant = mRichtigeAntworten[a];
return trant;
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public int punkteSpieler = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_test = findViewById(R.id.btn_test);
btn_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, BilderActivity.class);
i.putExtra("punkte",punkteSpieler);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
// return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id== R.id.Main){
Intent intent=new Intent( this,MainActivity.class);
Toast.makeText(this, "click on Main Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.ubersichtApp){
Intent intent=new Intent( this,UebersichtActivity.class);
Toast.makeText(this, "click on Main Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.BarCodeScanner){
Intent intent=new Intent( this,ScannerActivity.class);
Toast.makeText(this, "click on Scanner", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.hummel){
Intent intent=new Intent( this,HummelActivity.class);
Toast.makeText(this, "click on Main Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.settings){
Intent intent=new Intent( this,settingActivity.class);
Toast.makeText(this, "click on setting Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.search){
Intent intent=new Intent( this, searchActivity.class);
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
Toast.makeText(this, "click on Search Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.felsberg){
Intent intent=new Intent(this, SteinhaufenActivity.class);
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
Toast.makeText(this, "click on FelsBerg Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.hoch_stamm){
Intent intent=new Intent(this, HochStammActivity.class);
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
Toast.makeText(this, "click on Der Hochstamm Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.fr_brummer){
Intent intent=new Intent(this, FrBrummerActivity.class);
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
Toast.makeText(this, "click on Friedliche Brummer Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.schleiereule){
Intent intent=new Intent(this, SchleiereuleActivity.class);
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
Toast.makeText(this, "click on Die Schleiereule Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.quiz){
Intent intent=new Intent( this,QuizActivity.class);
Toast.makeText(this, "click on Das Quiz Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.puzzle){
Intent intent=new Intent( this,PuzzleActivity.class);
Toast.makeText(this, "click on Das Puzzle Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
if(id== R.id.memory){
Intent intent=new Intent( this,MemoryActivity.class);
Toast.makeText(this, "click on Das Memory Activity", Toast.LENGTH_LONG).show();
intent.putExtra("punkte",punkteSpieler);
this.startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class HummelActivity extends AppCompatActivity {
int punkteSpieler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hummel);
Intent intent = getIntent();
punkteSpieler = intent.getIntExtra("punkte",0);
TextView huTv1 = findViewById(R.id.HuTv1);
TextView huTv2 = findViewById(R.id.HuTv2);
TextView huTv3 = findViewById(R.id.HuTv3);
ImageView huIv1 = findViewById(R.id.HuIv1);
Button huBtn1 = findViewById(R.id.HuBtn1);
Button huBtn2 = findViewById(R.id.HuBtn2);
huBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openHuArtActivity();
}
});
}
public void openHuArtActivity(){
Intent intent = new Intent(this, HummelArtenActivity.class);
startActivity(intent);
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class SchleiereuleActivity extends AppCompatActivity {
int punkteSpieler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schleiereule);
Intent intent = getIntent();
punkteSpieler = intent.getIntExtra("punkte",0);
final MediaPlayer seSound = MediaPlayer.create(this, R.raw.aud_schleiereule);
TextView SeTV1 = findViewById(R.id.SeTV1);
TextView SeTV2 = findViewById(R.id.SeTV2);
TextView SeTV3 = findViewById(R.id.SeTV3);
TextView SeTV4 = findViewById(R.id.SeTV4);
ImageView seIv1 = findViewById(R.id.seIv_1);
ImageView seIv2 = findViewById(R.id.seIv_2);
ImageView seIv3 = findViewById(R.id.seIv_3);
ImageView seIv4 = findViewById(R.id.seIv_4);
Button seBtn1 = findViewById(R.id.seBtn1);
Button seBtn2 = findViewById(R.id.seBtn2);
Button seBtn3 = findViewById(R.id.seBtn3);
seBtn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
seSound.start();
}
});
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
// return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id== R.id.Main){
Intent intent=new Intent( this,MainActivity.class);
Toast.makeText(this, "click on Main Activity", Toast.LENGTH_LONG).show();
this.startActivity(intent);
return true;
}
if(id== R.id.settings){
Intent intent=new Intent( this,settingActivity.class);
Toast.makeText(this, "click on setting Activity", Toast.LENGTH_LONG).show();
this.startActivity(intent);
return true;
}
if(id== R.id.search){
Intent intent=new Intent( this, searchActivity.class);
this.startActivity(intent);
Toast.makeText(this, "click on Search Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.felsberg){
Intent intent=new Intent(this, SteinhaufenActivity.class);
this.startActivity(intent);
Toast.makeText(this, "click on FelsBerg Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.hoch_stamm){
Intent intent=new Intent(this, HochStammActivity.class);
this.startActivity(intent);
Toast.makeText(this, "click on Der Hochstamm Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.fr_brummer){
Intent intent=new Intent(this, FrBrummerActivity.class);
this.startActivity(intent);
Toast.makeText(this, "click on Friedliche Brummer Activity", Toast.LENGTH_LONG).show();
return true;
}
if(id== R.id.schleiereule){
Intent intent=new Intent(this, SchleiereuleActivity.class);
this.startActivity(intent);
Toast.makeText(this, "click on Die Schleiereule Activity", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.provider.FontsContract;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class PuzzleActivity extends AppCompatActivity {
int punkteSpieler;
private ImageView ivp1,ivp2,ivp3,ivp4,ivp5,ivp6;
public int auswahl = 1;
private int[] arr = {0,0,0,0,0,0,0};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
Intent intent = getIntent();
punkteSpieler = intent.getIntExtra("punkte",0);
ivp1 = findViewById(R.id.ivp1);
ivp2 = findViewById(R.id.ivp2);
ivp3 = findViewById(R.id.ivp3);
ivp4 = findViewById(R.id.ivp4);
ivp5 = findViewById(R.id.ivp5);
ivp6 = findViewById(R.id.ivp6);
Intent i = getIntent();
final int number = i.getIntExtra("Bildnummer", 0);
final int auswa = i.getIntExtra("numH",0);
arr[0] = 0;
arr[1] = i.getIntExtra("arr1",0);
arr[2] = i.getIntExtra("arr2",0);
arr[3] = i.getIntExtra("arr3",0);
arr[4] = i.getIntExtra("arr4",0);
arr[5] = i.getIntExtra("arr5",0);
arr[6] = i.getIntExtra("arr6",0);
// int number2 = i.getIntExtra("Bildnummer2", 0);
// int number3 = i.getIntExtra("Bildnummer3", 0);
// int number4 = i.getIntExtra("Bildnummer4", 0);
// int number5 = i.getIntExtra("Bildnummer5", 0);
// int number6 = i.getIntExtra("Bildnummer6", 0);
ivp1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 1;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 1);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
ivp2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 2;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 2);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
ivp3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 3;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 3);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
ivp4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 4;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 4);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
ivp5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 5;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 5);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
ivp6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auswahl = 6;
Intent i = new Intent(PuzzleActivity.this, BilderPuzzleActivity.class);
i.putExtra("numH", 6);
i.putExtra("arr1",arr[1]);
i.putExtra("arr2",arr[2]);
i.putExtra("arr3",arr[3]);
i.putExtra("arr4",arr[4]);
i.putExtra("arr5",arr[5]);
i.putExtra("arr6",arr[6]);
startActivityForResult(i,0);
}
});
arr[i.getIntExtra("numH",0)]= number;
if(arr[1] == 1)
{
ivp1.setImageResource(R.drawable.ic_101);
} else if (arr[1] == 2){
ivp1.setImageResource(R.drawable.ic_102);
} else if (arr[1] == 3){
ivp1.setImageResource(R.drawable.ic_103);
} else if (arr[1] == 4){
ivp1.setImageResource(R.drawable.ic_104);
} else if (arr[1] == 5){
ivp1.setImageResource(R.drawable.ic_105);
} else if (arr[1] == 6){
ivp1.setImageResource(R.drawable.ic_106);
}
if(arr[2] == 1)
{
ivp2.setImageResource(R.drawable.ic_101);
} else if (arr[2] == 2){
ivp2.setImageResource(R.drawable.ic_102);
} else if (arr[2] == 3){
ivp2.setImageResource(R.drawable.ic_103);
} else if (arr[2] == 4){
ivp2.setImageResource(R.drawable.ic_104);
} else if (arr[2] == 5){
ivp2.setImageResource(R.drawable.ic_105);
} else if (arr[2] == 6){
ivp2.setImageResource(R.drawable.ic_106);
}
if(arr[3] == 1)
{
ivp3.setImageResource(R.drawable.ic_101);
} else if (arr[3] == 2){
ivp3.setImageResource(R.drawable.ic_102);
} else if (arr[3] == 3){
ivp3.setImageResource(R.drawable.ic_103);
} else if (arr[3] == 4){
ivp3.setImageResource(R.drawable.ic_104);
} else if (arr[3] == 5){
ivp3.setImageResource(R.drawable.ic_105);
} else if (arr[3] == 6){
ivp3.setImageResource(R.drawable.ic_106);
}
if(arr[4] == 1)
{
ivp4.setImageResource(R.drawable.ic_101);
} else if (arr[4] == 2){
ivp4.setImageResource(R.drawable.ic_102);
} else if (arr[4] == 3){
ivp4.setImageResource(R.drawable.ic_103);
} else if (arr[4] == 4){
ivp4.setImageResource(R.drawable.ic_104);
} else if (arr[4] == 5){
ivp4.setImageResource(R.drawable.ic_105);
} else if (arr[4] == 6){
ivp4.setImageResource(R.drawable.ic_106);
}
if(arr[5] == 1)
{
ivp5.setImageResource(R.drawable.ic_101);
} else if (arr[5] == 2){
ivp5.setImageResource(R.drawable.ic_102);
} else if (arr[5] == 3){
ivp5.setImageResource(R.drawable.ic_103);
} else if (arr[5] == 4){
ivp5.setImageResource(R.drawable.ic_104);
} else if (arr[5] == 5){
ivp5.setImageResource(R.drawable.ic_105);
} else if (arr[5] == 6){
ivp5.setImageResource(R.drawable.ic_106);
}
if(arr[6] == 1)
{
ivp6.setImageResource(R.drawable.ic_101);
} else if (arr[6] == 2){
ivp6.setImageResource(R.drawable.ic_102);
} else if (arr[6] == 3){
ivp6.setImageResource(R.drawable.ic_103);
} else if (arr[6] == 4){
ivp6.setImageResource(R.drawable.ic_104);
} else if (arr[6] == 5){
ivp6.setImageResource(R.drawable.ic_105);
} else if (arr[6] == 6){
ivp6.setImageResource(R.drawable.ic_106);
}
check();
/*
if(i.getIntExtra("numH",0)==1)
{
if(number == 1)
{
ivp1.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp1.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp1.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp1.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp1.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp1.setImageResource(R.drawable.ic_image106);
}
}
if(i.getIntExtra("numH",0)==2)
{
if(number == 1)
{
ivp2.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp2.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp2.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp2.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp2.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp2.setImageResource(R.drawable.ic_image106);
}
}
if(i.getIntExtra("numH",0)==3)
{
if(number == 1)
{
ivp3.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp3.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp3.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp3.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp3.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp3.setImageResource(R.drawable.ic_image106);
}
}
if(i.getIntExtra("numH",0)==4)
{
if(number == 1)
{
ivp4.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp4.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp4.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp4.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp4.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp4.setImageResource(R.drawable.ic_image106);
}
}
if(i.getIntExtra("numH",0)==5)
{
if(number == 1)
{
ivp5.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp5.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp5.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp5.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp5.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp5.setImageResource(R.drawable.ic_image106);
}
}
if(i.getIntExtra("numH",0)==6)
{
if(number == 1)
{
ivp6.setImageResource(R.drawable.ic_image101);
} else if (number == 2){
ivp6.setImageResource(R.drawable.ic_image102);
} else if (number == 3){
ivp6.setImageResource(R.drawable.ic_image103);
} else if (number == 4){
ivp6.setImageResource(R.drawable.ic_image104);
} else if (number == 5){
ivp6.setImageResource(R.drawable.ic_image105);
} else if (number == 6){
ivp6.setImageResource(R.drawable.ic_image106);
}
}else {
if(number == 1)
{
ivp1.setImageResource(R.drawable.up);
} else if (number == 2){
ivp1.setImageResource(R.drawable.up);
} else if (number == 3){
ivp1.setImageResource(R.drawable.up);
} else if (number == 4){
ivp1.setImageResource(R.drawable.up);
} else if (number == 5){
ivp1.setImageResource(R.drawable.up);
} else if (number == 6){
ivp1.setImageResource(R.drawable.up);
}
}*/
}
private void check() {
if(ivp1.getDrawable().equals(R.drawable.ic_101) &&
ivp2.getDrawable().equals(R.drawable.ic_102) &&
ivp3.getDrawable().equals(R.drawable.ic_103) &&
ivp4.getDrawable().equals(R.drawable.ic_104) &&
ivp5.getDrawable().equals(R.drawable.ic_105) &&
ivp6.getDrawable().equals(R.drawable.ic_106))
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(PuzzleActivity.this);
alertDialogBuilder
.setMessage("Game Over!\n")
.setCancelable(false)
.setPositiveButton("New", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),PuzzleActivity.class);
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
arr[3] = 0;
arr[4] = 0;
arr[5] = 0;
arr[6] = 0;
startActivity(intent);
finish();
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class FlussActivity extends AppCompatActivity {
int punkteSpieler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fluss);
Intent intent = getIntent();
punkteSpieler = intent.getIntExtra("punkte",0);
}
}
<file_sep>package com.example.streuobstpfad;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class QuizActivity extends AppCompatActivity {
int punkteSpieler;
Button antwort1, antwort2, antwort3, antwort4;
TextView score, frage;
private Fragen mFragen = new Fragen();
private String mAntworten;
private int mScore = 0;
private int mFragenLaenge = mFragen.mFragen.length;
Random r;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent = getIntent();
punkteSpieler = intent.getIntExtra("punkte",0);
r = new Random();
antwort1 = (Button) findViewById(R.id.antwort1);
antwort2 = (Button) findViewById(R.id.antwort2);
antwort3 = (Button) findViewById(R.id.antwort3);
antwort4 = (Button) findViewById(R.id.antwort4);
score = (TextView) findViewById(R.id.score);
frage = (TextView) findViewById(R.id.frage);
score.setText("Score " + mScore);
updateFragen(r.nextInt(mFragenLaenge));
antwort1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(antwort1.getText() == mAntworten){
mScore++;
score.setText("Score " + mScore);
updateFragen(r.nextInt(mFragenLaenge));
} else {
gameOver();
}
}
});
antwort2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(antwort2.getText() == mAntworten){
mScore++;
score.setText("Score " + mScore);
updateFragen(r.nextInt(mFragenLaenge));
} else {
gameOver();
}
}
});
antwort3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(antwort3.getText() == mAntworten){
mScore++;
score.setText("Score " + mScore);
updateFragen(r.nextInt(mFragenLaenge));
} else {
gameOver();
}
}
});
antwort4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(antwort4.getText() == mAntworten){
mScore++;
score.setText("Score " + mScore);
updateFragen(r.nextInt(mFragenLaenge));
} else {
gameOver();
}
}
});
}
private void updateFragen(int num) {
frage.setText(mFragen.getFrage(num));
antwort1.setText(mFragen.getAntworten1(num));
antwort2.setText(mFragen.getAntworten2(num));
antwort3.setText(mFragen.getAntworten3(num));
antwort4.setText(mFragen.getAntworten4(num));
mAntworten = mFragen.getRichtigeAntwort(num);
}
private void gameOver(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(QuizActivity.this);
alertDialogBuilder
.setMessage("Game Over. Dein Score ist " + mScore + "Punkte.")
.setCancelable(false)
.setPositiveButton("New Game", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(),QuizActivity.class));
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}
| 34063cce43583b96da05e3bb83710b57b7f0701a | [
"Java"
] | 7 | Java | SteffenWei/Streuobstpfad | 46076732ba908e896a570fb2bad12127f4e71c12 | b77b4bebdb047f5901188ab3c84d6d70f09bb7b8 |
refs/heads/master | <repo_name>patrickhenrique/aula-processos<file_sep>/GerenciadorContasBancarias/src/br/edu/cesmac/bancomgr/sistema/contas/IConta.java
package br.edu.cesmac.bancomgr.sistema.contas;
import java.util.Date;
import java.util.List;
import br.edu.cesmac.bancomgr.sharedmodel.Transacao;
public interface IConta {
public int criarContaPoupanca(int numero, int senha, int diaAniversario, float taxaRendimento);
public int criarContaCorrente(int numero, int senha, float limite, float taxaJuros);
public int desativarConta(int numero);
public int ativarConta(int numero);
public float consultarSaldo(int numeroConta, int senha);
public List<Transacao> obterExtrato(int numeroConta, int senha, Date dataInicio, Date dataFim);
public List<Transacao> obterExtrato(int numeroConta, int senha);
public float sacar(int numero, int senha, float valor);
}
<file_sep>/GerenciadorContasBancarias/src/br/edu/cesmac/bancomgr/sistema/rendimento/IRendimento.java
package br.edu.cesmac.bancomgr.sistema.rendimento;
public interface IRendimento {
public void aplicarRendimento();
public void cobrarJuros();
}
| 5a798b8e2ca159bffc9b2f367d9fe60f982a1b02 | [
"Java"
] | 2 | Java | patrickhenrique/aula-processos | 9eff39c52bc16b0b371473b301ffb61a0054998c | ae514a8da31619f7b426d8294bc0421b235d9561 |
refs/heads/master | <repo_name>JPRoland/soapbox-api<file_sep>/routes/story.js
const router = require("express").Router();
const { storyController, authcontroller } = require("../controllers");
router.get(
"/stories",
authcontroller.authOptional,
storyController.getStories
);
router.get(
"/stories/feed",
authcontroller.requireAuth,
storyController.getFeedStories
);
router.get(
"/stories/:slug",
authcontroller.authOptional,
storyController.getStoryBySlug
);
router.post(
"/stories",
authcontroller.requireAuth,
storyController.createStory
);
router.put(
"/stories/:slug",
authcontroller.requireAuth,
storyController.updateStory
);
router.delete(
"/stories/:slug",
authcontroller.requireAuth,
storyController.deleteStory
);
router.post(
"/stories/:slug/comments",
authcontroller.requireAuth,
storyController.createStoryComment
);
router.get(
"/stories/:slug/comments",
authcontroller.authOptional,
storyController.getStoryComments
);
router.delete(
"/stories/:slug/comments/:id",
authcontroller.requireAuth,
storyController.deleteStoryComment
);
router.post(
"/stories/:slug/favorite",
authcontroller.requireAuth,
storyController.favoriteStory
);
router.delete(
"/stories/:slug/favorite",
authcontroller.requireAuth,
storyController.unfavoriteStory
);
module.exports = router;
<file_sep>/controllers/tag.js
const Tag = require("../models").Tag;
const getTags = async (req, res, next) => {
try {
const tags = await Tag.findAll({ attributes: ["name"] });
return res.json({ tags });
} catch (error) {
return next(error);
}
};
module.exports = { getTags };
<file_sep>/README.md
# Fabler
Fabler is social storytelling platform built with Node.js, Sequelize, and Postgres.
API Documentation: https://documenter.getpostman.com/view/5586492/RWgqVyne
# Getting Started
To run the server locally:
- Clone the repo
- `npm install` or `yarn install` to install all dependencies
- Install Postgres or other SQL database supported by Sequelize
- Create a `.env` file with the follwing variables:
```
PORT=SETME
APP_ENV=*SETME*
DB_DIALECT=*SETME*
DB_HOST=*SETME*
DB_PORT=*SETME*
DB_NAME=*SETME*
DB_USER=*SETME*
DB_PASS=*SETME*
JWT_SECRET=*SETME*
```
- `npm run dev` or `yarn dev` to start the server
<file_sep>/controllers/story.js
const { Story, User, Tag, Comment, Favorite, Genre } = require("../models");
const assignDefined = require("../helpers/assignDefined");
const getStories = async (req, res, next) => {
const { tag, author, favorited, genre, offset = 0, limit = 20 } = req.query;
try {
let tagWhere, authorWhere, favoritedWhere, genreWhere;
if (tag) {
tagWhere = { name: tag };
}
if (author) {
authorWhere = { username: author };
}
if (favorited) {
favoritedWhere = { username: favorited };
}
if (genre) {
genreWhere = { name: genre };
}
const stories = await Story.findAll({
include: [
{
model: Tag,
attributes: ["name"],
where: tagWhere,
through: { attributes: [] }
},
{
model: User,
as: "Author",
where: authorWhere
},
{
model: User,
as: "Favorited",
where: favoritedWhere,
through: { attributes: [] }
},
{
model: Genre,
attributes: ["name"],
where: genreWhere,
through: { attributes: [] }
}
],
limit,
offset,
order: [["createdAt", "DESC"]]
});
const response = [];
for (let story of stories) {
response.push(await story.buildResponse(req.user));
}
return res.json({ stories: response, storiesCount: response.length });
} catch (error) {
return next(error);
}
};
const getFeedStories = async (req, res, next) => {
const { limit = 20, offset = 0 } = req.query;
try {
const user = await User.findById(req.user.id, {
include: [
{
model: User,
as: "Followed"
}
]
});
const followedIds = user.Followed.map(f => f.id);
const stories = await Story.findAll({
where: { AuthorId: followedIds },
include: { model: User, as: "Author" },
limit,
offset
});
const response = [];
for (let story of stories) {
response.push(await story.buildResponse(req.user));
}
res.json({ stories: response, storiesCount: response.length });
} catch (error) {
return next(error);
}
};
const getStoryBySlug = async (req, res, next) => {
const { slug } = req.params;
try {
const story = await Story.findOne({
where: { slug },
include: [
{ model: Tag, attributes: ["name"], through: { attributes: [] } },
{ model: User, as: "Author" },
{ model: Genre, attributes: ["name"], through: { attributes: [] } }
]
});
let response = await story.buildResponse(req.user);
return res.json({ story: response });
} catch (error) {
return next(error);
}
};
const createStory = async (req, res, next) => {
const { story } = req.body;
try {
const user = await User.findById(req.user.id);
if (!user) {
return res.sendStatus(401);
}
let builtStory = await Story.create({
title: story.title,
body: story.body,
description: story.description
});
let tags = [];
for (let tag of story.tags) {
const tagInstance = await Tag.findCreateFind({
where: { name: tag.name.toLowerCase() }
});
tags.push(tagInstance[0]);
}
let genres = [];
for (let genre of story.genres) {
const genreInstance = await Genre.findCreateFind({
where: { name: genre.name }
});
genres.push(genreInstance[0]);
}
await builtStory.addGenres(genres);
await builtStory.addTags(tags);
await builtStory.setAuthor(user);
return res.json({ story: builtStory });
} catch (error) {
return next(error);
}
};
const updateStory = async (req, res, next) => {
const { slug } = req.params;
const updates = assignDefined({}, req.body);
try {
const story = await Story.findOne({ where: { slug } });
if (story.AuthorId !== req.user.id) {
return res.sendStatus(403);
}
await story.update(updates, { returning: true });
return res.json({ story });
} catch (error) {
return next(error);
}
};
const deleteStory = async (req, res, next) => {
const { slug } = req.params;
try {
const story = await Story.findOne({ where: { slug } });
if (story.AuthorId !== req.user.id) {
return res.sendStatus(403);
}
await story.destroy();
return res.sendStatus(204);
} catch (error) {
return next(error);
}
};
const favoriteStory = async (req, res, next) => {
const { slug } = req.params;
try {
const story = await Story.findOne({
where: { slug },
include: [{ model: User, as: "Author" }]
});
const user = await User.findById(req.user.id);
await Favorite.create({
UserId: user.id,
StoryId: story.id
});
await story.increment("favoriteCount");
let response = await story.buildResponse(req.user.id);
return res.json({ story: response });
} catch (error) {
return next(error);
}
};
const unfavoriteStory = async (req, res, next) => {
const { slug } = req.params;
try {
const story = await Story.findOne({
where: { slug },
include: [{ model: User, as: "Author" }]
});
const user = await User.findById(req.user.id);
await Favorite.destroy({
where: { UserId: user.id, StoryId: story.id }
});
await story.decrement("favoriteCount");
let response = await story.buildResponse(req.user.id);
return res.json({ story: response });
} catch (error) {
return next(error);
}
};
const createStoryComment = async (req, res, next) => {
const { slug } = req.params;
const { comment } = req.body;
try {
const story = await Story.findOne({ where: { slug } });
const createdComment = await Comment.create({
body: comment.body,
UserId: req.user.id,
StoryId: story.id
});
await createdComment.reload({ include: "User" });
const responseBody = await createdComment.buildResponse(req.user);
return res.json({ comment: responseBody });
} catch (error) {
return next(error);
}
};
const getStoryComments = async (req, res, next) => {
const { slug } = req.params;
try {
const story = await Story.findOne({
where: { slug }
});
const comments = await story.getComments({ include: "User" });
const response = [];
for (let comment of comments) {
response.push(await comment.buildResponse(req.user));
}
return res.json({ comments: response });
} catch (error) {
return next(error);
}
};
const deleteStoryComment = async (req, res, next) => {
const { id } = req.params;
try {
const comment = await Comment.findById(id);
if (comment.UserId !== req.user.id) {
return res.sendStatus(403);
}
await comment.destroy();
return res.sendStatus(204);
} catch (error) {
return next(error);
}
};
module.exports = {
getStories,
getStoryBySlug,
getStoryComments,
createStory,
updateStory,
deleteStory,
createStoryComment,
deleteStoryComment,
favoriteStory,
unfavoriteStory,
getFeedStories
};
<file_sep>/routes/profile.js
const router = require("express").Router();
const { profileController, authcontroller } = require("../controllers");
router.get(
"/profiles/:username",
authcontroller.authOptional,
profileController.getProfile
);
router.post(
"/profiles/:username/follow",
authcontroller.requireAuth,
profileController.follow
);
router.delete(
"/profiles/:username/follow",
authcontroller.requireAuth,
profileController.unfollow
);
module.exports = router;
<file_sep>/models/genre.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var Genre = sequelize.define(
"Genre",
{
name: DataTypes.STRING
},
{}
);
Genre.associate = function(models) {
Genre.belongsToMany(models.Story, { through: "StoryGenre" });
};
return Genre;
};
<file_sep>/routes/user.js
const router = require("express").Router();
const { userController, authcontroller } = require("../controllers");
router.get("/user", authcontroller.requireAuth, userController.getUser);
router.put("/user", authcontroller.requireAuth, userController.updateUser);
router.post("/user", userController.createUser);
router.post("/user/login", authcontroller.requireSignIn, authcontroller.signIn);
module.exports = router;
<file_sep>/services/passport.js
const passport = require("passport");
const LocalStrategy = require("passport-local");
const JwtStrategy = require("passport-jwt").Strategy;
const AnonymousStrategy = require("passport-anonymous").Strategy;
const { ExtractJwt } = require("passport-jwt");
const { User } = require("../models");
const { jwt_secret } = require("../config/config");
const localOptions = {
usernameField: "email"
};
const localLogin = new LocalStrategy(
localOptions,
async (email, password, done) => {
try {
const user = await User.findOne({
where: { email: email },
attributes: { exclude: ["password"] }
});
if (!user) return done(null, false);
const isMatch = user.comparePassword(password);
if (!isMatch) return done(null, false);
return done(null, user.get());
} catch (error) {
return done(error);
}
}
);
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: jwt_secret
};
const jwtLogin = new JwtStrategy(jwtOptions, async (payload, done) => {
try {
const user = await User.findById(payload.sub, {
attributes: { exclude: ["password"] }
});
if (!user) return done(null, false);
return done(null, user.get());
} catch (error) {
return done(error);
}
});
passport.use(new AnonymousStrategy());
passport.use(jwtLogin);
passport.use(localLogin);
module.exports = {
requireAuth: passport.authenticate("jwt", { session: false }),
requireSignIn: passport.authenticate("local", { session: false }),
authOptional: passport.authenticate(["jwt", "anonymous"], { session: false })
};
<file_sep>/controllers/profile.js
const User = require("../models").User;
const getProfile = async (req, res, next) => {
const { username } = req.params;
try {
const profile = await User.findOne({
where: { username }
});
const following = req.user.id
? await profile.hasFollower(req.user.id)
: false;
return res.json({
profile: {
username: profile.username,
bio: profile.bio,
image: profile.image,
following
}
});
} catch (error) {
return next(error);
}
};
const follow = async (req, res, next) => {
const { username } = req.params;
try {
const userToFollow = await User.findOne({ where: { username } });
userToFollow.addFollower(req.user.id);
const follower = await User.findById(req.user.id);
follower.addFollowed(userToFollow);
return res.json({
profile: {
username: userToFollow.username,
bio: userToFollow.bio,
image: userToFollow.image,
following: true
}
});
} catch (error) {
return next(error);
}
};
const unfollow = async (req, res, next) => {
const { username } = req.params;
try {
const user = await User.findById(req.user.id);
const followedUser = await User.findOne({ where: { username } });
user.removeFollowed(followedUser);
return res.json({
profile: {
username: followedUser.username,
bio: followedUser.bio,
image: followedUser.image,
following: false
}
});
} catch (error) {
return next(error);
}
};
module.exports = { getProfile, follow, unfollow };
<file_sep>/controllers/index.js
module.exports = {
userController: require("./user"),
storyController: require("./story"),
tagController: require("./tag"),
profileController: require("./profile"),
authcontroller: require("./auth"),
genreController: require("./genre")
};
<file_sep>/controllers/user.js
const User = require("../models").User;
const assignDefined = require("../helpers/assignDefined");
const createUser = async (req, res, next) => {
const { email, password, username } = req.body;
try {
const user = await User.create({ email, password, username });
return res.json({ created: true });
} catch (error) {
next(error);
}
};
const updateUser = async (req, res, next) => {
const updatedFields = assignDefined({}, req.body);
try {
const user = User.update(updatedFields, {
where: { id: req.user.id },
returning: true
});
return res.json({ user });
} catch (error) {
next(error);
}
};
const getUser = async (req, res, next) => {
try {
const user = await User.findById(req.user.id);
return res.json({ user });
} catch (error) {
next(error);
}
};
module.exports = { createUser, updateUser, getUser };
<file_sep>/helpers/token.js
const jwt = require("jsonwebtoken");
const moment = require("moment");
const { jwt_secret } = require("../config/config");
module.exports = user => {
return jwt.sign(
{
sub: user.id,
name: user.username,
iat: moment().unix(),
exp: moment()
.add(1, "hour")
.unix()
},
jwt_secret
);
};
<file_sep>/bin/www
#!/usr/bin/env node
const app = require('../app');
const debug = require('debug')('soapbox-api');
const http = require('http');
const CONFIG = require('../config/config');
const models = require('../models');
const port = normalizePort(CONFIG.port || '3001');
app.set('port', port);
const server = http.createServer(app);
if(CONFIG.app_env === 'dev') {
models.sequelize.sync().then(() => {
server.listen(port, () => {
debug(`Server listening on port ${port}...`);
});
server.on('error', makeErrorHandler(port));
server.on('listening', makeListeningHandler(server));
});
}
function normalizePort(val) {
const port = parseInt(val, 10);
return isNaN(port) ? val : port >= 0 ? port : false;
}
function makeErrorHandler(port) {
return (err) => {
if(err.syscall !== 'listen') {
throw err;
}
const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
switch(err.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw err;
}
}
}
function makeListeningHandler(server) {
return () => {
const addr = server.address();
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}...`);
}
}<file_sep>/helpers/assignDefined.js
module.exports = function(target, ...sources) {
sources.forEach(source => {
Object.keys(source).forEach(key => {
const val = source[key];
if (val !== undefined) {
target[key] = val;
}
});
});
return target;
};
<file_sep>/config/db.js
require("dotenv").config();
module.exports = {
development: {
username: process.env.DB_USER,
password: <PASSWORD>,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DIALECT,
port: process.env.DB_PORT
},
test: {
username: process.env.TESTDB_USER,
password: <PASSWORD>,
database: process.env.TESTDB_NAME,
host: process.env.TESTDB_HOST,
dialect: process.env.TESTDB_DIALECT,
port: process.env.TESTDB_PORT
},
production: {
username: process.env.PROD_DB_USERNAME,
password: <PASSWORD>,
database: process.env.PROD_DB_NAME,
host: process.env.PROD_DB_HOSTNAME,
dialect: process.env.DB_DIALECT,
port: process.env.DB_PORT
}
};
<file_sep>/controllers/genre.js
const Genre = require("../models").Genre;
const getGenres = async (req, res, next) => {
try {
const genres = await Genre.findAll({ attributes: ["name"] });
return res.json({ genres });
} catch (error) {
return next(error);
}
};
module.exports = { getGenres };
<file_sep>/models/comment.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var Comment = sequelize.define(
"Comment",
{
body: DataTypes.TEXT
},
{}
);
Comment.prototype.buildResponse = async function(user) {
const following = user ? await this.User.hasFollower(user.id) : false;
return {
body: this.body,
id: this.id,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: {
username: this.User.username,
bio: this.User.bio,
image: this.User.image,
following
}
};
};
Comment.associate = function(models) {
Comment.belongsTo(models.User);
Comment.belongsTo(models.Story);
};
return Comment;
};
<file_sep>/models/favorite.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var Favorite = sequelize.define(
"Favorite",
{
UserId: DataTypes.INTEGER,
StoryId: DataTypes.INTEGER
},
{}
);
return Favorite;
};
<file_sep>/config/config.js
require("dotenv").config();
const CONFIG = {};
CONFIG.port = process.env.PORT || 3001;
CONFIG.app_env = process.env.APP_ENV;
CONFIG.jwt_secret = process.env.JWT_SECRET;
module.exports = CONFIG;
| 3a53f1a1db8c6bc8afac0dedb62e0f290ac75ce6 | [
"JavaScript",
"Markdown"
] | 19 | JavaScript | JPRoland/soapbox-api | 5a4aad6b1370438de8b765701bea710168e87815 | 4a4a305df7cd3b13bb78b5e5e662e5457cf8982a |
refs/heads/master | <file_sep>#!/usr/bin/python
#-*- coding:utf-8 -*-
import requests
import re as R
from bs4 import BeautifulSoup
import json
import sys
import time
import MySQLdb
from .database import SinaDB
# # Set Default Encode
# reload(sys)
# sys.setdefaultencoding('utf-8')
HEADERS = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Cookie':'_T_WM=17697dedf066ddd5401f30f0bf9288ac; SCF=AsZPw5rkbPDnnKWKR1i3EMxVD2eXvWt_SHHKeyYZnOVHTVZwtw0PkcdtskgwGDG80x__hwiS-NVVZBNSsY-qMHc.; SUB=_2A256lwaqDeTxGeRN6FMW9C7PyDmIHXVWe6rirDV6PUJbkdBeLVLukW1gxb10yJZVq7ECwH1xdsHzhTZKUg..; SUHB=0A0IMYg-F0CP0j; SSOLoginState=1469282042; gsid_CTandWM=4uy8CpOz5VnL3buGYpKfK9MAI5p; M_WEIBOCN_PARAMS=uicode%3D20000174',
'Host':'m.weibo.cn',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
}
# Get user information, Return Dict
def getInformation(uid, headers=HEADERS):
url = "http://m.weibo.cn/users/%d" % int(uid)
reponse = requests.get(url, headers=headers)
reponse.close()
content = BeautifulSoup(reponse.content.replace("\\", '').replace("rn", ""), "html.parser")
content = content.find_all('div', 'item-info-page')
info = {}
for v in content:
key = str(v.find('span'))[6:-7]
value = str(v.find('p'))[3:-4]
if key == '备注':
continue
elif key == '勋章':
continue
elif key[-12:] == '微博认证':
key = key[-12:]
info[key] = value.decode('utf-8')
info['UID'] = int(uid)
return info
# Get User Folloer List, Return List
def getFollowersList(uid, headers=HEADERS):
url = 'http://m.weibo.cn/page/json?containerid=100505%d_-_FOLLOWERS' % uid
rep = requests.get(url)
jsonData = json.loads(rep.content)
max_page = jsonData['cards'][0]['maxPage']
follow_list = []
for page in range(1, max_page+1):
page_url = 'http://m.weibo.cn/page/json?containerid=100505%d_-_FOLLOWERS&page=%d' % (uid, page)
reponse = requests.get(page_url)
jsonData = json.loads(reponse.content)
for user in jsonData['cards'][0]['card_group']:
follow_list.append(int(user['user']['id']))
time.sleep(1)
return follow_list
# Get User Fans Total, Return Int
def getUserFans(uid, headers=HEADERS):
while True:
try:
url = "http://m.weibo.cn/page/card?itemid=100505%d_-_WEIBO_INDEX_PROFILE_APPS&callback=_1467532491343_4&retcode=6102" % uid
reponse = requests.get(url)
reponse.close()
content = reponse.content.replace('\\', '')
data = json.loads(content[17:-1])
fans = data['apps'][3]['count'].split('u')
if len(fans) > 1:
if fans[1] == '4ebf':
totalFans = fans[0] + '00000000'
return int(totalFans)
elif fans[1] == '4e07':
totalFans = fans[0] + '0000'
return int(totalFans)
else:
return int(fans[0])
except:
time.sleep(10)
continue
# Get User Image Links, Return List
def getImageLinks(uid, headers=HEADERS):
# while True:
# try:
imgLinks = []
content = ''
url = "http://m.weibo.cn/page/json?containerid=103003index%d_-_photo_all_l&page=1&retcode=6102" % (uid)
reponse = requests.get(url, headers=headers)
reponse.close()
if reponse:
content = reponse.content.replace('\\', '')
data = json.loads(content)
if data['cards'][0]['mod_type'] == 'mod/empty':
return None
try:
total_page = int(data['cards'][0]['maxPage'])
except:
total_page = 1
print('[*]Total Page:', total_page)
test = 0
test2 = total_page / 10
for page in range(1, total_page + 1):
print('[*]Processing Page:', page)
if page >= 10:
if page % test2 == 0 and page >= test2:
test += 10
print("[*]" + str(test) + "%")
index = 1
while True:
print('[*]The', index)
try:
url = "http://m.weibo.cn/page/json?containerid=103003index%d_-_photo_all_l&page=%d&retcode=6102" % (uid, page)
reponse = requests.get(url, headers=headers)
content = reponse.content.replace('\\', '')
data = json.loads(content)
if data['cards'][0]['mod_type'] == 'mod/empty':
break
for src in data['cards'][0]['card_group'][0]['pics']:
while True:
try:
link = src['pic_ori'].replace('large', 'thumb300')
print('[*]Get Link', link)
imgLinks.append(link) # Large Type Picture is too Big
break
except:
continue
time.sleep(8) # Set timeout, Prevent the account to be disabled
break
except:
index += 1
time.sleep(8)
if index == 6:
print('[*]Ignore Page', page)
break
continue
return imgLinks
# except:
# continue
# Save Image To Database
def saveImageLink(uid, imgLinks):
print('[*]Processing User', uid)
if imgLinks == None:
return None
index = 1
dbConnection = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', db='sina_spider', charset='utf8')
cursor = dbConnection.cursor()
cursor.execute("SET NAMES utf8")
cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
dbConnection.commit()
for imgLink in imgLinks:
print('[*]The', index)
insert_data = []
insert_data.append(str(uid))
insert_data.append(imgLink)
cursor.execute('INSERT INTO user_img(uid, img_src) values(%s, %s)', insert_data)
dbConnection.commit()
print('[*]Processed')
print( cursor.close())
dbConnection.close()
# Get User Icon
def getUserIcon(uid):
url = 'http://m.weibo.cn/u/%d' % uid
rep = requests.get(url)
content = rep.content.replace('\\', '')
# print(content)
content = content.split(';')[2]
pattern = '"profile_image_url":"(.*)","id"'
result = R.findall(pattern, content)[0]
pattern2 = 'crop.\d*\.\d*\.\d*\.\d*\.\d*'
result2 = R.findall(pattern2, result)
icon = result.replace(result2[0], 'thumb300')
return icon
# Save User info
def saveUser(uid):
print('[*]Processing User', uid, '...')
data = getInformation(uid)
time.sleep(8)
print('[*]Get info completed')
fans = getUserFans(uid)
data['粉丝'] = fans
time.sleep(8)
print('[*]Get fans completed')
dbConnection = MySQLdb.connect(host='localhost', user='root',passwd='<PASSWORD>', db='sina_spider', charset='utf8')
insert_data = []
insert_data.append(str(uid))
insert_data.append(data['性别'])
insert_data.append(data['昵称'])
insert_data.append(str(fans))
insert_data.append(str(data))
insert_data.append(getUserIcon(uid))
cursor = dbConnection.cursor()
cursor.execute("SET NAMES utf8")
cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
cursor.execute('INSERT INTO user_detail(uid, sex, uname, fans, detail, icon) values(%s, %s, %s, %s, %s, %s)', insert_data)
dbConnection.commit()
cursor.close()
dbConnection.close()
print('[*]Processed')
print()
if __name__ == '__main__':
# follow_list = getFollowersList(1826792401)
#
# for i in range(223, len(follow_list)):
# print('[*]The', i)
# saveUser(i)
myDb = SinaDB()
userList = myDb.getAllUserUid()
for uid in userList:
uid = int(uid[0])
print('[*]Processing', uid)
imageLinks = getImageLinks(uid)
saveImageLink(uid, imageLinks)
<file_sep>CREATE DATABASE sina_spider;
USE sina_spider;
CREATE TABLE user_img (
id INT PRIMARY KEY AUTO_INCREMENT,
uid VARCHAR(16),
img_src VARCHAR(255)
) CHARSET=UTF8;
CREATE TABLE user_detail (
id INT PRIMARY KEY AUTO_INCREMENT,
uid VARCHAR(16),
sex VARCHAR(8),
uname VARCHAR(255),
fans VARCHAR(16),
icon VARCHAR(255),
detail text
) CHARSET=UTF8;
<file_sep>#!/usr/bin/python
# coding=utf-8
import pymysql as MySQLdb
class SinaDB():
dbConn = ''
cursor = ''
def __init__(self):
self.dbConn = MySQLdb.connect(host='localhost', user='root', passwd="", db='sina_spider', charset="utf8")
self.cursor = self.dbConn.cursor()
self.cursor.execute("SET NAMES utf8")
self.cursor.execute("SET CHARACTER_SET_CLIENT=utf8")
self.cursor.execute("SET CHARACTER_SET_RESULTS=utf8")
def getUserDetail(self, uid):
query = "SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s" % uid
self.cursor.execute(query)
data = self.cursor.fetchall()
return data
def getUserInfo(self, condition):
if type(condition) != str:
condition = str(condition)
condition = "%" + condition + "%"
query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uname LIKE "%s" OR fans LIKE "%s" OR uid LIKE "%s" OR icon LIKE "%s"' % (condition, condition, condition, condition)
self.cursor.execute(query)
result = self.cursor.fetchall()
if result != ():
return result
else:
return None
def getAllGirlInfo(self, page, limit):
page = page - 1
page = page * limit
query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \'女\' LIMIT %d, %d' % (page, limit)
self.cursor.execute(query)
result = self.cursor.fetchall()
rows = self.cursor.execute('SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \'女\'')
if rows % limit > 0:
rows = rows / limit + 1
else:
rows = rows / limit
if result != ():
return (result, rows)
else:
return None
def getAllBoyInfo(self, page, limit):
page = page - 1
page = page * limit
query = 'SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \'男\' LIMIT %d, %d' % (page, limit)
self.cursor.execute(query)
result = self.cursor.fetchall()
rows = self.cursor.execute('SELECT uname, sex, fans, uid, icon FROM user_detail WHERE sex = \'男\'')
if rows % limit > 0:
rows = rows / limit + 1
else:
rows = rows / limit
if result != ():
return (result, rows)
else:
return None
def getUserImageLinks(self, uid, page, limit):
page = page - 1
page = page * limit
query = 'SELECT img_src FROM user_img WHERE uid = %s LIMIT %d, %d' % (uid, page, limit)
self.cursor.execute(query)
result = self.cursor.fetchall()
query = 'SELECT img_src FROM user_img WHERE uid = %s' % uid
rows = self.cursor.execute(query)
if rows % limit > 0:
rows = rows / limit + 1
else:
rows = rows / limit
if result != ():
return (result, rows)
else:
return None
def getColumnsNames(self):
columns = [index[0] for index in self.cursor.description]
return columns
def isHasImg(self, uid):
query = 'SELECT * FROM user_img WHERE uid = %s' % uid
self.cursor.execute(query)
result = self.cursor.fetchall()
if result != ():
return 1
else:
return 0
def getAllUserUid(self):
query = 'SELECT uid FROM user_detail WHERE uid != ALL (SELECT uid FROM user_img GROUP BY uid)'
self.cursor.execute(query)
result = self.cursor.fetchall()
if result != ():
return result
else:
return None
@property
def getDataAnalysis(self):
query = "SELECT count(uid) FROM user_detail"
self.cursor.execute(query)
all_users_count = self.cursor.fetchall()[0][0]
query = "SELECT count(id) FROM user_img"
self.cursor.execute(query)
all_imgs = self.cursor.fetchone()[0]
query = "SELECT count(uid) FROM user_detail WHERE sex = '男'"
self.cursor.execute(query)
male_users_count = self.cursor.fetchall()[0][0]
query = "SELECT count(uid) FROM user_detail WHERE sex = '女'"
self.cursor.execute(query)
female_users_count = self.cursor.fetchall()[0][0]
query = "SELECT uname, sex, fans, uid, icon FROM user_detail ORDER BY CAST(fans AS UNSIGNED) DESC"
self.cursor.execute(query)
greater_fans_user_info = self.cursor.fetchone()
query = "SELECT uname, sex, fans, uid, icon FROM user_detail ORDER BY CAST(fans AS UNSIGNED)"
self.cursor.execute(query)
smaller_fans_user_info = self.cursor.fetchone()
query = "SELECT count(uid) AS a, uid FROM user_img GROUP BY uid ORDER BY a DESC"
self.cursor.execute(query)
greater_send_img_user = self.cursor.fetchone()
query = "SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s" % greater_send_img_user[1]
self.cursor.execute(query)
greater_send_img_user_info = self.cursor.fetchone()
query = "SELECT count(uid) AS a, uid FROM user_img GROUP BY uid ORDER BY a"
self.cursor.execute(query)
smaller_send_img_user = self.cursor.fetchone()
query = "SELECT uname, sex, fans, uid, icon FROM user_detail WHERE uid = %s" % smaller_send_img_user[1]
self.cursor.execute(query)
smaller_send_img_user_info = self.cursor.fetchone()
return {
'all':all_users_count,
'all_imgs':all_imgs,
'male':male_users_count,
'female':female_users_count,
'greater_fans_user_info':greater_fans_user_info,
'smaller_fans_user_info':smaller_fans_user_info,
'greater_send_img':greater_send_img_user[0],
'smaller_send_img':smaller_send_img_user[0],
'greater_send_img_user_info':greater_send_img_user_info,
'smaller_send_img_user_info':smaller_send_img_user_info,
}
<file_sep>#!/usr/bin/env python
# coding=utf-8
from flask import Flask, render_template, request, send_file
from libs.database import SinaDB
from libs.Core_lib import getFollowersList, getUserFans, getImageLinks, getInformation, saveUser, saveImageLink
import sys
# reload(sys)
# sys.setdefaultencoding("utf-8")
myDB = SinaDB()
WebAPP = Flask(__name__)
def getData(uid):
saveUser(uid)
# imageLinks = getImageLinks(uid)
# saveImageLink(uid, imageLinks)
@WebAPP.route('/', methods=['GET', 'POST'])
def index():
# user_info = myDB.getAllGirlInfo()
# columns = ['Name', 'Sex', 'Fans', 'ID']
return render_template('Views/index.html')
@WebAPP.route('/search.html', methods=['GET', 'POST'])
def filter_show():
condition = request.args.get("condition")
if condition != None:
user_info = myDB.getUserInfo(condition)
final_info = []
for i in range(0, len(user_info)):
final_info.append(user_info[i] + ( myDB.isHasImg( int(user_info[i][3]) ), ))
columns = ['Name', 'Sex', 'Fans', 'ID']
return render_template('Views/search.html', user_info=final_info, columns=columns)
else:
return render_template('Views/search.html')
@WebAPP.route('/showGirl.html', methods=['GET', 'POST'])
def show_girl():
page = 1
limit = 16
if request.args.get("limit") != None:
limit = int (request.args.get("limit"))
if request.args.get("page") != None:
page = int(request.args.get("page"))
if page < 0:
page = 0
data = myDB.getAllGirlInfo(page, limit)
user_info = data[0]
total_page = int(data[1])
final_info = []
for i in range(0, len(user_info)):
final_info.append(user_info[i] + ( myDB.isHasImg( int(user_info[i][3]) ), ))
columns = ['Name', 'Sex', 'Fans', 'ID']
return render_template('Views/show.html', user_info=final_info, columns=columns, current_page=page, total_page=total_page, limit=limit)
@WebAPP.route('/showBoy.html', methods=['GET', 'POST'])
def show_boy():
page = 1
limit = 16
if request.args.get("limit") != None:
limit = int (request.args.get("limit"))
if request.args.get("page") != None:
page = int(request.args.get("page"))
if page < 0:
page = 0
data = myDB.getAllBoyInfo(page, limit)
user_info = data[0]
total_page = int(data[1])
final_info = []
for i in range(0, len(user_info)):
final_info.append(user_info[i] + ( myDB.isHasImg( int(user_info[i][3]) ), ))
columns = ['Name', 'Sex', 'Fans', 'ID']
return render_template('Views/show.html', user_info=final_info, columns=columns, current_page=page, total_page=total_page, limit=limit)
@WebAPP.route('/show_img', methods=['GET'])
def show_img():
page = 1
limit = 25
if request.args.get("limit") != None:
limit = int (request.args.get("limit"))
if request.args.get("page") != None:
page = int(request.args.get("page"))
uid = request.args.get('uid')
data = myDB.getUserImageLinks(uid, page, limit)
imgLinks = data[0]
total_page = data[1]
details = myDB.getUserDetail(uid)
columns = ['Name', 'Sex', 'Fans', 'ID']
return render_template('Views/show_img.html', imgLinks=imgLinks, current_page=page, total_page=total_page, limit=limit, uid=uid, details=details, columns=columns)
@WebAPP.route('/getInfo', methods=['GET'])
def getInfo():
if request.args.get('uid') != None:
uid = int(uid)
getData(uid)
return render_template('Views/getInfo.html', flag='Success')
else:
return render_template('Views/getInfo.html')
@WebAPP.route('/task_manager', methods=['GET', 'POST'])
def task_manager():
return render_template("Views/task_manager.html")
@WebAPP.route('/data_analysis', methods=['GET', 'POST'])
def data_analysis():
datas = myDB.getDataAnalysis
columns = ['Name', 'Sex', 'Fans', 'ID']
datas['greater_fans_user_info'] = ( datas['greater_fans_user_info'] + (myDB.isHasImg(datas['greater_fans_user_info'][3]), ))
datas['greater_send_img_user_info'] = ( datas['greater_send_img_user_info'] + (myDB.isHasImg(datas['greater_send_img_user_info'][3]), ))
datas['smaller_fans_user_info'] = ( datas['smaller_fans_user_info'] + (myDB.isHasImg(datas['smaller_fans_user_info'][3]), ))
datas['smaller_send_img_user_info'] = ( datas['smaller_send_img_user_info'] + (myDB.isHasImg(datas['smaller_send_img_user_info'][3]), ))
greater = []
for i in range(0, len(datas['greater_fans_user_info'])):
greater.append(datas['greater_fans_user_info'][i])
datas['greater_fans_user_info'] = greater
if datas['greater_fans_user_info'][2][-8:] == '00000000':
datas['greater_fans_user_info'][2] = datas['greater_fans_user_info'][2][0:-8] + "亿"
elif datas['greater_fans_user_info'][2][-4:] == '0000':
datas['greater_fans_user_info'][2] = datas['greater_fans_user_info'][2][0:-4] + "万"
greater = []
for i in range(0, len(datas['greater_send_img_user_info'])):
greater.append(datas['greater_send_img_user_info'][i])
datas['greater_send_img_user_info'] = greater
if datas['greater_send_img_user_info'][2][-8:] == '00000000':
datas['greater_send_img_user_info'][2] = datas['greater_send_img_user_info'][2][0:-8] + "亿"
elif datas['greater_send_img_user_info'][2][-4:] == '0000':
datas['greater_send_img_user_info'][2] = datas['greater_send_img_user_info'][2][0:-4] + "万"
smaller = []
for i in range(0, len(datas['smaller_fans_user_info'])):
smaller.append(datas['smaller_fans_user_info'][i])
datas['smaller_fans_user_info'] = smaller
if datas['smaller_fans_user_info'][2][-8:] == '00000000':
datas['smaller_fans_user_info'][2] = datas['smaller_fans_user_info'][2][0:-8] + "亿"
elif datas['smaller_fans_user_info'][2][-4:] == '0000':
datas['smaller_fans_user_info'][2] = datas['smaller_fans_user_info'][2][0:-4] + "万"
smaller = []
for i in range(0, len(datas['smaller_send_img_user_info'])):
smaller.append(datas['smaller_send_img_user_info'][i])
datas['smaller_send_img_user_info'] = smaller
if datas['smaller_send_img_user_info'][2][-8:] == '00000000':
datas['smaller_send_img_user_info'][2] = datas['smaller_send_img_user_info'][2][0:-8] + "亿"
elif datas['smaller_send_img_user_info'][2][-4:] == '0000':
datas['smaller_send_img_user_info'][2] = datas['smaller_send_img_user_info'][2][0:-4] + "万"
return render_template("Views/data_analysis.html", datas=datas, columns=columns)
@WebAPP.route('/setting', methods=['GET', 'POST'])
def setting():
return render_template("Views/setting.html")
WebAPP.debug = True
WebAPP.run(host="0.0.0.0")
| 397627956d0fca68f766286deab38b38c63d3b6b | [
"SQL",
"Python"
] | 4 | Python | c0hb1rd/Final_Sina_Spider | 299d1423f505cb509d972aaa212ea5a1994583b6 | e3dd0da7b0c4571b103aeb57e7fdb76291ef32ad |
refs/heads/master | <file_sep>//
// ViewDiseaseViewController.swift
// BloodBankApp
//
// Created by <NAME> on 3/9/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ViewDiseaseViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var disease = [String]()
var isCurrentUserComing = false
var user:User?
// {
// didSet {
// navigationItem.title = ("\(user!.firstName)'s Disease")
// }
// }
@IBOutlet weak var addBtn: UIBarButtonItem!
@IBOutlet weak var viewDiseaseTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fetchDiseases()
viewDiseaseTableView.delegate = self
viewDiseaseTableView.dataSource = self
if isCurrentUserComing == true {
navigationItem.title = "My Diseases"
addBtn.isEnabled = true
} else {
navigationItem.title = ("\(user!.firstName)'s Disease")
addBtn.isEnabled = false
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchDiseases()
}
func fetchDiseases () {
ServerCommunication.sharedDelegate.fetchUserDiseases(userId:user!.userId) { (status, message, disease) in
if status {
self.disease = disease!
print (disease)
self.viewDiseaseTableView.reloadData()
} else {
// self.disease.removeAll()
self.showAlert(controller: self, title: "Found Nil", message: "User Have Not Added Any Disease") { (Ok) in
self.navigationController?.popViewController(animated: true)
}
print ("Unable To Get Any Diseases")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return disease.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "viewDiseasesTableViewCell") as! ViewDiseaseTableViewCell
if disease.isEmpty{
self.showAlert(controller: self, title: "Found Nil", message: "User Have Not Added Any Disease") { (Ok) in
self.navigationController?.popViewController(animated: true)
return
}
}else{
//let cell = tableView.dequeueReusableCell(withIdentifier: "viewDiseasesTableViewCell") as! ViewDiseaseTableViewCell
cell.disease.text = disease[indexPath.row]
}
return cell
}
func showAlert(controller:UIViewController,title:String,message:String,completion:@escaping(_ okBtnPressed:Bool)->Void){
let alerController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default) { (alertAction) in
// ok button press
completion(true)
}
alerController.addAction(okAction)
controller.present(alerController, animated: true)
}
}
<file_sep>//
// ViewDiseaseTableViewCell.swift
// BloodBankApp
//
// Created by <NAME> on 3/9/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ViewDiseaseTableViewCell: UITableViewCell {
@IBOutlet weak var disease: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
disease.isEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// Disease.swift
// TableViewANdJsonParsing
//
// Created by <NAME> on 1/31/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct Disease: Decodable,Hashable{
var disease: String
}
<file_sep>//
// ForgotPasswordViewController.swift
// BloodBankApp
//
// Created by <NAME> on 3/4/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class ForgotPasswordViewController: UIViewController {
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var retrievePassBtnOut: UIButton!
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setUpElements()
}
@IBAction func retreivePasswordBtn(_ sender: Any) {
if emailAddress.text?.isEmpty == true{
errorLabel.alpha = 1
errorLabel.text = "Please enter your email"
}else{
Auth.auth().sendPasswordReset(withEmail: emailAddress.text!) { (error) in
if let error = error {
self.errorLabel.alpha = 1
self.errorLabel.text = error.localizedDescription
}else{
self.emailAddress.isEnabled = false
self.showAlert(controller: self, title: "Email Sent", message: "Password recovery email is sent to your Email Address") { (ok) in
self.navigationController?.popViewController(animated: true)
}
}
}
}
}
func setUpElements (){
errorLabel.alpha = 0
Utilities.styleTextField(emailAddress)
Utilities.styleFilledButton(retrievePassBtnOut)
}
func showAlert(controller:UIViewController,title:String,message:String,completion:@escaping(_ okBtnPressed:Bool)->Void){
let alerController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default) { (alertAction) in
// ok button press
completion(true)
}
alerController.addAction(okAction)
controller.present(alerController, animated: true)
}
}
<file_sep>//
// DonarsData.swift
// BloodBankApp
//
// Created by <NAME> on 1/14/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct Donars {
var firstName: String
var bloodGroup:String
var userId:String
var imageUrl:String
}
<file_sep># BloodBank
The idea is to connect blood donor and blood receiver through mobile app. It has login/Signup feature implemented through
firebase authentication, the user can see the list of matching donors respective to his/her blood group, can add custom
request of any blood group, can interact with the respective person through live chat (using real time firebase),
and can manage his/her profile.
| bb6e359fdde355d085df4e0587f30ce2896731f5 | [
"Swift",
"Markdown"
] | 6 | Swift | Nayyerali/BloodBank | bfc0c5a7e4eee71830ce5dadee8bf970d3343ab7 | 7a72acae999c31703f7836550e641667c6f831f2 |
refs/heads/master | <file_sep>var excelbuilder = require('msexcel-builder');
var XmlWriter = require('./XMLWriter');
module.exports = function(options) {
var xmlWriter = new XmlWriter(excelbuilder, options);
return function(page, spider, next) {
if(page.data && page.valid) {
}
setImmediate(next);
}
}
<file_sep>var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var mrspiderExcel = require('..');
var XMLWriter = require('../XMLWriter');
describe('mrspider excel', function () {
var validPage;
var validSpider;
var validOptions;
beforeEach(function () {
validPage = {
data: {
name: 'sean',
age: 42
}
};
validOptions = {
savePath: '.',
saveFile: 'example.xls'
};
validSpider = {};
});
it('should throw an error if no savePath is defined in the options', function () {
delete validOptions.savePath;
(function () {
var excel = mrspiderExcel(validOptions);
}).should.throw(Error);
});
it('should throw an error if no saveFile is given in the options.', function () {
delete validOptions.saveFile;
(function () {
var excel = mrspiderExcel(validOptions);
}).should.throw(Error);
});
it('should call next', function (done) {
var excel = mrspiderExcel(validOptions);
excel(validPage, validSpider, done);
});
describe('XMLWriter#appendData', function () {
it('should setup the writer with saveFile and savePath', function () {
var stub = sinon.stub();
var workbookSpy = {
createSheet: sinon.spy()
};
stub.returns(workbookSpy);
var fakeMsExcelBuilder = {
createWorkbook: stub
};
var xmlWriter = new XMLWriter(fakeMsExcelBuilder, validOptions);
fakeMsExcelBuilder.createWorkbook.called.should.equal(true);
fakeMsExcelBuilder.createWorkbook.firstCall.args[0].should.equal('.');
fakeMsExcelBuilder.createWorkbook.firstCall.args[1].should.equal('example.xls');
});
it('should create a worksheet called sheet1', function () {
var stub = sinon.stub();
var workbookSpy = {
createSheet: sinon.spy()
};
stub.returns(workbookSpy);
var fakeMsExcelBuilder = {
createWorkbook: stub
};
var xmlWriter = new XMLWriter(fakeMsExcelBuilder, validOptions);
workbookSpy.createSheet.called.should.equal(true);
});
});
});
<file_sep>#Mr Spider excel
| 76e85b44c38ed8ba9c2ea961c604e99a5169eb9b | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | vermiculite/mrspider-excel | 5388030f7f4dd2e41956dc6f5d10c2dd1ad84733 | eb66f575db0c808880effccfcdb7de746a6e0870 |
refs/heads/master | <file_sep>/**
* apeman app to verify email.
* @function apemanAppVerify
* @param {object} UserVerify - User verify model.
* @param {object} [options] - Optional settings.
* @param {function} [options.beforeSend] - Handle before send
* @param {function} [options.beforeVerify] - Handle before verify
* @param {function} [options.afterSend] - Handle after send
* @param {function} [options.afterVerify] - Handle after verify
* @param {object} [sendSchema=defaultSchema('send')] - JSON schema for send.
* @param {object} [verifySchema=defaultSchema('verify')] - JSON schema for verify.
* @returns {function} - Defined app function.
*/
'use strict'
const assert = require('assert')
const schemas = require('./schemas')
const rest = require('apeman-app-rest')
const debug = require('debug')('apeman:react:verify')
const ONE_DAY = 24 * 60 * 60 * 1000
/** @lends create */
function create (UserVerify, options = {}) {
assert.ok(UserVerify, 'UserVerify is required.')
assert.ok(!!(UserVerify.$$inherited && UserVerify.$$inherited.ApUserVerify), 'UserVerify should inherit ApUserVerify.')
let pathname = options.pathname || '/verify'
let format = options.format
let expireDuration = options.expireDuration || ONE_DAY
return rest(UserVerify, {
format,
pathname,
createSchema: options.createSchema || schemas('recover-create'),
updateSchema: options.updateSchema || schemas('recover-update'),
bulkUpdateDisabled: true,
bulkDestroyDisabled: true,
relatedDisabled: true,
relationDisabled: true,
doList: require('./doing/do_list_verify')({ expireDuration }),
doCreate: require('./doing/do_create_verify')({ expireDuration }),
doUpdate: require('./doing/do_update_verify')({})
})
}
module.exports = create
<file_sep>/**
* Test case for doCreateVerify.
* Runs with mocha.
*/
'use strict'
const doCreateVerify = require('../lib/doing/do_create_verify.js')
const assert = require('assert')
describe('do-create-verify', () => {
before((done) => {
done()
})
after((done) => {
done()
})
it('Do create verify', (done) => {
done()
})
})
/* global describe, before, after, it */
<file_sep>/**
* @function doCreateVerify
* @returns {function}
*/
'use strict'
const co = require('co')
const uuid = require('uuid')
const successPayload = require('apeman-app-rest/lib/payloads/success_payload')
const failurePayload = require('apeman-app-rest/lib/payloads/failure_payload')
const apemanmodel = require('apemanmodel')
const validateDataType = require('apeman-app-rest/lib/validating/validate_data_type')
const errors = require('../errors')
/** @lends doCreateVerify */
function doCreateVerify (config) {
const ACTION_NAME = 'create'
let success = successPayload(ACTION_NAME)
let failure = failurePayload(ACTION_NAME)
let { expireDuration } = config
return function createVerify (UserVerify, context) {
const User = UserVerify.getRef('user').model
let oneUser = apemanmodel.defineOne(User, context.transaction)
let update = apemanmodel.defineUpdate(UserVerify, context.transaction)
let { data, transaction, req } = context
return co(function * () {
let signed = req.signed()
let hasSign = signed && signed.sign
if (!hasSign) {
return failure(errors.signinRequiredError())
}
let { userId } = signed.sign
let user = yield oneUser(userId)
if (!user) {
return failure(
errors.notFoundError(apemanmodel.toType(User), { id: userId })
)
}
let typeError = validateDataType(data, apemanmodel.toType(UserVerify))
if (typeError) {
return failure(typeError)
}
let kind = data.attributes.kind
let target = user[ kind ]
if (!target) {
// TODO Give more detailed error
return failure(errors.somethingWrongError())
}
let token = uuid.v4().replace(/\-/g, '')
let verifies = yield UserVerify.findOrCreate({
transaction,
where: { userId },
defaults: { userId, kind, token, target }
})
let verify = [].concat(verifies || [])[ 0 ]
let updated = yield update(verify, {
token,
kind,
target,
expireAt: new Date(new Date().getTime() + expireDuration),
done: false
})
return success(
{},
apemanmodel.toData(UserVerify, updated)
)
})
}
}
module.exports = doCreateVerify
<file_sep>/**
* @function doListVerify
* @returns {function}
*/
'use strict'
const co = require('co')
const successPayload = require('apeman-app-rest/lib/payloads/success_payload')
const failurePayload = require('apeman-app-rest/lib/payloads/failure_payload')
const apemanmodel = require('apemanmodel')
const doList = require('apeman-app-rest/lib/doing/do_list')
const errors = require('../errors')
/** @lends doListVerify */
function doListVerify (config) {
const ACTION_NAME = 'list'
// let success = successPayload(ACTION_NAME)
let failure = failurePayload(ACTION_NAME)
return function listVerify (UserVerify, context) {
const User = UserVerify.getRef('user').model
let oneUser = apemanmodel.defineOne(User, context.transaction)
let req = context.req
return co(function * () {
let signed = req.signed()
let hasSign = signed && signed.sign
if (!hasSign) {
return failure(errors.signinRequiredError())
}
let { userId } = signed.sign
let user = yield oneUser(userId)
if (!user) {
return failure(
errors.notFoundError(apemanmodel.toType(User), { id: userId })
)
}
let result = yield doList(UserVerify, context)
if (result.data) {
result.data = result.data.map(afterData)
}
return result
})
}
}
let afterData = (data) => {
delete data.relationships
let attributes = data.attributes
delete attributes.token
return Object.assign(data, { attributes })
}
module.exports = doListVerify
<file_sep>'use strict'
const apemanerror = require('apemanerror')
const ApErrorCodes = apemanerror.ApErrorCodes
const trigger = 'apeman-app-verify'
module.exports = Object.assign(exports, {
signinRequiredError (type, condition) {
let code = ApErrorCodes.SIGN_IN_REQUIRED_ERROR
return Object.assign(
apemanerror.newError(code, null, {
trigger,
context: { type, condition }
}),
{ status: '401' }
)
},
notFoundError (type, condition) {
let code = ApErrorCodes.RESOURCE_NOT_FOUND_ERROR
return Object.assign(
apemanerror.newError(code, null, {
trigger,
context: { type, condition }
}),
{ status: '404' }
)
},
tokenInvalidError () {
let code = ApErrorCodes.TOKEN_WRONG_ERROR
return Object.assign(
apemanerror.newError(code, null, {
trigger,
context: {}
}),
{ status: '401' }
)
},
tokenExpiredError () {
let code = ApErrorCodes.TOKEN_EXPIRED_ERROR
return Object.assign(
apemanerror.newError(code, null, {
trigger,
context: {}
}),
{ status: '401' }
)
},
somethingWrongError () {
let code = ApErrorCodes.SOMETHING_WRONG_ERROR
return Object.assign(
apemanerror.newError(code, null, {
trigger,
context: {}
}),
{ status: '500' }
)
}
})
<file_sep>/**
* Test case for doUpdateVerify.
* Runs with mocha.
*/
'use strict'
const doUpdateVerify = require('../lib/doing/do_update_verify.js')
const assert = require('assert')
describe('do-update-verify', () => {
before((done) => {
done()
})
after((done) => {
done()
})
it('Do update verify', (done) => {
done()
})
})
/* global describe, before, after, it */
| da66f4d01e60302fca536106b0d969146c2087cb | [
"JavaScript"
] | 6 | JavaScript | apeman-app-labo/apeman-app-verify | 1bb6cc10862d4d52860c271e05b6c7254f2f9129 | 7c6a82d69e63d3633ff66fdc730b196530e57f1b |
refs/heads/master | <repo_name>sushantn145/AWP-Exam<file_sep>/README.md
# AWP-Exam
Exam
<file_sep>/2.js
function submithere() {
var name = document.getElementById('username').value;
var password = document.getElementById('psd').value;
console.log('name');
console.log('password');
//var cmtbox = documnet.getElementById('bottom-box').cloneNode(true);
var commentbox = document.getElementById('userdetails').innerHTML;
document.getElementById('userdetails').children[0].children[0].children[1].innerHTML = name;
document.getElementById('userdetails').children[0].children[1].children[1].innerHTML = password;
var name = document.getElementById('username').value = "";
var password = document.getElementById('psd').value = "";
} | d10e296f15d6d97d5717903b9a308fa4d00315c3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | sushantn145/AWP-Exam | 69734bf3093eea9e090052a28061d5ec335a13d9 | cef626824fb0c6165ab2f3f1a3cd4c203788a09c |
refs/heads/master | <file_sep>using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Win10BloatRemover.Utils;
namespace Win10BloatRemover.Operations
{
/*
* Performs backup (export of registry keys) and removal of those services whose name starts with the service names
* passed into the constructor.
* This is made in order to include services that end with a random code.
*/
public class ServiceRemover : IOperation
{
private readonly string[] servicesToRemove;
private readonly DirectoryInfo backupDirectory;
private readonly IUserInterface ui;
private const int SC_EXIT_CODE_MARKED_FOR_DELETION = 1072;
public static void BackupAndRemove(string[] servicesToRemove, IUserInterface ui)
{
var serviceRemover = new ServiceRemover(servicesToRemove, ui);
string[] actualBackuppedServices = serviceRemover.PerformBackup();
serviceRemover.PerformRemoval(actualBackuppedServices);
}
public ServiceRemover(string[] servicesToRemove, IUserInterface ui)
{
this.servicesToRemove = servicesToRemove;
this.ui = ui;
backupDirectory = new DirectoryInfo($"servicesBackup_{DateTime.Now:yyyy-MM-dd_hh-mm-ss}");
}
void IOperation.Run()
{
ui.PrintHeading("Backing up services...");
string[] actualBackuppedServices = PerformBackup();
if (actualBackuppedServices.Length > 0)
{
ui.PrintHeading("Removing services...");
PerformRemoval(actualBackuppedServices);
}
}
public string[] PerformBackup()
{
string[] existingServices = FindExistingServicesWithNames(servicesToRemove);
foreach (string service in existingServices)
BackupService(service);
return existingServices;
}
private string[] FindExistingServicesWithNames(string[] servicesNames)
{
string[] allExistingServices = GetAllServicesNames();
List<string> allMatchingServices = new List<string>();
foreach (string serviceName in servicesNames)
{
var matchingServices = allExistingServices.Where(name => name.StartsWith(serviceName)).ToArray();
if (matchingServices.Length == 0)
ui.PrintMessage($"No services found with name {serviceName}.");
else
allMatchingServices.AddRange(matchingServices);
}
return allMatchingServices.ToArray();
}
private string[] GetAllServicesNames()
{
using RegistryKey servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
return servicesKey.GetSubKeyNames();
}
private void BackupService(string service)
{
EnsureBackupDirectoryExists();
int regExportExitCode = SystemUtils.RunProcessBlocking(
"reg", $@"export HKLM\SYSTEM\CurrentControlSet\Services\{service} {backupDirectory.FullName}\{service}.reg"
);
if (regExportExitCode == 0)
ui.PrintMessage($"Service {service} backed up.");
else
throw new Exception($"Could not backup service {service}.");
}
private void EnsureBackupDirectoryExists()
{
if (!backupDirectory.Exists)
backupDirectory.Create();
}
private void PerformRemoval(string[] backuppedServices)
{
foreach (string service in backuppedServices)
RemoveService(service);
}
private void RemoveService(string service)
{
int scExitCode = SystemUtils.RunProcessBlocking("sc", $"delete {service}");
if (IsScExitCodeSuccessful(scExitCode))
PrintSuccessMessage(scExitCode, service);
else
{
Debug.WriteLine($"SC removal failed with exit code {scExitCode} for service {service}.");
DeleteServiceRegistryKey(service);
}
}
private bool IsScExitCodeSuccessful(int exitCode)
{
return exitCode == SystemUtils.EXIT_CODE_SUCCESS ||
exitCode == SC_EXIT_CODE_MARKED_FOR_DELETION;
}
private void PrintSuccessMessage(int scExitCode, string service)
{
if (scExitCode == SystemUtils.EXIT_CODE_SUCCESS)
ui.PrintMessage($"Service {service} removed successfully.");
else if (scExitCode == SC_EXIT_CODE_MARKED_FOR_DELETION)
ui.PrintMessage($"Service {service} will be removed after reboot.");
else
Debug.Fail($"There must be an error in {nameof(IsScExitCodeSuccessful)}: exit code {scExitCode}.");
}
// reg command with /f option allows to remove unstoppable system services, like Windows Defender ones
private void DeleteServiceRegistryKey(string service)
{
int regExitCode = SystemUtils.RunProcessBlocking("reg", $@"delete HKLM\SYSTEM\CurrentControlSet\Services\{service} /f");
if (regExitCode == SystemUtils.EXIT_CODE_SUCCESS)
ui.PrintMessage($"Service {service} removed, but it will continue to run until the next restart.");
else
ui.PrintError($"Service {service} removal failed: couldn't delete its registry keys.");
}
}
}
<file_sep>using Win10BloatRemover.Operations;
using Xunit;
using Xunit.Abstractions;
using Xunit.Repeat;
namespace Win10BloatRemover.Tests.Operations
{
[Collection("ModifiesSystemState")]
public class WindowsDefenderRemoverTests
{
private readonly ITestOutputHelper output;
public WindowsDefenderRemoverTests(ITestOutputHelper output) => this.output = output;
[Theory]
[Repeat(2)]
public void ShouldNotEncounterErrors(int attempt)
{
var ui = new TestUserInterface(output);
var defenderRemover = new WindowsDefenderRemover(ui, new MockInstallWimTweak(), new MockOperation("UWPAppRemover", ui));
defenderRemover.Run();
Assert.Equal(0, ui.ErrorMessagesCount);
}
}
}
<file_sep>using System.Management.Automation;
using Win10BloatRemover.Utils;
namespace Win10BloatRemover.Operations
{
public class FeaturesRemover : IOperation
{
private readonly string[] featuresToRemove;
private readonly IUserInterface ui;
private /*lateinit*/ PowerShell powerShell;
#nullable disable warnings
public FeaturesRemover(string[] featuresToRemove, IUserInterface ui)
{
this.featuresToRemove = featuresToRemove;
this.ui = ui;
}
#nullable restore warnings
public void Run()
{
using (powerShell = PowerShellExtensions.CreateWithImportedModules("Dism").WithOutput(ui))
{
foreach (string featureName in featuresToRemove)
RemoveFeaturesWhoseNameStartsWith(featureName);
}
ui.PrintNotice("A system reboot is recommended.");
}
private void RemoveFeaturesWhoseNameStartsWith(string featureName)
{
var featurePackages = powerShell.Run($"Get-WindowsPackage -Online -PackageName {featureName}*");
if (featurePackages.Length > 0)
{
foreach (var package in featurePackages)
{
ui.PrintMessage($"Removing feature {package.PackageName}...");
powerShell.Run($"Remove-WindowsPackage -Online -NoRestart -PackageName {package.PackageName}");
}
if (featureName.Contains("Windows-Hello-Face"))
new ScheduledTasksDisabler(new[] { @"\Microsoft\Windows\HelloFace\FODCleanupTask" }, ui).Run();
}
else
ui.PrintMessage($"Feature {featureName} is not installed.");
}
}
}
<file_sep>using Win10BloatRemover.Operations;
using Win10BloatRemover.Utils;
namespace Win10BloatRemover.Tests
{
class MockInstallWimTweak : InstallWimTweak
{
public void RemoveComponentIfAllowed(string component, IMessagePrinter printer)
{
printer.PrintNotice($"Requested removal of component {component} through install-wim-tweak.");
}
}
class MockOperation : IOperation
{
private readonly string operationName;
private readonly IUserInterface ui;
public MockOperation(string operationName, IUserInterface ui)
{
this.operationName = operationName;
this.ui = ui;
}
public void Run()
{
ui.PrintNotice($"Requested execution of operation {operationName}.");
}
}
}
| 330a3a636b0074fd40789b3044219c3e6735c8e3 | [
"C#"
] | 4 | C# | doneme/Win10BloatRemover | 33fb08c2072f42bd9efc195776bcaab8f98db5d3 | bf9ec3683a08076b68e0f7e62d04b9cca9dcdbb8 |
refs/heads/main | <file_sep>const paginate = (followers) => {
const followerPerPage= 9
const pages = Math.ceil(followers.length / followerPerPage)
console.log(pages)
const newArray = Array.from({length : pages}, (_, index) => {
const start = index * followerPerPage
return followers.slice(start, start+ followerPerPage)
})
return newArray
}
export default paginate
<file_sep>import React, { useState, useEffect } from 'react'
import List from './List'
import Alert from './Alert'
const getLocalStorage = () => {
let itemList2 = localStorage.getItem('itemList')
if(itemList2){
const data=localStorage.getItem('itemList')
return (itemList2 = JSON.parse(data));
}
else{
return [];
}
}
function App() {
const [name, setName] = useState('')
const [itemList, setItemList] = useState(getLocalStorage())
const [isEditing, setisEditing]= useState(false)
const [editId, setEditId] =useState(null)
const [alertmsg, setAlertmsg] = useState({show:false, msg:'', type:''}) //this fora alerting after adding or deleting
const handleSubmit=(e)=>{
e.preventDefault()
if(!name){
console.log("clicked")
showAlert(true, "Please Enter the input", 'danger')
}
else if(name && isEditing ){
setItemList(itemList.map((item)=>{
if(item.id === editId){
return { ...item, title:name};
}
return item;
})
);
setName('')
setEditId(null)
setisEditing(false)
showAlert(true, "value changed", "success")
}
else {
showAlert(true, "Item added to the list", "success")
const newItem = {id:new Date().getTime().toString(), title:name}
setItemList(()=>{
return [...itemList, newItem]
})
setName('')
}
}
const showAlert =(show='false', msg='', type='')=>{
console.log(show)
setAlertmsg({show, msg, type});
console.log(alertmsg)
}
const removeItem =(id)=>{
showAlert(true, "item deleted", "danger")
setItemList(itemList.filter((item)=> item.id !== id))
}
const editItem =(id)=>{
const specificItem = itemList.find((item)=> item.id === id)
setisEditing(true)
setEditId(id)
setName(specificItem.title)
}
useEffect(()=>{
localStorage.setItem('itemList', JSON.stringify(itemList)) ;
}, [itemList]);
return <>
<section className="section-center">
<form className="grocery-form" onSubmit={handleSubmit}>
{alertmsg.show && <Alert {...alertmsg} removeAlert={showAlert} list={itemList}/>}
<h3>Grocery Bud</h3>
<div className="form-control">
<input type="text" className="grocery" placeholder="e.g eggs" value={name}
onChange={(e)=> setName(e.target.value)}
></input>
<button type="submit" className="submit-btn">
{isEditing ? 'edit' : 'submit'}
</button>
</div>
</form>
{
itemList.length >0 && (
<div className="grocery-container">
<List itemList={itemList} removeItem={removeItem} editItem={editItem}/>
<button className="clear-btn" onClick={()=>{
setItemList([]);
showAlert(true, "Empty list", "danger")
}}>
Clear Items Value
</button>
</div>
)
}
</section>
</>
}
export default App
| 965ba1edcf0892ab58c2338b8298daa8f889f25e | [
"JavaScript"
] | 2 | JavaScript | pratiksha2395/React_Projects | 683545ce71371b8f39e27c78e04204bb9c405386 | 1a4733b37c8c383ae9861dfa827ad21556fbd327 |
refs/heads/master | <repo_name>martynling/vue-grid-sf<file_sep>/index.js
import VueGridSf from './src/components/VueGridSf.vue'
module.exports = VueGridSf
<file_sep>/README.md
# vue-grid-sf
A rather handy grid UI component for Vue.js. Define the columns, bind the data, handle the events and off you go.
Column headings are sortable by default, triggering an event.
An optional action column with dropdown menu can also be defined with actions that are either links to other pages or triggers for custom events.
An optional checkbox column for multiple row selection and select all.
# Requirements
- Vue.js ^`2.0.0`
- momentjs ^`2.12.0`
- node-esapi ^`0.0.1`
## Optional
- bootstrap ^`3.3.0`
If you want to use the action menu or expandable column functionality, these depend on Bootstrap js.
The default styling of the grid is also based on Bootstrap, but you can override that with your own if desired.
# Installation
Assuming that you'll be using gulp or browserify to roll all your js into a single file:
```shell
$ npm install vue-grid-sf --save-dev
```
To make this work in my Laravel project, I needed to add the following to the devDependencies of that project:
```
"babel-preset-stage-2": "^6.1.18"
```
## Build Setup
``` bash
# install dependencies
npm install
```
A simple demo app is available at localhost:8080/demo
``` bash
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# lint all *.js and *.vue files
npm run lint
# run unit tests
npm test
```
For more information see the [docs for vueify](https://github.com/vuejs/vueify).
# Upgrade from v0.0 to v1.0
`vue-grid-sf` has been upgraded to work with Vue 2.0. Vue 2.0 does not support two-way binding of properties. Instead any changes to bound properties are passed back via events. The following component properties are affected by this change:
- data
- sort-column
- sort-dir
- rows-selected (this property been deprecated as row selections are handled entirely via events)
# Usage
```javascript
let Vue = require('vue');
import VueGridSf from 'vue-grid-sf'
Vue.component('vue-grid-sf', VueGridSf)
```
## Simple Example
After installing the plugin you can use it like this:
```html
<vue-grid-sf
v-on:sort-order-changed="handleSortOrderChanged"
v-bind:columns="columns"
v-bind:data="myData"
></vue-grid-sf>
```
```javascript
var vm = new Vue({
el: 'body',
created () {
// If you're using AJAX, you probably want to fetch your data here
this.fetchData()
},
data: {
columns: [
{
name: 'id',
displayName: '#',
dataType: 'integer'
}, {
name: 'first_name',
displayName: '<NAME>',
dataType: 'string'
}, {
name: 'languages_spoken',
displayName: 'Languages Spoken Fluently',
dataType: 'choice',
options: [
{ key: 'en', value: 'English' },
{ key: 'fr', value: 'French' },
{ key: 'pt', value: 'Portuguese' },
{ key: 'es', value: 'Spanish' }
// ...more languages
],
maxItems: 10,
hidden: true // Don't display in grid (might be used for filtering if vue-filter-control is used)
}, {
name: languages_spoken_display_name,
displayName: 'Languages Spoken Fluently',
dataType: 'string',
notFilterable: true // Don't include in list of columns that can be used for filtering (if vue-filter-control is sharing the columns data)
}
],
myData: [],
sortColumn: null,
sortDir: null
},
methods: {
fetchData() {
// Your AJAX or other code to display the data based on the new sort order
this.MyData = [] // data fetched via AJAX or otherwise imported/sorted
},
handleSortColumnChanged (e) {
this.sortColumn = e.column;
this.sortDir = e.dir;
this.fetchData();
},
}
});
```
## Fully Featured Example
If you want to make use of all of the features of vue-grid-sf:
```html
<vue-grid-sf
v-on:cell-clicked="handleCellClicked"
v-on:row-clicked="handleRowClicked"
v-on:row-selected="handleRowSelected"
v-on:sort-order-changed="handleSortOrderChanged"
v-on:my-custom-event="handleMyCustomEvent"
v-bind:columns="columns"
v-bind:data="myData"
v-bind:sort-column="sortColumn"
v-bind:sort-dir="sortDir"
v-bind:actions="actions"
actions-column-heading="Actions"
show-action-menu=true
show-checkbox-selection=true
></vue-grid-sf>
```
```javascript
var vm = new Vue({
el: 'body',
created () {
// If you're using AJAX, you probably want to fetch your data here
this.fetchData()
},
data: {
actions: [
{
class: 'link',
displayText: 'URL test',
url: '/things/{key}/edit', // for each row, {key} is replaced by the rowData for the urlKey column
urlKey: 'id'
}, {
class: 'divider'
}, {
class: 'event',
displayText: 'Event test',
event: 'my-custom-event'
}
],
columns: [
{
name: 'id',
displayName: '#',
dataType: 'integer'
}, {
name: 'first_name',
displayName: '<NAME>',
dataType: 'string'
}, {
name: 'languages_spoken',
displayName: 'Languages Spoken Fluently',
dataType: 'multi-select',
options: [
{ key: 'en', value: 'English' },
{ key: 'fr', value: 'French' },
{ key: 'pt', value: 'Portuguese' },
{ key: 'es', value: 'Spanish' }
// ...more languages
],
maxItems: 10,
hidden: true // Don't display in vue-grid-sf (column might be used by vue-filter-control for filtering)
}, {
name: languages_spoken_display_name,
displayName: 'Languages Spoken Fluently',
dataType: 'string',
notFilterable: true // Don't include in list of columns that can be used for filtering (if vue-filter-control is sharing the columns data)
}
],
myData: [],
sortColumn: 'id', // How the initial data is sorted (can be left blank)
sortDir: 'asc'
},
methods: {
fetchData() {
// Your AJAX or other code to display the data based on the new sort order
// Set myData, which is bound to vue-grid-sf's data property with data fetched via AJAX or otherwise imported/sorted
this.myData = []
},
handleCellClicked(e) { // Object e has rowData and column properties
if (e.column.name === 'something-special') {
// do something special
} else {
// do something else, perhaps with e.rowData
}
},
handleMyCustomEvent(rowData) {
// rowData for the row that triggered the event
alert('Event triggered for row with id #' + rowData.id)
},
handleRowClicked(rowData) {
},
handleRowSelected(rows) {
},
handleSortColumnChanged (e) {
this.sortColumn = e.column;
this.sortDir = e.dir;
this.fetchData();
},
}
});
```
# Props
## Required
- `columns`
- `data`
## Optional
- `column-key` - the name of the column that contains a unique key for the data. Used by row selection functionality. Defaults to `id`.
- `sort-column` - the column that the data is sorted by (**Note:** the grid does not do the sorting, you provide sorted data). Defaults to `''`.
- `sort-dir` - the direction that the data in sortColumn, either `'asc'` or `'desc'`. Defaults to `'asc'`.
- `table-class` - CSS class applied to table. Defaults to `'table table-striped table-responsive table-box table-hover'`.
- `sort-asc-class` - CSS class applied to ascending sort. Defaults to `'glyphicon glyphicon-triangle-top'`.
- `sort-desc-class` - CSS class applied to descending sort. Defaults to `'glyphicon glyphicon-triangle-bottom'`.
- `show-action-menu` - determines whether the action menu column should be shown. Defaults to `false`.
- `actions` - array of actions to be added to action menu for every row in the grid. Defaults to `null`.
- `actions-column-heading` - Column heading for the actions menu defaults to `''`
- `show-checkbox-selection` - determines whether a column should be shown that enables multiple selection of rows. Defaults to `false`.
## Columns definition
### Required
- `name` - the attribute in the `data` property that contains the data to be displayed in the column
- `displayName` - the column heading
- `dataType` - the column's dataType - currently supports `string`, `number`, `date`, `datetime`, `choice` (`choice` is more relevant to `vue-filter-control`) and `html` (only use if you know your content is safe to display).
### Optional
- `dataFormat` - see `dataFormat` below for more info.
- `expandable` - see `expandable` below for more info.
- `expandableFrom` - see `expandable` below for more info.
- `expandableText` - see `expandable` below for more info.
- `hidden` - see `Using with vue-filter-control` for more info.
- `notFilterable` - see `Using with vue-filter-control` for more info.
### dataFormat
- for string dataType, setting `dataFormat` to `paragraph` will HTML encode the text and convert newlines to line breaks.
- for date and datetime dataTypes, you can set `dataFormat` to a momentjs compatible format (otherwise date will default to `ll` and datetime will default to `lll`).
### expandable
If you have a column where the data will contain lots of text data, you may want to truncate what is displayed in the grid and provide a hoverable and clickable popover (using Bootstrap's popover) to display the full text.
To do this for the column:
* Set `dataFormat` to `paragraph`
* Set `expandable` to `true`
* Set `expandableFrom` to the number of characters that you want displayed in the grid.
* Set `expandableText` to provide a hoverable, clickable text to trigger the popover displaying the full text. Defaults to `'(...)'`.
You will also need to run this code every time that new data populates the grid:
``` javascript
this.$nextTick(function () {
$('[data-toggle="popover"]').popover(
{container: 'body', html: false, placement: 'auto bottom', trigger: 'hover click'}
)
})
```
NOTE: the `html` option should be set to false unless you are absolutely sure that the popover content is safe from XSS.
### Using with vue-filter-control
You can share a common `columns` definition between `vue-grid-sf` and `vue-filter-control` since many of the column configurations will be the same for the grid and the filter.
However, there will be some filter columns that you wouldn't want to be shown in the grid. In these cases, set:
```
hidden: true
```
and some columns you may want to be listed in the grid, but you wouldn't want them to be available for filtering. In these cases, set:
```
notFilterable: true
```
## Special data fields
- `actionMenu` - see `Actions` below
- `rowClass`
## Actions
Adding an action menu to the grid is made possible via some action specific properties and also via `data` property:
Setting `show-action-menu` to true will display an action menu column on the left side of the grid.
Setting the `actions` property to an array of actions will fill the action menu with these actions for every row in the grid.
In addition to the `actions` property, an array of actions can be defined per row in the data property. So, if you're fetching your data via AJAX, your server-side code can define the appropriate actions based on user permissions or row-specific conditions by passing the actions in an array via the column name `actionMenu`. The same action definition format is used for both the `actions` property and the `actionMenu` column in the `data` property.
### Action definition format
```
actions: [
{
class: 'link',
displayText: 'URL test',
url: '/things/{key}/edit', // for each row, {key} is replaced by the row data for the urlKey column
urlKey: 'id'
}, {
class: 'divider'
}, {
class: 'event',
displayText: 'Event test',
event: 'my-custom-event'
// Note: you need to add v-on:my-custom-event={yourHandler} to the <vue-grid-sf> component
// The event handler will be passed the rowData
}
],
```
## Row Selection
Adding the ability to select multiple or all rows in the grid is as simple as setting `show-checkbox-selection` to true.
Listen out for a `row-selected` event to do something with the selected rows, such as bulk actions.
# Events
- `cell-clicked` - object passed has `rowData` and `column` properties
- `row-clicked` - object passed is `rowData`
- `sort-order-changed` - object passed has `column` (the column name) and `dir` (set to either `'asc'` or `'desc'`) properties.
- `row-selected` - an array of rowData is passed for the selected rows.
- custom events as defined in the `actions` property and/or within the `actionMenu` data field in the data provided to the `data` property. Passed rowData.
| 2e64a399c9f749e421a5ffdd682ad09916dc870d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | martynling/vue-grid-sf | 295711e31d5d3d9e05edcae1b92dcf2585f094e5 | 6cbe2923a561acd775af5faea70c3856c7a778aa |
refs/heads/main | <repo_name>rubeneggel72/Entrega10<file_sep>/server/server.js
var express = require('express')
var app = express();
var router = express.Router();
const bodyParser = require("body-parser");
const port = process.env.PORT || 8080;
const handlebars = require('express-handlebars');
app.set('view engine', 'hbs');
app.engine('hbs', handlebars({
layoutsDir: __dirname + '../../views/layouts',
extname: 'hbs',
defaultLayout: 'index',
partialsDir: __dirname + '../../views/partials/'
}));
app.use(express.static('./public'));
app.use(express.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/api', require('../rutas/api'))
app.use('/', router)
app.listen(port, (err) => {
if (err) throw new Error(err);
console.log(`Servidor corriendo en puerto ${port}`);
});
// JSON productos para agregar
//{"title":"iPhone 11 64 GB (Product)Red","price":159000,"thumbnail":"a001.jpg"}
//{"title":"iPhone 12 64 GB azul","price":200000,"thumbnail":"a002.jpg"}
//{"title":"iPhone XR 64 GB negro","price":139000,"thumbnail":"a003.jpg"}
//{"title":"iPhone XR 64 GB negro","price":139000,"thumbnail":"a003.jpg"}
| 0cca6cf3a0c10ad88386b72cc37f158e739d6907 | [
"JavaScript"
] | 1 | JavaScript | rubeneggel72/Entrega10 | 539269ab797204f6030c911301f76403b1a0a4da | 2716036285432a6ef5fc0c759ec9142204d83511 |
refs/heads/master | <repo_name>SkeLLLa/mongo-cache-example<file_sep>/lib/api-doc.js
/// <reference types="node" />
/// <reference types="config" />
const {version, description, name} = require('../package.json');
const config = require('config');
const apiConfig = config.get('api');
const serverConfig = config.get('server');
const api = {
swagger: '2.0',
info: {
title: name,
description,
version,
},
produces: ['text/plain', 'application/json'],
host: `${serverConfig.host}:${serverConfig.port}`,
basePath: apiConfig.basePath,
paths: {
'/keys': {
get: {
'x-swagger-router-controller': 'cache',
'operationId': 'getKeys',
'tags': ['cache'],
'description': 'Get all keys',
'produces': 'application/json',
'parameters': [],
'responses': {
200: {
description: 'All cache keys list',
schema: {
type: 'array',
items: {
type: 'string',
},
},
},
},
},
},
'/cache': {
get: {
'x-swagger-router-controller': 'cache',
'operationId': 'getAll',
'tags': ['cache'],
'description': 'Get all cache entries',
'produces': 'application/json',
'parameters': [],
'responses': {
200: {
description: 'All cache entries list',
schema: {
type: 'array',
items: {
type: 'object',
properties: {
key: {
type: 'string',
},
value: {
type: 'string',
},
ttl: {
type: 'number',
},
},
},
},
},
},
},
delete: {
'x-swagger-router-controller': 'cache',
'operationId': 'deleteAll',
'tags': ['cache'],
'description': 'Delete all cache entries',
'parameters': [],
'responses': {
204: {
description: 'Cache cleared',
},
},
},
},
'/cache/{key}': {
get: {
'x-swagger-router-controller': 'cache',
'operationId': 'get',
'tags': ['cache'],
'description': 'Get cache entry',
'parameters': [
{
name: 'key',
in: 'path',
type: 'string',
required: true,
description: 'Cache key',
},
],
'responses': {
200: {
description: 'Cache HIT',
schema: {
type: 'string',
},
},
201: {
description: 'Cache MISS. New value created',
schema: {
type: 'string',
},
},
400: {
description: 'Bad request',
schema: {
type: 'string',
},
},
},
},
put: {
'x-swagger-router-controller': 'cache',
'operationId': 'set',
'tags': ['cache'],
'description': 'Set cache entry',
'consumes': ['text/plain'],
'parameters': [
{
name: 'key',
in: 'path',
type: 'string',
required: true,
description: 'Cache key',
},
{
name: 'ttl',
in: 'query',
type: 'number',
required: false,
description: 'Cache item ttl',
},
{
name: 'value',
in: 'body',
type: 'string',
consumes: ['text/plain'],
required: true,
description: 'Cache value',
},
],
'responses': {
201: {
description: 'Cache item created',
schema: {
type: 'string',
},
},
400: {
description: 'Bad request',
schema: {
type: 'string',
},
},
},
},
delete: {
'x-swagger-router-controller': 'cache',
'operationId': 'delete',
'tags': ['cache'],
'description': 'Remove entry from cache',
'parameters': [
{
name: 'key',
in: 'path',
type: 'string',
required: true,
description: 'Cache key',
},
],
'responses': {
204: {
description: 'Cache item removed',
},
400: {
description: 'Bad request',
schema: {
type: 'string',
},
},
404: {
description: 'Key not found',
schema: {
type: 'string',
},
},
},
},
},
},
};
module.exports = api;
<file_sep>/CHANGELOG.md
#### 1.0.0 (2018-06-15)
##### Chores
* **package.json:** revert version ([7e595d42](https://github.com/SkeLLLa/mongo-cache-example/commit/7e595d42caf0c9b66c591c2767856d3ec48befe9))
* **deps:** add deps ([5af02fc5](https://github.com/SkeLLLa/mongo-cache-example/commit/5af02fc59d9e1a3e44312eda745c6aa2fed57ef7))
* **config:** add tsconfig ([23c92fc4](https://github.com/SkeLLLa/mongo-cache-example/commit/23c92fc4e390839c425b9cabe3cc5e9edeada328))
* **ignore:** add ignore files ([edb16ede](https://github.com/SkeLLLa/mongo-cache-example/commit/edb16eded4cea4e5c45619e79412518b9e1a156c))
* **initial:** initial commit ([9b8131a8](https://github.com/SkeLLLa/mongo-cache-example/commit/9b8131a8dfd7fecaaed5981a6673b80a1a14c963))
##### Documentation Changes
* **readme:** update readme with getting started info ([983ed2a8](https://github.com/SkeLLLa/mongo-cache-example/commit/983ed2a82cb19d4572513184133753498d7d77cd))
* **changelog:** add changelog file ([df335fba](https://github.com/SkeLLLa/mongo-cache-example/commit/df335fbaf5d595cd3fa0da04f7209e96b5b36107))
* **task:** add task pdf ([e9f9881f](https://github.com/SkeLLLa/mongo-cache-example/commit/e9f9881f3cca1b54e3bf17f97d404af276bcdc50))
##### New Features
* **server:** add server ([e34b3d9d](https://github.com/SkeLLLa/mongo-cache-example/commit/e34b3d9dff89fbe07a6ca5c41a0c00d7c5626b21))
* **db:** add db module ([1aceac38](https://github.com/SkeLLLa/mongo-cache-example/commit/1aceac3831f2d6c0af904c6bd2dcd1bfcc38a09d))
* **api:**
* add api implementation ([7f65b642](https://github.com/SkeLLLa/mongo-cache-example/commit/7f65b642b90790db30dd2008c2400c2b866821fa))
* add api docs ([b6096838](https://github.com/SkeLLLa/mongo-cache-example/commit/b60968385d3dc79523306458a32af8dc8808e915))
* **data:** add random data generator ([7ecfa34c](https://github.com/SkeLLLa/mongo-cache-example/commit/7ecfa34ceb3999d09f8276446628ddee2a620581))
* **config:** add default config ([fdb8a2bf](https://github.com/SkeLLLa/mongo-cache-example/commit/fdb8a2bfb250242cb3361ead3bdc426f3902c68f))
##### Bug Fixes
* **package.json:** fix typo in scripts ([8b128df8](https://github.com/SkeLLLa/mongo-cache-example/commit/8b128df83cfa6032d48ccd6121ce2d5fdd953ed2))
##### Refactors
* **changelog:** revert changelog ([4fe7673c](https://github.com/SkeLLLa/mongo-cache-example/commit/4fe7673c513f5b28f6c252c6d13a6b6da89cef76))
* **package.json:** update repo name ([c3a6cb4e](https://github.com/SkeLLLa/mongo-cache-example/commit/c3a6cb4e9ebbfb0adacb2b0eb452bde397166030))
* **server:** add api information ([1a859ef9](https://github.com/SkeLLLa/mongo-cache-example/commit/1a859ef9524de8404d8873e11c01600fdefa7b29))
##### Code Style Changes
* **codestyle:** add codestyle config ([54868aae](https://github.com/SkeLLLa/mongo-cache-example/commit/54868aaee707d22f8f6dc1439c3282894336cbfc))
<file_sep>/lib/data-generator.js
const crypto = require('crypto');
const {promisify} = require('util');
const randomBytes = promisify(crypto.randomBytes);
exports.getRandomString = async (size = 32) => {
const buffer = await randomBytes(size);
return buffer.toString('hex');
};
<file_sep>/lib/db.js
/// <reference types="node" />
/// <reference types="mongodb" />
/// <reference types="config" />
const {MongoClient} = require('mongodb');
const config = require('config').get('db');
let db;
let collection;
const mongo = {
get db() {
return db;
},
get collection() {
return collection;
},
async connect() {
try {
const client = await MongoClient.connect(config.url);
db = client.db(config.db);
collection = db.collection(config.collection);
await collection.createIndex(
{expireAt: 1},
{expireAfterSeconds: 0}
);
await collection.createIndex('key', {unique: true, dropDups: true});
} catch (ex) {
console.error(ex);
console.log(`Can't connect to DB`);
process.exit(1);
}
},
close() {
if (db) {
db.close();
}
},
};
module.exports = mongo;
<file_sep>/README.md
# mongo-cache-example
Example express app that implements mongo-backed cache server with plain HTTP API
## Getting started
### Requirements
- `>=node-8.0.0`
- `>=mongodb-3.4.0`
### Install dependencies
```bash
npm i
```
### Update configuration
In order to update configuration (if needed) you may create `local.js` in `config/` directory with needed variables overrides.
Example:
```js
const config = {};
module.exports = config;
config.cache = {
size: 100,
ttl: 3 * 60 * 1000,
};
config.db = {
url: 'mongodb://example.com:27017',
};
```
### Run server
```bash
npm start
```
## Releasing new version
Use `npm version` command to release new version. It will do all necessary checks and will push it to VCS
<file_sep>/bin/run.js
#!/usr/bin/env node
const server = require('../lib/server');
(async () => {
try {
server.start();
} catch (ex) {
console.error(ex);
console.error('Failed to start server');
process.exit(1);
}
})();
<file_sep>/config/default.js
const config = {};
module.exports = config;
config.api = {
basePath: '/api',
docsPath: '/api-docs',
};
config.cache = {
size: 10,
ttl: 60 * 1000,
};
config.server = {
host: 'localhost',
port: 3000,
};
config.db = {
url: 'mongodb://localhost:27017',
db: 'cache',
collection: 'items',
};
<file_sep>/lib/server.js
/// <reference types="node" />
/// <reference types="mongodb" />
/// <reference types="config" />
/// <reference types="express" />
const express = require('express');
const ui = require('swagger-ui-express');
const apiDoc = require('./api-doc');
const bodyParser = require('body-parser');
const router = require('swagger-express-router');
const api = require('./api');
const config = require('config');
const app = express();
const {connect} = require('./db');
const apiConfig = config.get('api');
const serverConfig = config.get('server');
app.use(
apiConfig.docsPath,
ui.serve,
ui.setup(apiDoc, {
explorer: true,
})
);
app.use(bodyParser.text());
router.setUpRoutes(api, app, apiDoc, true);
exports.start = async () => {
await connect();
app.listen(serverConfig);
console.info(
`Server started. Browse api: http://${serverConfig.host}:${
serverConfig.port
}/api-docs`
);
};
<file_sep>/lib/api/cache.js
/// <reference types="node" />
/// <reference types="mongodb" />
/// <reference types="express" />
const mongo = require('../db');
const config = require('config').get('cache');
const {getRandomString} = require('../data-generator');
const getValue = (value, ttl = config.ttl) => {
const now = new Date();
return {
updatedAt: now,
expireAt: new Date(now.getTime() + ttl),
ttl,
value,
};
};
const updateOne = async (key, obj) => {
const data = await mongo.collection.updateOne(
{key},
{$set: obj},
{
upsert: true,
}
);
const count = await mongo.collection.count();
// check if cache count exceeds cache size
// and delete oldest entry
if (count > config.size) {
await deleteOledst();
}
return data;
};
const getOne = async (key) => {
return mongo.collection.findOne({key});
};
const deleteOne = async (key) => {
return mongo.collection.deleteOne({key});
};
const deleteOledst = async () => {
const oldest = await mongo.collection.findOne({}, {sort: {updatedAt: 1}});
await deleteOne(oldest.key);
return;
};
const deleteAll = async () => {
return mongo.collection.deleteMany({});
};
const getAll = async (fields = []) => {
const projection = {_id: 0};
fields.forEach((it) => {
projection[it] = 1;
});
return mongo.collection.find({}, {projection}).toArray();
};
exports.get = async (req, res) => {
try {
const {key} = req.params;
const {ttl} = req.query;
if (typeof key === 'undefined') {
res.status(400).send('Bad request');
return;
}
const data = await getOne(key);
if (data !== null) {
console.info(`Cache HIT. "${data.value}"`);
res.status(200).send(data.value);
await updateOne(key, getValue(data.value, data.ttl));
return data.value;
}
const newVal = await getRandomString();
console.info(`Cache MISS. New value created "${newVal}"`);
await updateOne(key, getValue(newVal, ttl));
res.status(201).send(newVal);
return newVal;
} catch (ex) {
console.error(ex);
res.status(500).send('Something went wrong!');
}
};
exports.getKeys = async (req, res) => {
try {
const data = await getAll(['key']);
const result = data.map((it) => it.key);
res.status(200).send(result);
return result;
} catch (ex) {
res.status(500).send('Something went wrong!');
}
};
exports.getAll = async (req, res) => {
try {
const data = await getAll(['key', 'value', 'ttl']);
const result = data.map((it) => {
return {
key: it.key,
value: it.value,
ttl: it.ttl,
};
});
res.status(200).send(result);
return result;
} catch (ex) {
res.status(500).send('Something went wrong!');
}
};
exports.set = async (req, res) => {
try {
const {key} = req.params;
const value = req.body;
const {ttl} = req.query;
if (typeof key === 'undefined' || typeof value === 'undefined') {
res.status(400).send('Bad request');
return;
}
await updateOne(key, getValue(value, ttl));
res.status(201).send('Ok');
} catch (ex) {
res.status(500).send('Something went wrong!');
}
};
exports.delete = async (req, res) => {
try {
const {key} = req.params;
if (typeof key === 'undefined') {
res.status(400).send('Bad request');
return;
}
const {deletedCount} = await deleteOne(key);
if (deletedCount) {
res.status(204).end();
return;
}
res.status(404).end(`Key "${key}" not found`);
} catch (ex) {
res.status(500).send('Something went wrong!');
}
};
exports.deleteAll = async (req, res) => {
try {
await deleteAll();
res.status(204).end();
} catch (ex) {
res.status(500).send('Something went wrong!');
}
};
| 31e05e7070d6e2b4dede5430ef372c6cd4bd196e | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | SkeLLLa/mongo-cache-example | 135ee84c861a3f4b6cadc179c6cfd0f776c47355 | 16c0653e82367662a46e16d43999935f4c1b1332 |
refs/heads/master | <repo_name>bladeyul/exercise<file_sep>/quota.py
from config import quota_file
import os
import re
#都按照G计数
class Quota(object):
def __init__(self):
pass
#比较函数
def __lt__(self,other):
return self.quota<other.quota
def setQuota(self,quota):
self.quota=self.quota
def getQuota(self,quota):
return self.quota
class UserQuota(Quota):
def __init__(self,path):
self.quota=0
with open(quota_file) as fo:
for line in fo.readlines:
data=line.split(",")
if path==data[0]:
self.quota=data[1]
break
class ActualQuota(Quota):
def __init__(self,path):
self.quota=0
cmd="df -sg "+path
res=os.system(cmd)
if res:
self.quota=int(res.split()[0])
class QuotaHandler(object):
def overControl(self,path):
if UserQuota(path)>ActualQuota(path):
FilePathController(path).acquire()
class FilePathController(object):
def __init__(self,path):
self.path=path
def acquire(self):
cmd="chattr +i "+self.path
return os.system(cmd)
def release(self):
cmd="chattr -i "+self.path
return os.system(cmd)
class Message(object):
def __init__(self,**kwargs):
pass
def setHandle(self,Handler):
self.handlers.append(Handler)
def connection(self):
if __name__=="__main__":
msgServer=Message(message_config)
msgServer.setHandle(QuotaHandler)
msgServer.listen()
<file_sep>/Design_pattern.py
#单例模式
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance=super(Singleton,cls).__new__(cls)
return cls.instance
#单例模式懒加载
class Singleton2(object):
__instance=None
def __init__(self):
if not Singleton2.__instance:
pass
else:
return self.getInstance()
@classmethod
def getInstance(cls):
if not cls.__instance:
cls.__instance=Singleton()
return cls.__instance
#Monostate模式
class Borg(object):
__shared_dict={}
def __init__(self):
self.__dict__=self.__shared_dict
class Borg2(object):
__shared_dict={}
def __new__(cls,*args,**kwargs):
obj=super(Borg,cls).__new__(cls,*args,**kwargs)
obj.__dict__=cls.__shared_dict
return obj
#基于元类的实现
class MetaSingleton(type):
_instances={}
def __call__(cls,*args,**kwargs):
if cls not in cls._instances:
cls._instances[cls]=super(MetaSingleton,cls).__call__(*args,**kwargs)
return cls._instances[cls]
#简单工厂模式
from abc import ABCMeta,abstractmethod
class Animal(metaclass=ABCMeta):
@abstractmethod
def do_say(self):
pass
class Dog(Animal):
def do_say(self):
print("wang wang")
class Cat(Animal):
def do_say(self):
print("Meow Meow")
class ForestFactory(object):
def make_sound(self,object_type):
return eval(object_type().do_say())
#工厂方法
class Section(metaclass=ABCMeta):
@abstractmethod
def describe(self):
pass
class PersonalSection(Section):
def describe(self):
print("PersonalSection")
class AlbumSection(Section):
def describe(self):
print("AlbumSection")
class PatentSection(Section):
def describe(self):
print("PatentSection")
class PublicationSection(Section):
def describe(self):
print("PublicationSection")
class Profile(metaclass=ABCMeta):
def __init__(self):
self.sections=[]
self.createProfile()
@abstractmethod
def createProfile(self):
pass
def getSections(self):
return self.sections
def addSections(self,section):
self.sections.append(section)
class Linkedin(Profile):
def createProfile(self):
self.addSections(PersonalSection())
self.addSections(PatentSection())
self.addSections(PublicationSection())
class Facebook(Profile):
def createProfile(self):
self.addSections(PersonalSection())
self.addSections(AlbumSection())
#抽象工厂模式
class PizzaFactory(metaclass=ABCMeta):
@abstractmethod
def createVegPizza(self):
pass
@abstractmethod
def createNonVegPizz(self):
pass
class IndiaPizzaFactory(PizzaFactory):
def createVegPizza(self):
return DeluxVeggiePizza()
def createNoneVegPizza(self):
return ChickenPizza()
class USPizzaFactory(PizzaFactory):
def createVegPizza(self):
return MexicanVegPizza()
def crateNonVegPizza(self):
return HanPizza()
class VegPizza(metaclass=ABCMeta):
@abstractmethod
def prepare(self,VegPizza):
pass
class NonVegPizza(metaclass=ABCMeta):
@abstractmethod
def serve(self,VegPizza):
pass
class DeluxVeggiePizza(VegPizza):
def prepare(self):
print(type(self).__name__)
class ChickenPizza(NonVegPizza):
def serve(self,VegPizza):
print(type(self).__name__,type(VegPizza).__name__)
class MexicanVegPizza(VegPizza):
def prepare(self):
print(type(self).__name__)
class HanPizza(NonVegPizza):
def serve(self,VegPizza):
print(type(self).__name__,type(VegPizza).__name__)
class PizzaStore:
def __init__(self):
pass
def makePizzas(self):
for factory in [IndiaPizzaFactory(),USPizzaFactory()]:
self.factory=factory
self.NoneVegPizza=self.factory.createNonVegPizz()
self.VegPizza=section.factory.createVegPizza()
self.VegPizza.prepare()
self.NoneVegPizza.serve(self.VegPizza)
#门面模式
class EventManager(object):
def __init__(self):
pass
def arrange(self):
self.hotelier=Hotelier()
self.hotelier.bookHotel()
self.florist=Florist()
self.florist.setFlowerRequirements()
self.caterer=Caterer()
self.caterer.setCuisine()
self.musician=Musician()
self.musician.setMusicType()
class Hotelier(object):
def __init__(self):
pass
def __isAvailable(self):
return True
def bookHotel(self):
if self.__isAvailable():
pass
class Floriest(object):
def setFlowRequirements(self):
pass
class Caterer:
def setCuisine(self):
pass
class Musician(object):
def setMusicType(self):
pass
class You(object):
def askEventManager(self):
em=EventManager()
em.arrange()
#代理模式
class Actor(object):
def __init__(self):
self.isBusy=False
def occupied(self):
self.isBusy=True
def avaliable(self):
self.isBusy=False
def getStatus(self):
return self.isBusy
class Agent(object):
def __init__(self):
self.principal=None
def work(self):
self.actor=Actor()
if self.actor.getStatus:
self.actor.occupied()
else:
self.actor.avaliable()
#代理模式
class You:
def __init__(self):
self.debitCard=DebitCard()
self.isPurchased=None
def make_payment(self):
self.isPurchased=self.debitCard.do_pay()
class Payment(metaclass=ABCMeta):
@abstractmethod
def do_pay(self):
pass
class Bank(Payment):
def __init__(self):
self.card=None
self.account=None
def __getAccount(self):
self.account=self.card
return self.account
def __hasFunds(self):
return True
def setCard(self,card):
self.card=card
def do_pay(self):
if self.__hasFunds()
return True
else:
return False
class DebitCard(Payment):
def __init__(self):
self.bank=Bank()
def do_pay(self):
self.bank.setCard(card)
return self.bank.do_pay()
#观察者模式
class Subject:
def __init__(self):
self.__observers=[]
def register(self,observer):
self.__observers.append(observer)
def notifyAll(self,*args,**kwargs):
for observer in self.__observers:
observer.notify(self,*args,**kwargs)
class Observer1:
def __init__(self,subject):
subject.register(self)
def notify(self,subject,*args):
print(type(self).__name__)
class Observer2:
def __init__(self,subject):
subject.register(self)
def notify(self,subject,*args):
print(type(self).__name__)
class NewPublisher:
def __init__(self):
self.__subscribes=[]
self.__latestNews=None
def attatch(self,subscriber):
self.__subscribes.append(subscriber)
def detach(self):
return self.__subscribes.pop()
def subscribes(self):
return [type(x).__name__ for x in self.__subscribers]
def notifySubscribers(self):
for sub in self.__subscribes:
sub.update()
def addNews(self,news):
self.__latestNews=news
def getNews(self):
return self.__latestNews
class Subscriber(metaclass=ABCMeta):
@abstractmethod
def update(self):
pass
class SMSSubscriber:
def __init__(self,publisher):
self.publisher=publisher
self.publisher.attatch(self)
def update(self):
print(self.publisher.getNews())
class EmailSubscriber:
def __init__(self,publisher):
self.publisher=publisher
self.publisher.attatch(self)
def update(self):
print(self.publisher.getNews())
class AnyOtherSubscriber:
def __init__(self,publisher):
self.publisher=publisher
self.publisher.attache(self)
def update(self):
print(self.publisher.getNews())
#命令模式
class Wizard():
def __init__(self,src,rootdir):
self.choices=[]
self.rootdir=rootdir
self.src=src
def preferences(self,command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
if list(choice.valus())[0]:
print()
class Command(metaclass=ABCMeta):
def __init__(self,recv):
self.recv=recv
def execute(self):
pass
class ConcreteCommand(Command):
def __init__(self,recv):
self.recv=recv
def execute(self):
self.recv.action()
class Receiver:
def action(self):
print("receive")
class Invoker:
def command(self,cmd):
self.cmd=cmd
def execute(self):
self.cmd.execute()
class Order(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class BusyStockOrder(Order):
def __init__(self,stock):
self.stock=stock
def execute(self):
self.stock.buy()
class SellStockOrder(Order):
def __init__(self,stock):
self.stock=stock
def execute(self):
self.stock.sell()
class StockTrade:
def buy(self):
print("buy")
def sell(self):
print("sell")
class Agent:
def __init__(self):
self.__orderQueue=[]
def placeOrder(self,order):
self.__orderQueue.append(order)
order.execute()
#模板方法
class Compiler(metaclass=ABCMeta):
@abstractmethod
def collectSource(self):
pass
@abstractmethod
def compileToObject(self):
pass
@abstractmethod
def run(self):
pass
def compileAndRun(self):
self.collectSource()
self.compileToObject()
self.run()
class IOSCompiler(Compiler):
def collectSource(self):
print("collect source")
def compileToObject(self):
prit("compiling code")
def run(self):
print("run")
class Trip(metaclass=ABCMeta):
@abstractmethod
def setTransport(self):
pass
@abstractmethod
def day1(self):
pass
@abstractmethod
def day2(self):
pass
@abstractmethod
def day3(self):
pass
@abstractmethod
def returnHome(self):
pass
def itinerary(self):
self.setTransport()
self.day1()
self.day2()
self.day3()
self.returnHome()
class VeniceTrip(Trip):
def setTransport(self):
print("transport")
def day1(self):
print("day1")
def day2(self):
print("day2")
def day3(self):
print("day3")
def returnHome(self):
print("get home")
class MaldivesTrip(Trip):
def setTransport(self):
print("transport")
def day1(self):
print("day1")
def day2(self):
print("day2")
def day3(self):
print("day3")
def returnHome(self):
print("get home")
class TravelAgency:
def arrange_trip(self,choice):
if choice=="historical":
self.trip=VeniceTrip()
self.trip.itinerary()
#MVC模式
class Model(object):
services={
'email':{'number':1000,'prices':2,},
'sms':{'number':1000,'proce':10,},
'voice':{'number':1000,'proce':15,},
}
class View(object):
def list_services(self,services):
for svc in services:
print(svc)
def list_pricing(self,services):
for svc in services:
print(Model.services[svc]['number'],
Model.services[svc]['price'])
class Controller(object):
def __init__(self):
self.model=Model()
self.view=View()
def get_services(self):
services=self.model.services.keys()
return (self.view.list_services(services))
def get_pricing(self):
services=self.model.services.keys()
return (self.view.list_pricing(services))
class Client:
controller=Controller()
controller.get_services()
controller.get_pricing()
#状态模式
class State(metaclass=ABCMeta):
@abstractmethod
def Handle(self):
pass
class ConcreteStateB(State):
def Handle(self):
print("ConcreteStateB")
class ConcreteStateA(State):
def Handle(self):
print("ConcreteStateA")
class Context(State):
def __init__(self):
self.state=None
def getState(self):
return self.state
def setState(self,state):
self.state=state
def Handle(self):
self.state.Handle()
class State(metaclass=ABCMeta):
@abstractmethod
def doThis(self):
pass
class StartState(State):
def doThis(self):
print("TV switch on")
class StopState(State):
def doThis(self):
print("Tv switch off")
class TVContext(State):
def __init__(self):
self.state=None
def getState(self):
return self.state
def setState(self,state):
self.state=state
def doThis(self):
self.state.doThis()
class ComputerState(object):
name="state"
allowd=[]
def switch(self,state):
if state.name in self.allowd:
self.__class__=state
else:
print("cannot switch "+state.name)
def __str__(self):
return self.name
class Off(ComputerState):
name="off"
allowed=['on']
class On(ComputerState):
name='on'
allowed=['off','suspend','hibernate']
class Suspend(ComputerState):
name="suspend"
allowd=['on']
class Hibernate(ComputerState):
name="hibernate"
allowd=['on']
class Computer(object):
def __init__(self,model='HP'):
self.model=model
self.state=Off()
def change(self,state):
self.state.switch(state)
<file_sep>/设计模式.md
面向对象的主要概念:
1、封装,外部不可见
2、多态,输入参数不同,实现不同
3、继承,重用基类
4、抽象,提供简单的客户端接口
5、组合,调用其他类及其函数
面向对象的原则
1、开放、封闭原则,开放扩展,封闭修改
2、控制反转原则,细节依赖于抽象,依赖模块之间有一个明确的抽象层
3、接口隔离原则,客户端不应该依赖于不需要的接口
4、单一职责原则,类的职责单一,引起类变化的原因单一
5、替换原则原则,派生类完全取代基类
创建型模式
1、运行机制基于对象的创建方式
2、创建细节隔离
3、与创建的类型无关
结构型模式
1、组合可获得更强大功能的对象和类
2、简化结构,识别类和对象之间的关系
3、关注类的继承和组合
行为型模式
1、关注对象之间的交互与对象的响应
2、对象交互的同时保持松散耦合
单例模式
1、日志记录、数据库操作、资源等操作
2、确保类有且只有一个对象被创建
3、提供一个全局访问点
4、控制共享资源的并行访问
5、模块导入是单例模式
6、缺点:
1、全局变量的耦合性很高
2、同一个对象可能有多个引用
工厂模式
1、松耦合,对象创建独立于类的实现
2、简化客户端的实现
3、轻松创建其他对象
4、重用现有对象
5、简单工厂模式
6、工厂模式
1、灵活性更好
2、松耦合
7、抽象工厂方法
1、包含一个或多个工厂方法
2、使用组合将创建对象的任务委托给其他类
3、创建相关产品的系列
迪米特法则:
1、每个单元对系统中其他单元知道的越少越好
2、单位只与其朋友交流
3、单元不知道操作的对象的内部细节
代理模式:
1、以简单的方式表示复杂的系统
2、提高对象的安全性
3、为远程对象提供本地接口
4、为大资源对象提供句柄
5、虚拟代理:缩略图
6、远程代理:
7、保护代理
8、智能代理
观察者模式:
1、对象之间一对多依赖关系
2、封装主题核心组件
3、分布式系统中事件服务
4、股票市场
5、拉模型
主题对观察者进行广播
观察者拉取数据
6、推模型
主题直接向观察者发送详细信息
7、交互的对象之间保持松耦合
8、无需修改时,发送数据交互
9、随时增减观察者
10、缺点
1、接口必须由具体观察者实现
2、通知的不可靠性,导致竞争条件或不一致
命令模式
1、请求封装为对象;
2、不同的请求对客户进行参数化
3、允许将请求保存在队列中
4、提供面向对象的回调
5、重做或回滚
6、异步任务执行
7、优点:
调用的类与执行的类解耦
提供队列后,可以创建一系列命令
添加命令方便
可以定义回滚系统
8、缺点:
1、增加了需要维护的类的数量
模版方法模式
1、使用基本操作定义算法框架
2、代码重用并避免重复工作
3、重新定义子类的某些操作
4、利用通用接口或实现
5、优点:
代码重复少
灵活性
6、缺点:
流程序列有点困惑
模版的维护比较麻烦
MVC模式
1、数据和展示隔离
2、类的维护和实现简单
3、灵活改变存储和显示
4、优点:
提高可维护性,强制松耦合,降低复杂性
状态设计模式
1、开发有限状态机
2、易于添加状态来支持额外的行为
3、提高了聚合性
4、提高了代码的可维护性
5、缺点:
1、类爆炸
2、上下文行为更容易受到新行为的影响
不良设计:
1、不动性
2、刚性
3、脆弱性
4、粘滞性
5、反模式
软件开发反模式
1、意大利面条式代码
2、金锤
3、熔岩流
4、复制粘贴式编程
软件架构反模式
1、重新发明轮子
2、供应商套牢
3、委员会设计
| cb1d94103b4af02be2001be3bd7a6dcd9ca78adf | [
"Markdown",
"Python"
] | 3 | Python | bladeyul/exercise | c3ff21a4a2613ae1ade9c37d27a4dc7733729638 | acbec42c03ef1f05ae5bdabe42f82f984bf042d9 |
refs/heads/master | <file_sep>import sys
a2 = a1 = None
in_header = True
while (in_header):
line = sys.stdin.readline()
if line.startswith("ATOM") or line.startswith("HETATM"):
in_header = False
eof = False
atoms = []
bonds = []
angles = []
abs_bonds = []
abs_angles = []
order = ["C1", "H1", "H2", "H3", "H4"]
atoms_per_molecule = len(order)
atom_index = 0
relative_bonds = [[1,2],[1,3],[1,4],[1,5]]
relative_angles = [[2,1,3],[2,1,4],[2,1,5],[3,1,4],[3,1,5],[4,1,5]]
num_molecules = 0
while (line):
v = [line[:6], line[6:11], line[12:16], line[17:20], line[21], line[22:26], line[30:38], line[38:46], line[46:54]]
a = {'atom_id': v[1], 'local_index': v[2].strip(), 'molecule_id': v[5], 'x': v[6], 'y': v[7], 'z': v[8]}
# last molucule in file should be the total number
num_molecules = v[5]
# IMPORTANT: these checks are important to make sure that the file is ordered as we expect
# otherwise, when we extrapolate the atoms to types, they will not be correct.
atom_index += 1
# make sure our expected atom_index equals the index in file
assert atom_index == int(v[1])
# make sure our expected order equals order in file
assert order[(atom_index - 1) % atoms_per_molecule] == v[2].strip()
if a['local_index'] == "C1":
a['atom_type'] = "1"
a['charge'] = "-0.542"
else:
a['atom_type'] = "2"
a['charge'] = "0.135"
atoms += [" ".join([a['atom_id'], a['molecule_id'], a['atom_type'], a['charge'], a['x'], a['y'], a['z']])]
line = sys.stdin.readline()
if not line.startswith("ATOM") and not line.startswith("HETATM"):
line = None
assert atom_index % atoms_per_molecule == 0
for m in range(0, int(num_molecules)):
a0 = m * atoms_per_molecule # starting atom index
abs_bonds += [[str(x[0] + a0), str(x[1] + a0)] for x in relative_bonds]
abs_angles += [[str(x[0] + a0), str(x[1] + a0), str(x[2] + a0)] for x in relative_angles]
bonds = [" ".join([str(i), "1", *x]) for i,x in enumerate(abs_bonds)]
angles = [" ".join([str(i), "1", *x]) for i,x in enumerate(abs_angles)]
print("# lammps data file generated from packed_methane_pdb_to_lammps.py")
print("%s atoms" % len(atoms))
print("%s bonds" % len(bonds))
print("%s angles" % len(angles))
print("\n\n Atoms\n\n" + "\n".join(atoms))
print("\n\n Bonds\n\n" + "\n".join(bonds))
print("\n\n Angles\n\n" + "\n".join(angles))
<file_sep>
import h5py
from molmod.io.fchk import FCHKFile
from quickff.program import DeriveDiagFF, DeriveNonDiagFF
from quickff.reference import SecondOrderTaylor, get_ei_ff
from quickff.tools import guess_ffatypes
from yaff import System
fchk = FCHKFile('../qff_inputs/ch4.fchk')
numbers = fchk.fields.get('Atomic numbers')
energy = fchk.fields.get('Total Energy')
coords = fchk.fields.get('Current cartesian coordinates').reshape([len(numbers), 3])
grad = fchk.fields.get('Cartesian Gradient').reshape([len(numbers), 3])
hess = fchk.get_hessian().reshape([len(numbers), 3, len(numbers), 3])
system = System(numbers, coords)
system.detect_bonds() # doesn't change anything?
system.set_standard_masses() # doesn't change anything?
#Construct a QuickFF SecondOrderTaylor object containing the AI reference
ai = SecondOrderTaylor('ai', coords=coords, energy=energy, grad=grad, hess=hess)
guess_ffatypes(system, 'low')
#construct electrostatic force field from HE charges in gaussian_wpart.h5
f = h5py.File('../qff_inputs/ch4.h5')
charges = f['charges'][:]
scales = [0.0, 0.0, 0.5, 1.0]
ff_ei = get_ei_ff('EI', system, charges, scales, radii=None, average=True, pbc=[0,0,0])
#initialize and run program
program = DeriveDiagFF(system, ai, ffrefs=[ff_ei], fn_yaff='pars_cov.txt', plot_traj=True, xyz_traj=True)
program.run()
<file_sep>from yaff import System
from molmod.io.fchk import FCHKFile
import numpy as np
from quickff.reference import SecondOrderTaylor, get_ei_ff
from quickff.program import BaseProgram
from quickff.log import log
import h5py
#define class for deriving the force field
class Program(BaseProgram):
def run(self):
with log.section('PROGRAM', 2):
#deriving diagonal force field
self.do_pt_generate()
self.do_pt_estimate()
self.average_pars()
self.do_hc_estimatefc(['HC_FC_DIAG'])
#adding and fitting cross terms
self.do_cross_init()
self.do_hc_estimatefc(['HC_FC_CROSS'], logger_level=1)
#write output
self.make_output()
#load Gaussian Formatted Checkpoint file
fchk = FCHKFile('./output.fchk')
numbers = fchk.fields.get('Atomic numbers')
energy = fchk.fields.get('Total Energy')
coords = fchk.fields.get('Current cartesian coordinates').reshape([len(numbers), 3])
grad = fchk.fields.get('Cartesian Gradient').reshape([len(numbers), 3])
with open("./methane.psi.ch4.66427.hess") as f:
f.readline()
lines = f.readlines()
elements = np.array([line.split() for line in lines]).ravel()
elements = np.array([float(e) for e in elements])
hess = elements.reshape([len(numbers), 3, len(numbers), 3])
# hess = fchk.get_hessian().reshape([len(numbers), 3, len(numbers), 3])
#Construct Yaff System file
system = System(numbers, coords)
system.detect_bonds()
system.set_standard_masses()
#Construct a QuickFF SecondOrderTaylor object containing the AI reference
ai = SecondOrderTaylor('ai', coords=coords, energy=energy, grad=grad, hess=hess)
#define atom types
rules = [
('H', '1 & =1%6'), #hydrogen atom with one oxygen neighbor
('C', '6 & =4%1'), #oxygen atom with two hydrogen neighbors
]
system.detect_ffatypes(rules)
#construct electrostatic force field from HE charges in gaussian_wpart.h5
f = h5py.File('./wpart_mbis.h5')
charges = f['charges'][:]
scales = [1.0, 1.0, 1.0, 1.0]
ff_ei = get_ei_ff('EI', system, charges, scales, radii=None, average=True, pbc=[0,0,0])
#initialize and run program
program = Program(system, ai, ffrefs=[ff_ei], fn_yaff='pars_cov.txt', plot_traj=True, xyz_traj=True)
program.run()
<file_sep>
# import numpy as np
from quickff.program import Program
from quickff.system import System
from quickff.model import Model
system = System.from_files(['qff_inputs/ch4.fchk', 'qff_inputs/ch4.h5'], ei_path='')
system.read_uff_vdw() # doesn't seem to affect much with CH4
system.guess_ffatypes('low')
system.determine_ics_from_topology()
model = Model.from_system(system,
ei_pot_kind='HarmPoint',
vdw_pot_kind='HarmLJ',
ic_ids=['bonds', 'bends'],
ei_scales=[0.0,0.0,0.5,1.0],
vdw_scales=[0.0,0.0,0.5,1.0]
)
#initialize and run program
program = Program(system, model)
program.run()
<file_sep># QuickFF Force Field Fit on Methane - Test
## QuickFF
This is _close_ to what we want, but assumes a scale of [1,1,1,1] instead of [0.0, 0.0, 0.5, 1.0]. We are using the programatic interface still due to this lack of configuration options.
```
qff-input-ei.py --ffatypes="low" -o ei_pars.yaff ./qff_inputs/ch4.fchk ./qff_inputs/ch4.h5 '/'
qff.py -m "DeriveDiagFF" --ei=ei_pars.yaff --ffatypes=low ./qff_inputs/ch4.fchk
```
Actual run instructions:
```
cd results && python ../qff2-derive-gaussian.py
```
Results should look like:
```
BondHarm/C.H (kjmol/A^2 A)
fc = 3072 ± .000 rv = 1.093 ± .132
BendAHarm/H.C.H (kjmol/rad^2 deg)
fc = 276.7 ± .000 rv = 109.4 ± .001
```
Notes:
- For CH4, VDW and EI interactions make no difference when using the scales [0.0, 0.0, 0.5, 1.0]
because there are no 1-4, 1-5 pairs.
- Using the DeriveNonDiagFF (i.e. with cross terms) does change the produced parameters.
## Packmol / LAMMPS
IMPORTANT: The LAMMPS input file lamps-NPT.input needs to be manually updated with the FF parameters
from QuickFF!
```
mkdir results
~/workspace/packmol/packmol < ./packmol-methane.txt
python3 ./packed_methane_pdb_to_lammps.py < ./results/methane2087.pdb > ./results/methane2087.data
# ADD THE CORRECT HEADER INFO to the data file
cd results && ~/workspace/lammps/src/lmp_serial < ../lammps-NPT.input
```
| ebe2e06de96d9be36a9b1808cdd0dcc95ff06dfd | [
"Markdown",
"Python"
] | 5 | Python | paulboone/qff-methane-test | e0e9b2aee3ce901adb7bbbd14728774d100e760a | ad715b14bba05f69537b925d26b062312993e43e |
refs/heads/master | <file_sep>package com.example.coroutinesfirst.First
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
//fun main() {
// GlobalScope.launch {
// delay(1000L)
// println("hello")
// }
//
// println("word")
// Thread.sleep(3000L)
//}
//fun main() {
// val start = System.currentTimeMillis()
// runBlocking {
// repeat(1_000_000){
// launch {
// println("hello")
// }
// }
// }
// val end = System.currentTimeMillis()
// println("Time : ${end-start} ms")
//}<file_sep>package com.example.coroutinesfirst.CoroutinesContext
import android.util.Log
import com.example.coroutinesfirst.MainActivity
import kotlinx.coroutines.*
object TestDispatchers {
fun TestDispatchersOne(){
// GlobalScope.launch(Dispatchers.Default){
// Log.d(MainActivity::class.java.simpleName, "Default run in ${Thread.currentThread().name}")
// }
// GlobalScope.launch(Dispatchers.IO){
// Log.d(MainActivity::class.java.simpleName, "IO run in ${Thread.currentThread().name}")
// }
// GlobalScope.launch(Dispatchers.Unconfined){
// Log.d(MainActivity::class.java.simpleName, "befor Unconfined run in ${Thread.currentThread().name}")
// delay(1000)
// Log.d(MainActivity::class.java.simpleName, "Unconfined run in ${Thread.currentThread().name}")
// }
// GlobalScope.launch(Dispatchers.Main){
// Log.d(MainActivity::class.java.simpleName, "Main run in ${Thread.currentThread().name}")
// }
// GlobalScope.launch(newSingleThreadContext("my thread")){
// Log.d(MainActivity::class.java.simpleName, "run in ${Thread.currentThread().name}")
// }
}
}<file_sep>package com.example.coroutinesfirst
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.coroutinesfirst.CoroutinesContext.TestDispatchers
import com.example.coroutinesfirst.CoroutinesContext.TestWithContext
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
TestWithContext.Test()
}
}<file_sep>package com.example.coroutinesfirst.CoroutinesContext
import kotlinx.coroutines.*
object TestWithContext {
fun Test() {
runBlocking {
val job = launch {
try {
repeat(1000) {
delay(100)
println("hello coroutines")
}
} finally {
println("frint finally")
withContext(NonCancellable) {
repeat(2){
delay(100)
println("non $it")
}
}
}
}
delay(1000)
job.cancel()
println("cancel coroutines")
}
}
} | 0a63e38305c86cc23b86d3018d4c568c44dc9ec2 | [
"Kotlin"
] | 4 | Kotlin | tienclever/Test_coroutines | 05ea0f4711dbb8255534c081dd1e0d1e495a65e8 | 1ddd7036ec3bfe4c1216ad4518783c5ade96e751 |
refs/heads/master | <repo_name>uc-cdis/indexclient<file_sep>/indexclient/parsers/delete.py
import sys
import json
import logging
import argparse
import requests
from indexclient.errors import BaseIndexError
def delete_record(host, port, did, rev, **kwargs):
"""
Create a new record.
"""
resource = "http://{host}:{port}/index/{did}".format(host=host, port=port, did=did)
params = {"rev": rev}
res = requests.delete(resource, params=params)
try:
res.raise_for_status()
except Exception as err:
raise BaseIndexError(res.status_code, res.text)
def config(parser):
"""
Configure the delete command.
"""
parser.set_defaults(func=delete_record)
parser.add_argument("did", help="id of record to delete")
parser.add_argument("rev", help="current revision of record")
<file_sep>/Pipfile
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[packages]
requests = "*"
indexclient = {editable = true, path = "."}
[dev-packages]
pytest = "*"
mock = "*"
cdisutilstest = {editable = true, git = "https://github.com/uc-cdis/cdisutils-test.git", ref = "1.0.0"}
indexd = {git = "https://github.com/uc-cdis/indexd.git", ref = "5.0.1"}
[requires]
python_version = "3.9"
<file_sep>/README.md
Indexclient
===
 [](LICENSE) [](https://travis-ci.org/uc-cdis/indexclient)
Indexclient is a prototype data indexing and tracking client. It is intended to
provide a simple means of interactively investigating
[indexd](https://github.com/LabAdvComp/indexd) deployments. It is built upon
a basic REST-like API and demonstrates how a client utility can be built to
interact with the index in a meaningful manner.
## Installation
The prototype implementation for the client is requests based. This
provides a minimum list of requirements and allows for deployment on a wide
range of systems with next to no configuration overhead. That said, it is
highly recommended to use pip and a virtualenv to isolate the installation.
To install the prototype implementation, simply run
```bash
pip install .
```
## Configuration
At present, all configuration options are hard-coded in the prototype. This
will be subject to change in the future, as options are moved to configuration
files. Until that time, the primary hard-coded configurations to keep in
mind is the index host and port combination.
```python
HOST = 'localhost'
PORT = 8080
```
## Index Records
Records are collections of information necessary to as-uniquely-as-possible
identify a piece of information. This is done through the use of hashes and
metadata. Records are assigned a UUIDv4 at the time of creation. This allows
records to be uniquely referenced amongst multiple records. To prevent an
update conflict when multiple systems are editing the same record, a revision
is stored and changed for every update. This is an opaque string and is
not used for anything other than avoiding update conflicts.
Hashes used by the index are deployment specific, but are intended to be the
results of widely known and commonly available hashing algorithms, such as
MD5 or SHA1. This is similar to the way that torrents are tracked, and provides
a mechanism by which data can be safely retrieved from potentially untrusted
sources in a secure manner.
Additional metadata that is store in index records include the size of the
data as well as the type.
Records adhere to the json-schema described in [indexd](https://github.com/LabAdvComp/indexd/blob/master/indexd/index/schema.py#L1):
An example of one such record:
```json
{
"id": "119d292f-b786-421e-a8dd-72208e77c269",
"rev": "dbee8496-5d03-4fbd-9115-6871c4ebf59f",
"size": 512,
"hash": {
"md5": "e2a3a55aa1596f87f502c8ff29d74244",
"sha1": "cb4e5ba5d30fd4667beba95bf73ea9d76ad3dcd4",
"sha256": "20b599fa98f5f98e89e128ba6de3b65ff753c662721f368649fb8d7e7d4933b0"
},
"type": "object",
"urls": [
"s3://endpointurl/bucket/key"
]
}
```
## Making Queries
All queries to the index are made through HTTP using JSON data payloads.
This gives a simple means of interaction that is easily accessible to any
number of languages.
These queries are handled via requests and wrapped into the index client.
### Create a record
#### Method: `create`
Example:
```python
indexclient.create(
hashes = {'md5': ab167e49d25b488939b1ede42752458b'},
size = 5,
# optional arguments
acl = ["a", "b"]
)
```
### Retrieve a record
#### Method: `get`
Example:
```python
indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
```
#### Method: `global_get`
Example:
```python
indexclient.global_get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
```
or
```python
indexclient.global_get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e", no_dist=True)
```
`global_get` can also be used to retrieve records by alias. See [Add an alias for a record](#add-an-alias-for-a-record).
```python
# Retrieve a document by its alias, "10.1000/182"
doc = indexclient.global_get("10.1000/182")
print(doc.did) # >> "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"
```
#### Method: `get_with_params`
Example:
```python
params = {
'hashes': {'md5': ab167e49d25b488939b1ede42752458b'},
'size': 5
# or any other params (metadata, acl, authz, etc.)
}
indexclient.get_with_params(params)
```
### Retrieve multiple records
#### Method: `bulk_request`
Example:
```python
dids = [
"03eed607-acb0-4532-b0ee-9e3766b1aa6e",
"15684515-15b0-4532-b0ee-9e3766b65515",
"03ee4857-acb0-4123-b0ee-9e3766bffa23",
"1258d607-acb0-4532-b0ee-9e3766bffa23"
]
indexclient.bulk_request(dids)
```
### Update a record
First: get a Document object of the desired record with one of the get methods
Second: Update any of the records updatable attributes.
- the format to do this is: `doc.attr = value`
- eg: `doc.file_name = new_file_name`
- Updatable attributes are: file_name urls, version, metadata, acl, authz, urls_metadata, uploader
Lastly: Update all the local changes that were made to indexd using the
Document patch method: doc.patch()
Example:
```python
doc = indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"')
# or any other get method (global_get, etc.)
doc.metadata["dummy_field"] = "dummy var"
doc.acl = ['a', 'b']
doc.version = '2'
doc.patch()
```
### Delete a record
First: get a Document object of the desired record with one of the get methods
Second: Delete the record from indexd with the delete method: `doc.delete()`
Lastly: Check if the record was deleted with: `if doc._deleted`
Example:
```python
doc = indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
# or any other get method (global_get, etc.)
doc.delete()
if doc._deleted == False:
return "Record is not deleted"
```
### Add an alias for a record
You can use `indexclient` to create aliases for documents in `indexd`, which enable you to retrieve documents by the alias instead of by the Document identifier (`did` / `GUID`). Aliases can be created using `indexclient.add_alias_for_did(alias=alias, did=did)` and can be retrieved using `indexclient.global_get(alias)`.
Example:
```python
res = indexclient.add_alias_for_did("10.1000/182", "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
if res.status_code != 200:
# alias creation failed -- handle error
doc = indexclient.global_get("10.1000/182")
print(doc.did) # >> "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"
```
<file_sep>/bin/index
#!/usr/bin/env python
import sys
import json
import logging
import argparse
try:
from urllib import parse as urlparse
except ImportError: # Python 2.x
import urlparse
import requests
from index import errors
from index.parsers import info
from index.parsers import name
from index.parsers import search
from index.parsers import create
from index.parsers import retrieve
from index.parsers import update
from index.parsers import delete
def setup_logging(log_levels, log_stream, **kwargs):
"""
Sets up basic logging.
"""
logging.basicConfig(
level=min(log_levels), stream=log_stream,
)
def not_implemented(*args, **kwargs):
"""
Simply raises a NotImplementedError.
"""
raise NotImplementedError("this feature has not been implemented")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.set_defaults(log_levels=[logging.ERROR])
parser.add_argument(
"--debug",
action="append_const",
dest="log_levels",
const=logging.DEBUG,
help="enable debugging logs",
)
parser.add_argument(
"--verbose",
action="append_const",
dest="log_levels",
const=logging.INFO,
help="enable verbose logs",
)
parser.add_argument(
"--log",
dest="log_stream",
metavar="LOGFILE",
type=argparse.FileType("a"),
default=sys.stdout,
help="target log file",
)
parser.add_argument(
"--host", default="localhost", help="indexd server host [localhost]",
)
parser.add_argument(
"--port", default=8080, type=int, help="indexd server port [8080]",
)
# Add index and alias sub-commands.
subparsers = parser.add_subparsers(title="commands", dest="command",)
subparsers.required = True
info_subparser = subparsers.add_parser("info", help="retrieve information by name",)
info_subparser.set_defaults(func=not_implemented)
info.config(info_subparser)
name_subparser = subparsers.add_parser(
"name", help="create or update a name with information",
)
name_subparser.set_defaults(func=not_implemented)
name.config(name_subparser)
search_subparser = subparsers.add_parser("search", help="search for records",)
search_subparser.set_defaults(func=not_implemented)
search.config(search_subparser)
create_subparser = subparsers.add_parser("create", help="create a record",)
create_subparser.set_defaults(func=not_implemented)
create.config(create_subparser)
retrieve_subparser = subparsers.add_parser("retrieve", help="retrieve a record",)
retrieve_subparser.set_defaults(func=not_implemented)
retrieve.config(retrieve_subparser)
update_subparser = subparsers.add_parser("update", help="update a record",)
update_subparser.set_defaults(func=not_implemented)
update.config(update_subparser)
delete_subparser = subparsers.add_parser("delete", help="delete a record",)
delete_subparser.set_defaults(func=not_implemented)
delete.config(delete_subparser)
# Parse command line arguments and set up for execution.
args = parser.parse_args()
setup_logging(**args.__dict__)
logging.debug(args)
# Grab whatever function has been declared for use and pass it everything.
try:
args.__dict__.pop("func")(**args.__dict__)
except errors.BaseIndexError as err:
status = err.code
reason = str(err)
logging.error("{status}:{reason}".format(status=status, reason=reason))
sys.exit(1)
except requests.exceptions.ConnectionError as err:
logging.error("{reason}".format(reason="connection error"))
sys.exit(1)
<file_sep>/indexclient/parsers/search.py
import sys
import json
import logging
import argparse
import warnings
import requests
from indexclient import errors
def search_record(host, port, limit, start, size, hashes, **kwargs):
"""
Finds records matching specified search criteria.
"""
if size is not None and size < 0:
raise ValueError("size must be non-negative")
if limit is not None and limit < 0:
raise ValueError("limit must be non-negative")
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
hashes = [":".join([h, v]) for h, v in hash_dict.items()]
resource = "http://{host}:{port}/index/".format(host=host, port=port)
params = {"limit": limit, "start": start, "hash": hashes, "size": size}
res = requests.get(resource, params=params)
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def search_names(host, port, limit, start, size, hashes, **kwargs):
"""
Finds records matching specified search criteria.
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
if size is not None and size < 0:
raise ValueError("size must be non-negative")
if limit is not None and limit < 0:
raise ValueError("limit must be non-negative")
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
hashes = [":".join([h, v]) for h, v in hash_dict.items()]
resource = "http://{host}:{port}/alias/".format(host=host, port=port)
params = {"limit": limit, "start": start, "size": size, "hashes": hashes}
res = requests.get(resource, params=params)
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
def config(parser):
"""
Configure the search command.
"""
parser.set_defaults(func=search_record)
parser.add_argument(
"--names",
action="store_const",
const=search_names,
dest="func",
help="search names instead of records",
)
parser.add_argument(
"--limit", default=None, type=int, help="limit on number of ids to retrieve"
)
parser.add_argument("--start", default=None, help="starting id or alias")
parser.add_argument("--size", default=None, type=int, help="filter based on size")
parser.add_argument(
"--hash",
nargs=2,
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help="filter based on hash values",
)
parser.add_argument(
"--url", action="append", dest="urls", default=[], help="filter based on urls"
)
<file_sep>/setup.py
from subprocess import check_output
from setuptools import setup
def get_version():
# https://github.com/uc-cdis/dictionaryutils/pull/37#discussion_r257898408
try:
tag = check_output(
["git", "describe", "--tags", "--abbrev=0", "--match=[0-9]*"]
)
return tag.decode("utf-8").strip("\n")
except Exception:
raise RuntimeError(
"The version number cannot be extracted from git tag in this source "
"distribution; please either download the source from PyPI, or check out "
"from GitHub and make sure that the git CLI is available."
)
setup(
name="indexclient",
version=get_version(),
packages=["indexclient", "indexclient.parsers"],
install_requires=["requests>=2.5.2,<3.0.0"],
)
<file_sep>/tests/test_import.py
# Python 2 and 3 compatible
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def test_import_index():
"""
Try to import the index package.
"""
import indexclient
@patch("indexclient.client.handle_error")
@patch("requests.get")
def test_hashes(get_request_mock, handle_error_mock):
from indexclient.client import IndexClient
input_params = {"hashes": {"md5": "00000000000000000000000000000001"}, "size": "1"}
expected_format = {
"hash": ["md5:00000000000000000000000000000001"],
"size": "1",
"limit": 1,
}
with patch("indexclient.client.IndexClient._get") as get_mock:
client = IndexClient("base_url")
client.get_with_params(input_params)
assert get_mock.called
args, kwargs = get_mock.call_args_list[0]
assert kwargs["params"] == expected_format
<file_sep>/tests/test_client.py
import pytest
from cdisutilstest.code.indexd_fixture import (
create_random_index,
create_random_index_version,
)
from requests import HTTPError
def test_instantiate(index_client):
baseid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
urls = ["s3://url/bucket/key"]
urls_metadata = {url: {"state": "doing ok"} for url in urls}
size = 5
acl = ["a", "b"]
authz = ["/gen3/programs/a/projects/b"]
hashes = {"md5": "ab167e49d25b488939b1ede42752458b"}
doc = index_client.create(
hashes=hashes,
size=size,
urls=urls,
acl=acl,
authz=authz,
baseid=baseid,
urls_metadata=urls_metadata,
)
assert doc.size == 5
assert doc.hashes == hashes
assert doc.size == size
assert doc.urls == urls
assert doc.baseid == baseid
assert doc.urls_metadata == urls_metadata
assert doc.acl == acl
assert doc.authz == authz
def test_create_with_metadata(index_client):
urls = ["s3://bucket/key"]
urls_metadata = {"s3://bucket/key": {"k": "v"}}
size = 5
acl = ["a", "b"]
authz = ["/gen3/programs/a/projects/b"]
hashes = {"md5": "ab167e49d25b488939b1ede42752458b"}
metadata = {"test": "value"}
doc = index_client.create(
hashes=hashes,
size=size,
urls=urls,
acl=acl,
authz=authz,
metadata=metadata,
urls_metadata=urls_metadata,
)
assert doc.urls_metadata == urls_metadata
assert doc.metadata == metadata
def test_list_with_params(index_client):
hashes = {"md5": "ab167e49d25b488939b1ede42752458c"}
doc1 = create_random_index(index_client, hashes=hashes)
doc2 = create_random_index(index_client, hashes=hashes)
docs_with_hashes = index_client.list_with_params(
page_size=1, params={"hashes": hashes}
)
dids = [doc1.did, doc2.did]
found = []
for d in docs_with_hashes:
if d.did in dids:
found.append(d.did)
assert set(dids) == set(found)
def test_list_with_params_negate(index_client):
doc1 = create_random_index(index_client, version="1")
create_random_index(index_client, version="2")
docs = index_client.list_with_params(negate_params={"version": "2"})
dids = {record.did for record in docs}
assert dids == {doc1.did}
def test_get_latest_version(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
latest = index_client.get_latest_version(doc.did)
assert latest.did == doc.did
assert latest.file_name == doc.file_name
assert latest.hashes == doc.hashes
def test_get_latest_version_with_skip(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client, version="1")
doc_2 = create_random_index_version(index_client, did=doc.did)
v_doc = index_client.get_latest_version(doc_2.did, skip_null_versions=True)
assert v_doc.did == doc.did
assert v_doc.version == doc.version
assert v_doc.baseid == doc_2.baseid
@pytest.mark.parametrize("arg, exception", [("AAA", HTTPError), (None, TypeError)])
def test_invalid_input(arg, exception, index_client):
"""
Args:
arg(str): uuid
exception (Exception): Exception class
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
with pytest.raises(exception):
index_client.get_latest_version(arg)
def test_add_version(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
rev_doc = create_random_index_version(index_client, doc.did, version="1")
assert rev_doc.did is not doc.did
assert rev_doc.baseid == doc.baseid
assert rev_doc.version == "1"
latest = index_client.get_latest_version(doc.did)
assert latest.did == rev_doc.did
assert latest.version == "1"
def test_list_versions(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
# add a version
rev_doc = create_random_index_version(index_client, did=doc.did, version="1")
assert rev_doc is not None
# list versions
versions = index_client.list_versions(doc.did)
assert len(versions) == 2
def test_updating_metadata(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
doc.metadata["dummy_field"] = "Dummy Var"
doc.urls_metadata[doc.urls[0]] = {"a": "b"}
doc.patch()
same_doc = index_client.get(doc.did)
assert same_doc.metadata is not None
assert same_doc.metadata.get("dummy_field", None) == "Dummy Var"
assert same_doc.urls_metadata == {doc.urls[0]: {"a": "b"}}
def test_updating_acl(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
doc.acl = ["a"]
doc.patch()
same_doc = index_client.get(doc.did)
assert same_doc.acl == ["a"]
def test_updating_authz(index_client):
"""
Args:
index_client (indexclient.client.IndexClient): IndexClient Pytest Fixture
"""
doc = create_random_index(index_client)
doc.authz = ["/gen3/programs/a"]
doc.patch()
same_doc = index_client.get(doc.did)
assert same_doc.authz == ["/gen3/programs/a"]
def test_bulk_request(index_client):
dids = [create_random_index(index_client).did for _ in range(20)]
docs = index_client.bulk_request(dids)
for doc in docs:
assert doc.did in dids
def test_add_alias_for_did(index_client):
# Create a record in indexd and retrieve the did
did = create_random_index(index_client).did
# Add an alias for the did using indexclient
alias = "test_alias_123"
index_client.add_alias_for_did(alias, did)
# Confirm that we can retrieve the original document using this alias
# on the global_get endpoint
doc = index_client.global_get(alias)
assert doc is not None, "Failed to retrieve document {} using alias {}".format(
did, alias
)
assert doc.did == did, "Retrieved incorrect document {}, expected {}".format(
did, alias
)
<file_sep>/indexclient/parsers/name.py
import sys
import json
import argparse
import warnings
import requests
from indexclient import errors
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def name_record(
host, port, name, rev, size, hashes, release, metadata, hosts, keeper, **kwargs
):
"""
Alias a record.
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
resource = "http://{host}:{port}/alias/{name}".format(
host=host, port=port, name=name
)
params = {"rev": rev}
if size is not None and size < 0:
raise ValueError("size must be non-negative")
host_set = set(hosts)
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
data = {
"size": size,
"hashes": hash_dict,
"release": release,
"metadata": metadata,
"host_authorities": [h for h in host_set],
"keeper_authority": keeper,
}
res = requests.put(resource, params=params, json=data)
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
def config(parser):
"""
Configure the name command.
"""
parser.set_defaults(func=name_record)
parser.add_argument("name", help="name to assign")
parser.add_argument("rev", nargs="?", help="revision of name")
parser.add_argument(
"--size", default=None, type=int, help="size of underlying data"
)
parser.add_argument(
"--hash",
nargs=2,
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help="hash type and value",
)
parser.add_argument(
"--release",
choices=["public", "private", "controlled"],
help="data release type",
)
parser.add_argument("--metadata", help="metadata string")
parser.add_argument(
"--host", action="append", dest="hosts", default=[], help="host authority"
)
parser.add_argument("--keeper", help="data keeper authority")
<file_sep>/tests/test_document.py
import pytest
from indexclient.client import Document, recursive_sort
def create_document(
did=None,
hashes=None,
size=None,
file_name=None,
acl=None,
authz=None,
urls=None,
urls_metadata=None,
):
return Document(
None,
did,
json={
"hashes": hashes or {},
"size": size or 1,
"file_name": file_name or "file.txt",
"urls": urls or ["one", "two", "three"],
"acl": acl or ["1", "2", "3"],
"authz": authz or "/gen3/programs/1/projects/2/3",
"urls_metadata": urls_metadata
or {"one": {"1": "one"}, "two": {"2": "two"}, "three": {"3": "three"}},
},
)
def test_equals():
doc1 = create_document()
doc2 = create_document()
assert doc1 == doc2
# Out of order values are still equal because the contents are the same.
doc1.acl = ["4", "5"]
doc2.acl = ["5", "4"]
assert doc1 == doc2
def test_not_equals():
doc1 = create_document(acl=["1", "2"])
doc2 = create_document(acl=["2", "3"])
assert doc1 != doc2
def test_less_than():
doc1 = create_document(did="11111111-1111-1111-1111-111111111111")
doc2 = create_document(did="11111111-1111-1111-1111-111111111112")
assert doc1 < doc2
# reverse order docs
docs = [
create_document(did="11111111-1111-1111-1111-11111111111" + str(suffix))
for suffix in range(10, 0, -1)
]
# sorted() sorts it in order from lowest to highest did because of __lt__/__gt__
assert sorted(docs) == docs[::-1]
def test_greater_than():
doc1 = create_document(did="11111111-1111-1111-1111-111111111111")
doc2 = create_document(did="11111111-1111-1111-1111-111111111112")
assert doc2 > doc1
# reverse order docs
docs = [
create_document(did="11111111-1111-1111-1111-11111111111" + str(suffix))
for suffix in range(10, 0, -1)
]
# sorted() sorts it in order from lowest to highest did because of __lt__/__gt__
assert sorted(docs) == docs[::-1]
@pytest.mark.parametrize(
"given, expected",
[
(1, 1),
("one", "one"),
([1, 4, 3, 2], [1, 2, 3, 4]),
({"dict": [1, 4, 3, 2]}, {"dict": [1, 2, 3, 4]}),
({"one": {"two": [1, 4, 3, 2]}}, {"one": {"two": [1, 2, 3, 4]}}),
],
)
def test_recursive_sort(given, expected):
assert recursive_sort(given) == expected
<file_sep>/indexclient/client.py
import copy
import json
import warnings
import requests
from indexclient.errors import BaseIndexError
MAX_RETRIES = 10
UPDATABLE_ATTRS = [
"file_name",
"urls",
"version",
"metadata",
"acl",
"authz",
"urls_metadata",
"description",
"content_created_date",
"content_updated_date",
]
def json_dumps(data):
return json.dumps({k: v for (k, v) in data.items() if v is not None})
def handle_error(resp):
if 400 <= resp.status_code < 600:
try:
json_resp = resp.json()
resp.reason = json_resp["error"]
except (json.decoder.JSONDecodeError, KeyError):
pass
finally:
resp.raise_for_status()
def timeout_wrapper(func):
def timeout(*args, **kwargs):
kwargs.setdefault("timeout", 60)
return func(*args, **kwargs)
return timeout
def retry_and_timeout_wrapper(func):
def retry_logic_with_timeout(*args, **kwargs):
kwargs.setdefault("timeout", 60)
retries = 0
while retries < MAX_RETRIES:
try:
return func(*args, **kwargs)
except requests.exceptions.ReadTimeout:
retries += 1
if retries == MAX_RETRIES:
raise
return retry_logic_with_timeout
class IndexClient(object):
def __init__(self, baseurl, version="v0", auth=None):
self.auth = auth
self.url = baseurl
self.version = version
def url_for(self, *path):
subpath = "/".join(path).lstrip("/")
return "{}/{}".format(self.url.rstrip("/"), subpath)
def check_status(self):
"""Check that the API we are trying to communicate with is online"""
resp = requests.get(self.url + "/index")
handle_error(resp)
def global_get(self, did, no_dist=False):
"""
Makes a web request to the Indexd service global endpoint to retrieve
an index document record.
:param str did:
The UUID for the index record we want to retrieve.
:param boolean no_dist:
*optional* Specify if we want distributed search or not
:returns: A Document object representing the index record
"""
try:
if no_dist:
response = self._get(did, params={"no_dist": ""})
else:
response = self._get(did)
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
else:
raise e
return Document(self, did, json=response.json())
def get(self, did):
"""
Makes a web request to the Indexd service to retrieve an index document record.
:param str did:
The UUID for the index record we want to retrieve.
:returns: A Document object representing the index record
"""
try:
response = self._get("index", did)
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
else:
raise e
return Document(self, did, json=response.json())
def bulk_request(self, dids):
"""
bulk_get makes one http request to the indexd service and retrieves
a list of Documents based on the dids provided.
Args:
dids (list): list of dids for potential documents
Returns:
list: Document objects representing index records
"""
headers = {"content-type": "application/json"}
try:
response = self._post("bulk/documents", json=dids, headers=headers)
except requests.HTTPError as exception:
if exception.response.status_code == 404:
return None
else:
raise exception
return [Document(self, doc["did"], json=doc) for doc in response.json()]
def get_with_params(self, params=None):
"""
Return a document object corresponding to the supplied parameters, such
as ``{'hashes': {'md5': '...'}, 'size': '...', 'metadata': {'file_state': '...'}}``.
"""
# need to include all the hashes in the request
# index client like signpost or indexd will need to handle the
# query param `'hash': 'hash_type:hash'`
params_copy = copy.deepcopy(params) or {}
if "hashes" in params_copy:
params_copy["hash"] = params_copy.pop("hashes")
reformatted_params = dict()
for param in ["hash", "metadata"]:
if param in params_copy:
reformatted_params[param] = []
for k, v in params_copy[param].items():
reformatted_params[param].append(str(k) + ":" + str(v))
del params_copy[param]
reformatted_params.update(params_copy)
reformatted_params["limit"] = 1
try:
response = self._get("index", params=reformatted_params)
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
else:
raise e
if not response.json()["records"]:
return None
json = response.json()["records"][0]
did = json["did"]
return Document(self, did, json=json)
def list(self, limit=float("inf"), start=None, page_size=100):
"""Returns a generator of document objects."""
return self.list_with_params(limit, start, page_size)
def list_with_params(
self,
limit=float("inf"),
start=None,
page_size=100,
params=None,
negate_params=None,
):
"""
Return a generator of document object corresponding to the supplied parameters, such
as ``{'hashes': {'md5': '...'},
'size': '...',
'metadata': {'file_state': '...'},
'urls_metadata': {'s3://url': {'state': '...'}
}``.
"""
params_copy = copy.deepcopy(params) or {}
if "hashes" in params_copy:
params_copy["hash"] = params_copy.pop("hashes")
if "urls_metadata" in params_copy:
params_copy["urls_metadata"] = json.dumps(params_copy.pop("urls_metadata"))
reformatted_params = dict()
for param in ["hash", "metadata"]:
if param in params_copy:
reformatted_params[param] = []
for k, v in params_copy[param].items():
reformatted_params[param].append(str(k) + ":" + str(v))
del params_copy[param]
reformatted_params.update(params_copy)
reformatted_params.update({"limit": page_size, "start": start})
if negate_params:
reformatted_params.update({"negate_params": json.dumps(negate_params)})
yielded = 0
while True:
resp = self._get("index", params=reformatted_params, timeout=60)
handle_error(resp)
json_str = resp.json()
if not json_str["records"]:
return
for doc in json_str["records"]:
if yielded < limit:
yield Document(self, None, json=doc)
yielded += 1
else:
return
if len(json_str["records"]) == page_size:
reformatted_params["start"] = json_str["records"][-1]["did"]
else:
# There's no more results
return
def create(
self,
hashes,
size,
did=None,
urls=None,
file_name=None,
metadata=None,
baseid=None,
acl=None,
urls_metadata=None,
version=None,
authz=None,
description=None,
content_created_date=None,
content_updated_date=None,
):
"""Create a new entry in indexd
Args:
hashes (dict): {hash type: hash value,}
eg ``hashes={'md5': ab167e49d25b488939b1ede42752458b'}``
size (int): file size metadata associated with a given uuid
did (str): provide a UUID for the new indexd to be made
urls (list): list of URLs where you can download the UUID
acl (list): access control list
authz (str): RBAC string
file_name (str): name of the file associated with a given UUID
metadata (dict): additional key value metadata for this entry
urls_metadata (dict): metadata attached to each url
baseid (str): optional baseid to group with previous entries versions
version (str): entry version string
Returns:
Document: indexclient representation of an entry in indexd
"""
if urls is None:
urls = []
json = {
"urls": urls,
"form": "object",
"hashes": hashes,
"size": size,
"file_name": file_name,
"metadata": metadata,
"urls_metadata": urls_metadata,
"baseid": baseid,
"acl": acl,
"authz": authz,
"version": version,
"description": description,
"content_created_date": content_created_date,
"content_updated_date": content_updated_date,
}
if did:
json["did"] = did
resp = self._post(
"index/",
headers={"content-type": "application/json"},
data=json_dumps(json),
auth=self.auth,
)
return Document(self, resp.json()["did"])
def add_alias_for_did(self, alias, did):
"""
Adds an alias for a document id (did). Once an alias is created for
a did, the document can be retrieved by the alias using the
`global_get(alias)` function.
:param str alias:
The alias we want to assign to the document id.
:param str did:
The document id for the index record we want to alias.
:raises BaseIndexError:
Raised if aliasing operation fails.
"""
alias_payload = {"aliases": [{"value": alias}]}
resp = self._post(
"index/{}/aliases".format(did),
headers={"content-type": "application/json"},
data=json.dumps(alias_payload),
auth=self.auth,
)
try:
return resp.json()
except ValueError as err:
reason = json.dumps(
{"error": "invalid json payload returned: {}".format(err)}
)
raise BaseIndexError(resp.status_code, reason)
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias_for_did` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def create_alias(
self,
record,
size,
hashes,
release=None,
metastring=None,
host_authorities=None,
keeper_authority=None,
):
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
data = json_dumps(
{
"size": size,
"hashes": hashes,
"release": release,
"metastring": metastring,
"host_authorities": host_authorities,
"keeper_authority": keeper_authority,
}
)
url = "alias/" + record
headers = {"content-type": "application/json"}
resp = self._put(url, headers=headers, data=data, auth=self.auth)
return resp.json()
def get_latest_version(self, did, skip_null_versions=False):
"""
Args:
did (str): document id of an existing entry whose latest version is requested
skip_null_versions (bool): if True, exclude entries without a version
Returns:
Document: latest version of the entry
"""
params = {"has_version": "true" if skip_null_versions else "false"}
doc = self._get("index", did, "latest", params=params).json()
if doc and "did" in doc:
return Document(self, doc["did"], doc)
return None
def add_version(self, current_did, new_doc):
"""
Args:
current_did (str): did of an existing index whose baseid will be shared
new_doc (Document): the document version to add
Return:
Document: the version that was just added
"""
rev_doc = self._post(
"index", current_did, json=new_doc.to_json(), auth=self.auth
).json()
if rev_doc and "did" in rev_doc:
return Document(self, rev_doc["did"])
return None
def list_versions(self, did):
# type: (str) -> list[Document]
versions_dict = self._get("index", did, "versions").json() # type: dict
versions = []
for _, version in versions_dict.items():
versions.append(Document(self, version["did"], version))
return versions
@retry_and_timeout_wrapper
def _get(self, *path, **kwargs):
resp = requests.get(self.url_for(*path), **kwargs)
handle_error(resp)
return resp
@timeout_wrapper
def _post(self, *path, **kwargs):
resp = requests.post(self.url_for(*path), **kwargs)
handle_error(resp)
return resp
@timeout_wrapper
def _put(self, *path, **kwargs):
resp = requests.put(self.url_for(*path), **kwargs)
handle_error(resp)
return resp
@timeout_wrapper
def _delete(self, *path, **kwargs):
resp = requests.delete(self.url_for(*path), **kwargs)
handle_error(resp)
return resp
class DocumentDeletedError(Exception):
pass
class Document(object):
def __init__(self, client, did, json=None):
self.client = client
self.did = did
self._fetched = False
self._deleted = False
self._load(json)
def __eq__(self, other_doc):
"""
equals `==` operator overload
It doesn't matter the order of the urls list. What matters is the
existence of the urls are the same on both sides.
"""
return self._sorted_doc == other_doc._sorted_doc
def __ne__(self, other_doc):
"""
not equals `!=` operator overload
It doesn't matter the order of the urls list. What matters is the
existence of the urls are the same on both sides.
"""
return self._sorted_doc != other_doc._sorted_doc
def __lt__(self, other_doc):
return self.did < other_doc.did
def __gt__(self, other_doc):
return self.did > other_doc.did
def __repr__(self):
"""
String representation of a Document
Example:
<Document(size=1, form=object, file_name=filename.txt, ...)>
"""
attributes = ", ".join(
["{}={}".format(attr, self.__dict__[attr]) for attr in self._attrs]
)
return "<Document(" + attributes + ")>"
def _check_deleted(self):
if self._deleted:
raise DocumentDeletedError("document {} has been deleted".format(self.did))
def _render(self, include_rev=True):
self._check_deleted()
if not self._fetched:
raise RuntimeError(
"Document must be fetched from the server before being rendered as json"
)
return self._doc
def to_json(self, include_rev=True):
json = self._render(include_rev=include_rev)
if self.did:
json["did"] = self.did
return json
def _load(self, json=None):
"""Load the document contents from the server or from the provided dictionary"""
self._check_deleted()
json = json or self.client._get("index", self.did).json()
# set attributes to current Document
for k, v in json.items():
self.__dict__[k] = v
self._attrs = json.keys()
self._fetched = True
def _doc_for_update(self):
"""
return document with subset of attributes that are allowed
to be updated
"""
return {k: v for k, v in self._doc.items() if k in UPDATABLE_ATTRS}
@property
def _doc(self):
return {k: self.__dict__[k] for k in self._attrs}
@property
def _sorted_doc(self):
"""Return the _doc object but with all arrays in sorted order.
This will allow us to compare dictionaries with lists correctly. We
only care about the contents of the arrays not the order of them.
"""
return recursive_sort(self._doc)
def patch(self):
"""Update attributes in an indexd Document
"Patch" the current document attributes then upload the
changed result to the indexd server.
"""
self._check_deleted()
self.client._put(
"index",
self.did,
params={"rev": self.rev},
headers={"content-type": "application/json"},
auth=self.client.auth,
data=json.dumps(self._doc_for_update()),
)
self._load() # to sync new rev from server
def delete(self):
self._check_deleted()
self.client._delete(
"index", self.did, auth=self.client.auth, params={"rev": self.rev}
)
self._deleted = True
def recursive_sort(value):
"""
Sort all the lists in the dictionary recursively so that we can compare a
dictionary's contents being the same instead of comparing their order.
"""
if isinstance(value, dict):
return {key: recursive_sort(value[key]) for key in value.keys()}
elif isinstance(value, list):
return sorted([recursive_sort(element) for element in value])
else:
return value
<file_sep>/indexclient/parsers/retrieve.py
import sys
import json
import logging
import argparse
import requests
from indexclient import errors
def retrieve_record(host, port, did, **kwargs):
"""
Retrieve a record by id.
"""
resource = "http://{host}:{port}/index/{did}".format(host=host, port=port, did=did)
res = requests.get(resource)
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
def config(parser):
"""
Configure the retrieve command.
"""
parser.set_defaults(func=retrieve_record)
parser.add_argument("did", help="id of record to retrieve")
<file_sep>/indexclient/errors.py
class BaseIndexError(Exception):
"""
Base index error.
"""
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return str(self.msg)
<file_sep>/indexclient/parsers/create.py
import sys
import json
import argparse
import requests
from indexclient.errors import BaseIndexError
def create_record(host, port, form, size, urls, hashes, **kwargs):
"""
Create a new record.
"""
resource = "http://{host}:{port}/index/".format(host=host, port=port)
if size < 0:
raise ValueError("size must be non-negative")
urls_set = set(urls)
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
data = {
"form": form,
"size": size,
"urls": [u for u in urls_set],
"hashes": hash_dict,
}
res = requests.post(resource, json=data)
try:
res.raise_for_status()
except Exception as err:
raise BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
def config(parser):
"""
Configure the create command.
"""
parser.set_defaults(func=create_record)
parser.add_argument(
"form", choices=["object", "container", "multipart"], help="record format"
)
parser.add_argument("--size", required=True, type=int, help="size in bytes")
parser.add_argument(
"--hash",
required=True,
nargs=2,
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help="hash type and value",
)
parser.add_argument(
"--url",
metavar="URL",
action="append",
dest="urls",
default=[],
help="known URLs associated with data",
)
<file_sep>/indexclient/parsers/info.py
import sys
import json
import logging
import argparse
import warnings
import requests
from indexclient import errors
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def info(host, port, name, **kwargs):
"""
Retrieve info by name.
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
resource = "http://{host}:{port}/alias/{name}".format(
host=host, port=port, name=name
)
res = requests.get(resource)
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)
sys.stdout.write(json.dumps(doc))
def config(parser):
"""
Configure the info command.
"""
parser.set_defaults(func=info)
parser.add_argument("name", help="name of information to retrieve")
<file_sep>/tests/conftest.py
import pytest
from cdisutilstest.code.conftest import ( # pylint: disable=unused-import
indexd_server,
indexd_client,
)
@pytest.fixture(scope="function")
def index_client(indexd_client):
"""
Handles getting all the docs from an
indexing endpoint. Currently this is changing from
signpost to indexd, so we'll use just indexd_client now.
I.E. test to a common interface this could be multiply our
tests:
https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures
"""
return indexd_client
| fabd5cd39521c768ce40141e168a434698b82986 | [
"TOML",
"Python",
"Markdown"
] | 16 | Python | uc-cdis/indexclient | 7b3e3a56191c8500a22118b1ba363080c47807b0 | 17d08745ae7672c5fbf16d0312a5e033a28d4f08 |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import '../App.css';
class Registro extends Component{
constructor(props){
super(props);
this.state = {
nombre:'',
edad:'',
telefono:'',
mail:'',
patente:'',
modelo:'',
año:'',
listaConductores:[]
}
this.onChange = this.onChange.bind(this);
}
onChange(e){
let name = e.target.name;
let value = e.target.value;
this.setState({
[name]: value,
});
console.log(this.state);
}
mySubmitHandler = (event) => {
var Nombre = this.state.nombre;
var Edad = this.state.edad;
var Telefono = this.state.telefono;
var Mail = this.state.mail;
var Patente = this.state.patente;
var Modelo = this.state.modelo;
var Año = this.state.año;
var data = {Nombre,Edad,Telefono,Mail,Patente,Modelo,Año}
this.state.listaConductores.push(data);
alert("Nombre: "+this.state.listaConductores[0].Nombre +
" / Edad: " + this.state.listaConductores[0].Edad +
" / Telefono: " + this.state.listaConductores[0].Telefono +
" / Mail: " + this.state.listaConductores[0].Mail +
" / Patente: " + this.state.listaConductores[0].Patente +
" / Modelo: " + this.state.listaConductores[0].Modelo +
" / Año: " + this.state.listaConductores[0].Año) ;
}
render(){
return (
<div className="AddConductor">
<div className="">
<div>
<div>
<div className="card col-sm-6">
<div className="card-body">
<form action="" method="">
<h1>Registrar Nuevo Conductor</h1>
<div className="form-group">
<input type="text" className="form-control" name="nombre" id="Nombre" placeholder="Nombre" value={this.state.Nombre} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="edad" placeholder="Edad" value={this.state.Edad} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="telefono" placeholder="Telefono" value={this.state.Telefono} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="mail" placeholder="Mail" value={this.state.Mail} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="patente" placeholder="Patente" value={this.state.Patente} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="modelo" placeholder="Modelo" value={this.state.Modelo} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="text" className="form-control" name="año" placeholder="Año" value={this.state.Año} onChange={this.onChange}/>
</div>
<div className="form-group"><button type="submit" className="btn btn-outline-light" onClick={this.mySubmitHandler} >Registrar</button></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Registro;<file_sep>import React from 'react';
import Conductor from './img/Conductor.jpg';
import Avenida from './img/Avenida.jpg';
import Ruta from './img/Ruta.jpg';
import './App.css';
function App() {
return (
<div className="App">
<div className="container Home">
<div className="card">
<img src={Avenida} alt="a" id="ImgHome"/>
<div className="card-body">
<h3 className="card-title">Bienvenidos a TaxiDrive</h3>
<p className="card-text">Brindamos la posibilidad de que los usuarios puedan moverse de un lado a otro, pudiendo elegir su conductor para poder tener una mayor seguridad a la hora de viajar. </p>
<p className="card-text">Lo hacemos a un muy bajo costo, de forma rapida y eficaz</p>
<p>Descarga la APP y enterate de mas!</p>
</div>
</div>
</div>
</div>
);
}
export default App;
| 6c4090aa7122437c1850e752b17125baf06f45ac | [
"JavaScript"
] | 2 | JavaScript | tomassalasmesa/coding-challenge-taxidrive-tomassalasmesa | f06275bf4377770339c7c1e05c8291f269ae6e28 | ca2d23ab01668c66dabb596115a0133f475441cf |
refs/heads/master | <repo_name>Kohzuki-Nanako/react-profile<file_sep>/src/slider3.js
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import bread1 from "./media/IMG_3594.jpeg"
import bread2 from "./media/IMG_3539.jpeg"
import bread3 from "./media/IMG_0775.jpeg"
import bread4 from "./media/IMG_9693.jpg"
import bread5 from "./media/IMGP3111.jpg"
import bread6 from "./media/IMG_3712.jpeg"
const SimpleSlider3 = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
return (
<Slider {...settings}>
<div align="center">
<img src={bread1} width={1200} height={900} alt="画像1"/>
<center>ハイジの白パン</center>
</div>
<div align="center">
<img src={bread2} width={1200} height={900} alt="画像2"/>
<center>シナモンロール</center>
</div>
<div align="center">
<img src={bread3} width={1200} height={900} alt="画像3"/>
<center>さつまいもパン</center>
</div>
<div align="center">
<img src={bread4} width={1200} height={900} alt="画像4"/>
<center>フランスパン</center>
</div>
<div align="center">
<img src={bread5} width={1200} height={900} alt="画像5"/>
<center>プロシュート</center>
</div>
<div align="center">
<img src={bread6} width={1200} height={900} alt="画像5"/>
<center>マルゲリータ</center>
</div>
</Slider>
);
}
export default SimpleSlider3;<file_sep>/src/slider5.js
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import birdie1 from "./media/IMG_3730.jpg"
import birdie2 from "./media/IMG_1824.jpeg"
import birdie3 from "./media/IMG_3253.jpeg"
import birdie4 from "./media/IMG_3731.jpg"
import birdie5 from "./media/IMG_7871.jpeg"
import birdie6 from "./media/IMG_8794.jpeg"
const SimpleSlider5 = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
return (
<Slider {...settings}>
<div align="center">
<img src={birdie1} width={1200} height={900} alt="画像1"/>
<center>エリザベスカラーをつけるバーディー</center>
</div>
<div align="center">
<img src={birdie2} width={1200} height={900} alt="画像2"/>
<center>これ以上階段に登れないバーディー</center>
</div>
<div align="center">
<img src={birdie3} width={900} height={1200} alt="画像3"/>
<center>兄に顔を挟まれるバーディー</center>
</div>
<div align="center">
<img src={birdie4} width={900} height={1200} alt="画像4"/>
<center>熟睡中・・・</center>
</div>
<div align="center">
<img src={birdie5} width={900} height={1200} alt="画像5"/>
<center>busaikuバーディー</center>
</div>
<div align="center">
<img src={birdie6} width={900} height={1200} alt="画像6"/>
<center>もっと美味しいのがいい!と訴えるバーディー笑</center>
</div>
</Slider>
);
}
export default SimpleSlider5;<file_sep>/src/App.js
import React from "react";
import Image from 'react-image-resizer';
import nanako from "./media/IMG_8225.jpg"
import family from "./media/IMG_2454.jpeg"
import birdie from "./media/IMG_8912.jpg"
import vdslab from "./media/スクリーンショット 2020-06-15 10.40.21.png"
import vdslab1 from "./media/スクリーンショット 2020-06-15 10.40.21.jpeg"
import sousyoku1 from "./media/IMG_1511.jpg"
import sousyoku2 from "./media/IMG_1474.jpg"
import processing from "./media/IMG_1518.PNG"
import R from "./media/kisspng-rstudio-data-analysis-logo-datacamp-inc-editorial-clipart-collection-68-5baa304fb0fd72.033036701537880143725 (1).png"
import Ruby from "./media/kisspng-ruby-on-rails-logo-5b382677430a38.5004713115304065192746.png"
import C from "./media/kisspng-the-c-programming-language-c-computer-programmin-language-5abd180755e448.3999244815223418953518.png"
import python from "./media/kisspng-python-programming-language-computer-programming-c-hanuman-png-transparent-images-free-download-clip-5b814ed35d07d0.8307633215352009793811.png"
import CSS from "./media/kisspng-logo-cascading-style-sheets-html5-css3-prags-h-python-stickers-5b5ed262588918.5038573515329408983627.png"
import vs from "./media/kisspng-visual-studio-code-microsoft-visual-studio-source-c-5acd3e97a1c707.4865550215234003436627.png"
import slack from "./media/kisspng-slack-business-microsoft-teams-organization-slack-5b366ae3ae5f04.6125345015302929637142.png"
import github from "./media/kisspng-computer-icons-logo-portable-network-graphics-clip-icons-for-free-iconza-circle-social-5b7fe46b4ec817.2080142615351082033227.png"
import CPR from "./media/kisspng-logo-brand-font-cpr-5b2389c53733c0.9425013215290556852261.png"
import head from "./media/IMG_1457.JPG"
import cookpad from "./media/スクリーンショット 2020-06-18 10.54.00.png"
import rice from "./media/スクリーンショット 2020-06-18 10.55.55.png"
import cuoca from "./media/スクリーンショット 2020-06-18 10.57.21.png"
import kewpie from "./media/スクリーンショット 2020-06-18 11.01.14.png"
import today from "./media/スクリーンショット 2020-06-18 11.01.37.png"
import yutori from "./media/スクリーンショット 2020-06-18 11.29.16.png"
import pinterest from "./media/スクリーンショット 2020-06-18 11.00.17.png"
import { HashRouter as Router, Switch, Route} from "react-router-dom";
import SimpleSlider from "./slider";
import SimpleSlider1 from "./slider1";
import SimpleSlider2 from "./slider2";
import SimpleSlider3 from "./slider3";
import SimpleSlider4 from "./slider4";
import SimpleSlider5 from "./slider5";
const style = {
image: {
border: '0.5px solid #ccc',
background: '#fefefe',
},
};
const style1 = {
image: {
border: '0.0px solid #ccc',
background: '#000000',
},
};
const Home = () => {
return <div>
<div className="container">
<div className="tile is-ancestor">
<div className="tile is-3 is-vertical is-parent">
<div className="tile is-child box">
<h1 className = "title"> profile</h1>
<figure className="image is-256x256">
<img className="is-rounded" src={nanako} alt = "Nanako"/>
</figure>
<ul>
<li><b>名前</b> こーづき</li>
<li><b>職業</b> 大学生(情報科)</li>
<li><b>住んでいる地域</b> 東京</li>
<li><b>一言</b> 食べること、体を動かすことが好きです!基本スポーツは好きですが、体育の授業のダンスだけは苦手でした。</li>
</ul>
</div>
<div className="tile is-child box">
<p className="title">リンク</p>
<aside className="menu">
<ul className="menu-list">
<li className="level">
<div className="level-left">
<div className="level-item">
<span className="icon is-large has-text-link">
<i className="fab fa-github fa-2x"></i>
</span>
<a href="https://github.com/Kohzuki-Nanako">GitHub</a>
</div>
</div>
</li>
<li className="level">
<div className="level-left">
<div className="level-item">
<span className="icon is-large has-text-link">
<i className="fab fa-twitter fa-2x"></i>
</span>
<a href="https://twitter.com/0129birdie">Twitter</a>
</div>
</div>
</li>
<li className="level">
<div className="level-left">
<div className="level-item">
<span className="icon is-large has-text-link">
<i className="fab fa-instagram fa-2x"></i>
</span>
<a href="https://www.instagram.com/k.nanako52/">instgram</a>
</div>
</div>
</li>
</ul>
</aside>
</div>
</div>
<div className="tile is-9 is-vertical is-parent">
<div className="tile is-child box">
<h1 className="title">こういう人物です</h1>
<h3 className="title">ME</h3>
<p> 1999年1月29生まれ、最近身体の衰えをとても感じるようになった21歳です。</p>
<p> 東京生まれ東京育ち。東京がもちろん好きですが、父の実家が神戸なので、神戸も好きです!</p>
<br/>
<h3 className="title">家族</h3>
<p>兄と姉がいて、イングリッシュブルドッグのバーディーを飼っています。</p>
<table border="0">
<tr>
<td width="300"><img src={family} alt="家族"/></td>
<td width ="150"></td>
<td width="300" height="300"><img src={birdie} alt="Birdie"/></td>
</tr>
</table>
<br/>
<h3 className="title">趣味</h3>
<p>運動や、料理をすることが好きです。特に運動は、部活動でテニスをやっていたので今でも友達と部活に顔出したり、コートを借りてテニスを楽しんでいます!
料理については、<a href="#/photo">Photoライブラリー</a>をのぞいてみてください!</p>
<h3 className="title">大学では</h3>
<p>大学では、情報科に進みプログラミングや情報数学について学んでいます。大変なプログラミングの授業も受けつつ、好きな数学の授業もあるので、とても充実した学校生活を送っています。3年生から、尾上研究室に配属され真面目な同期のみんなに感化されながら、頑張っています。</p>
<p>これは、尾上研究室のHPです。<small>↓Click!!↓</small></p>
<div class="demo04">
<a href="https://vdslab.jp/">
<img src={vdslab} width="1800" height="400" alt="Vds" onmouseover={vdslab1} onmouseout={vdslab}/>
</a>
</div>
<br/>
<h3 className="title">その他</h3>
<p>大学生になってから、プールの監視員としてアルバイトをしています。また、水泳教室で幼稚園年長さんから小学生6年生までの子供達に水泳を教えています。まだ、サブコーチなのでメインコーチになれるよう頑張ります!</p>
<p>嬉しいことに、事務職も手伝わせてもらっていて、年度ごとに自治体に提出する業務書類なども書いています。そのほかには、館内の装飾にも携わっています。</p>
<div class="box">
<article class="media">
<div class="media-left">
<Image src={sousyoku1}
width={300}
height={220}
style={style.image}
/>
</div>
<div class="media-content">
<div class="content">
<p><h4>お散歩マップ</h4></p>
<p>各地域の駅周りの地図とオススメのお店などを紹介しているものを作成しました。</p>
</div>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={sousyoku2}
width={300}
height={300}
style={style.image}
/>
</div>
<div class="media-content">
<div class="content">
<p><h4>2020東京オリンピック・パラリンピックに向けて</h4></p>
<p>冬季・夏季オリンピックの年表を作成しました。日本ってこんなに開催されてたんだなど新しい発見がたくさんありました。</p>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
<footer calssname="footer">
<div className="content has-text-centered">
<p>2020 © Kohzuki_Nanako</p>
</div>
</footer>
</div>
</div>;
};
const Photo = () => {
return <div>
<div className="container">
<div className="tile is-ancestor">
<div className="tile is-3 is-vertical is-parent">
<div className="tile is-child box">
<h1 className = "title"> よく参考にするサイト</h1>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={cookpad} alt="クックパッド"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://cookpad.com/">
<p class="title is-4">クックパッド</p>
</a>
</div>
</div>
<div class="content">
みなさんによくお馴染みのクックパッド。いろんな状況に合わせた特集など、毎日更新されていて 見ていて飽きません。つくれぽがすごい、人気の記事を検索するコツがあります!
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={rice} alt="白ご飯"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://www.sirogohan.com/">
<p class="title is-4">白ご飯.com</p>
</a>
</div>
</div>
<div class="content">
白米に合う、いろんな和食がぎゅっと集まったサイトです。出汁のとり方など、料理の基本なども教えてくれます!
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={cuoca} alt="クオカ"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="http://recipe.cuoca.com/pc/">
<p class="title is-4">cuoca</p>
</a>
</div>
</div>
<div class="content">
手作りお菓子とパンのレシピが見られます。レシピとともに材料とキッチン用品も同じサイト内で購入できるため便利です!
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={kewpie} alt="キューピー"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://www.ntv.co.jp/3min/">
<p class="title is-4">キューピー3分クッキング</p>
</a>
</div>
</div>
<div class="content">
今日の放送を見逃した!ってなっても、一週間前までなら放送のビデオも見れるところがおすすめです
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={today} alt="今日の"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://www.kyounoryouri.jp/">
<p class="title is-4">きょうの料理</p>
</a>
</div>
</div>
<div class="content">
私の好きな講師さんがたくさんレシピを公開してくれています!古いレシピから最新のレシピまでなんでも揃っています
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={yutori} alt="栗原"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://www.yutori.co.jp/recipe/">
<p class="title is-4">栗原はるみ</p>
</a>
</div>
</div>
<div class="content">
<small>栗原はるみさんの出ている番組はいつも録画するほど、尊敬している方です。かっこいいキッチンも憧れます</small>
</div>
</div>
</div>
<div class="card">
<div class="card-image">
<figure class="image is-5by3">
<img src={pinterest} alt="ピント"/>
</figure>
</div>
<div class="card-content">
<div class="media">
<div class="media-content">
<a href="https://www.pinterest.jp/">
<p class="title is-4">Pinterest</p>
</a>
</div>
</div>
<div class="content">
写真やイラストを探したいときによく使用します。レシピももちろん調べられるのでおすすめです!
</div>
</div>
</div>
</div>
</div>
<div className="tile is-9 is-vertical is-parent">
<div className="tile is-child box">
<h1 className="tital"><strong>こーづき食堂</strong></h1>
<h2 className="subtital">家族の甘党に合わせていたらスイーツ作りが趣味になりました。もともと母が、お料理が上手でハンドミキサーやハンドブレンダーなどの器具はもちろん、シフォン型やタルト型などの製菓用品が充実していたため、初期費用ゼロだったので趣味にしやすかったです笑</h2>
<div className="App">
<center><p>一眼レフで撮ったスイーツたち。</p>
<p>一眼レフにはまっていた時に、ケーキを作ってはパシャパシャしていました</p></center>
<SimpleSlider />
<br></br>
<br></br>
<center>こちらはiphoneで撮ったスイーツたちです。バスチーが簡単なのにめっちゃ美味しかった!</center>
<SimpleSlider1 />
<br></br>
<br></br>
<center>オムレツ、オムライスは簡単なので好きです(笑)ケチャップで文字を書くのは定番です。<br/>(基本兄に作ったものに書いてます笑)</center>
<SimpleSlider2 />
<br></br>
<br></br>
<center>ホームベーカリーでパンを焼いたり、ピザ生地を作って一からピザを作ったりします!労力はあまりかかりませんが、時間がとてもかかります</center>
<SimpleSlider3 />
<br></br>
<br></br>
<center><p>こーづき食堂</p>
<p>日々の夜ご飯などです。</p></center>
<SimpleSlider4 />
<br></br>
<br></br>
<center><p>おまけ</p>
<p>愛犬バーディーの一コマ。小3からの付き合いです。少々内弁慶なところがありますが、優しい子です。</p></center>
<SimpleSlider5 />
<br></br>
</div>
</div>
</div>
</div>
<footer calssname="footer">
<div className="content has-text-centered">
<p>2020 © Kohzuki_Nanako</p>
</div>
</footer>
</div>
</div>;
};
const Body = () => {
return (
<Router>
<Switch>
<Route path="/photo">
<Photo />
</Route>
<Route path="/question">
<Question />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
};
const App = () => {
return <div>
<section className="hero">
<div className="hero-head">
<nav className="navbar">
<div class="navbar-brand">
<span class="navbar-item">Nanako&Co.</span>
</div>
<div class="navbar-end">
<div class="navbar-item">
<a href="https://vdslab.jp/"><p>vdslab 尾上研究室Webサイト</p></a>
</div>
</div>
</nav>
</div>
<figure class="image is-3by1">
<img src={head} alt="Head"/>
</figure>
<div className="hero-foot">
<nav className="tabs is-boxed is-fullwidth">
<div className="container">
<ul>
<li className="is-active"><a href="#/">Home</a></li>
<li className="is-active"><a href="#/question">About me</a></li>
<li className="is-active"><a href="#/photo">Photoライブラリー</a></li>
</ul>
</div>
</nav>
</div>
<div>
<Body />
</div>
</section>
</div>
};
const Question = () => {
return <div>
<div className="container">
<div className="tile is-ancestor">
<div className="tile is-3 is-vertical is-parent">
<div className="tile is-child box">
<strong>習った言語</strong>
<div class="box">
<article class="media">
<div class="media-left">
<Image src={processing}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={C}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={R}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={Ruby}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={python}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={CSS}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
</div>
<strong>ツール</strong>
<div class="box">
<article class="media">
<div class="media-left">
<Image src={vs}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={github}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
<article class="media">
<div class="media-left">
<Image src={slack}
width={240}
height={240}
style={style1.image}
/>
</div>
</article>
</div>
<strong>資格</strong>
<div class="box">
<p>・英検準2級</p>
<p>・書道1段</p>
<p>・水上安全法</p>
<p>・公益財団法人日本体育施設協会スポーツ救急手当プロバイダー</p>
<article class="media">
<div class="media-left">
<Image src={CPR}
width={200}
height={200}
style={style1.image}
/>
</div>
</article>
</div>
</div>
</div>
<div className="tile is-9 is-vertical is-parent">
<div className="tile is-child box">
<h1 className="title">誰得100の質問</h1>
<h2>よくある100の質問に答えてみました。長いし、誰に利益があるのかわかりませんが暇な人は、読んでください笑</h2>
<article class="message">
<div class="message-body">
<p><b>1.お名前は?</b> 那奈子</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>2.その名前の由来は?</b> 姉(=春奈)と同じ漢字を入れるため</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>3.誕生日は?</b> 1月29日 1月の肉の日!!!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>4.何座?</b> 水瓶座</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>5.何型?</b> 大雑把のO型!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>6.チャームポイントは?</b> 常に笑ってます。</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>7.自分が思うあなたの性格は?</b> ネガティブ、声でかい</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>8.他人からどんな性格だと言われますか?</b> 知りません!教えて!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>9.自分の好きなところあえて一つあげるなら??</b> 初対面でも誰でも話せる</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>10.自分の嫌いなところあえて一つあげるなら?</b> ありすぎて1つとか無理!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>11.芸能人似てるとしたら? </b> いない!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>12.動物に例えるとしたら?</b> さる!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>13.色で表すとしたら?</b> オレンジ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>14.自分を言葉で表すとしたら?</b> 日焼け大好き馬鹿野郎</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>15.好きな言葉は?</b> another match to play</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>16.趣味は? </b> 運動?</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>17.特技は? </b> テニス</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>18.将来の夢は? </b> 専業主婦だったけど、今はティファニーが普通に買えちゃうような暮らしがしたいな!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>19.何人家族? </b> 4人と1匹</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>20.兄弟姉妹はいる? </b> 兄、姉</p>
</div>
</article>
<h2 className="tital">ここからは好きなもの嫌いなものを答えます</h2>
<article class="message">
<div class="message-body">
<p><b>21.楽曲 </b> 2012~2014年くらいの洋楽</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>22.映画</b> チャーリーとチョコレート工場</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>23.テレビ </b> わかんない</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>24.YouTuber </b> 最近朝倉兄弟のハマりました</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>25.色彩 </b> グレー</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>26.教科 </b> 数学、体育</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>27.食べ物 </b> スイカ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>28.動物または生き物 </b> ブルドッグ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>29.休日は何してる? </b> バイト</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>30.よく行く場所は? </b> 家の近くの洋食屋さん</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>31.インドア派?アウトドア派? </b> 誰かについていく系のアウトドア</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>32.海?山? </b> 山!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>33. 犬?猫? </b> 犬!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>34. S?M? </b> ノーマルのN!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>35.LINEの返信は早い方?遅い方? </b> 早い!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>36.LINEと電話ならどっち派? </b> LINE</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>37.LINEの友達どれぐらいいる? </b> 300くらい</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>38. 一番使うアプリは? </b> <a href="https://www.instagram.com/k.nanako52/">instgram</a></p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>39.好きなタイプは? </b> 嘘つかない人</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>40.今もしかして恋してる? </b> いいえ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>41.その人はどんな人? </b> ー</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>42.愛したい?愛されたい? </b> どっちも</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>43.初デートに行きたいスポットは? </b> どこでもw</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>44.好きな人とは手を繋ぐ派? </b> どんな派だよw</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>45.将来、結婚したい? </b> したい。扶養に入りたいwww</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>46.子供は何人欲しい? </b> 2!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>47.男の子?女の子?</b> 男の子、女の子一人ずつ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>48.子供の名前はなに? </b> 2文字がいい</p>
</div>
</article>
<h2 className = "tital">折り返し地点 ここからは○×コーナー(これみんな100まで見んのかな)</h2>
<article class="message">
<div class="message-body">
<p><b>49.ズバリ、自分が好き! </b> x</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>50.実はすぐ泣いちゃう! </b> o</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>51.めっちゃモテると思う! </b> x</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>52.優柔不断な性格だと思う! </b> o</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>53. 実はヲタクです! </b> x</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>54. 人見知りします! </b> x</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>55. 怒ると怖いです! </b> x</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>56. 怒ると怖いです! </b> x</p>
</div>
</article>
<h2 className = "tital">もし、〇〇〇だったら?コーナー</h2>
<article class="message">
<div class="message-body">
<p><b>57. もし、100万円あったらなにに使う? </b> 貯金</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>58. もし、魔法が一つだけ使えるならどんな魔法? </b> 頭が良くなる魔法</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>59. もし、生まれ変わるなら何になりたい? </b> 人</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>60. もし、明日世界が滅亡するとしたらなにする? </b> いろんな人に会う</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>61. もし、政治家になったらどんな日本にしたい? </b> 子育て支援を充実させる</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>62.部活何やってる?または何やってた? </b> テニス、ラクロス</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>63.それは楽しかった? </b> 楽しかった!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>64.勉強はできる方? </b> 中学校までは頑張ってたなw</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>65.最高何点とったことある? </b> 100点</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>66.今まで何人に告白されたことある? </b> いない!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>67.今まで何人に告白したことある? </b> 1!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>68.今更ですが、性別は? </b> 女性です</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>69.学校は楽しい?または楽しかった? </b> 楽しい!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>70.先生に恋したことある? </b> ない</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>71.どんな男の子が好き? </b> よく笑うひと、嘘つかない人</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>72.どんな女の子が好き? </b> 面白い、楽しい子!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>73.友達は多い方? </b> 少ないです</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>74.花火大会やハロウィン、クリスマスなどのイベントは好き? </b> 好き</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>75.どんな思い出があるか教えて? </b> ハロウィンの日、高校の友達がガチ仮装して行ったら怒られてた</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>76.自分の名前であいうえお作文どうぞ! </b> こ:こんにちは う:嬉しいな づ:づ? き:きょうは な:なんだか な:なんでも こ:こんにちは</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>77.ホラー映画得意? </b> 無理!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>78.辛いものは得意? </b> 不得意</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>79.甘いものは得意? </b> 超得意</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>80.春夏秋冬どの季節が好き?</b> 秋10月の始まり</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>81.その理由は?</b> 部活終わりの夕方の空気感が好きだった</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>82.その季節に何したい?</b> スポーツ</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>83.朝起きて何する?</b> トイレ!</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>84.夜寝る前何する? </b> コップ一杯の水飲む</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>85.夜寝る前何する? </b> コップ一杯の水飲む</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>86.行きたい地方は? </b> 九州地方</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>87.その理由は? </b> 食べ物が美味しそう</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>88.そこでどんなことしたい? </b> 屋台行きたい</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>89.行きたい国は? </b> イタリア</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>90. その理由は?</b> 高くて絶対買えないけど服を見たい</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>91. そこでどんなことしたい? </b> 観光</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>92.人生で一番楽しかった思い出は? </b> 高校生活</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>93.これだけは知っててほしいことは? </b> 黒いです</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>94.好きな匂いは? </b> バーディーの匂い</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>95.雨は好き? </b> 大っ嫌い</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>96.和食、洋食、中華どれが一番好き? </b> 和食</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>97.尊敬している人は? </b> いません</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>98.この質問、楽しかった? </b> まぁ笑</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>99.では質問してた人にむかって一言どうぞ! </b> 100問もよく考えられますねw</p>
</div>
</article>
<article class="message">
<div class="message-body">
<p><b>100.最後に一言どうぞ! </b> 最後まで読んで頂き、ありがとうございました!</p>
</div>
</article>
</div>
</div>
</div>
<footer calssname="footer">
<div className="content has-text-centered">
<p>2020 © Kohzuki_Nanako</p>
</div>
</footer>
</div>
</div>
}
export default App;<file_sep>/src/slider2.js
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import omuretu1 from "./media/IMG_5772.jpeg"
import omuretu2 from "./media/IMG_9862.jpg"
import omuretu3 from "./media/IMG_9985.jpg"
import omuretu4 from "./media/IMG_0857.jpg"
import omuretu5 from "./media/IMG_1098.jpg"
const SimpleSlider2 = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
return (
<Slider {...settings}>
<div align="center">
<img src={omuretu4} width={900} height={900} alt="画像1"/>
<center>オムライス</center>
</div>
<div align="center">
<img src={omuretu5} width={900} height={900} alt="画像2"/>
<center>デミグラスソースオムレツ</center>
</div>
<div align="center">
<img src={omuretu2} width={900} height={900} alt="画像3"/>
<center>アホ</center>
</div>
<div align="center">
<img src={omuretu1} width={900} height={900} alt="画像4"/>
<center>オヤジ</center>
</div>
<div align="center">
<img src={omuretu3} width={900} height={900} alt="画像4"/>
<center>きもい</center>
</div>
</Slider>
);
}
export default SimpleSlider2; | 48beb7a1cb91ae9b47d714b1ba573631e15239db | [
"JavaScript"
] | 4 | JavaScript | Kohzuki-Nanako/react-profile | 37d471a0dc7ba745ae47975220bf15f93d8ffeae | 0ed9c1b46fdc9cd6ac69a2aa898d7acdf7d75c43 |
refs/heads/master | <repo_name>fuad90/new-staff<file_sep>/www/js/services.js
angular.module('starter.services', [])
.factory('Chats', function($http) {
//var baseUrl = 'http://localhost/api/web/index.php/staff/';
var baseUrl = 'http://192.168.0.128/api/web/index.php/staff/';
return {
getAll: function() {
return $http.get(baseUrl+'index');
},
getId: function (id){
return $http.get(baseUrl+'view/'+id);
}
};
});
| 64ba5c581b3fabb81d89c1d6fedabb7a969bb57f | [
"JavaScript"
] | 1 | JavaScript | fuad90/new-staff | 438ebbaca3819656c89d7468e64757e11b054ccb | 689ddb30cf5c41a5430c99e1c230bbb261f917bc |
refs/heads/master | <repo_name>Saga09/UpstoxAssignment<file_sep>/my-app/src/webSocket/header.js
import React from 'react';
import {NavLink} from 'react-router-dom';
class Home extends React.Component {
constructor(props)
{
super(props);
}
render() {
return (
<div className="header">
<div className="navMenu">
<ul>
<li>
<NavLink to={"/home"}>Home</NavLink>
</li>
<li>
<NavLink to={"/liveChart"}> Live Chart</NavLink>
</li>
</ul>
</div>
</div>
)
}
}
export default Home;<file_sep>/README.md
# Upstox Assignment
This assignment include two pages
1) Open-high-low-close(OHLC) chart with date
2) Live OHLC updating chart
Both charts are responsive and has a zoom option you can zoom the chart by scrolling your mouse, and by selecting a date range.
## I used below technologies to complete this assignment
1) HTML5
2) CSS3
3) JavaScript
4) React.js and Redux
For OHLC chart i used third party JavaScript (HTML5) tool "fusioncharts.com". <br />
I used redux (Redux Thunk middleware) for fatching api's data and store the data in redux-store.
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm install`
### `npm start`
### `npm build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
<file_sep>/my-app/src/actions/upstox-actions.js
import * as actionTypes from './action-types'
import store from "../store"
export function receivedData(data)
{
return {
type: actionTypes.GET_DATA_SUCCESS,
data: data
}
}
export function getAuthenticationStatus()
{
return (dispatch, getState) => {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetch(url)
.then((response) =>
response.json().then(function(data) {
dispatch(receivedData(data));
})
)
}
}
export function fetchData(intervel)
{
return (dispatch, getState) => {
let newUrl = 'http://kaboom.rksv.net/api/historical?interval='+intervel;
console.log("newUrl",newUrl);
fetch(newUrl)
.then((response) =>
response.json().then(function(data) {
dispatch(receivedData(data));
})
)
}
}
export function frequitlyFetchData(intervel)
{
return (dispatch, getState) => {
let newUrl = 'http://kaboom.rksv.net/api/historical?interval='+intervel;
console.log("newUrl",newUrl);
fetch(newUrl)
.then((response) =>
response.json().then(function(data) {
dispatch(receivedLiveData(data));
frequitlyFetchDataContinue(intervel+1)
})
)
}
}
export function frequitlyFetchDataContinue(intervel)
{
let newUrl = 'http://kaboom.rksv.net/api/historical?interval='+intervel;
console.log("frequitlyFetchDataContinue",newUrl);
fetch(newUrl)
.then((response) =>
response.json().then(function(data) {
store.dispatch(receivedLiveData(data));
setTimeout(function() {
store.dispatch(frequitlyFetchData(intervel+1))
}, 5000);
})
)
}
export function receivedLiveData(data)
{
return {
type: actionTypes.GET_LIVE_DATA_SUCCESS,
data: data
}
} | 34430ee510f9bd3b5fdf0ee37058067f05eeaa41 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Saga09/UpstoxAssignment | de26b12c008580f581a8a02ea2812626353bf275 | e4d5a54555acdd186e1d2563ca245bb43415599b |
refs/heads/master | <file_sep>package com.rfrnamnd1414245rikate.mlkit_example
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.rfrnamnd1414245rikate.mlkit_example.databinding.FragmentBlankBinding
import java.io.IOException
/**
* A simple [Fragment] subclass.
*
*/
class BlankFragment : Fragment() {
private lateinit var binding: FragmentBlankBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_blank, container, false)
binding.openButton.setOnClickListener {
openLibrary()
}
return binding.root
}
val RESULT_PICK_IMAGEFILE = 2
fun openLibrary() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent, RESULT_PICK_IMAGEFILE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == RESULT_PICK_IMAGEFILE && resultCode == Activity.RESULT_OK) {
data?.data?.also { uri ->
val image: FirebaseVisionImage
try {
image = FirebaseVisionImage.fromFilePath(context!!, uri)
detectML(image)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
fun detectML(image: FirebaseVisionImage) {
val options = FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(
FirebaseVisionBarcode.FORMAT_QR_CODE)
.build()
val detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options)
detector.detectInImage(image)
.addOnSuccessListener { barcodes ->
// Task completed successfully
// ...
Log.d("barcodes", barcodes.size.toString())
for (barcode in barcodes) {
}
}
.addOnFailureListener {
// Task failed with an exception
// ...
}
}
}
<file_sep># ML_Kit
This project has problems.
| 6c176cbe6bbe0c52be778a017d7d72b5742c1669 | [
"Markdown",
"Kotlin"
] | 2 | Kotlin | kohei0219/ML_Kit | ab71564985fa3478f07c37450442f934961f7ae8 | 65949df65b586d5f12ae76b536a4c7f56bfb066d |
refs/heads/master | <repo_name>vatokato/reactStart<file_sep>/src/components/Article.js
import React from 'react';
import PropTypes from 'prop-types';
class Article extends React.Component {
state = {
visible: false, // определили начальное состояние
}
handleReadMoreClick = (e) => {
(e).preventDefault();
this.setState({visible:true});
}
render() {
const { id, author, text, bigText } = this.props.data;
const { visible } = this.state;
return (
<div className="news__article">
<p className="news__author">{author}:</p>
<p className="news__text">{text}</p>
{
!visible && <a href={"#new-"+id} onClick={this.handleReadMoreClick} className='news__readmore'>Подробнее</a>
}
{
visible && <p className="news__bigText">{bigText}</p>
}
</div>
);
}
}
Article.propTypes = {
data: PropTypes.shape({
id: PropTypes.number.isRequired,
author: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
bigText: PropTypes.string.isRequired
})
}
export default Article;
<file_sep>/src/App.js
import React from 'react';
import {News} from "./components/News";
import Add from "./components/Add";
//import myNews from "../public/data/newsData";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
news: null,
isLoading: true
}
}
componentDidMount = () => {
fetch('./data/newsData.json')
.then((response)=>response.json())
.then((data)=>{
this.setState({
news: data,
filteredNews:null,
isLoading:false
});
})
.catch(function(error) {
console.log(error.message);
});
}
static getDerivedStateFromProps(props, state) {
if(!Array.isArray(state.news)) return null;
let nextFilteredNews = [...state.news];
nextFilteredNews.forEach((item, index) => {
if (item.bigText.toLowerCase().indexOf('pubg') !== -1) {
item.bigText = 'СПАМ';
}
});
return {
filteredNews: nextFilteredNews,
}
}
handleAddNews = (data) => {
const newNews = [data, ...this.state.news];
this.setState({news: newNews});
}
render() {
const {news, filteredNews, isLoading} = this.state;
return (
<React.Fragment>
<Add onAddNews={this.handleAddNews}/>
{isLoading && <p>Загружаю...</p>}
{Array.isArray(news) && <News data={filteredNews} />}
</React.Fragment>
)
}
}
export default App;
<file_sep>/README.md
DEMO: https://vatokato.github.io/reactStart/build
<file_sep>/src/components/News.js
import React from 'react';
import './News.scss';
import Article from "./Article";
class News extends React.Component {
renderNews = () => {
const {data } = this.props;
let newsTemplate = <p>К сожалению, новостей нет</p>;
if(data.length>0) {
newsTemplate = data.map(function(item, index) {
return (
<Article key={item.id} data={item}/>
)
});
}
return newsTemplate;
}
render() {
const {data } = this.props;
return (
<div className="news">
<h3>Новости</h3>
<div className="news__list">
{this.renderNews()}
</div>
{
data.length>0?<strong>Всего новостей: {data.length}</strong>:null
}
</div>
)
}
}
export {News};
| 01304e336455b6de87157a0267c1c09f3cfe2499 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | vatokato/reactStart | 21b25cb9e9a25bd1ebbf099bf4dde033e8e4a99d | d3f254b3c33fe15ad901a11c8862d68d89e3fbed |
refs/heads/master | <file_sep>#pragma once
// include this library to use NULL, otherwise use nullptr instead
#include <cstddef>
#include <iostream>
#include "node.hpp"
template <class T>
class BST
{
public:
// Constructor for the BST class, creates an empty tree
BST(void);
// Destructor for the BST class, destroys the tree
~BST(void);
// Inserts data into the tree
// param: The data to be inserted into the tree
void insert(T);
// Removes data from the tree
// param: The data to be removed from the tree
void remove(T);
// Performs an inorder traversal
// returns: pointer to a vector containing the tree traversal
std::vector<T> *inorder(void);
// Performs an postorder traversal
// returns: pointer to a vector containing the tree traversal
std::vector<T> *postorder(void);
// Performs an preorder traversal
// returns: pointer to a vector containing the tree traversal
std::vector<T> *preorder(void);
// Searches the tree for a given value
// param: the data to search for
// returns: a pointer to the node containing the data or NULL if the data
// was not found
Node<T> *search(T);
// Recursive search
// param: node and value of node searched
// returns: node found
Node<T> *search_rec(Node<T>* cur_Node, T& val);
// Gets the current number of nodes in the tree
// returns: the number of nodes in the tree
int get_size(void);
// Recursive counter
// param: Current node for count
// returns: number of nodes found
int count_rec(Node<T>* cur_Node);
private:
// the root node of the tree
Node<T> *root;
// the number of nodes in the tree
int node_count;
};
template <class T>
BST<T>::BST()
{
root = NULL;
node_count = 0;
}
template <class T>
BST<T>::~BST()
{
root = NULL;
while (root != NULL)
{
remove(root->get_data());
}
}
template <class T>
std::vector<T> *BST<T>::inorder()
{
std::vector<T> *vec = new std::vector<T>;
std::vector<int> inorder_Data;
Node<T> *cur_Node;
Node<T> *prev_Node;
cur_Node = root;
while (cur_Node != NULL)
{
if (cur_Node->get_left() == NULL)
{
inorder_Data.push_back(cur_Node->get_data());
cur_Node = (cur_Node->get_right());
}
else
{
prev_Node = cur_Node->get_left();
while (prev_Node->get_right() != NULL && prev_Node->get_right() != cur_Node)
prev_Node = prev_Node->get_right();
if (prev_Node->get_right() == NULL)
{
prev_Node->set_right(cur_Node);
cur_Node = cur_Node->get_left();
}
else
{
prev_Node->set_right(NULL);
inorder_Data.push_back(cur_Node->get_data());
cur_Node = cur_Node->get_right();
}
}
}
*vec = inorder_Data;
return vec;
}
template <class T>
std::vector<T> *BST<T>::preorder()
{
std::vector<T> *vec = new std::vector<T>;
std::vector<int> preorder_Data;
Node<T> *cur_Node;
Node<T> *temp_Node;
cur_Node = root;
while (cur_Node != NULL)
{
if (cur_Node->get_left() == NULL)
{
preorder_Data.push_back(cur_Node->get_data());
cur_Node = cur_Node->get_right();
}
else
{
temp_Node = cur_Node->get_left();
while (temp_Node->get_right() != NULL && temp_Node->get_right() != cur_Node)
{
temp_Node = temp_Node->get_right();
}
}
if (temp_Node->get_right() == cur_Node)
{
temp_Node->set_right(NULL);
cur_Node = cur_Node->get_right();
}
else
{
preorder_Data.push_back(cur_Node->get_data());
temp_Node->set_right(cur_Node);
cur_Node = cur_Node->get_left();
}
}
*vec = preorder_Data;
return vec;
}
template <class T>
std::vector<T> *BST<T>::postorder()
{
std::vector<T> *vec = new std::vector<T>;
std::vector<int> postorder_Data;
std::vector<Node<T>*> temp_Data;
Node<T> *cur_Node;
Node<T> *temp_Node;
cur_Node = root;
temp_Data.push_back(cur_Node);
while(!temp_Data.empty())
{
temp_Node = temp_Data.back();
temp_Data.pop_back();
postorder_Data.push_back(temp_Node->get_data());
if(temp_Node->get_left() != NULL)
{
temp_Data.push_back(temp_Node->get_left());
}
if(temp_Node->get_right() != NULL)
{
temp_Data.push_back(temp_Node->get_right());
}
}
*vec = postorder_Data;
return vec;
}
template <class T>
void BST<T>::insert(T new_data)
{
Node<T> * new_Node = NULL;
Node<T> *prev_Node = NULL;
Node<T> *temp_Node = NULL;
new_Node = new Node<T>(new_data);
temp_Node = root;
while(temp_Node != NULL)
{
prev_Node = temp_Node;
if(temp_Node->get_data() < new_Node->get_data())
{
temp_Node = temp_Node->get_right();
} else
{
temp_Node = temp_Node->get_left();
}
}
if (prev_Node == NULL)
{
root = new_Node;
}
else
{
if (prev_Node->get_data() < new_Node->get_data())
{
prev_Node->set_right(new_Node);
} else
{
prev_Node->set_left(new_Node);
}
}
}
template <class T>
Node<T> *BST<T>::search(T val)
{
return search_rec(root, val);
}
template<class T>
Node<T> *BST<T>::search_rec(Node<T>* cur_Node, T& val)
{
if (cur_Node == NULL)
{
return NULL;
}
else if (cur_Node->get_data() == val)
{
return cur_Node;
}
else
{
if (cur_Node->get_data() > val)
{
return search_rec(cur_Node->get_left(), val);
} else
{
return search_rec(cur_Node->get_right(), val);
}
}
}
template <class T>
void BST<T>::remove(T val)
{
Node<T> *temp_Node = NULL;
Node<T> *cur_Node = root;
while(cur_Node != NULL)
{
if(cur_Node->get_data() == val)
{
if(!cur_Node->get_left() && !cur_Node->get_right())
{
if (!temp_Node)
{
root = NULL;
}
else if (temp_Node->get_left() == cur_Node)
{
temp_Node->set_left(NULL);
}
else
{
temp_Node->set_right(NULL);
}
}
else if (cur_Node->get_left() && !cur_Node->get_right())
{
if (!temp_Node)
{
root = cur_Node->get_left();
}
else if (temp_Node->get_left() == cur_Node)
{
temp_Node->set_left(cur_Node->get_left());
}
else
{
temp_Node->set_right(cur_Node->get_left());
}
}
else if (!cur_Node->get_left() && cur_Node->get_right())
{
if (!temp_Node)
{
root = cur_Node->get_right();
}
else if (temp_Node->get_left() == cur_Node)
{
temp_Node->set_left(cur_Node->get_right());
}
else
{
temp_Node->set_right(cur_Node->get_right());
}
}
else
{
Node<T> *suc_Node = cur_Node->get_right();
while (suc_Node->get_left() != NULL)
{
suc_Node = suc_Node->get_left();
int suc_Data = suc_Node->get_data();
remove(suc_Node->get_data());
suc_Node->set_data(suc_Data);
}
return;
}
}
else if (cur_Node->get_data() < val)
{
temp_Node = cur_Node;
cur_Node = cur_Node->get_right();
}
else
{
temp_Node = cur_Node;
cur_Node = cur_Node->get_left();
}
}
return;
}
template <class T>
int BST<T>::get_size()
{
if (root != NULL)
{
node_count = count_rec(root);
}
return node_count;
}
template<class T>
int BST<T>::count_rec(Node<T>* cur_Node)
{
int rec_count = 1;
if (cur_Node->get_left() != NULL){
rec_count += count_rec(cur_Node->get_left());
}
if (cur_Node->get_right() != NULL){
rec_count += count_rec(cur_Node->get_right());
}
return rec_count;
} | 8e9bc814345df3e4b0d6dc8fed37ace657191cc1 | [
"C++"
] | 1 | C++ | dsu-cs/a3-airelwold | 93667b2fb151c27e943e0db19134df6b76b314e1 | 595839f61c9b91d01fe9ffa9f9ded4c58c627d6f |
refs/heads/master | <file_sep>#pragma once
#ifndef _USER_H_
#define _USER_H_
void userg(void);
#endif /*_USER_H_*/
<file_sep>#DWMS sample status time for dwm
*build
`make ; make install ; make clean`
<file_sep>#define _BSD_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <X11/Xlib.h>
#include <locale.h>
#define true 1
#define false 0
static Display *dpy;
void status(char *str)
{
XStoreName(dpy, DefaultRootWindow(dpy), str);
XSync(dpy, False);
}
int main(void)
{
if (!(dpy = XOpenDisplay(NULL))) {
fprintf(stderr, "dwmstatus: cannot open display.\n");
return 1;
};
int len=0;
char * str_date=NULL;
time_t timer;
while(true)
{
sleep(1);
timer = time(NULL);
str_date = ctime(&timer);
len = strlen(str_date);
str_date[len-1] = '\0'; //remove '\n'
status(str_date);
memset(str_date,'\0',sizeof(str_date));
};
XCloseDisplay(dpy);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* Running autorun script ~/.dwmrc */
void userg()
{
printf("[USER] start user programm\n");
system("/home/$USER/.dwmrc");
}
<file_sep>
CC =gcc
CFLAGS = -g -std=c99 -O0 -I. -I/usr/include -I/usr/X11R6/include
LDFLAGS = -g -L/usr/lib -lc -L/usr/X11R6/lib -lX11
OBJ = dwms.o
EXE = dwms
all: $(EXE)
$(EXE): $(OBJ)
clean:
rm ./$(EXE) ./$(OBJ)
install:
cp ./dwms /usr/local/bin/$(EXE)
uninstall:
rm /usr/local/bin/$(EXE)
| 9609ba6fcca1571a0f539be112abd71b69e2a7f7 | [
"Markdown",
"C",
"Makefile"
] | 5 | C | fedor-elizarov/dwm | 9481e8fefa15101f1f48e0fb3c9b1784b4744104 | 4fcd2e90028b198be717d9bbd78b5481dc489f73 |
refs/heads/master | <file_sep>
<?php include 'header.php';
$sql="DELETE FROM orderlist";
$query=mysqli_query($conn, $sql);
session_destroy();
?>
<script>
document.getElementById('simpleCart_quantity')=0;
document.getElementById('pid')=0;
</script>
<?php
header('Location:index.php');
?>
<?php include 'footer.php';?>
<file_sep><?php include 'header.php';?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists"><h4>Pizzas</h4>
<p>Exotic Combo of Cheese & Basil</p>
<P> Capsicum, Tomatoes, Onion</P>
<P> Chicken Tikka & Cheese</P>
<P> Chicken Stripse</P>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Burgers</h4>
<p>Vegetable Patty With Coleslaw</p>
<p>Fajita Paneer & Vegetable</p>
<p>Chicken Patty With Vegetable</p>
<p>Chicken Cut in Mexican Style</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Hot Dogs</h4>
<p>Mixed Vegetable With Cheese</p>
<p>Grilled Paneer & Vegetable</p>
<p>Chicken Sausage With Mustard</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Desserts</h4>
<p>(Black Forest/Truffle/Noughat)</p>
<p>Apple Pie With Ice Cream</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Cold Beverages</h4>
<p>Strawberry Milk Shake</p>
<p>Chocolate Milk Shake</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">Pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Sandwiches</h4>
<p>(Mint With Cheese Tomato)</p>
<p>(Fresh Tomatoes, Cucumber)</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Exotic Cakes</h4>
<p>Pineapple Flavoured Cream)</p>
<p>A Chocolate Sponge Base</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div><br /><div class="order-top">
<li class="item-lists"><h4>Ice Creams</h4>
<p>Butter Scotch</p>
<p>Pineapple</p>
<p>Black Forest</p>
<p>Chocolate with Orange</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><a href="#">pick</a></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="contact-section" id="contact">
<div class="container">
<div class="contact-section-grids">
<!--<div class="col-md-3 contact-section-grid wow fadeInLeft" data-wow-delay="0.4s">
<h4>Site Links</h4>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">About Us</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Contact Us</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Privacy Policy</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Terms of Use</a></li>
</ul>
</div>-->
<div class="col-md-3 contact-section-grid wow fadeInLeft" data-wow-delay="0.4s">
<h4>Site Links</h4>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">About Us</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Contact Us</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Privacy Policy</a></li>
</ul>
<ul>
<li><i class="point"></i></li>
<li class="data"><a href="#">Terms of Use</a></li>
</ul>
</div>
<div class="col-md-3 contact-section-grid wow fadeInRight" data-wow-delay="0.4s">
<h4>Follow Us On...</h4>
<ul>
<li><i class="fb"></i></li>
<li class="data"> <a href="#"> Facebook</a></li>
</ul>
<ul>
<li><i class="tw"></i></li>
<li class="data"> <a href="#">Twitter</a></li>
</ul>
<ul>
<li><i class="in"></i></li>
<li class="data"><a href="#"> Linkedin</a></li>
</ul>
<ul>
<li><i class="gp"></i></li>
<li class="data"><a href="#">Google Plus</a></li>
</ul>
</div>
<div class="col-md-3 contact-section-grid nth-grid wow fadeInRight" data-wow-delay="0.4s">
<h4>Subscribe Newsletter</h4>
<p>To get latest updates and food deals every week</p>
<input type="text" class="text" value="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}">
<input type="submit" value="submit">
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<div class="footer">
<div class="container">
<p class="wow fadeInLeft" data-wow-delay="0.4s">© 2018 All rights Reserved | OFDS</p>
</div>
</div>
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep><?php
$conn = mysqli_connect("localhost:3306", "root", "","pcs_msit_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
//function start
function SignIn() {
$conn=$GLOBALS['conn'];
$ID = $_POST["email"];
$Password = $_POST["<PASSWORD>"];
$email = $_POST["email"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$Adress = $_POST["address"];
$Phonenumber = $_POST["tel"];
$city = $_POST["city"];
$Confirmpass = $_POST["conpassword"];
if($Confirmpass==$Password){
unset($_SESSION['error']);
$sql="INSERT INTO Userinfo VALUES ('', '$fname','$lname', '$email','$Adress', '$Phonenumber', '$city', '$Password')";
//$query=mysqli_query($conn, $sql);
if (!mysqli_query($conn, $sql))
{
echo("Error description: " . mysqli_error($conn));
}
else
{
header('Location:login.php');
}
}
else
{$_SESSION['error']=1;
header('Location:register.php');
}
}
//function end
if(isset($_POST['submit'])) {
SignIn();
}
else{
echo "not call";
}
?>
<file_sep><?php include 'header.php';
$quer=mysqli_query($conn, "SELECT * FROM orderlist");
if(isset($_SESSION['uid']))
{
$sid=$_SESSION['uid'];
$sql="SELECT * FROM userinfo WHERE uid=$sid";
$query=mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query,MYSQLI_NUM);
$_SESSION['price']=$_POST['price'];
$mailto = $row[3];
$mailSub ="Bill from OFDS";
$mailMsg = "Your Order will be delivered soon,<html><Body><h2>Your Order is</h2>";
while ($row = mysqli_fetch_array($quer))
{
$mailMsg .= "<h3>".$row['name']."</h3></br>";
}
$mailMsg .= "</body></html>"."Please keep the change ready of ₹".$_POST['price'];
require 'PHPMailer-master/PHPMailerAutoload.php';
require 'PHPMailer-master/class.phpmailer.php';
require 'PHPMailer-master/class.phpmaileroauth.php';
require 'PHPMailer-master/class.phpmaileroauthgoogle.php';
require 'PHPMailer-master/class.smtp.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0;// Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '<EMAIL>'; // SMTP username
$mail->Password = '<PASSWORD>!'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('<EMAIL>', '<NAME>');
$mail->addAddress($mailto); // Add a recipient
//$mail->addAddress('<EMAIL>'); // Name is optional
$mail->addReplyTo('<EMAIL>', 'Information');
// $mail->addCC($mailcc);
// $mail->addBCC($mailcc);
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $mailSub;
$mail->Body = $mailMsg;
// $mail->AltBody = $mailMsg;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
else
{
header('Location:login.php');
}
?>
<?php include 'footer.php';?><file_sep><?php
$conn = mysqli_connect("localhost:3306", "root", "","pcs_msit_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$ID = $_POST["email"];
$Password = $_POST["<PASSWORD>"];
session_start();
function SignIn() {
$conn=$GLOBALS['conn'];
if(!empty($_POST['email'])) //checking the 'user' name which is from Sign-In.php, is it empty or have some text
{
$query=mysqli_query($conn, "SELECT * FROM Userinfo where email = '$_POST[email]' AND password = '$_POST[password]'");
$row = mysqli_fetch_array($query,MYSQLI_NUM);
if(!empty($row[7]) AND !empty($row[3]))
{ $_SESSION['password'] = $row[7];
$_SESSION['uid'] = $row[0];
$_SESSION['uname'] = $row[1];
header('Location:index.php');
}
else
{
header('Location:register.php');
}
}
}
if(isset($_POST['submit'])) {
SignIn();
}
else{
echo "not call";
}
?>
<file_sep><?php include 'header.php';?>
<script>
function fun(item1)
{
document.getElementById('hidden1').value=item1;
/*<?php
/*$id=$_SESSION['uid'];
$item1= "<script>document.getElementByID('item1').value</script>";
$sql="INSERT INTO orderlist VALUES ('$id','','$item1','30')";
$query=mysqli_query($conn, $sql);
*/?>*/
}
</script>
<?php
if(isset($_POST['hid']))
{
$name=$_POST['hid'];
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name','30')";
$query=mysqli_query($conn, $sql);
}
?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists">
<form method="POST">
<input type="hidden" id="hidden1" name="hid" onchange="<?php echo $_SERVER['PHP_SELF']; ?>"/>
</form>
<h4>Noodles</h4>
<p>Hakka Noodles</p>
<p>Manchurian Noodles</p>
<p>Schezwan Noodles</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('HakkaNoodles')" type="submit" value="Pick" name="Pick1"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ManchurianNoodles')" type="submit" value="Pick" name="Pick2"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('SchezwanRice')" type="submit" value="Pick" name="Pick3"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Rice</h4>
<p><input type="hidden" name="item1" value="FriedRice"/>Fried Rice</p>
<p><input type="hidden" name="item2" value="ManchurianRice"/>Manchurian Rice</p>
<p><input type="hidden" name="item3" value="CombinationRice"/>Combination Rice</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input type="submit" value="Pick" name="Pick1"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input type="submit" value="Pick" name="Pick2"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input type="submit" value="Pick" name="Pick3"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Soup</h4>
<p onclick="fun(">Manchaw Soup</p>
<p>Manchurain Soup</p>
<p>Hot & Sour Soup</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY $30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<?php $uid=$_SESSION['uid'];
$query=mysqli_query($conn, "SELECT * FROM Userinfo where uid='$uid'");
if(!$row = mysqli_fetch_array($query))
?>
<style>
.labsty {font-size: 30px;
}
</style>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
<div class="main">
<div class="container">
<div class="register">
<form action="signup123.php" method="post">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div class="wow fadeInLeft" data-wow-delay="0.4s">
<span>First Name</span>
<label class="labsty"><?php echo $row[1]; ?></label>
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Last Name<label></label></span>
<label class="labsty"><?php echo $row[2]; ?></label>
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Email Address<label></label></span>
<label class="labsty"><?php echo $row[3]; ?></label>
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Address<label>*</label></span>
<label class="labsty"><?php echo $row[4]; ?></label>
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Contact Number<label>*</label></span>
<label class="labsty"><?php echo $row[5]; ?></label>
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>City<label>*</label></span>
<label class="labsty"><?php echo $row[6]; ?></label>
</div>
<div class="clearfix"> </div>
<a class="news-letter" href="#">
<!--<label class="checkbox"><input type="checkbox" name="checkbox" checked=""><i> </i>Sign Up for Newsletter</label>-->
</a>
</div>
<script >
<?php
if($_SESSION['error']){
?>
document.getElementById("er").innerHTML ="password and confirm password are not match.";//titary[c]
<?php
}
?>
</script>
</div>
<div class="clearfix"> </div>
<div class="register-but">
<div class="clearfix"> </div>
</div>
</form >
</div>
</div>
</div>
<div class="special-offers-section">
<div class="container">
<div class="special-offers-section-head text-center dotted-line">
<h4>Special Offers</h4>
</div>
<div class="special-offers-section-grids">
<div class="m_3"><span class="middle-dotted-line"> </span> </div>
<div class="container">
<ul id="flexiselDemo3">
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p1.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Olister Combo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p2.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Chicken Jumbo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p1.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Crab Combo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p2.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Chicken Jumbo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
</ul>
<script type="text/javascript">
$(window).load(function() {
$("#flexiselDemo3").flexisel({
visibleItems: 3,
animationSpeed: 1000,
autoPlay: true,
autoPlaySpeed: 3000,
pauseOnHover: true,
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint:480,
visibleItems: 1
},
landscape: {
changePoint:640,
visibleItems: 2
},
tablet: {
changePoint:768,
visibleItems: 3
}
}
});
});
</script>
<script type="text/javascript" src="js/jquery.flexisel.js"></script>
</div>
</div>
</div>
</div>
<?php include 'footer.php';?>
<?php include 'footer.php';?><file_sep><?php
$conn = mysqli_connect("localhost:3306", "root", "","pcs_msit_db");
$itemid=$_POST['name'];
$sql = "DELETE FROM orderlist WHERE itemid=$itemid";
if(mysqli_query($conn, $sql)){
header('Location:checkout.php');
}
else{
echo "ERROR: Could not able to execute $sql. ". mysqli_error($link);
}
?><file_sep><?php include 'header.php';?>
<script>
function fun(item1)
{
document.getElementById('hidden1').value=item1;
document.getElementById("form_id").submit();
/*<?php
/*$id=$_SESSION['uid'];
$item1= "<script>document.getElementByID('item1').value</script>";
$sql="INSERT INTO orderlist VALUES ('$id','','$item1','30')";
$query=mysqli_query($conn, $sql);
*/?>*/
}
</script>
<?php
if(isset($_POST['hid']))
{
$name=$_POST['hid'];
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name','30')";
$query=mysqli_query($conn, $sql);
header('Location:punjabi.php');
}
?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists">
<form method="POST" id="form_id">
<input type="hidden" id="hidden1" name="hid" onchange="<?php echo $_SERVER['PHP_SELF']; ?>"/>
<input style="display: none;" type="submit"/>
</form>
<h4>Sabzi</h4>
<p>Panner Toofani</p>
<p>Kaju Butter Masala</p>
<p>Panner Angara</p>
<p>Palak Panner</p>
<p>Kaju Kofta</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('PannerToofani')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('KajuButterMasala')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('PannerAngara')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('PalakPanner')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('KajuKofta')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Rice</h4>
<p>Cheese Pulav</p>
<p>Kashmiri Pulav</p>
<p>Kaju Pulav</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('CheesePulav')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('KashmiriPulav')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('KajuPulav')" type="submit" value="Pick" name="Pick"/></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Add-ons</h4>
<p>Butter Tawa Roti</p>
<p>Kulcha</p>
<p>Butter Naan</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ButterTawaRoti')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('Kulcha')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ButterNaan')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep>
<!DOCTYPE php>
<php>
<head>
<title>Food_Template Bootstrap Responsive Website Template | order page :: w3layouts</title>
<link href="css/bootstrap.css" rel='stylesheet' type='text/css' />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Custom Theme files -->
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<!-- Custom Theme files -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfont-->
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900,200italic,300italic,400italic,600italic,700italic,900italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lobster+Two:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<!--Animation-->
<script src="js/wow.min.js"></script>
<link href="css/animate.css" rel='stylesheet' type='text/css' />
<script>
new WOW().init();
</script>
<script type="text/javascript" src="js/move-top.js"></script>
<script type="text/javascript" src="js/easing.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('php,body').animate({scrollTop:$(this.hash).offset().top},1200);
});
});
</script>
<script src="js/jquery.carouFredSel-6.1.0-packed.js"></script>
<script src="js/tms-0.4.1.js"></script>
<script>
$(window).load(function(){
$('.slider')._TMS({
show:0,
pauseOnHover:false,
prevBu:'.prev',
nextBu:'.next',
playBu:false,
duration:800,
preset:'fade',
pagination:true,//'.pagination',true,'<ul></ul>'
pagNums:false,
slideshow:8000,
numStatus:false,
banners:false,
waitBannerAnimation:false,
progressBar:false
})
});
$(window).load (
function(){$('.carousel1').carouFredSel({auto: false,prev: '.prev',next: '.next', width: 960, items: {
visible : {min: 1,
max: 4
},
height: 'auto',
width: 240,
}, responsive: false,
scroll: 1,
mousewheel: false,
swipe: {onMouse: false, onTouch: false}});
});
</script>
<script src="js/jquery.easydropdown.js"></script>
<script src="js/simpleCart.min.js"> </script>
</head>
<body>
<!-- header-section-starts -->
<div class="header">
<div class="container">
<div class="top-header">
<div class="logo">
<a href="index.php"><img src="images/logo.png" class="img-responsive" alt="" /></a>
</div>
<div class="queries">
<p>Questions? Call us Toll-free!<span>9099022373 </span><label>(11AM to 11PM)</label></p>
</div>
<div class="header-right">
<div class="cart box_1">
<a href="checkout.php">
<h3> <span class="simpleCart_total"> $0.00 </span> (<span id="simpleCart_quantity" class="simpleCart_quantity"> 0 </span> items)<img src="images/bag.png" alt=""></h3>
</a>
<p><a href="javascript:;" class="simpleCart_empty">Empty card</a></p>
<div class="clearfix"> </div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="menu-bar">
<div class="container">
<div class="top-menu">
<ul>
<li><a href="index.php">Home</a></li>|
<li><a href="restaurants.php">MENU</a></li>|
<!--<li><a href="order.php">Order</a></li>|-->
<li class="active"><a href="#contact" class="scroll">contact</a></li>
<div class="clearfix"></div>
</ul>
</div>
<div class="login-section">
<ul>
<li><a href="login.php">Login</a> </li> |
<li><a href="register.php">Register</a> </li> |
<li><a href="#">Help</a></li>
<div class="clearfix"></div>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- header-section-ends -->
<div class="order-section-page">
<div class="ordering-form">
<div class="container">
<div class="order-form-head text-center wow bounceInLeft" data-wow-delay="0.4s">
<h3>Restaurant Order Form</h3>
<p>Ordering Food Was Never So Simple !!!!!!</p>
</div>
<div class="col-md-6 order-form-grids">
<div class="order-form-grid wow fadeInLeft" data-wow-delay="0.4s">
<h5>Order Information</h5>
<span>Type of Order</span>
<div class="dropdown-button">
<select class="dropdown" tabindex="9" data-settings='{"wrapperClass":"flat"}'>
<option value="0">Pick up</option>
<option value="1">Delivery</option>
<option value="2">Catering</option>
</select>
</div>
<span>Restaurant Location</span>
<div class="dropdown-button wow">
<select class="dropdown" tabindex="9" data-settings='{"wrapperClass":"flat"}'>
<option value="0">Restaurent A,144 East MG Road Indore</option>
<option value="1">Restaurent B,64 Paarli Hills IndoreIndore</option>
</select>
</div>
<span>Location name</span>
<div class="dropdown-button">
<select class="dropdown" tabindex="9" data-settings='{"wrapperClass":"flat"}'>
<option value="0"> Secunderabad</option>
<option value="1">Location-1</option>
<option value="2">Location-2</option>
</select>
</div>
<span>cuisine-name</span>
<div class="dropdown-button">
<select class="dropdown" tabindex="9" data-settings='{"wrapperClass":"flat"}'>
<option value="0">cuisine-name</option>
<option value="1">cuisine-name</option>
<option value="2">cuisine-name</option>
</select>
</div>
<input type="text" class="text" value="Time" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Time';}"><br>
<div class="wow swing animated" data-wow-delay= "0.4s">
<input type="button" value="order now">
</div>
</div>
</div>
<div class="col-md-6 ordering-image wow bounceIn" data-wow-delay="0.4s">
<img src="images/order.jpg" class="img-responsive" alt="" />
</div>
</div>
</div>
<div class="special-offers-section">
<div class="container">
<div class="special-offers-section-head text-center dotted-line">
<h4>Special Offers</h4>
</div>
<div class="special-offers-section-grids">
<div class="m_3"><span class="middle-dotted-line"> </span> </div>
<div class="container">
<ul id="flexiselDemo3">
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p1.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Olister Combo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p2.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Chicken Jumbo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p1.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Crab Combo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
<li>
<div class="offer">
<div class="offer-image">
<img src="images/p2.jpg" class="img-responsive" alt=""/>
</div>
<div class="offer-text">
<h4>Chicken Jumbo pack lorem</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
<input type="button" value="Grab It">
<span></span>
</div>
<div class="clearfix"></div>
</div>
</li>
</ul>
<script type="text/javascript">
$(window).load(function() {
$("#flexiselDemo3").flexisel({
visibleItems: 3,
animationSpeed: 1000,
autoPlay: true,
autoPlaySpeed: 3000,
pauseOnHover: true,
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint:480,
visibleItems: 1
},
landscape: {
changePoint:640,
visibleItems: 2
},
tablet: {
changePoint:768,
visibleItems: 3
}
}
});
});
</script>
<script type="text/javascript" src="js/jquery.flexisel.js"></script>
</div>
</div>
</div>
</div>
</div>
<!-- footer-section-starts -->
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<script>
function fun(item1)
{
document.getElementById('hidden1').value=item1;
document.getElementById("form_id").submit();
/*<?php
/*$id=$_SESSION['uid'];
$item1= "<script>document.getElementByID('item1').value</script>";
$sql="INSERT INTO orderlist VALUES ('$id','','$item1','30')";
$query=mysqli_query($conn, $sql);
*/?>*/
}
</script>
<?php
if(isset($_POST['hid']))
{
$name=$_POST['hid'];
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name','30')";
$query=mysqli_query($conn, $sql);
header('Location:chinese.php');
}
?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists">
<form method="POST" id="form_id">
<input type="hidden" id="hidden1" name="hid" onchange="<?php echo $_SERVER['PHP_SELF']; ?>"/>
<input style="display: none;" type="submit"/>
</form>
<h4>Noodles</h4>
<p>Hakka Noodles</p>
<p>Manchurian Noodles</p>
<p>Schezwan Noodles</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('HakkaNoodles')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ManchurianNoodles')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('SchezwanRice')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Rice</h4>
<p>Fried Rice</p>
<p>Manchurian Rice</p>
<p>Combination Rice</p>
<p>Schezwan Rice</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('FriedRice')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ManchurianRice')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('CombinationRice')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('SchezwanRice')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Soup</h4>
<p>Manchaw Soup</p>
<p>Manchurain Soup</p>
<p>Hot & Sour Soup</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ManchawSoup')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ManchurianSoup')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('Hot&SourSoup')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
<div class="container">
<div class="login-page">
<div class="dreamcrub">
<ul class="breadcrumbs">
<li class="home">
<a href="index.php" title="Go to Home Page">Home</a>
<span>></span>
</li>
<li class="women">
Login
</li>
</ul>
<ul class="previous">
<li><a href="index.php">Back to Previous Page</a></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="account_grid">
<div class="col-md-6 login-left wow fadeInLeft" data-wow-delay="0.4s">
<h3>NEW CUSTOMERS</h3>
<p>By creating an account with our site, you will be able to move through the checkout process faster, view your order.</p>
<a class="acount-btn" href="register.php">Create an Account</a>
</div>
<div class="col-md-6 login-right wow fadeInRight" data-wow-delay="0.4s">
<h3>REGISTERED CUSTOMERS</h3>
<p>If you have an account with us, please log in.</p>
<form action="./login123.php" method="post">
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="email">
</div>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password">
</div>
<a class="forgot" href="#">Forgot Your Password?</a>
<input type="submit" value="submit" name="submit">
</form>
<!--<form action="<?php $_PHP_SELF ?>" method="POST">
Username: <input type="email" name="email"><br/>
Password: <input type="<PASSWORD>" name="password"><br />
<input type="submit" value="Login" name="submit" />
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['email']) && !empty($_POST['password'])) {
$user=$_POST['email'];
$pass=$_POST['password'];
$con=mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('psc_msit_db') or die("cannot select DB");
$query=mysql_query("SELECT * FROM admin WHERE username='".$user."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['<PASSWORD>'];
}
if($user == $dbusername && $password == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
/* Redirect browser */
header("Location:index.php");
}
} else {
echo "Invalid username or password!";
}
} else {
echo "All fields are required!";
}
}
?> -->
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep><?php
$conn = mysqli_connect("localhost", "root", "","pcs_msit_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$c=0;
$sql="SELECT * FROM orderlist";
$query=mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
++$c;
}
session_start();?>
<!DOCTYPE php>
<php>
<head>
<title>OFDS | <NAME> |</title>
<link href="css/bootstrap.css" rel='stylesheet' type='text/css' />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Custom Theme files -->
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<!-- Custom Theme files -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfont-->
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900,200italic,300italic,400italic,600italic,700italic,900italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lobster+Two:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<!--Animation-->
<script src="js/wow.min.js"></script>
<link href="css/animate.css" rel='stylesheet' type='text/css' />
<script>
new WOW().init();
</script>
<script src="js/simpleCart.min.js"> </script>
<script type="text/javascript" src="js/move-top.js"></script>
<script type="text/javascript" src="js/easing.js"></script>
</head>
<body>
<!-- header-section-starts -->
<div class="header">
<div class="container">
<div class="top-header">
<div class="logo">
<a href="index.php"><img src="images/logo.png" class="img-responsive" alt="" /></a>
</div>
<div class="queries">
<p>Questions? Call us Toll-free!<span>9427490278 | 8980483853 </span><label>(11AM to 11PM)</label></p>
</div>
<div class="header-right">
<div class="cart box_1">
<a href="checkout.php">
<h3> <span id="pid" > ₹<?php echo $c*30;?> </span> (
<span id="simpleCart_quantity" ><?php echo $c;?></span> items)<img src="images/bag.png" alt=""></h3>
</a>
<div class="clearfix"> </div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="menu-bar">
<div class="container">
<div class="top-menu">
<ul>
<li><a href="index.php">Home</a></li>|
<li class="active"><a href="restaurants.php">MENU</a></li>|
<!--<li><a href="order.php">Order</a></li>|-->
<li><a href="contact.php">contact</a></li>
<div class="clearfix"></div>
</ul>
</div>
<div class="login-section">
<ul>
<?php if(isset($_SESSION['uid']))
{ ?>
<li><a href="profile.php">Hii, <?php echo $_SESSION['uname'];?></a></li>|
<li><a href="./logout.php">logout</a></li>
<?php
}
else{
?>
<li><a href="login.php">Login</a> </li>|
<li><a href="register.php">Register</a> </li>
<?php } ?>
<div class="clearfix"></div>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="Popular-Restaurants-content">
<div class="Popular-Restaurants-grids">
<div class="container">
<div class="Popular-Restaurants-grid wow fadeInRight" data-wow-delay="0.4s">
<div class="col-md-3 restaurent-logo">
<img src="images/chinese.jpg" class="img-responsive" alt="" />
</div>
<div class="col-md-2 restaurent-title">
<div class="logo-title">
<h4><a href="chinese.php">Chinese</a></h4>
</div>
<div class="rating">
<span>ratings</span>
<a href="#"> <img src="images/star1.png" class="img-responsive" alt="">(004)</a>
</div>
</div>
<div class="col-md-7 buy">
<span></span>
<a class="morebtn hvr-rectangle-in" href="chinese.php">Order</a>
</div>
<div class="clearfix"></div>
</div>
<div class="Popular-Restaurants-grid wow fadeInLeft" data-wow-delay="0.4s">
<div class="col-md-3 restaurent-logo">
<img src="images/punjabi.jpg" class="img-responsive" alt="" />
</div>
<div class="col-md-2 restaurent-title">
<div class="logo-title logo-title-1">
<h4><a href="punjabi.php">Punjabi</a></h4>
</div>
<div class="rating">
<span>ratings</span>
<a href="#"> <img src="images/star2.png" class="img-responsive" alt="">(005)</a>
</div>
</div>
<div class="col-md-7 buy">
<span></span>
<a class="morebtn hvr-rectangle-in" href="punjabi.php">Order</a>
</div>
<div class="clearfix"></div>
</div>
<div class="Popular-Restaurants-grid wow fadeInLeft" data-wow-delay="0.4s">
<div class="col-md-3 restaurent-logo">
<img src="images/pizza.jpg" class="img-responsive" alt="" />
</div>
<div class="col-md-2 restaurent-title">
<div class="logo-title logo-title-3">
<h4><a href="#">Fast Food</a></h4>
</div>
<div class="rating">
<span>ratings</span>
<a href="#"> <img src="images/star2.png" class="img-responsive" alt="">(005)</a>
</div>
</div>
<div class="col-md-7 buy">
<span></span>
<a class="morebtn hvr-rectangle-in" href="fastfood.php">Order</a>
</div>
<div class="clearfix"></div>
</div>
<div class="Popular-Restaurants-grid wow fadeInRight" data-wow-delay="0.4s">
<div class="col-md-3 restaurent-logo">
<img src="images/dessert.jpg" class="img-responsive" alt="" />
</div>
<div class="col-md-2 restaurent-title">
<div class="logo-title logo-title-4">
<h4><a href="#">Desserts</a></h4>
</div>
<div class="rating">
<span>ratings</span>
<a href="#"> <img src="images/star1.png" class="img-responsive" alt="">(004)</a>
</div>
</div>
<div class="col-md-7 buy">
<span></span>
<a class="morebtn hvr-rectangle-in" href="desserts.php">Order</a>
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<!-- checkout -->
<?php
$c=0;
$sql="SELECT * FROM orderlist";
$query=mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
++$c;
}
?>
<h1 align="center">My Shopping Bag <?php echo $c?></h1>
<?php
$a=0;
$sql="SELECT * FROM orderlist";
$query=mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
++$a;
?>
<div class="cart-items">
<div class="container">
<form method="POST" action="checkout12.php">
<div class="cart-header">
<div class="cart-sec simpleCart_shelfItem">
<div class="cart-item cyc">
</div>
<div class="cart-item-info">
<h3><a href="#"> </a><span></span></h3>
<ul class="qty">
<li><p style="font-size: 25px"><?php echo $row[2]?> </p></li></br>
<li><p style="font-size: 25px" ><?php echo $row[3]?></p></li>
<input type="hidden" name="name" value=<?php echo $row[1]?>>
<input class="close1" type="submit" name="submit" value=" ">
</ul>
<div class="delivery">
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</form>
</div>
</div>
<?php
}
?>
<div align="center">
<form action="mail.php" method="POST">
<input type="hidden" name="price" value=<?php echo $c*30?>>
<input style=" background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;" type="submit" name="checkout" value="checkout"/>
</form>
</div>
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<div class="banner wow fadeInUp" data-wow-delay="0.4s" id="Home">
<div class="container">
<div class="banner-info">
<div class="banner-info-head text-center wow fadeInLeft" data-wow-delay="0.5s">
<h1>Variety of Delicious Dishes</h1>
<div class="line">
<h2> To Order Online</h2>
</div>
</div>
<div style="size: 500px" align="center" class="form-list wow fadeInRight" data-wow-delay="0.5s">
<form>
<ul style="size: 50px" class="navmain">
<!--<li><span>Location Name</span>
<input type="text" class="text" value="Secunderabad" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Secunderabad';}">
</li>-->
<li ><span align="center"></span>
<a href=restaurants.php><input style="background-color: grey; color: WHITE;" type="button" class="text" value="MENU" ></a>
</li>
<!--<li><span>Cuisine Name</span>
<input type="text" class="text" value="<NAME>" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '<NAME>';}">
</li>-->
</ul>
</form>
</div>
<!-- start search-->
<!--<div class="main-search">
<form action="search.php">
<input type="text" value="Search" onFocus="this.value = '';" onBlur="if (this.value == '') {this.value = 'Search';}" class="text"/>
<input type="submit" value=""/>
</form>
<div class="close"><img src="images/cross.png" /></div>
</div>-->
<!--<div class="srch"><button></button></div>
<script type="text/javascript">
$('.main-search').hide();
$('button').click(function (){
$('.main-search').show();
$('.main-search text').focus();
}
);
$('.close').click(function(){
$('.main-search').hide();
});
</script>
</div>-->
</div>
</div>
</div>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
<div class="ordering-section" id="Order">
<div class="container">
<div class="ordering-section-head text-center wow bounceInRight" data-wow-delay="0.4s">
<h3>Ordering food was never so easy</h3>
<div class="dotted-line">
<h4>Just 4 steps to follow </h4>
</div>
</div>
<div class="ordering-section-grids">
<div class="col-md-3 ordering-section-grid">
<div class="ordering-section-grid-process wow fadeInRight" data-wow-delay="0.4s"">
<i class="one"></i><br>
<i class="one-icon"></i>
<p>Choose <span>MENU</span></p>
<label></label>
</div>
</div>
<div class="col-md-3 ordering-section-grid">
<div class="ordering-section-grid-process wow fadeInRight" data-wow-delay="0.4s"">
<i class="two"></i><br>
<i class="two-icon"></i>
<p>Order <span>Your Cuisine</span></p>
<label></label>
</div>
</div>
<div class="col-md-3 ordering-section-grid">
<div class="ordering-section-grid-process wow fadeInRight" data-wow-delay="0.4s"">
<i class="three"></i><br>
<i class="three-icon"></i>
<p>Pay <span> Cash on delivery</span></p>
<label></label>
</div>
</div>
<div class="col-md-3 ordering-section-grid">
<div class="ordering-section-grid-process wow fadeInRight" data-wow-delay="0.4s"">
<i class="four"></i><br>
<i class="four-icon"></i>
<p>Enjoy <span>your food </span></p>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="popular-restaurents" id="Popular-Restaurants">
<div class="container">
<!--<div class="col-md-4 top-restaurents">
<div class="top-restaurent-head">
<h3>Top Restaurants</h3>
</div>
<div class="top-restaurent-grids">
<div class="top-restaurent-logos">
<div class="res-img-1 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-1.jpg" class="img-responsive" alt="" />
</div>
<div class="res-img-2 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-2.jpg" class="img-responsive" alt="" />
</div>
<div class="res-img-1 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-3.jpg" class="img-responsive" alt="" />
</div>
<div class="res-img-2 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-4.jpg" class="img-responsive" alt="" />
</div>
<div class="res-img-1 nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-5.jpg" class="img-responsive" alt="" />
</div>
<div class="res-img-2 nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<img src="images/restaurent-6.jpg" class="img-responsive" alt="" />
</div>
<div class="clearfix"></div>
</div>
</div>
</div>-->
<div style="align-content: center" >
<div class="top-cuisine-head">
<h3 align="center" >-------------------- Top Cuisines ----------------------</h3>
</div>
<div align="center" class="top-cuisine-grids">
<div class="top-cuisine-grid wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine1.jpg" class="img-responsive" alt="" /> </a>
<label>Margherita Pizza</label>
</div>
<div class="top-cuisine-grid wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine2.jpg" class="img-responsive" alt="" /> </a>
<label>Veg Burger</label>
</div>
<div class="top-cuisine-grid wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine3.jpg" class="img-responsive" alt="" /> </a>
<label>Stuff Roll</label>
</div>
<div class="top-cuisine-grid nth-grid wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine4.jpg" class="img-responsive" alt="" /> </a>
<label>Cheese Pulav</label>
</div>
<div class="top-cuisine-grid nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine5.jpg" class="img-responsive" alt="" /> </a>
<label>Mnachurain Noodles</label>
</div>
<div class="top-cuisine-grid nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine6.jpg" class="img-responsive" alt="" /> </a>
<label>Sizzling Brownie with IceCream</label>
</div>
<div class="top-cuisine-grid nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine7.jpg" class="img-responsive" alt="" /> </a>
<label>Sitafal Rabdi</label>
</div>
<div class="top-cuisine-grid nth-grid nth-grid1 wow bounceIn" data-wow-delay="0.4s">
<a href=""><img src="images/cuisine8.jpg" class="img-responsive" alt="" /> </a>
<label>Veg Crisps</label>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<!--<div class="service-section">
<div class="service-section-top-row">
<div class="container">
<div class="service-section-top-row-grids wow bounceInLeft" data-wow-delay="0.4s">
<div class="col-md-3 service-section-top-row-grid1">
<h3>Enjoy Exclusive Food Order any of these</h3>
</div>
<div class="col-md-2 service-section-top-row-grid2">
<ul>
<li><i class="arrow"></i></li>
<li class="lists">Party Orders</li>
</ul>
<ul>
<li><i class="arrow"></i></li>
<li class="lists">Home Made Food</li>
</ul>
<ul>
<li><i class="arrow"></i></li>
<li class="lists"> Diet Food </li>
</ul>
</div>
<div class="col-md-5 service-section-top-row-grid3">
<img src="images/lunch.png" class="img-responsive" alt="" />
</div>
<div class="col-md-2 service-section-top-row-grid4 wow swing animated" data-wow-delay= "0.4s">
<a href="order.php"><input type="submit" value="Order Now"></a>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>-->
<div class="service-section-bottom-row">
<div class="container">
<div class="col-md-4 service-section-bottom-grid wow bounceIn "data-wow-delay="0.2s">
<div class="icon">
<img src="images/icon1.jpg" class="img-responsive" alt="" />
</div>
<div class="icon-data">
<h4>100% Faster Service</h4>
<p>Your Order Reaches to You in the Fastest Way. </p>
</div>
<div class="clearfix"></div>
</div>
<div class="col-md-4 service-section-bottom-grid wow bounceIn "data-wow-delay="0.2s">
<div class="icon">
<img src="images/icon2.jpg" class="img-responsive" alt="" />
</div>
<div class="icon-data">
<h4>Affordable</h4>
<p>Good Quality Low Price. </p>
</div>
<div class="clearfix"></div>
</div>
<div class="col-md-4 service-section-bottom-grid wow bounceIn "data-wow-delay="0.2s">
<div class="icon">
<img src="images/icon3.jpg" class="img-responsive" alt="" />
</div>
<div class="icon-data">
<h4>Variety of Dishes</h4>
<p>Choose dishes you like.</p>
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<script>
function fun(item1)
{
document.getElementById('hidden1').value=item1;
document.getElementById("form_id").submit();
/*<?php
/*$id=$_SESSION['uid'];
$item1= "<script>document.getElementByID('item1').value</script>";
$sql="INSERT INTO orderlist VALUES ('$id','','$item1','30')";
$query=mysqli_query($conn, $sql);
*/?>*/
}
</script>
<?php
if(isset($_POST['hid']))
{
$name=$_POST['hid'];
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name','30')";
$query=mysqli_query($conn, $sql);
header('Location:fastfood.php');
}
?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists">
<form method="POST" id="form_id">
<input type="hidden" id="hidden1" name="hid" onchange="<?php echo $_SERVER['PHP_SELF']; ?>"/>
<input style="display: none;" type="submit"/>
</form>
<h4>Pizzas</h4>
<p>Margherita Pizza</p>
<p>Mexican Delight</p>
<p>Cheese Burst Pizza</p>
<p>American Heat</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('MargheritaPizza')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('MexicanDelight')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('CheeseBurstPizza')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('AmericanHeat')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Burgers</h4>
<p><NAME> Burger</p>
<p>Masala Twist Burger</p>
<p>Panner Burger</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('HerbChillyBurger')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('MasalaTwistBurger')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('PannerBurger')" type="submit" value="Pick" name="Pick"/></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Hot Dogs</h4>
<p>Veg Cheese Hot Dog</p>
<p>Colesaw Hot Dog</p>
<p>Grill Cheese Masala Hot Dog</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('VegCheeseHotDog')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ColesawHotDog')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('GrillCheeseMasalaHotDog')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep><?php include 'header.php';?>
<script>
function fun(item1)
{
document.getElementById('hidden1').value=item1;
document.getElementById("form_id").submit();
/*<?php
/*$id=$_SESSION['uid'];
$item1= "<script>document.getElementByID('item1').value</script>";
$sql="INSERT INTO orderlist VALUES ('$id','','$item1','30')";
$query=mysqli_query($conn, $sql);
*/?>*/
}
</script>
<?php
if(isset($_POST['hid']))
{
$name=$_POST['hid'];
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name','30')";
$query=mysqli_query($conn, $sql);
header('Location:desserts.php');
}
?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="orders">
<div class="container">
<div class="order-top">
<li class="item-lists">
<form method="POST" id="form_id">
<input type="hidden" id="hidden1" name="hid" onchange="<?php echo $_SERVER['PHP_SELF']; ?>"/>
<input style="display: none;" type="submit"/>
</form>
<h4>Ice Creams</h4>
<p>Sundaes</p>
<p>Hot Fudge</p>
<p>Black Forest Pastery Ice Cream</p>
<p>Royal Scoops</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('Sundaes')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('HotFudge')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('BlackForestPasteryIceCream')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('RoyalScoops')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Thick Shakes</h4>
<p>Choco Blast</p>
<p>Royal Vanilla</p>
<p>Litchi</p>
<p>Choco Oreo</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ChocoBlast')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('RoyalVanilla')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('Litchi')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ChocoOreo')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="order-top">
<li class="item-lists"><h4>Special</h4>
<p>Classic Vanilla Cheesecake</p>
<p>Sizzling Brownie With Ice Cream</p>
<p>Sitafal Rabdi</p>
</li>
<li class="item-lists">
<div class="special-info grid_1 simpleCart_shelfItem">
<h4>Price</h4>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('ClassicVanillaCheesecake')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('SizzlingBrownieWithIceCream')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
<div class="pre-top">
<div class="pr-left">
<div class="item_add"><span class="item_price"><h6>ONLY ₹30.00</h6></span></div>
</div>
<div class="pr-right">
<div class="item_add"><span class="item_price"><input onclick="fun('SitafalRabdi')" type="submit" value="Pick" name="Pick"/></span></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</li>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<!-- footer-section-ends -->
<?php include 'footer.php';?><file_sep># OFDS
Online Food Delivery System
<file_sep><?php include 'header.php';?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
<div class="main">
<div class="container">
<div class="register">
<form action="signup123.php" method="post">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div class="wow fadeInLeft" data-wow-delay="0.4s">
<span>First Name<label>*</label></span>
<input type="text" name="fname" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Last Name<label>*</label></span>
<input type="text" name="lname" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Email Address<label>*</label></span>
<input type="text" name="email" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Address<label>*</label></span>
<input type="textarea" name="address" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Contact Number<label>*</label></span>
<input type="text" name="tel" pattern="[789][0-9]{9}" title="You must enter 10 digits" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>City<label>*</label></span>
<input type="text" name="city" required="required">
</div>
<div class="clearfix"> </div>
<a class="news-letter" href="#">
<!--<label class="checkbox"><input type="checkbox" name="checkbox" checked=""><i> </i>Sign Up for Newsletter</label>-->
</a>
</div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div class="wow fadeInLeft" data-wow-delay="0.4s">
<span>Password<label>*</label></span>
<input type="<PASSWORD>" name="password" required="required">
</div>
<div class="wow fadeInRight" data-wow-delay="0.4s">
<span>Confirm Password<label>*</label><label id="er"> </label></span>
<input type="password" name="conpassword" required="required">
</div>
<script >
<?php
if($_SESSION['error']){
?>
document.getElementById("er").innerHTML ="password and confirm password are not match.";//titary[c]
<?php
}
?>
</script>
</div>
<div class="clearfix"> </div>
<div class="register-but">
<input type="submit" value="submit" name="submit">
<div class="clearfix"> </div>
</div>
</form >
</div>
</div>
</div>
</div>
</div>
<?php include 'footer.php';?><file_sep><?php
session_start();
$conn = mysqli_connect("localhost:3306", "root", "","pcs_msit_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["Pick1"]))
{
$name1=$_POST["item1"];
}
elseif(isset($_POST["Pick2"]))
{
$name1=$_POST["item2"];
}
elseif(isset($_POST["Pick3"]))
{$name1=$_POST["item3"];}
$id=$_SESSION['uid'];
$sql="INSERT INTO orderlist VALUES ('$id','','$name1','30')";
$query=mysqli_query($conn, $sql);
header('Location:chinese.php');
?>
| 02f091e1ddc0e89aff12073dd1c10db76ea1e029 | [
"Markdown",
"PHP"
] | 20 | PHP | jimmi1998/OFDS | b742ca4a3411973f2abbe0fa4eaba595a1f0d909 | 618f8884837981775bb40753e4cbd2cd06e0269f |
refs/heads/master | <file_sep>#source("utilAD.R")
#source("simulation.R")
#Example 1
#Generate a time series of ER graphs of length 12,
#create graph anomaly at time point 6
n <- 100
glist <- list()
for (i in 1:5) {
glist[[i]] <- sample_gnp(n,.1)
}
glist[[6]] <- sample_gnp(n,.9)
glist[[7]] <- sample_gnp(n,.1)
for (i in 8:12) {
glist[[i]] <- sample_gnp(n,.1)
}
# Do anomaly detection with OMNI, provide the quantitative control chart for GraphAD and VertexAD
result.OMNI<- qccAD(glist, l=4,d=1,dsvd=NULL,method="OMNI",
diag.augment = TRUE, approx=FALSE, par=FALSE, numpar=2)
#print the number of deviation for GraphAD, only positive ones are meaningful
print(result.OMNI$GraphAD)
# Do anomaly detection with MASE
result.MASE<- qccAD(glist, l=4,d=2,dsvd=2,method="MASE",
diag.augment = TRUE, approx=FALSE, par=FALSE, numpar=2)
#print the number of deviation for GraphAD, only positive ones are meaningful
print(result.MASE$GraphAD)
#Example 2
# Sample a time series of RDPG graph (length tmax > 17) with same 1-1 matched vertices unweighted
# hollow symmetric undirected graphs, the latent positions i.i.d uniform.
# Some vertices in 16-th and 17-th graphs are given perturbations so there exists anomalies at 16:17.
n <- 100 #number of vertices
nperturb <- 20 #number of perturbed vertices
cperturb <- .12 #number of perturbation, larger cperturb means more obvious anomalies.
rmin <- .2 # parameter for uniform[rmin, rmax].
rmax <- .8 # parameter for uniform[rmin, rmax].
tmax <- 22 # number of graphs must be greater than 17.
#Generate data or load the data you want
glist <- generate.tsg(n, nperturb, cperturb=NULL, rmin, rmax, tmax)$glist
#Do anomaly detection with OMNI in parallel
result.OMNI <- qccAD(glist, l=11,d=1,dsvd=NULL,method="OMNI",
diag.augment = TRUE, approx=FALSE, par=TRUE, numpar=2)
#print the number of deviation for GraphAD, only positive ones are meaningful
print(result.OMNI$GraphAD)
# Do anomaly detection with MASE in parallel
result.MASE<- qccAD(glist, l=11,d=1,dsvd=2,method="MASE",
diag.augment = TRUE, approx=FALSE, par=TRUE, numpar=2)
#print the number of deviation for GraphAD, only positive ones are meaningful
print(result.MASE$GraphAD)
#Example 3
#five of ER tsg with change point at t=6 and five at t=8.
n <- 100
dat <- matrix(0, 10, 8)
for (j in 1:5) {
glist <- list()
for (i in 1:5) {
glist[[i]] <- sample_gnp(n,.1)
}
glist[[6]] <- sample_gnp(n,.9)
for (i in 7:12) {
glist[[i]] <- sample_gnp(n,.1)
}
# Do anomaly detection with OMNI, provide the quantitative control chart for GraphAD and VertexAD
result.OMNI<- qccAD(glist, l=4,d=1,dsvd=NULL,method="OMNI",
diag.augment = TRUE, approx=FALSE, par=FALSE, numpar=2, plot.figure = FALSE)
dat[j,] <- result.OMNI$GraphAD
}
for (j in 6:10) {
glist <- list()
for (i in 1:7) {
glist[[i]] <- sample_gnp(n,.1)
}
glist[[8]] <- sample_gnp(n,.9)
for (i in 9:12) {
glist[[i]] <- sample_gnp(n,.1)
}
# Do anomaly detection with OMNI, provide the quantitative control chart for GraphAD and VertexAD
result.OMNI<- qccAD(glist, l=4,d=1,dsvd=NULL,method="OMNI",
diag.augment = TRUE, approx=FALSE, par=FALSE, numpar=2, plot.figure = FALSE)
dat[j,] <- result.OMNI$GraphAD
}
df <- data.frame(dat,class=factor(c(rep("t6",5),rep("t8",5))))
pca_res <- prcomp(dat, scale. = TRUE)
library(ggfortify)
autoplot(pca_res, data = df,colour="class")
<file_sep># library(igraph)
# library(dplyr)
# library(ggplot2)
# library(latex2exp)
# library(qcc)
# library(gtools)
#'
#' Given a decreasingly sorted vector, return the given number of elbows
#'
#' @param dat a input vector (e.g. a vector of standard deviations), or a input feature matrix
#' @param n the number of returned elbows
#' @param threshold either FALSE or a number. If threshold is a number, then all the elements in d that are not larger than the threshold will be ignored.
#' @param plot logical. When T, it depicts a scree plot with highlighted elbows
#' @param main a string of the plot title
#'
#' @return a vector of length \eqn{n}
#'
#' @references <NAME> (2006), Automatic dimensionality selection from
#' the scree plot via the use of profile likelihood, Computational
#' Statistics & Data Analysis, Volume 51 Issue 2, pp 918-930, November, 2006.
#'
#' @export
#' @importFrom graphics plot points
#' @importFrom stats sd dnorm
#'
getElbows <- function(dat, n = 3, threshold = FALSE, plot = TRUE, main="", ...) {
## Given a decreasingly sorted vector, return the given number of elbows
##
## Args:
## dat: a input vector (e.g. a vector of standard deviations), or a input feature matrix.
## n: the number of returned elbows.
## threshold: either FALSE or a number. If threshold is a number, then all
## the elements in d that are not larger than the threshold will be ignored.
## plot: logical. When T, it depicts a scree plot with highlighted elbows.
##
## Return:
## q: a vector of length n.
##
## Reference:
## <NAME> <NAME> (2006), "Automatic dimensionality selection from
## the scree plot via the use of profile likelihood", Computational
## Statistics & Data Analysis, Volume 51 Issue 2, pp 918-930, November, 2006.
# if (is.unsorted(-d))
if (is.matrix(dat)) {
d <- sort(apply(dat,2,sd), decreasing=TRUE)
} else {
d <- sort(dat,decreasing=TRUE)
}
if (!is.logical(threshold))
d <- d[d > threshold]
p <- length(d)
if (p == 0)
stop(paste("d must have elements that are larger than the threshold ",
threshold), "!", sep="")
lq <- rep(0.0, p) # log likelihood, function of q
for (q in 1:p) {
mu1 <- mean(d[1:q])
mu2 <- mean(d[-(1:q)]) # = NaN when q = p
sigma2 <- (sum((d[1:q] - mu1)^2) + sum((d[-(1:q)] - mu2)^2)) /
(p - 1 - (q < p))
lq[q] <- sum( dnorm( d[1:q ], mu1, sqrt(sigma2), log=TRUE) ) +
sum( dnorm(d[-(1:q)], mu2, sqrt(sigma2), log=TRUE) )
}
q <- which.max(lq)
# print(n)
# print(q)
# print(p)
if (n > 1 && q < (p-1)) {
q <- c(q, q + getElbows(d[(q+1):p], n-1, plot=FALSE))
}
if (plot==TRUE) {
if (is.matrix(dat)) {
sdv <- d # apply(dat,2,sd)
plot(sdv,type="b",xlab="dim",ylab="stdev",main=main,...)
points(q,sdv[q],col=2,pch=19)
} else {
plot(dat, type="b",main=main,...)
points(q,dat[q],col=2,pch=19)
}
}
return(q)
}
#' Function to perform diagonal augmentation for graph adjacency matrix.
#' @param A a hollow adjacency matrix
#' @return a non-hollow adjacency matrix
#' @export
diagAug <- function(A) {
diag(A) <- Matrix::rowSums(A) / (nrow(A)-1)
return(A)
}
#' Calculate \eqn{l_2} distance between latent positions for vertices.
#' @param X,Y are matrices with n rows and d columns
#' @return A vector of size \eqn{n}, with element being \eqn{l_2} distance between rows of X and Y.
#' @export
pdistXY <- function(X,Y) {
D <- Matrix::rowSums((as.matrix(X) - as.matrix(Y))^2)
return(sqrt(D))
}
#'
#' Function to perform graph adjacency spectral embedding (ASE)
#' @param A adjacency matrix
#' @param d number of embedding dimension. If NULL, dimension is chosen automatically.
#' @param approx whether to find a few approximate singular values and corresponding singular vectors of a matrix using irlba package (TRUE/FALSE).
#' @param diagaug whether to do diagonal augmentation (TRUE/FALSE)
#' @param d.max maximum number of embedding dimensions to try when d is not provided. Default is round(log(nrow(A))).
#' @param elbow number of elbow selected in Zhu & Ghodsi method for the scree plot of each individual graph singular values. Default is \eqn{2}.
#' @references Zhu, Mu and Ghodsi, Ali (2006), Automatic dimensionality selection from
#' the scree plot via the use of profile likelihood, Computational
#' Statistics & Data Analysis, Volume 51 Issue 2, pp 918-930, November, 2006.
#' @return A matrix with n rows and d columns containing the estimated latent positions
#' @export
#' @references <NAME>., <NAME>., <NAME>., <NAME>. A
#' Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs,
#' \emph{Journal of the American Statistical Association}, Vol. 107(499), 2012
ase <- function(A, d=NULL, d.max=round(log(nrow(A))),diagaug=TRUE, approx=TRUE, elbow=2) {
n <- nrow(A)
#require(Matrix)
# diagaug
if (diagaug) {
diag(A) <- Matrix::rowSums(A) / (n-1)
}
if (approx) {
#require(irlba)
if (is.null(d)){
A.svd <- irlba::irlba(A, d.max, maxit=10000, tol=1e-10)
result = getElbows(A.svd$d, plot = TRUE)
if(length(result)==1){
d = result
print(paste0("do not have ",elbow," elbows, output first elbow instead"))
}else{
d = result[elbow]
}
}
A.svd <- irlba::irlba(A, d, maxit=10000, tol=1e-10)
} else {
#require(rARPACK)
if (is.null(d)){
A.svd <- svd(A,d.max)
result = getElbows(A.svd$d, plot = TRUE)
if(length(result)==1){
d = result
print(paste0("do not have ",elbow," elbows, output first elbow instead"))
}else{
d = result[elbow]
}
}
A.svd <- svd(A,d)
}
Xhat <- as.matrix(A.svd$u[,1:d]) %*% diag(sqrt(A.svd$d[1:d]), nrow=d, ncol=d)
return(list(eval=A.svd$d, Xhat=Matrix(Xhat)))
}
#' Function to build OMNI matrix
#' @param Alist a list (length M) of n x n adjacency matrices or igraph objects
#' @param diagaug whether to do diagonal augmentation (TRUE/FALSE)
#' @return Omnibus matrix of Mn x Mn
#' @import igraph
buildOmni <- function(Alist, diagaug=FALSE) {
# require(igraph)
# require(Matrix)
if (class(Alist[[1]]) == "igraph") {
Alist <- lapply(Alist, igraph::get.adjacency)
}
if (diagaug) {
Alist <- lapply(Alist, diagAug)
}
m <- length(Alist)
nvec <- sapply(Alist, nrow)
nsum <- c(0, cumsum(nvec))
omni <- (bdiag(Alist))
for (i in 1:(m-1)) {
irng <- (nsum[i]+1):nsum[i+1]
for (j in (i+1):m) {
jrng <- (nsum[j]+1):nsum[j+1]
omni[irng,jrng] <- (Alist[[i]] + Alist[[j]]) / 2
omni[jrng,irng] <- omni[irng,jrng]
}
}
return(omni)
}
#' Function to build OMNI matrix with two matrix
#' @param Alist a list (length \eqn{2}) of n x n adjacency matrices or igraph objects
#' @param diagaug whether to do diagonal augmentation (TRUE/FALSE)
#' @return Omnibus matrix of 2n x 2n
fast2buildOmni <- function(Alist, diagaug=FALSE, attrweight=NULL ) {
# require(igraph)
# require(Matrix)
if (class(Alist[[1]]) == "igraph") {
Alist <- lapply(Alist, function(x) igraph::get.adjacency(x, attr = attrweight ) )
}
if (diagaug) {
Alist <- lapply(Alist, diagAug)
}
omni <- cbind(Alist[[1]], (Alist[[1]]+Alist[[2]])/2 )
omni <- rbind(omni, cbind((Alist[[1]]+Alist[[2]])/2, Alist[[2]]))
return(omni)
}
#' Function to calculate \eqn{l_2} distance between adjacent latent position estmate for graphs and vertices with OMNI
#' @param n number of vertices in each graph
#' @param Z a matrix of size 2n x d as the latent estimate for the omnibus matrix contructed by adjacent graphs
#' @return A list containing a numeric value tnorm, with the \eqn{l_2} norm of
#' latent position estmate difference for adjacent graphs, and a vector pdist
#' with \eqn{l_2} distance between latent position estmates for each vertex (size n).
fast2doOmni <- function(n, Z) {
norm <- sapply(Z, function(x) norm(x$Xhat[1:n,] - x$Xhat[-(1:n),], "2"))
pdist <- sapply(Z, function(x) pdistXY(x$Xhat[1:n,],x$Xhat[-(1:n),]))
return(list(tnorm=norm, pdist=pdist))
}
#' Function to obtain latent position estmates for MASE (Multiple Adjancency Spectral Embedding) with individual ASE estimates for corresponding graphs
#' @param A a list (length M-1) of n x n adjacency matrices
#' @param latpos.list a list (length M-1) of individual ASE estimates for the corresponding adjacency matrices
#' @param dsvd dimension for joint embedding. If NULL then dimension is chosen automatically as the second elbow selected in Zhu & Ghodsi method for the scree plot of the singular values of the concatenated spectral embeddings of invidual ASE estimates.
#' @return A list with length (M-1) consists of matrices with size n x dsvd each.
mase.latent <- function(A, latpos.list, dsvd=NULL){
m <- length(A)
A <- lapply(A, function(x) (x) )
jrdpg <- mase(A, latpos.list,dsvd, show.scree.results = TRUE)
d2 <- dim(jrdpg$R[[1]])[1]
B.svd <- lapply(jrdpg$R, function (x) svd(x) )
Xhat <- lapply(B.svd, function(x) (jrdpg$V) %*% as.matrix(x$u) %*% diag(sqrt(x$d), nrow=d2, ncol=d2) %*% diag(sign(x$d)) %*% t(as.matrix(x$u) ) )
return(list(Xhat=Xhat))
}
#' Function to calculate \eqn{l_2} distance between adjacent latent position estmate for graphs and vertices with MASE
#' @param glist a list (length M) of n x n adjacency matrices or igraph objects
#' @param latpos.list a list (length M) of ASE estimates for each graphs
#' @param nmase number of graphs to do joint embedding of MASE. It can only be 2 or M.
#' @param dsvd dsvd is number of dimension to do joint svd for MASE. If NULL then dimension is chosen automatically as the second elbow selected in Zhu & Ghodsi method for the scree plot of the singular values of the concatenated spectral embeddings of invidual ASE estimates.
#' @return A list containing a vector tnorm of length M-1, with the
#' latent position estmate difference for graphs, and a matrix pdist
#' with latent position estmate difference for vertices (size n x M-1 ).
doMase <- function(glist, latpos.list, nmase=2, dsvd=NULL,attrweight=NULL)
{
n <- igraph::vcount(glist[[1]])
tmax <- length(glist)
if (nmase == 2) {
Xhat <- lapply(1:(tmax-1), function(x) mase.latent(lapply(glist[x:(x+1)], function(y) igraph::get.adjacency(y,attr=attrweight) ), latpos.list[x:(x+1)] , dsvd))
norm <- sapply(1:(tmax-1), function(x) norm((Xhat[[x]]$Xhat)[[1]] - (Xhat[[x]]$Xhat)[[2]], "2"))
pdist <- sapply(1:(tmax-1), function(x) pdistXY((Xhat[[x]]$Xhat)[[1]] , (Xhat[[x]]$Xhat)[[2]]))
dsvd <- sapply(Xhat, function(x) x$d)
} else {
adj <- lapply(glist, function(y) igraph::get.adjacency(y, attr = attrweight) )
Xhat <- mase.latent(adj, latpos.list,dsvd)
norm <- sapply(1:(tmax-1), function(x) norm(Xhat$Xhat[[x]]-Xhat$Xhat[[x+1]], "2"))
pdist <- sapply(1:(tmax-1), function(x) pdistXY(Xhat$Xhat[[x]], Xhat$Xhat[[x+1]]))
dsvd <- Xhat$d
}
return(list(tnorm=norm, pdist=pdist,d=dsvd))
}
#' Function to perform joint embedding part of MASE
#'
#' @param Adj_list a list of adjacency matrices with the same size n x n
#' @param d number of joint embedding dimensions. If NA, dimension is chosen automatically
#' @param latpos.list Individual ASE estimate for the adjacent graphs
#' @param elbow_mase number of elbow selected in Zhu & Ghodsi method for the scree plot of the singular values of the concatenated spectral embeddings of MASE.
#' @param show.scree.results when TRUE, the histogram of the estimated d for each graph, and the scree plot of the singular values of the graph is shown if d is not specified.
#'
#' @return A list containing a matrix V of size n x d, with the
#' estimated invariant subspace, and a list R with the individual score parameters for each graph (size d x d each).
#'
#' @references
#' @export
mase <- function(Adj_list, latpos.list, dsvd = NULL,
elbow_mase = 2,
show.scree.results = FALSE) {
V_all <- Reduce(cbind, latpos.list)
#require(rARPACK)
jointsvd <- svd(V_all)
if(is.null(dsvd)) {
# if(show.scree.results) {
# hist(sapply(latpos.list, ncol), main = "Estimated d for each graph")
# }
result = getElbows(jointsvd$d, plot = show.scree.results)#[elbow_mase]
if(length(result)==1){
dsvd = result
}else{
dsvd = result[elbow_mase]
}
}
V = jointsvd$u[, 1:dsvd, drop = FALSE]
R <- project_networks(Adj_list, V)
return(list(V = V, sigma = jointsvd$d, R = R))
}
#'
#' Function to estimated the score matrices of a list of graphs given the common invariant subspace V
#'
#' @param Adj_list list of adjacency matrices, of size n x n
#' @param V common invariant subspace. A matrix of size n x d.
#' @return A list containing the score matrices
#'
project_networks <- function(Adj_list, V) {
# require(Matrix)
lapply(Adj_list, function(A) Matrix::crossprod(Matrix::crossprod(A, V), V))
}
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu^{t}-3\sigma^t}) .
#' Return a list of cases beyond limits and violating runs
#' @references see R package qcc
shewhart.rules <- function(object, limits = object$limits, run.length = qcc.options("run.length"),plot.LCL=FALSE)
{
# Return a list of cases beyond limits and violating runs
bl <- beyond.limits(object, limits = limits, plot.LCL=plot.LCL )
vr <- qcc::violating.runs(object, run.length = run.length)
list(beyond.limits = bl, violating.runs = vr)
}
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu^{t}-3\sigma^t}) .
#' Return cases beyond limits
#' @references see R package qcc
beyond.limits <- function(object, limits = object$limits, plot.LCL=FALSE)
{
statistics <- c(object$statistics, object$newstats)
lcl <- limits[,1]
ucl <- limits[,2]
index.above.ucl <- seq(along = statistics)[statistics > ucl]
if(plot.LCL){
index.below.lcl <- seq(along = statistics)[statistics < lcl]
return(c(index.below.lcl,index.above.ucl))
}else{
return(c(index.above.ucl))
}
}
#' Function to plot Shewhart chart for GraphAD
#' @param x a qcc object
#' @param l length of previous graphs to estimate moving averages and moving standard deviation.
#' @param title a string of the plot title
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu^{t}-3\sigma^t}) .
#' @return A control chart ggplot for GraphAD
#'
plot.qcc <- function(x, l=l, title, plot.LCL=FALSE){
object <- x # Argh. Really want to use 'object' anyway
if ((missing(object)) | (!inherits(object, "qcc")))
stop("an object of class `qcc' is required")
# collect info from object
type <- object$type
std.dev <- object$std.dev
data.name <- object$data.name
center <- object$center
stats <- object$statistics
limits <- object$limits
lcl <- limits[,1]
ucl <- limits[,2]
newstats <- object$newstats
newdata.name <- object$newdata.name
violations <- object$violations
statistics <- c(stats, newstats)
indices <- 1:length(statistics)
#library(ggplot2)
l.length <- length(indices)
tmax <- (l.length+l-1)
tvec <- 1:(l.length+l)
m2 <- names(gtools::running(tvec, width=2))
minx <- m2[l:(l.length+l-1)]
vioinx <- rep(0,length(indices))
runinx <- rep(0,length(indices))
vioinx[violations$beyond.limits] <- 1
runinx[violations$violating.runs] <- 1
df <- data.frame(time=indices, y= statistics,lcl=lcl,ucl=ucl,center=center,lim=vioinx,run=runinx)
if(plot.LCL){
p <- ggplot2::ggplot(df,aes(x=time, y=y))+
geom_step(aes(x=time, y=ucl), linetype="dashed")+
geom_step(aes(x=time, y=lcl), linetype="dashed")+
geom_step(aes(x=time, y=center), linetype="solid") +
geom_point(data = df, alpha=1, color="black")+ylab(TeX("$y^{(t)}$"))+
geom_line(aes(x=time, y=y))+
geom_point(data = df %>% filter(run==1), alpha=1, color="yellow")+
geom_point(data = df %>% filter(lim==1), alpha=1, color="red") +
scale_x_discrete(name ="time points",
limits=minx)+theme_bw()+
annotate("text", label = "UCL",
x = tmax-l+1.1, y = rev(ucl)[1]+.3)+
annotate("text", label = "CL",
x = tmax-l+1.1, y = rev(center)[1]+.1 )+
annotate("text", label = "LCL",
x = tmax-l+1.1, y = rev(lcl)[1]-.3 )+theme_classic(base_size = 18)+
theme(axis.text.x = element_text(angle=45),legend.position = "none",plot.title = element_text(hjust = 0.5,size=20, face='bold'),plot.subtitle = element_text(hjust = 0.5)) +ggtitle(title)
}else{
p <- ggplot2::ggplot(df,aes(x=time, y=y))+
geom_step(aes(x=time, y=ucl), linetype="dashed")+
geom_step(aes(x=time, y=center), linetype="solid") +
geom_point(data = df, alpha=1, color="black")+ylab(TeX("$y^{(t)}$"))+
geom_line(aes(x=time, y=y))+
geom_point(data = df %>% filter(run==1), alpha=1, color="yellow")+
geom_point(data = df %>% filter(lim==1), alpha=1, color="red") +
scale_x_discrete(name ="time points",
limits=minx)+theme_bw()+
annotate("text", label = "UCL",
x = tmax-l+1.1, y = rev(ucl)[1]+.3)+
annotate("text", label = "CL",
x = tmax-l+1.1, y = rev(center)[1]+.1 )+theme_classic(base_size = 18)+
theme(axis.text.x = element_text(angle=45),legend.position = "none",plot.title = element_text(hjust = 0.5,size=20, face='bold'),plot.subtitle = element_text(hjust = 0.5)) +ggtitle(title)
}
return(p)
invisible()
}
#' Function to plot Shewhart chart for VertexAD
#' @param x a list of qcc object
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu_i^{t}-3\sigma_i^t}) .
#' @param l length of previous graphs to estimate moving averages and moving standard deviation.
#' @param title a string of the plot title
#' @return A control chart ggplot for VertexAD
plot.qcc.vertex <- function(x, l=l, title, plot.LCL=FALSE){
l.length <- length(x)
df <- c() #c(2,6)
for (i in seq(l.length)) {
object <- x[[i]] # Argh. Really want to use 'object' anyway
if ((missing(object)) | (!inherits(object, "qcc")))
stop("an object of class `qcc' is required")
# collect info from object
type <- object$type
std.dev <- object$std.dev
data.name <- object$data.name
center <- object$center
stats <- object$statistics
limits <- object$limits
lcl <- limits[,1]
ucl <- limits[,2]
newstats <- object$newstats
newdata.name <- object$newdata.name
violations <- object$violations
statistics <- c(stats, newstats)
indices <- 1:length(statistics)
#library(ggplot2)
tmax <- l.length+1
tvec <- 1:(l.length+l)
m2 <- names(gtools::running(tvec, width=2))
minx <- m2[l:(l.length+l-1)]
vioinx <- rep(0,length(indices))
runinx <- rep(0,length(indices))
vioinx[violations$beyond.limits] <- 1
runinx[violations$violating.runs] <- 1
idf <- data.frame(vertex=indices, y= statistics, timepoints=factor(minx[i], levels = minx),lcl=lcl,ucl=ucl,center=center,lim=vioinx,run=runinx)
df <- rbind(df,idf)
}
if(plot.LCL){
p <- ggplot2::ggplot(df,aes(x=vertex, y=y))+
geom_point(data = df, alpha=.1, color="black",shape=20,size=.5)+
geom_point(data = df %>% filter(lim==1), alpha=.3, color="red",shape=20,size=1)+
geom_hline(aes(yintercept=center), linetype="solid")+facet_wrap(~timepoints,nrow = 1,switch = "x", scales = "fixed") +
geom_hline(aes(yintercept=ucl), linetype="dashed")+
geom_hline(aes(yintercept=lcl), linetype="dashed")+
labs(x="vertex")+theme_bw()+ylab(TeX("$y_{i}^{(t)}$"))+
theme(axis.text.x = element_text(angle=45),legend.position = "none",plot.title = element_text(hjust = 0.5,size=10, face='bold'),plot.subtitle = element_text(hjust = 0.5)) +ggtitle(title)
}else{
p <- ggplot2::ggplot(df,aes(x=vertex, y=y))+
geom_point(data = df, alpha=.1, color="black",shape=20,size=.5)+
geom_point(data = df %>% filter(lim==1), alpha=.3, color="red",shape=20,size=1)+
geom_hline(aes(yintercept=center), linetype="solid")+facet_wrap(~timepoints,nrow = 1,switch = "x", scales = "fixed") +
geom_hline(aes(yintercept=ucl), linetype="dashed")+
labs(x="vertex")+theme_bw()+ylab(TeX("$y_{i}^{(t)}$"))+
theme(axis.text.x = element_text(angle=45),legend.position = "none",plot.title = element_text(hjust = 0.5,size=10, face='bold'),plot.subtitle = element_text(hjust = 0.5)) +ggtitle(title)
}
return(p)
invisible()
}
comb <- function(x, ...) {
lapply(seq_along(x),
function(i) c(x[[i]], lapply(list(...), function(y) y[[i]])))
}
#-----------------------------------------------------------------------------#
# #
# QUALITY CONTROL CHARTS IN R #
# #
# An R package for statistical in-line quality control. #
# #
# Written by: <NAME> #
# Department of Statistics #
# University of Perugia, ITALY #
# <EMAIL>.unipg.it #
# #
#-----------------------------------------------------------------------------#
#
#' Main function to create a 'qcc' object
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu^{t}-3\sigma^t}) .
#' @references see R package qcc
qcc <- function(data, type = c("xbar", "R", "S", "xbar.one", "p", "np", "c", "u", "g"), sizes, center, std.dev, limits, data.name, labels, newdata, newsizes, newdata.name, newlabels, nsigmas = 3, confidence.level, rules = shewhart.rules, plot = TRUE, plot.LCL=FALSE,...)
{
call <- match.call()
if (missing(data))
stop("'data' argument is not specified")
if(identical(type, eval(formals(qcc)$type)))
{ type <- as.character(type)[1]
warning("chart 'type' not specified, assuming \"", type, "\"",
immediate. = TRUE) }
if(!exists(paste("stats.", type, sep = ""), mode="function") |
!exists(paste("sd.", type, sep = ""), mode="function") |
!exists(paste("limits.", type, sep = ""), mode="function"))
stop(paste("invalid", type, "control chart. See help(qcc) "))
if (missing(data.name))
data.name <- deparse(substitute(data))
data <- data.matrix(data)
if (missing(sizes))
{ if (any(type==c("p", "np", "u")))
stop(paste("sample 'sizes' must be given for a", type, "Chart"))
else
sizes <- apply(data, 1, function(x) sum(!is.na(x))) }
else
{ if (length(sizes)==1)
sizes <- rep(sizes, nrow(data))
else if (length(sizes) != nrow(data))
stop("sizes length doesn't match with data") }
if (missing(labels))
{ if (is.null(rownames(data))) labels <- 1:nrow(data)
else labels <- rownames(data) }
stats <- paste("stats.", type, sep = "")
if (!exists(stats, mode="function"))
stop(paste("function", stats, "is not defined"))
stats <- do.call(stats, list(data, sizes))
statistics <- stats$statistics
if (missing(center)) center <- stats$center
sd <- paste("sd.", type, sep = "")
if (!exists(sd, mode="function"))
stop(paste("function", sd, "is not defined!"))
missing.std.dev <- missing(std.dev)
if (missing.std.dev)
{ std.dev <- NULL
std.dev <- switch(type,
"xbar" = { if(any(sizes > 25)) "RMSDF"
else "UWAVE-R" },
"xbar.one" = "MR",
"R" = "UWAVE-R",
"S" = "UWAVE-SD",
NULL)
std.dev <- do.call(sd, list(data, sizes, std.dev)) }
else
{ if (is.character(std.dev))
{ std.dev <- do.call(sd, list(data, sizes, std.dev)) }
else
{ if (!is.numeric(std.dev))
stop("if provided the argument 'std.dev' must be a method available or a numerical value. See help(qcc).") }
}
names(statistics) <- rownames(data) <- labels
names(dimnames(data)) <- list("Group", "Samples")
object <- list(call = call, type = type,
data.name = data.name, data = data,
statistics = statistics, sizes = sizes,
center = center, std.dev = std.dev)
# check for new data provided and update object
if (!missing(newdata))
{ if (missing(newdata.name))
{newdata.name <- deparse(substitute(newdata))}
newdata <- data.matrix(newdata)
if (missing(newsizes))
{ if (any(type==c("p", "np", "u")))
stop(paste("sample sizes must be given for a", type, "Chart"))
else
newsizes <- apply(newdata, 1, function(x) sum(!is.na(x))) }
else
{ if (length(newsizes)==1)
newsizes <- rep(newsizes, nrow(newdata))
else if (length(newsizes) != nrow(newdata))
stop("newsizes length doesn't match with newdata") }
stats <- paste("stats.", type, sep = "")
if (!exists(stats, mode="function"))
stop(paste("function", stats, "is not defined"))
newstats <- do.call(stats, list(newdata, newsizes))$statistics
if (missing(newlabels))
{ if (is.null(rownames(newdata)))
{ start <- length(statistics)
newlabels <- seq(start+1, start+length(newstats)) }
else
{ newlabels <- rownames(newdata) }
}
names(newstats) <- newlabels
object$newstats <- newstats
object$newdata <- newdata
object$newsizes <- newsizes
object$newdata.name <- newdata.name
statistics <- c(statistics, newstats)
sizes <- c(sizes, newsizes)
}
conf <- nsigmas
if (!missing(confidence.level))
conf <- confidence.level
if (conf >= 1)
{ object$nsigmas <- conf }
else
if (conf > 0 & conf < 1)
{ object$confidence.level <- conf }
# get control limits
if (missing(limits))
{ limits <- paste("limits.", type, sep = "")
if (!exists(limits, mode="function"))
stop(paste("function", limits, "is not defined"))
limits <- do.call(limits, list(center = center, std.dev = std.dev,
sizes = sizes, conf = conf))
}
else
{ if (!missing.std.dev)
warning("'std.dev' is not used when limits is given")
if (!is.numeric(limits))
stop("'limits' must be a vector of length 2 or a 2-columns matrix")
limits <- matrix(limits, ncol = 2)
dimnames(limits) <- list(rep("",nrow(limits)), c("LCL ", "UCL"))
}
lcl <- limits[,1]
ucl <- limits[,2]
object$limits <- limits
#number of deviation for each data point, i.e., deviation=(x-mu)/sigma
object$deviation <- (object$data - object$center)/object$std.dev
if (is.function(rules)) violations <- rules(object,plot.LCL=plot.LCL)
else violations <- NULL
object$violations <- violations
class(object) <- "qcc"
if(plot) plot(object, ...)
return(object)
}
#' Function to perform anomaly detection for time series of graphs
#' @param glist a list of undirected simple graphs (simple graphs are graphs which do not contain self-loop and multiple edges)
#' in igraph format with same number of vertices with vertices are 1-1 matched.
#' Graphs can be weighted or binary. (Say the length of list to be tmax)
#' @param method a character variable to be chosen among c("OMNI","MASE").
#' The code will first do OMNIbus embedding (OMNI) or Multiple Adjacency Spectrally Ebedding (MASE) with two adjcaency matrices(can be weighted or not) of all input adjacent graphs sequentially.
#' Then use latent positions to calculate test statistics \eqn{y^{t}=||X^{t}- X^{t+1}||} using operator norm.
#' Then for \eqn{t=l,...,tmax-1}, we calculate the moving means \eqn{\mu^t} and moving standard deviations \eqn{\sigma^t} at \eqn{t} by \eqn{y^{t-l+1},...,y^{t-1}}.
#' So only tmax-l time points are ploted as first l graphs have been used as estimating moving means and standard deviations.
#' @param d a fixed integer of dimension to perform OMNI and individual ASE for MASE. If d is NULL, then dimension is chosen automatically.
#' @param l an integer of the number of graphs in time window in estimating the moving mean and moving standard deviation. l must be less than number of graphs and be greater than 3.
#' @param approx a Boolean variable to decide whether to use irlba package to find a few approximate singular values and corresponding singular vectors of a matrix. Default is TRUE.
#' @param diag.augment a Boolean variable to decide whether to do diagonal augmentation when performing adjacency spectral embedding. Default is TRUE.
#' @param par a Boolean variable to decide whether to run in parallel. Default is FALSE.
#' @param numpar an integer number to decide number of clusters for parallel implmentation. Default is 2.
#' @param dsvd An integer number of dimension only used in joint embedding for MASE. If NULL, then dimension is chosen automatically as second elbow selected in Zhu & Ghodsi method for the scree plot of the singular values of the concatenated spectral embeddings of MASE.
#' @param elbow number of elbow in Zhu & Ghodsi method for the scree plot of each individual graph singular values for MASE or of each omnibus matrix singular values for OMNI.
#' @param plot.figure a Boolean variable to decide whether plot control chart. Default is TRUE.
#' @param plot.LCL a Boolean variable to decide whether to show the anomalies lower than lower limits (LCL \eqn{\mu^{t}-3\sigma^t}) .
#' @references <NAME> (2006), Automatic dimensionality selection from
#' the scree plot via the use of profile likelihood, Computational
#' Statistics & Data Analysis, Volume 51 Issue 2, pp 918-930, November, 2006.
#' @references <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>., 2017, November. A central limit theorem for an omnibus embedding of multiple random dot product graphs. In 2017 IEEE International Conference on Data Mining Workshops (ICDMW) (pp. 964-967). IEEE.
#' @references <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>., 2019. Inference for multiple heterogeneous networks with a common invariant subspace. arXiv preprint arXiv:1906.10026.
#' @return A list containing a vector GraphAD of length tmax-l which consists of control charts deviations, with the
#' a list VertexAD (length tmax-l) with vectors of anomalous vertices indices for each graph.
#' @export
#' @examples
#' glist <- list()
#' for (i in 1:5) {
#' glist[[i]] <- sample_gnp(100,.1)
#' }
#' glist[[6]] <- sample_gnp(100,.9)
#' glist[[7]] <- sample_gnp(100,.1)
#' for (i in 8:12) {
#' glist[[i]] <- sample_gnp(100,.1)
#' }
#' result<- qccAD(glist, l=4,d=1,dsvd=1,method="OMNI",
#' diag.augment = TRUE,approx=FALSE, par=FALSE, numpar=2)
#' print(result.OMNI$GraphAD) #print the number of deviation for GraphAD, only positive ones are meaningful
#'
#' @examples
#' # Sample a time series of RDPG graph (length tmax > 17) with same 1-1 matched vertices unweighted
#' # hollow symmetric undirected graphs, the latent positions i.i.d uniform.
#' # Some vertices in 16-th and 17-th graphs are given perturbations so there exists anomalies at 16:17.
#' n <- 100 #number of vertices
#' nperturb <- 20 #number of perturbed vertices
#' cperturb <- .12 #number of perturbation, larger cperturb means more obvious anomalies.
#' rmin <- .2 # parameter for uniform[rmin, rmax].
#' rmax <- .8 # parameter for uniform[rmin, rmax].
#' tmax <- 22 # number of graphs must be greater than 17.
#' #Generate data or load the data you want
#' glist <- generate.tsg(n, nperturb, cperturb=NULL, rmin, rmax, tmax)$glist
#' #Do anomaly detection with OMNI in parallel
#' result.OMNI <- qccAD(glist, l=11,d=1,dsvd=NULL,method="OMNI",
#' diag.augment = TRUE, approx=FALSE, par=TRUE, numpar=2)
#' #print the number of deviation for GraphAD, only positive ones are meaningful
#' print(result.OMNI$GraphAD)
#'
#' # Do anomaly detection with MASE in parallel
#' result.MASE<- qccAD(glist, l=11,d=1,dsvd=2,method="MASE",
#' diag.augment = TRUE, approx=FALSE, par=TRUE, numpar=2)
#' #print the number of deviation for GraphAD, only positive ones are meaningful
#' print(result.MASE$GraphAD)
#'
qccAD <- function(glist, method="OMNI", diag.augment = TRUE, l=3,d=NULL, dsvd=d, approx=TRUE, par=FALSE, numpar=2, elbow=2, plot.figure=TRUE,plot.LCL=FALSE){
tmax <- length(glist)
n <- igraph::vcount(glist[[1]])
tvec <- 1:tmax
m2 <- names(gtools::running(tvec, width=2))
#check if all the graphs are binary
if(Reduce("+",lapply(glist, function(x) igraph::is.weighted(x)))){
attrweight <- "weight"
}else{
attrweight <- NULL
}
if(l>(tmax-1)||l<3||tmax<4){
print(paste0("l has to an integer between 3 and ",tmax-1, " and you need to at least have 4 graphs"))
}
#require(foreach)
if (method=="OMNI"){
#Initialize moving averages and moving standard deviation for GraphAD
mean2omni <- rep(1, (tmax-1)-(l-1))
std2omni <- rep(1,(tmax-1)-(l-1))
#Initialize moving averages and moving standard deviation for VertexAD
mean2vomni <- rep(1, (tmax-1)-(l-1))
std2vomni <- rep(1,(tmax-1)-(l-1))
#Do omnibus embedding
if(par){
#require(doParallel)
cl <- parallel::makeCluster(numpar)
doParallel::registerDoParallel(cl)
parallel::clusterEvalQ(cl, library("AnomalyDetection"))#source("utilAD.R"))
parallel::clusterExport(cl = cl, varlist = list("ase", "fast2buildOmni", "getElbows", "glist",
"elbow", "d","approx", "diag.augment","attrweight"), envir = environment())
allomni <- foreach::foreach(i =1:(tmax-1), .combine='comb', .multicombine=TRUE,.packages = "igraph",
.init=list(list(), list())) %dopar% {
O <- fast2buildOmni( glist[i:(i+1)] , diagaug=diag.augment, attrweight=attrweight)
a <- ase(O, d=d, diagaug=FALSE, approx=approx,elbow=elbow)
list(a, a$d)
}
parallel::stopCluster(cl)
} else {
foreach::registerDoSEQ()
allomni <- foreach::foreach(i =1:(tmax-1), .combine='comb', .multicombine=TRUE,.packages = "igraph",
.init=list(list(), list())) %dopar% {
O <- fast2buildOmni( glist[i:(i+1)] , diagaug=diag.augment, attrweight=attrweight)
Z <- ase(O, d=d, diagaug=FALSE, approx=approx,elbow=elbow)
list(Z, Z$d)
}
}
#Z is omnibus embedding estimates for latent positions
Z = allomni[[1]]
#Calculate l_2 distance between adjacent latent position estmate for graphs and vertices with OMNI
out2omni <- fast2doOmni(n, Z=Z)
for (w in 1:(tmax-1-(l-1))) {
#Iterative calulating moving averages and moving deviations
omni2v <- t(out2omni$pdist[,w:(w+l-2)])
mean2vomni[w] <- mean(omni2v)
std2vomni[w] <- sd.xbar(omni2v, rep(n,l-1), "UWAVE-SD")
omni2 <- matrix(out2omni$tnorm[w:(w+l-2)], l-1, 1)
mean2omni[w] <- mean(omni2)
std2omni[w] <- sd.xbar.one(omni2, rep(1,l-1), "MR")
}
#Do vertexAD
df <- out2omni$pdist
omni2v <- matrix(df, tmax-1, n, byrow = TRUE)
#c1o2v is a list of qcc (quantative control chart) object
c1o2v <- list()
for (i in l:(tmax-1)) {
c1o2v[[i-l+1]] <- qcc(omni2v[i,],type = "xbar.one",center = mean2vomni[i-l+1],std.dev = std2vomni[i-l+1], nsigmas=3, plot=FALSE, plot.LCL = plot.LCL)
}
#Do GraphAD
df <- out2omni$tnorm
omni2 <- matrix(df, tmax-1, 1)
#c1o2 is a qcc object
c1o2 <- qcc(omni2[l:(tmax-1)],type = "xbar.one",nsigmas=3, center = mean2omni, std.dev = std2omni, plot=FALSE, plot.LCL = plot.LCL)
if(plot.figure){
print(plot.qcc(c1o2,title="Control Chart OMNI", l=l,plot.LCL = plot.LCL ))
print(plot.qcc.vertex(c1o2v, l=l,title="Control Chart OMNI",plot.LCL = plot.LCL ))
}
#Let c1o2v be a list of anomalous vertices indices across time points
c1o2v <- list()
for (i in l:(tmax-1)) {
c1o2v[[i-l+1]] <- qcc(omni2v[i,],type = "xbar.one",center = mean2vomni[i-l+1],std.dev = std2vomni[i-l+1], nsigmas=3, plot=FALSE, plot.LCL = plot.LCL )$violations$beyond.limits
}
result <- list(GraphAD=c1o2$deviation, VertexAD=c1o2v)
return(result)
}else if(method=="MASE"){
#Initialize moving averages and moving standard deviation for GraphAD
mean2 <- rep(1,(tmax-1)-(l-1))
std2 <- rep(1,(tmax-1)-(l-1))
#Initialize moving averages and moving standard deviation for VertexAD
mean2v <- rep(1,(tmax-1)-(l-1))
std2v <- rep(1,(tmax-1)-(l-1))
#Do individual ASE for MASE
if(par){
#require(doParallel)
cl <- parallel::makeCluster(numpar)
doParallel::registerDoParallel(cl)
parallel::clusterEvalQ(cl, library("AnomalyDetection"))#source("utilAD.R"))
parallel::clusterExport(cl = cl, varlist = list("ase", "getElbows", "glist",
"elbow", "d","approx", "diag.augment","attrweight"), envir = environment())
allase <- foreach::foreach(i =1:tmax, .combine='comb', .multicombine=TRUE,.packages = "igraph",
.init=list(list(), list())) %dopar% {
latpos <- ase(igraph::get.adjacency(glist[[i]], attr=attrweight), d=d, diagaug=diag.augment, approx=approx,elbow=elbow)$Xhat
list(latpos, dim(latpos)[2])
}
parallel::stopCluster(cl)
} else {
foreach::registerDoSEQ()
allase <- foreach::foreach(i =1:tmax, .combine='comb', .multicombine=TRUE,.packages = "igraph",
.init=list(list(), list())) %dopar% {
latpos <- ase(igraph::get.adjacency(glist[[i]], attr=attrweight), d=d, diagaug=diag.augment, approx=approx,elbow=elbow)$Xhat
list(latpos, dim(latpos)[2])
}
}
latpos.list <- allase[[1]]
#Do joint embedding in MASE and calculate l_2 distance between adjacent latent position estmate for graphs and vertices with MASE
out2 <- doMase(glist,latpos.list, 2, dsvd, attrweight)
for (w in 1:(tmax-1-(l-1))) {
#Iterative calulating moving averages and moving deviations
mase2v <- t(matrix(out2$pdist[,w:(w+l-2)],n,l-1))
mean2v[w] <- mean(mase2v)
std2v[w] <- sd.xbar(mase2v, rep(n,l-1), "UWAVE-SD")
mase2 <- matrix(out2$tnorm[w:(w+l-2)], l-1, 1)
mean2[w] <- mean(mase2)
std2[w] <- sd.xbar.one(mase2, rep(1,l-1), "MR")
}
#Do VertexAD (vertex anomaly detection)
df <- out2$pdist
mase2v <- matrix(df, tmax-1, n, byrow = TRUE)
c1m2v <- list()
for (i in l:(tmax-1)) {
c1m2v[[i-l+1]] <- qcc(mase2v[i,],type = "xbar.one",center = mean2v[i-l+1],std.dev = std2v[i-l+1], nsigmas=3, plot=FALSE, plot.LCL = plot.LCL )
}
#Do GraphAD (graph anomaly detection)
df <- out2$tnorm
mase2 <- matrix(df, tmax-1, 1)
c1m2 <- qcc(mase2[l:(tmax-1)],type = "xbar.one",center = mean2 ,std.dev = std2, nsigmas=3, plot=FALSE, plot.LCL = plot.LCL )
if(plot.figure){
print(plot.qcc(c1m2,title="Control Chart MASE", l=l,plot.LCL = plot.LCL ))
print(plot.qcc.vertex(c1m2v, l=l,title="Control Chart MASE",plot.LCL = plot.LCL ))
}
c1m2v <- list()
for (i in l:(tmax-1)) {
c1m2v[[i-l+1]] <- qcc(mase2v[i,],type = "xbar.one",center = mean2v[i-l+1],std.dev = std2v[i-l+1], nsigmas=3, plot=FALSE, plot.LCL = plot.LCL)$violations$beyond.limits
}
result <- list(GraphAD=c1m2$deviation, VertexAD=c1m2v)
return(result)
}
}
<file_sep># preprocess
#' Run pass-to-rank on a weighted graph.
#'
#' It extracts (non-zero) edge weight vector \eqn{W} from a graph and replaces it with \eqn{2*R / (|E|+1)} where \eqn{R} is the rank of \eqn{W} and \eqn{|E|} is the number of edges. This does 'no-op' for an unweighted graph.
#'
#' @param g a graph in \code{igraph} format or an n x 2 edge list or an n x n adjacency matrix
#'
#' @export
#' @import igraph
ptr <- function(g)
{
if (class(g) != "igraph") {
if (!is.matrix(g)) stop("the input has to be either an igraph object or a matrix!")
else {
if (ncol(g)==2) g <- igraph::graph_from_edgelist(g)
else if (nrow(g)==ncol(g)) g <- igraph::graph_from_adjacency_matrix(g, weighted = TRUE)
else stop("the input matrix is not a graph format!")
}
}
if (igraph::is.weighted(g)) {
W <- E(g)$weight
} else { # no-op!
W <- rep(1,igraph::ecount(g))
}
E(g)$weight <- rank(W)*2 / (igraph::ecount(g)+1)
return(g)
}
#' find largest connected component in a graph
#' It extracts (non-zero) largest connected subgraph .
#'
#' @param graph a graph in \code{igraph} format
#'
#' @export
#' @import igraph
giant.component <- function(graph, ...) {
#require(igraph)
cl <- igraph::clusters(graph, ...)
igraph::induced.subgraph(graph, which(cl$membership == which.max(cl$csize)))
}
#' remove edges which has zero weights for all graphs (if any) and find jointly largest connected component in graphs. Finally it removes all self-loops,
#' It extracts (non-zero) igraph list \eqn{gip} and removes all edges with zero edge weights and return a list of jointly largest connected component in graphs without self-loops .
#'
#' @param gip a list of graphs in \code{igraph} format
#'
#' @export
#' @import igraph
#' @return A list of graphs in igraph format
jlcc <- function(gip){
l.length <- length(gip)
for (i in 1:l.length) {
gip[[i]] <- igraph::delete.edges(gip[[i]], which(E(gip[[i]])$weight==0))
}
#find joint largest connected component
df1 <- igraph::as_data_frame(gip[[1]])[,1:2]
df2 <- igraph::as_data_frame(gip[[2]])[,1:2]
g <- igraph::graph.intersection(gip[[1]],gip[[2]],keep.all.vertices = TRUE)
if(l.length>2){
for (i in 3:l.length) {
g <- igraph::graph.intersection(g,gip[[i]],keep.all.vertices = TRUE)
}
}
lcc <- giant.component(g)
glist <- gip
gip <- list()
for (i in 1:l.length) {
gip[[i]] <- igraph::induced_subgraph(glist[[i]], V(lcc)$name);
gip[[i]] <- igraph::permute.vertices(gip[[i]], match(V(gip[[i]])$name, V(gip[[1]])$name));
}
for (i in 1:l.length) {
gip[[i]] <- igraph::simplify(gip[[i]])
}
return(gip)
}
#' create a planted clique
#' It creates planted clique for a specific graph for a list of graphs.
#'
#' @param gip a list of graphs in \code{igraph} format.
#' @param p is the index of graph to be inserted a planted clique
#' @param art.anomaly.v is the vertex index in igraph.vs format to be planted clique.
#' @export
#' @import igraph
#' @return A list containing a planted clique size as size of art.anomaly.v at p-th graph
#
pltclique <- function(gip, p, art.anomaly.v){
middle.max.inx <- which(V(gip[[1]])%in% art.anomaly.v )
art.gip <- gip
adj <- as.matrix(igraph::get.adjacency(art.gip[[p]], attr = attrweigth))
adj[middle.max.inx,middle.max.inx] <- (adj[middle.max.inx,middle.max.inx] + 1)
art.gip[[p]] <- igraph::graph.adjacency(adj,mode = "undirected", weighted = TRUE,diag = FALSE)
art.anomaly.v <- V(art.gip[[p]])[middle.max.inx]
glist <- list()
l.length <- length(gip)
for (i in 1:l.length) {
glist[[i]] <- ptr(art.gip[[i]])
}
return(glist)
}
#get degree distribution for graphs
#'
#' It extracts (non-zero) degree change \eqn{deg.change} matrix n by m-1 from a list of graphs.
#'
#' @param gip a list of graphs in \code{igraph} format.
#' @export
#' @import igraph
#' @return A matrix of size n x t-1, with each element to be degree changes
getdegchange <- function(gip){
l.length <- length(gip)
num.edge <- matrix(0,length(V(gip[[1]])),l.length )
for (i in 1:l.length) {
num.edge[,i] <- igraph::degree(gip[[i]])
}
deg.change <- matrix(0,length(V(gip[[1]])),l.length-1)
for (i in 1:(l.length-1)) {
deg.change[,i] <- num.edge[,i+1]- num.edge[,i]
}
return(deg.change)
# plot(density(deg.change))
# plot(density(abs(deg.change)))
}
#' get weighted degree change for a list of weighted graphs
#' It extracts (non-zero) weighted degree change matrix n by m-1 \eqn{deg.change} from a list of graphs.
#'
#' @param gip a list of graphs in \code{igraph} format.
#' @export
#' @import igraph
#' @return A matrix of size n x t-1, with each element to be weight degree changes
getweightchange <- function(gip){
l.length <- length(gip)
num.edge.weight <- matrix(0,length(V(gip[[1]])), l.length )
for (i in 1:l.length) {
num.edge.weight[,i] <- igraph::graph.strength(gip[[i]],loops = FALSE)
}
deg.change.weight <- matrix(0,length(V(gip[[1]])),l.length-1)
for (i in 1:(l.length-1)) {
deg.change.weight[,i] <- num.edge.weight[,i+1]- num.edge.weight[,i]
}
return(deg.change.weight)
}
<file_sep>#' Sample RDPG graph with latent position
#' @param X latent position matrix of \eqn{d} columns and \eqn{n} rows.
#' @return A un-directed hollow symmeric unweighted graph generated from bernoulli \eqn{EA=P=XX^{T}}
rdpg.sample <- function(X) {
P <- X %*% t(X)
n <- nrow(P)
U <- matrix(0, nrow = n, ncol = n)
U[col(U) > row(U)] <- runif(n*(n-1)/2)
U <- (U + t(U))
diag(U) <- runif(n)
A <- (U < P) + 0 ;
diag(A) <- 0
return(igraph::graph.adjacency(A,"undirected"))
}
#' Sample a time series of RDPG graph (length tmax > 17) with same 1-1 matched vertices unweighted
#' hollow symmetric undirected graphs, the latent positions i.i.d uniform.
#' Some vertices in 16-th and 17-th graphs are given perturbations so there exists anomalies at 16:17.
#' @param n number of vertices
#' @param nperturb number of perturbed vertices
#' @param cperturb number of perturbation. Larger cperturb means more obvious anomalies.
#' @param rmin,rmax parameter for uniform[rmin, rmax].
#' @param tmax number of graphs must be greater than 17.
#' @return A list containing a vector tnorm of length tmax-1, with the
#' latent position difference for graphs, and a matrix pdist
#' with latent position estmate difference for vertices (size n x tmax-1 ),
#' and a list of length tmax of undirectected hollow symmeric unweighted graphs
#' @examples
#'
#' # Sample a time series of RDPG graph (length tmax > 17) with same 1-1 matched vertices unweighted
#' # hollow symmetric undirected graphs, the latent positions i.i.d uniform.
#' # Some vertices in 16-th and 17-th graphs are given perturbations so there exists anomalies at 16:17.
#' n <- 100 #number of vertices
#' nperturb <- 20 #number of perturbed vertices
#' cperturb <- .12 #number of perturbation, larger cperturb means more obvious anomalies.
#' rmin <- .2 # parameter for uniform[rmin, rmax].
#' rmax <- .8 # parameter for uniform[rmin, rmax].
#' tmax <- 22 # number of graphs must be greater than 17.
#' #Generate data or load the data you want
#' glist <- generate.tsg(n, nperturb, cperturb=NULL, rmin, rmax, tmax)$glist
generate.tsg <- function(n, nperturb, cperturb=NULL, rmin, rmax, tmax){
X1 <- runif(n, rmin, rmax)
pert1 <- ifelse(is.null(cperturb), min(X1), cperturb)
pert2 <- ifelse(is.null(cperturb), 1-max(X1), cperturb)
Xlist <- rep(list(X1), tmax)
Xlist[[10+6]] <- Xlist[[1]] + c(rep(c(pert2, -pert1), each=nperturb/2), rep(0, n-nperturb))
Xlist[[10+7]] <- Xlist[[1]] + c(rep(c(-pert1, pert2), each=nperturb/2), rep(0, n-nperturb))
norm <- sapply(1:(tmax-1), function(x) norm(Xlist[[x]]-Xlist[[x+1]], "2"))
pdist <- sapply(1:(tmax-1), function(x) pdistXY(Xlist[[x]], Xlist[[x+1]]))
glist <- lapply(Xlist, function(x) rdpg.sample(matrix(x,ncol=1)))
return(list(tnorm=norm, pdist=pdist, glist=glist))
}
<file_sep># Multiple Network Embedding for Anomaly Detection in Time Series of Graphs
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME>
https://arxiv.org/abs/2008.10055
## Abstract
This paper considers the graph signal processing
problem of anomaly detection in time series of graphs. We examine
two related, complementary inference tasks: the detection
of anomalous graphs within a time series, and the detection
of temporally anomalous vertices. We approach these tasks
via the adaptation of statistically principled methods for joint
graph inference, specifically multiple adjacency spectral embedding
(MASE) and omnibus embedding (OMNI). We demonstrate that
these two methods are effective for our inference tasks. Moreover,
we assess the performance of these methods in terms of the
underlying nature of detectable anomalies. Our results delineate
the relative strengths and limitations of these procedures, and
provide insight into their use.
# AnomalyDetection R package
AnomalyDetection is a R package to detect anomalies in time series of graphs.
Specifically, it can be applied in two related, complementary inference tasks:
the detection of anomalous graphs within a time series, and the detection
of temporally anomalous vertices.
## How the package works
The underlying algorithm approaches these tasks via the adaptation of statistically
principled methods for joint graph inference, specifically multiple adjacency
spectral embedding (MASE) and omnibus embedding (OMNI). It also builds upon the quantative
control chart (https://en.wikipedia.org/wiki/Control_chart) for detecting anomalies.
Note that it can be used to detect anomalies both in overall graphs as well as individual anomalies.
This is achieved by employing joint graph embedding for adjacent graphs sequentially, and track the
change of adjacent latent positions difference via quantative control charts.
The package provides some preprocessing tools to deal, for example, different number of vertices in
time series of graphs.
The user can specify the length of moving window of interest (such as seven days, twenty-four hours),
enable/disable singular value decompostion approximation etc.
## How to get started
Install the R package using the following commands on the R console:
```
install.packages("devtools")
devtools::install_github("gdchen94/AnomalyDetection")
library(AnomalyDetection)
```
Alternatively, you can download the file AnomalyDetection_0.1.0.tar.gz
and install it using either (within R)
```
install.packages("AnomalyDetection_0.1.0.tar.gz", repos = NULL, type ="source")
library(AnomalyDetection)
```
or in terminal (say you download it in Desktop)
```
R CMD INSTALL Desktop/AnomalyDetection_0.1.0.tar.gz
```
The function qccAD is called to detect one or more statistically
significant anomalies in the input time series of graphs. The documentation of the
function qccAD, which can be seen by using the following command,
details the input arguments and the output of the function qccAD.
```
?qccAD
```
## A simple example
To get started, the user is recommended to use the example dataset (time series of
independent Erdos-Reynyi graphs with anomaly at 6-th graph generated as in Example1 in
Example.R) which comes with the packages. Execute the following commands:
```
data(glistExample1)
result.OMNI<- qccAD(glist, l=4,d=1,dsvd=NULL,method="OMNI",
diag.augment = TRUE, approx=FALSE, par=FALSE, numpar=2)
```

*Control chart for a time series of Erdos-Renyi graphs with an anomaly at time points 5 and 6 (Example 1 in Example.R) for GraphAD. Center solid line (CL)
represents moving average of sample means, dashed line (UCL) represents moving means plus three adjusted moving sample range; black dots are at times where the latent positions are claimed to be normal, and the red dots are those which lie outside of UCL and are claimed as anomalous graphs.*

*Control chart for a time series of Erdos-Renyi graphs with an anomaly at time points 5 and 6 (Example 1 in Example.R) for VertexAD. Center solid line (CL)
represents moving average of sample means, dashed line (UCL) represents moving means plus three adjusted moving sample range; black dots are at times where the latent positions are claimed to be normal, and the red dots are those which lie outside of UCL and are claimed as anomalous vertices..*
From the plot, we observe that the input time series experiences positive anomalies
at time points 5:6.
To get started, the user is recommended to use the example.R file to
get the results in the example.pdf
## Demo
To see some further examples, run example.R as
```
require(knitr)
stitch("example.R")
```
and the result should look like https://github.com/gdchen94/AnomalyDetection/blob/master/example.pdf.
(This may take around 1 minute on a typical laptop.)
| 1578232d559ffa5886c810e38f983ff5b2d33cb7 | [
"Markdown",
"R"
] | 5 | R | gdchen94/AnomalyDetection | 17f9f0e08ca10b55fc20adee3320b884b2524f9c | 5028c2db741b938d95952601b9cb49e332cb9912 |
refs/heads/master | <repo_name>Nurchik/balance-test<file_sep>/src/kg/balance/test/controllers/CompanyController.java
package kg.balance.test.controllers;
import kg.balance.test.dto.BaseResponse;
import kg.balance.test.dto.Result;
import kg.balance.test.exceptions.CodedException;
import kg.balance.test.exceptions.CompanyNotFound;
import kg.balance.test.exceptions.UniqueConstraintViolation;
import kg.balance.test.models.Company;
import kg.balance.test.security.UserPrincipal;
import kg.balance.test.services.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/companies")
public class CompanyController {
@Autowired
CompanyService companyService;
@GetMapping("/")
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public ResponseEntity<?> getCompanies () {
List<Company> companiesList = companyService.getCompanies();
return ResponseEntity.ok(new BaseResponse("ok", null, new Result () {
public List<Company> companies = companiesList;
}));
}
@GetMapping("/{company_id}")
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public ResponseEntity<?> getCompany (@PathVariable Long company_id) throws CompanyNotFound {
Company companyData = companyService.getCompany(company_id);
return ResponseEntity.ok(new BaseResponse("ok", null, new Result () {
public Company company = companyData;
}));
}
@PostMapping("/")
@Secured({"ROLE_ADMIN"})
public ResponseEntity<?> createCompany (@Valid @RequestBody Company companyData) throws UniqueConstraintViolation {
Company newCompany = companyService.createCompany(companyData);
return ResponseEntity.ok(new BaseResponse("ok", null, new Result () {
public Company company = newCompany;
}));
}
@PutMapping("/{company_id}")
@Secured({"ROLE_ADMIN"})
// Здесь, также, не нужна аннотация @Valid. Мы сами отберем нужные поля в companyService для дальнейшей обработки
public ResponseEntity<?> updateCompany (@PathVariable Long company_id, @RequestBody Company companyData) throws CompanyNotFound, UniqueConstraintViolation {
Company updatedCompany = companyService.updateCompany(company_id, companyData);
return ResponseEntity.ok(new BaseResponse("ok", null, new Result () {
public Company company = updatedCompany;
}));
}
@DeleteMapping("/{company_id}")
@Secured({"ROLE_ADMIN"})
public ResponseEntity<?> deleteCompany (@PathVariable Long company_id) throws CodedException {
UserPrincipal up = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
companyService.deleteCompany(up.getUser(), company_id);
return ResponseEntity.ok(new BaseResponse("ok", null));
}
}
<file_sep>/init.sql
CREATE USER balance_user WITH PASSWORD '<PASSWORD>';
CREATE DATABASE balance OWNER balance_user;
DROP TABLE public.company;
CREATE TABLE public.company
(
id bigint NOT NULL,
name character varying(255) NOT NULL,
website character varying(255),
CONSTRAINT company_pkey PRIMARY KEY (id),
CONSTRAINT uk_niu8sfil2gxywcru9ah3r4ec5 UNIQUE (name)
)
WITH (OIDS=FALSE);
ALTER TABLE public.company OWNER TO balance_user;
DROP TABLE public."user";
CREATE TABLE public."user"
(
id bigint NOT NULL,
fullname character varying(255),
is_admin boolean,
name character varying(255) NOT NULL,
password character varying(255) NOT NULL,
phone_number character varying(255),
CONSTRAINT user_pkey PRIMARY KEY (id),
CONSTRAINT uk_gj2fy3dcix7ph7k8684gka40c UNIQUE (name),
CONSTRAINT uk_t8tbwelrnviudxdaggwr1kd9b UNIQUE (name)
)
WITH ( OIDS=FALSE);
ALTER TABLE public."user" OWNER TO balance_user;
DROP TABLE public.sellpoint;
CREATE TABLE public.sellpoint
(
id bigint NOT NULL,
address character varying(255),
latitude real,
longitude real,
name character varying(255),
phone_number character varying(255),
company_id bigint,
user_id bigint,
CONSTRAINT sellpoint_pkey PRIMARY KEY (id),
CONSTRAINT fk6mbmtk5m2rceuxvmasfh39b4 FOREIGN KEY (company_id)
REFERENCES public.company (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE SET NULL,
CONSTRAINT fkii8phjf6dkc40ettjuvi4vxpk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE SET NULL
)
WITH (OIDS=FALSE);
ALTER TABLE public.sellpoint OWNER TO balance_user;
INSERT INTO public."user"(id, fullname, is_admin, name, password, phone_number)
VALUES (1, 'Admin Test User', true, 'balance_admin', '$2a$10$oovG7yJYnwHZI9ihZA6eKu8ZlFjz2wAF3WPYJYzlTi1M88HY/Gz0e', '+996770000000');<file_sep>/src/kg/balance/test/dto/SigninRequest.java
package kg.balance.test.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.validation.constraints.NotBlank;
@JsonIgnoreProperties
public class SigninRequest {
@NotBlank
private String username = null;
@NotBlank
private String password = null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<file_sep>/src/kg/balance/test/exceptions/UniqueConstraintViolation.java
package kg.balance.test.exceptions;
public class UniqueConstraintViolation extends CodedException {
public UniqueConstraintViolation (String fieldName) {
super("duplicate_data_error", String.format("Field \"%s\" must be unique", fieldName));
}
}
<file_sep>/src/kg/balance/test/security/JWTFilter.java
package kg.balance.test.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import kg.balance.test.dto.BaseResponse;
import kg.balance.test.exceptions.UserNotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JWTFilter extends OncePerRequestFilter {
@Autowired
private JWTProvider jwtProvider;
@Autowired
private BalanceUserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Достаем токен из хэдера
try {
String jwtToken = getJwtTokenFromRequest(request);
if (jwtToken != null) {
// Сразу пытаемся получить ID пользователя. Ошибки при парсинге токена обработаем позже
Long userId = jwtProvider.getUserId(jwtToken);
UserDetails userDetails = userDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
} catch (UserNotFound ex) {
respondWithJson(new BaseResponse(ex.getCode(), ex.getMessage()), response);
} catch (SignatureException ex) {
respondWithJson(new BaseResponse("jwt_error", "Invalid JWT signature"), response);
} catch (MalformedJwtException ex) {
respondWithJson(new BaseResponse("jwt_error", "Invalid JWT token"), response);
} catch (ExpiredJwtException ex) {
respondWithJson(new BaseResponse("jwt_error", "Expired JWT token"), response);
} catch (UnsupportedJwtException ex) {
respondWithJson(new BaseResponse("jwt_error", "Unsupported JWT token"), response);
} catch (IllegalArgumentException ex) {
respondWithJson(new BaseResponse("jwt_error", "JWT claims string is empty"), response);
} catch (Exception ex) {
respondWithJson(new BaseResponse("unhandled_error", ex.getMessage()), response);
}
}
private String getJwtTokenFromRequest (HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (StringUtils.hasText(token) && token.startsWith("Bearer")) {
return token.substring(7);
}
return null;
}
private void respondWithJson (BaseResponse baseResponse, HttpServletResponse response) {
ObjectMapper om = new ObjectMapper();
response.setStatus(500);
response.setHeader("Content-Type", "application/json");
response.setCharacterEncoding("UTF-8");
try {
om.writeValue(response.getWriter(), baseResponse);
} catch (IOException ex) {
// Залогируем в будущем
}
}
}
<file_sep>/src/kg/balance/test/exceptions/UserNotFound.java
package kg.balance.test.exceptions;
public class UserNotFound extends CodedException {
public UserNotFound () {
super("user_not_found", "User not found");
}
}
<file_sep>/test/kg/balance/test/controller/AuthControllerTest.java
package kg.balance.test.controller;
import kg.balance.test.configs.RESTConfiguration;
import kg.balance.test.configs.SecurityConfiguration;
import kg.balance.test.models.User;
import kg.balance.test.services.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.Filter;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { RESTConfiguration.class, SecurityConfiguration.class})
@WebAppConfiguration
@Transactional
public class AuthControllerTest {
@Autowired
private WebApplicationContext wac;
@Autowired
UserService userService;
private MockMvc mockMVC;
@Autowired
@Qualifier("springSecurityFilterChain")
private Filter springSecurityFilterChain;
@Before
public void setup() throws Exception {
mockMVC = MockMvcBuilders
.webAppContextSetup(this.wac)
.apply(springSecurity(springSecurityFilterChain))
.build();
User user = new User();
user.setName("balance_admin");
user.setPassword("<PASSWORD>");
user.setIsAdmin(true);
userService.createUser(user);
User user_reg = new User();
user_reg.setName("balance_user");
user_reg.setPassword("<PASSWORD>");
userService.createUser(user_reg);
}
@Test
public void testUnathorizedAccess () throws Exception {
mockMVC.perform(get("/users/"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.errorCode", is("access_denied")))
.andExpect(jsonPath("$.errorText", containsString("Full authentication is required")));
}
@Test
public void testSuccessfulAdminLogin () throws Exception {
mockMVC.perform(post("/auth/signin/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"balance_admin\", \"password\":\"<PASSWORD>\"}")
).andExpect(status().isOk())
.andExpect(jsonPath("$.errorCode", is("ok")))
.andExpect(jsonPath("$.errorText", nullValue()))
.andExpect(jsonPath("$.result.auth_token", notNullValue(String.class)))
.andExpect(jsonPath("$.result.user.name", is("balance_admin")))
.andExpect(jsonPath("$.result.user.is_admin", is(true)));
}
@Test
public void testSuccessfulRegularUserLogin () throws Exception {
mockMVC.perform(post("/auth/signin/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"balance_user\", \"password\":\"<PASSWORD>\"}")
).andExpect(status().isOk())
.andExpect(jsonPath("$.errorCode", is("ok")))
.andExpect(jsonPath("$.errorText", nullValue()))
.andExpect(jsonPath("$.result.auth_token", notNullValue(String.class)))
.andExpect(jsonPath("$.result.user.name", is("balance_user")))
.andExpect(jsonPath("$.result.user.is_admin", is(false)));
}
@Test
public void testWrongPasswordLogin () throws Exception {
mockMVC.perform(post("/auth/signin/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"balance_user\", \"password\":\"<PASSWORD>\"}")
).andExpect(status().isForbidden())
.andExpect(jsonPath("$.errorCode", is("authentication_error")))
.andExpect(jsonPath("$.errorText", notNullValue(String.class)))
.andExpect(jsonPath("$.result", nullValue()));
}
@Test
public void testWrongUsernameLogin () throws Exception {
mockMVC.perform(post("/auth/signin/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"balance_user123\", \"password\":\"<PASSWORD>\"}")
).andExpect(status().isForbidden())
.andExpect(jsonPath("$.errorCode", is("authentication_error")))
.andExpect(jsonPath("$.errorText", notNullValue(String.class)))
.andExpect(jsonPath("$.result", nullValue()));
}
@Test
public void testWrongRequestLogin () throws Exception {
mockMVC.perform(post("/auth/signin/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"balance_user\", \"password\":\"<PASSWORD>\", \"username\": null}")
).andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errorCode", is("validation_error")))
.andExpect(jsonPath("$.errorText", notNullValue(String.class)))
.andExpect(jsonPath("$.result", nullValue()));
}
}
<file_sep>/src/kg/balance/test/configs/SecurityWebApplicationInitializer.java
package kg.balance.test.configs;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
// Данный класс нужен, чтобы DelegatingFilterProxy был зарегистрирован вкак фильтр сервлета.
// DelegatingFilterProxy подключит цепочку фильтров Spring Security
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
<file_sep>/src/kg/balance/test/security/JWTProvider.java
package kg.balance.test.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JWTProvider {
@Value("${jwt.secret}")
private String jwtSecret;
@Value("${jwt.tokenTTL}")
private int tokenTTL;
public Long getUserId (String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token).getBody();
return Long.parseLong(claims.getSubject());
}
public String generateToken (Long userId) {
Date now = new Date();
Date expirationDate = new Date (now.getTime() + tokenTTL);
return Jwts.builder()
.setSubject(userId.toString())
.setIssuedAt(now)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS256, jwtSecret)
.compact();
}
}
<file_sep>/src/kg/balance/test/configs/app.properties
jwt.secret = MySecretKeyJWT
jwt.tokenTTL = 7200000<file_sep>/src/kg/balance/test/controllers/AuthController.java
package kg.balance.test.controllers;
import com.fasterxml.jackson.annotation.JsonProperty;
import kg.balance.test.dto.Result;
import kg.balance.test.models.User;
import kg.balance.test.dto.BaseResponse;
import kg.balance.test.security.JWTProvider;
import kg.balance.test.dto.SigninRequest;
import kg.balance.test.security.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
JWTProvider tokenProvider;
@Autowired
AuthenticationManager authenticationManager;
@PostMapping("/signin/")
public ResponseEntity<?> authenticate (@Valid @RequestBody SigninRequest signupData) {
try {
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(signupData.getUsername(), signupData.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(auth);
UserPrincipal up = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
final User user = up.getUser();
final String jwtToken = tokenProvider.generateToken(user.getId());
return ResponseEntity.ok(new BaseResponse("ok", null, new Result() {
@JsonProperty("auth_token")
public String authToken = jwtToken;
@JsonProperty("user")
public User userData = user;
}));
} catch (AuthenticationException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new BaseResponse("authentication_error", ex.getMessage()));
} catch (Exception ex) {
return ResponseEntity.status(500).body(new BaseResponse("unhandled_exception", ex.getMessage()));
}
}
}
<file_sep>/src/kg/balance/test/dto/BaseResponse.java
package kg.balance.test.dto;
import com.fasterxml.jackson.annotation.JsonRootName;
public class BaseResponse {
private String errorCode;
private String errorText;
private Result result;
public BaseResponse (String errorCode, String errorText) {
this.errorCode = errorCode;
this.errorText = errorText;
this.result = null;
}
public BaseResponse (String errorCode, String errorText, Result result) {
this.errorCode = errorCode;
this.errorText = errorText;
this.result = result;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorText() {
return errorText;
}
public void setErrorText(String errorText) {
this.errorText = errorText;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
<file_sep>/src/kg/balance/test/exceptions/CompanyNotFound.java
package kg.balance.test.exceptions;
public class CompanyNotFound extends CodedException {
public CompanyNotFound () {
super("company_not_found", "Company not found");
}
}
<file_sep>/src/kg/balance/test/dto/Result.java
package kg.balance.test.dto;
public class Result {
}
<file_sep>/src/kg/balance/test/models/SellPoint.java
package kg.balance.test.models;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@Entity
@Table(name = "sellpoint", schema = "public")
public class SellPoint {
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column
private Long id;
@Column
@NotBlank
private String name;
@JsonIgnore
@Transient
private Long companyId;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "company_id")
// Здесь умышленно нет ответной части @OneToMany. В Company и User нам не нужно получать список привязанных точек продаж
private Company company;
@JsonProperty("phone_number")
@Column(name = "phone_number")
private String phoneNumber;
@Column
private String address;
@Column
private Float latitude;
@Column
private Float longitude;
@JsonIgnore
@Transient
private Long userId;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@PostLoad
public void setIdsOnLoad () {
setUserId(user.getId());
setCompanyId(company.getId());
}
@JsonProperty("id")
@JsonFormat(shape = JsonFormat.Shape.STRING)
// Этот параметр мы получим только при сериализации, а при десериализации он будет игнорироваться
public Long getId() {
return id;
}
@JsonIgnore
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Здесь мы запрашиваем id Company, чтобы при получении объекта из БД, временная перемененная получила id company, которая будет отдаваться в JSON-виде
@NotNull
public Long getCompanyId() {
return companyId;
}
@JsonSetter("company")
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
public Company getCompany() {
return company;
}
@JsonGetter("company")
// Для даноого парметра, будут сериализироваться только некоторые поля для каждой компании
public Map<String, String> getTrimmedCompanyData () {
Map<String, String> companyData = new HashMap<>();
companyData.put("id", getCompany().getId().toString());
companyData.put("name", getCompany().getName());
return companyData;
}
public void setCompany(Company company) {
this.company = company;
this.companyId = company.getId();
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public Long getUserId() {
return userId;
}
@JsonSetter("user")
public void setUserId(Long userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@JsonGetter("user")
// Для даноого парметра, будут сериализироваться только некоторые поля для каждого пользователя
public Map<String, String> getTrimmedUserData () {
Map<String, String> userData = new HashMap<>();
userData.put("id", getUser().getId().toString());
userData.put("name", getUser().getName());
return userData;
}
}
<file_sep>/src/kg/balance/test/services/CompanyServiceImpl.java
package kg.balance.test.services;
import kg.balance.test.dao.BalanceDAOImpl;
import kg.balance.test.exceptions.*;
import kg.balance.test.models.Company;
import kg.balance.test.models.User;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.util.ArrayList;
import java.util.List;
@Service
public class CompanyServiceImpl implements CompanyService {
private BalanceDAOImpl<Company> companyRepository;
@Autowired
SellPointService sellPointService;
@Autowired
UserService userService;
@Autowired
public void setCompanyRepository(BalanceDAOImpl<Company> companyRepository) {
this.companyRepository = companyRepository;
companyRepository.setEntityClass(Company.class);
}
@Transactional(readOnly = true)
public Company getCompany(Long id) throws CompanyNotFound {
return companyRepository.get(id).orElseThrow(CompanyNotFound::new);
}
@Transactional(readOnly = true)
public List<Company> getCompanies() {
return companyRepository.list().orElse(new ArrayList<>());
}
@Transactional
public Company createCompany(Company company) throws UniqueConstraintViolation{
try {
return companyRepository.add(company);
} catch (
PersistenceException ex) {
if (ex.getCause().getClass() == ConstraintViolationException.class) {
throw new UniqueConstraintViolation("name");
}
throw ex;
}
}
@Transactional
public Company updateCompany(Long companyId, Company companyData) throws CompanyNotFound, UniqueConstraintViolation {
Company company = companyRepository.get(companyId).orElseThrow(CompanyNotFound::new);
if (companyData.getName() != null) {
company.setName(companyData.getName());
}
if (companyData.getWebsite() != null) {
company.setWebsite(companyData.getWebsite());
}
companyData.setId(company.getId());
try {
companyRepository.update(company);
} catch (PersistenceException ex) {
// В общем, в ConstraintViolationException не только нарушения уникальности, но, для демо, будем считать, что только UniqueConstraintViolation
if (ex.getCause().getClass() == ConstraintViolationException.class) {
throw new UniqueConstraintViolation("name");
}
throw ex;
}
return company;
}
@Transactional
public void deleteCompany(User user, Long id) throws CodedException {
Company company = companyRepository.get(id).orElseThrow(CompanyNotFound::new);
companyRepository.delete(company);
}
}
| 63951483fed6ad823c53b2fb33cd7c46537a3730 | [
"Java",
"SQL",
"INI"
] | 16 | Java | Nurchik/balance-test | 8f0a91c01281c7a088007caf61651e60d07530e7 | 94e3e5ee0f40684ed9de29e3b6c95e0c19306afa |
refs/heads/master | <repo_name>a19860101/LCCNET-LARAVEL<file_sep>/README.md
## MVC
Model 模型
View 視圖
Controller 控制器
## 從github下載的執行方法
1. 將下載好的資料夾放到xampp/htdocs內
2. 透過localhost建立資料庫
3. 執行 ``` composer install``` 安裝所需套件
4. 執行 ``` copy .env.example .env``` 產生.env
5. 設定.env內的資料庫資訊
6. 執行 ``` php artisan key:generate ``` 產生金鑰
7. 執行 ``` php artisan serve ``` 開啟測試伺服器
## put 與 patch
* put(替換資源)
> 用put方法送出更新,不只使用者的姓名會更新,連帶的連其實沒有要更新的大頭照以及描述都會在更新一次。
* patch(更換資源部分內容)
> 用patch方法送出更新,則僅會將使用者姓名更新 ,沒有動到的大頭照以及描述並不會也一起更新一次。
## Artisan 指令
```bash
#執行開發者伺服器
php artisan serve
#建立資料表遷移 migration
php artisan make:migration create_posts_table
php artisan make:migration add_user_id_to_posts --table=posts
#執行migration (推到資料庫)
php artisan migrate
#回復上一次migrate
php artisan migrate:rollback
#重製migration
php artisan migrate:reset
#查看migration狀態
php artisan migrate:status
#建立Controller
php artisan make:controller PostController
#使用resource建立Controller
php artisan make:controller PostController --resource
#查詢路由
php artisan route:list
#建立Model
php artisan make:model Post
#參數
# c: controller
# m: migration
# r: resource
#建立storage連結
php artisan storage:link
```<file_sep>/app/Http/Controllers/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
//
function asdf(){
// return 'Hello ASDF!!!!';
return view('test');
}
function qwerty(){
return 'hello qwerty';
}
}
| 2bf022598fe8008e84fe12bb7a8de264d79a19c8 | [
"Markdown",
"PHP"
] | 2 | Markdown | a19860101/LCCNET-LARAVEL | 3938f62358095bdd109654a3f9737fbfec5cb46b | 25c73919af43619443851548be97bb7545a17e48 |
refs/heads/master | <file_sep>require 'yaml'
path_to_file = "./config/timing#{ENV['VARIANT']}.yml"
timing_data = YAML.load_file(path_to_file)['timing']
require 'pry'
class MetroInfopoint
def initialize(timing_file = nil)
@timing_file = timing_file
end
def calculate(from_station:, to_station:)
{ price: calculate_price(from_station: from_station, to_station: to_station),
time: calculate_time(from_station: from_station, to_station: to_station) }
end
def calculate_price(from_station:, to_station:)
metro_data_range = take_data_range(from_station, to_station)
price = metro_data_range.map { |arr_elem| arr_elem['price'] }.inject(0) {|x,n| x+n }
end
def calculate_time(from_station:, to_station:)
metro_data_range = take_data_range(from_station, to_station)
time = metro_data_range.map { |arr_elem| arr_elem['time'] }.inject(0) {|x,n| x+n }
end
private
def take_data_range(from_station, to_station)
@timing_file[@timing_file.index(@timing_file.find{ |e| (e['start'] == from_station.to_sym) })..@timing_file.index(@timing_file.find{ |e| (e['end'] == to_station.to_sym) })]
end
end
m = MetroInfopoint.new(timing_data)
puts m.calculate(from_station:'shevchenkivska',to_station:'banderivska')
| 477bd9ab788e742d6bb5108daf3c2ff910d34fb7 | [
"Ruby"
] | 1 | Ruby | Viktorkosandyak/Metro | b8f438920ab002fa780a856ac7033123240db607 | eb47580d9e09771869edc2ce3626114f2dd20b4b |
refs/heads/master | <repo_name>stefanfreitag/fullstack_graphql<file_sep>/backend/server.js
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import SERVER from './graphql/schema';
const APP = express();
APP.use(cors());
mongoose.connect('mongodb://localhost/graphqlserver');
const connection = mongoose.connection;
connection.once('open',
() => {console.log('MongDB connection established.');}
);
SERVER.applyMiddleware({
app: APP
});
APP.listen(4000, () => console.log('Express server running on port 4000'));
<file_sep>/README.md
# GraphQL full stack example
Based on the [Udemy](https://www.udemy.com/) course [GraphQL with Angular & Apollo - The Full-stack Guide
](https://www.udemy.com/graphql-angular-apollo-full-stack/)
## Frontend
The frontend is written in Typescript.After cloning the repository do an
```bash
$ npm install
```
to resolve all required dependencies. To execute the application run
```bash
$ ng serve
```
Open a browser and go to http://localhost:4200/.
## Backend
The backend is written in Javascript. After cloning the repository do an
```bash
$ npm install
```
to resolve all required dependencies. To execute the application run
```bash
$ npm run dev
```
The expected output after start of the application is
```
> backend@1.0.0 dev /home/stefan/fullstack_graphql/backend
> babel-watch server.js
Express server running on port 4000
```
You can open the URL http://localhost:4000/graphiql in the browser to access
the GraphiQL UI. It can be used to query/ modify data. To e.g. retrieve the ids
of all known courses
```
query AllCourses {
allCourses(searchTerm: "") {
id
}
}
```
### Database
The course data is persisted in a [MongoDB](https://www.mongodb.com/) instance.
Docker is used to make the instance available. The official MongoDB image is pulled
from the [Docker hub](https://hub.docker.com/).
```bash
docker pull mongo
```
When creating an instance from the image, we forward the container port 27017
(MongoDB default port) to 27017 on localhost. At the same time a volume is attached
to the instance - it serves as persistent data store.
```
docker run -d -p 27017:27017 -v ~/data:/data/db mongo
```
## FAQ
### MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
The backend connects per default to a MongoDB running on localhost. Please ensure
that the MongoDB is up and running. The start order of the three componentes is
* MongoDB instance
* Javascript backend
* Angular frontend<file_sep>/backend/models/course.js
import mongoose from 'mongoose';
import uuid from 'uuid';
const Schema = mongoose.Schema;
const courseSchema = new Schema({
id: {type: String, default: uuid.v1},
title: String,
author: String,
description: String,
topic: String,
url: String,
voteCount: {type: Number, default: 0}
});
courseSchema.index({'$**': 'text'});
const model = mongoose.model('course', courseSchema);
export default model; | e98070cc57208435aeea71ae33aa92e6970a5e28 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | stefanfreitag/fullstack_graphql | 325b338ab0d6913ec475c03aa5cc3f8f1bab67d7 | 62366e3e40f5db9aee31da2a0603755549bedfd8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.