There is no need to descript more about the project, the main role of this
project named music-api is to provide a web service for developers to exploit
indirectly the song’s information coming from any online source such as ZingMp3,
Nhaccuatui.
This project is an open source software, developers contribute and developer my
project. This time, this is only two online source ZingMp3 and Nhaccuatui,
however, the number source will be increased regarding developers’ demand.
The song information includes name, singers, lyrics, song's page and
inparticular song's source for downloading.
Why does it work ?
Fundamentally, this service send a request to music oridinary servers, after receiving responses, it analyze the response (inspect elements selectively). After finished analysis, it send json object which inlcluding all song’s information. Currently, the web service is deployed at USA by heroku, Because of IP filter applying by VNG(ZingMp3), there are some songs which you cannot search. I have tested by using VPN locating in the USA, the result is limited.
Good news is that Nhaccuatui is very generous, they allow foreign IP to access all song, meanwhile, you can exploit from more songs.
Request should be sent to http://silverlink.herokuapp.com/api, and server
will return a result in JSON object
there are three parameters to query:
– source: the source of music (zing mp3 = 1, nhaccuatui = 2) - this is compulsory
– keyword: the keyword - this is compulsory
– number: the expect number of song - this is optional. The maximum number of
song user can query from ZingMP3 is 60, and 111 for Nhaccuatui
Local variable: defined inside a method, the usage of local variable in only
inside a method. Prefix of local variable is _ or [a-z].
Instance variable: instance variable is available accross methods and object,
meanwhile, instance variable change from object to object. Prefix of instance
variable is @. Instance variable is not shared among its descedants.
Class variable: it belongs to a class and is a characteristic of this class.
Prefix is @@. Class variable is share among its descedants(childs).
Global variable: class varaible is not across class, however, global variable
does. The prefix of global variable is $.
Constant variable: it’s similar to class variable but it’s constant. Constant
varaibles should be in upper case for all letters.
#2. Commenting
Using =begin and =end
=begin
This is a multiline comment and con spwan as many lines as you
like. But =begin and =end should come in the first line only.
=end
Block must be named after a name of a method (or a function), other while,
it does not work. Usage: In a method, there might be an chunk of code which is
used many time within the method, the point is that, this chunk of code is not
worth making a new function or maybe programmers don’t want to make a function
on that chunk (they cannot think a name for that).
deffunction_nameputs"In a function"yieldputs"Come back to function"endfunction_name{puts"In a block"}
It’s also possible to insert parameters into a block. However, if a function has parameters, I don’t know but there is a error and
cannot use block with function which have parameters.
classBox#`@` is a declare of instance varaiblesdefinitialize(w,h)@width=w@height=hendend
Getters and setters
classBox@@number_of_box=0definitialize(w,h)@width=w@height=hend# These are gettersdefprintWidth@widthenddefprintHeight@heightend#These are settersdefsetWidth=(new_value)@width=new_valueenddefsetHeight=(new_value)@height=new_valueend#usage of @@class variablesdefprintNumberOfBoxputs@@number_of_boxendend
#6. Access control: Public, Private, Protected
Public method: is called by anyone. By default, all methods excepting
initialize method are public methods.
Private method: only class methods can access private methods
Protected method: is called by class method and its subclass method.
Method overloading: Unlike java, ruby is using dynamic typed language, as a
results, it’s impossible to using overriding if depending on variable types. On
the other hand, it uses number of parameters to differentiate methods.
deffunction_name(a,b)#there is no type declaring, compiler does not knowend#how to overridedeffunction_name(a,b)#As a consequence, compiler uses number of parameters toend#differentiate two methodsdeffunction_name(a)end
# range is [0-5]forcounterin0..5putscounterend# range is [0-5)forcounterin0...5putscounterend
#9. Symbols
a. What is this
Symbols in ruby are immutable. Besides this point, it’s a string. It’s able to print put the value of a symbol in term of string or integer
:age#this is a symbol named ageputs:age# print out age's value in stringputs:age.object_id# print out age's object id
b. Implementation
Automatic make new method based on the symbols
defmake_me_a_setter(thename)eval<<-SETTERDONE
def #{thename}(myarg)
@#{thename} = myarg
end
SETTERDONEendclassExamplemake_me_a_setter:symbollmake_me_a_setter"stringg"defshow_symbollputs@symbollenddefshow_stringgputs@stringgendendexample=Example.newexample.symboll("ITS A SYMBOL")example.stringg("ITS A STRING")example.show_symbollexample.show_stringg# reference: http://www.troubleshooters.com/codecorn/ruby/symbols.htm
This is a remember note to learn python, more or less, it’s writen for me -the author to rememeber main issues of python.
1. Scope and Namespace
defscope_test():defdo_local():spam="local spam"defdo_nonlocal():nonlocalspamspam="nonlocal spam"defdo_global():globalspamspam="global spam"spam="test spam"do_local()print("After local assignment:",spam)do_nonlocal()print("After nonlocal assignment:",spam)do_global()print("After global assignment:",spam)scope_test()print("In global scope:",spam)
The output is:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
Explaination:
Local variable always is always used inside local scope. In the example, local variable
spam has value is local spam, when do_local() invoked, spam only created inside a
function, it has no use outside.
Non local variable has been declared and it affect within scope_test and only within scope_test.
Global variable only used in global scope.
In Python, a function can exist inside a function, in the example above, do_local insides scope_test.
Functions make its own scope.
##2. Class
classDog:kind='canine'# class variable shared by all instances
def__init__(self,name):self.name=name# instance variable unique to each instance
>>>d=Dog('Fido')>>>e=Dog('Buddy')>>>d.kind# shared by all dogs
'canine'>>>e.kind# shared by all dogs
'canine'>>>d.name# unique to d
'Fido'>>>e.name# unique to e
'Buddy'
Notes:
Class variables shared by all instances, kind is class variable.
Instance variables shared by each instance,name is instance variable.
Function can be define outside class.
# Function defined outside the class
deff1(self,x,y):returnmin(x,x+y)classC:f=f1defg(self):return'hello world'h=g
When working on my assignment in course named Mobile Application. I had a
problem that my program has two tables, both of them belong to a single
database.
In my program, I used SQLiteHelper, the program has two diffirential classes
which handle database working process.
publicclassTaskDaoImplextendsSQLiteOpenHelperimplementsTaskDao{//singletonprivatestaticTaskDaoImplinstance=null;privateContextcontext;privateArrayList<Task>tasks;privatestaticfinalintDATABASE_VERSION=1;privatestaticfinalStringDATABASE_NAME="TaskManager";privatestaticfinalStringTABLE_TASK="task";//TABLE INFORMATIONprivatestaticfinalStringtaskId="ID";privatestaticfinalStringtaskTitle="TITLE";privatestaticfinalStringtaskNote="NOTE";privatestaticfinalStringtaskDueDate="DATE";privatestaticfinalStringtaskPriorityLevel="PRIORITY";privatestaticfinalStringtaskCollaborators="COLLABORATOR";privatestaticfinalStringtaskStatus="STATUS";privatestaticfinalStringtaskGroupId="GROUPID";privateSQLiteDatabasemydatabase;privateTaskDaoImpl(Contextcontext){super(context,DATABASE_NAME,null,DATABASE_VERSION);this.context=context;}publicstaticTaskDaoImplgetInstance(Contextctx){if(instance==null){instance=newTaskDaoImpl(ctx);instance.tasks=newArrayList<Task>();instance.createTableIfNotExist();Log.v("TaskDaoImpl: ","getInstance() active");}returninstance;}@OverridepublicvoidonCreate(SQLiteDatabasesqLiteDatabase){Stringcreate_db="CREATE TABLE "+TABLE_TASK+"("+taskId+" INTEGER PRIMARY KEY, "+taskTitle+" TEXT, "+taskNote+" TEXT, "+taskDueDate+" INTEGER, "+taskPriorityLevel+" INTEGER, "+taskCollaborators+" TEXT, "+taskStatus+" INTEGER, "+taskGroupId+" INTEGER"+")";sqLiteDatabase.execSQL(create_db);Log.v("TaskDaoImpl","Did create table "+TABLE_TASK);}@OverridepublicvoidonUpgrade(SQLiteDatabasesqLiteDatabase,inti,inti2){onCreate(sqLiteDatabase);}publicvoidcreateTableIfNotExist(){mydatabase=this.getWritableDatabase();Stringcreate_db="CREATE TABLE IF NOT EXISTS "+TABLE_TASK+"("+taskId+" INTEGER PRIMARY KEY, "+taskTitle+" TEXT, "+taskNote+" TEXT, "+taskDueDate+" INTEGER, "+taskPriorityLevel+" INTEGER, "+taskCollaborators+" TEXT, "+taskStatus+" INTEGER, "+taskGroupId+" INTEGER"+")";mydatabase.execSQL(create_db);}@OverridepublicArrayList<Task>getAllTasks(){returntasks;}@OverridepublicintcreateTask(Tasktask){intmaxID;if(tasks.isEmpty()==true){maxID=0;}else{intid=tasks.get(tasks.size()-1).getId();maxID=id+1;}task.setId(maxID);tasks.add(task);SQLiteDatabasedb=this.getWritableDatabase();ContentValuesvalues=newContentValues();values.put(taskId,task.getId());values.put(taskTitle,task.getTitle());values.put(taskNote,task.getNote());values.put(taskDueDate,task.getDueDate().getTime()/1000);values.put(taskPriorityLevel,task.getPriorityLevel());//collaborator from arraylist to StringStringBuilderstringB=newStringBuilder();for(inti=0;i<task.getCollaborator().size();i++){stringB.append(task.getCollaborator().get(i));if(i<task.getCollaborator().size()-1){stringB.append(",");}}values.put(taskCollaborators,stringB.toString());values.put(taskStatus,task.isCompletionStatus());values.put(taskGroupId,task.getGroupID());db.insert(TABLE_TASK,null,values);db.close();return1;}@OverridepublicTaskgetTaskByID(intid){for(inti=0;i<tasks.size();i++){if(tasks.get(i).getId()==id){returntasks.get(i);}}returnnull;}publicArrayList<Task>getTaskByGroupID(intid){ArrayList<Task>filteredList=newArrayList<Task>();for(inti=0;i<tasks.size();i++){if(tasks.get(i).getGroupID()==id){filteredList.add(tasks.get(i));}}returnfilteredList;}publicvoiddeleteTaskByGroupID(intgroupID){for(intx=0;x<tasks.size();x++){if(tasks.get(x).getGroupID()==groupID){deleteTask(tasks.get(x));x--;}}}@OverridepublicintupdateTask(Tasktask){for(inti=0;i<tasks.size();i++){if(tasks.get(i).getId()==task.getId()){tasks.get(i).setCollaborator(task.getCollaborator());tasks.get(i).setCompletionStatus(task.isCompletionStatus());tasks.get(i).setDueDate(task.getDueDate());tasks.get(i).setPriorityLevel(task.getPriorityLevel());tasks.get(i).setTitle(task.getTitle());tasks.get(i).setNote(task.getNote());return1;}}return0;}@OverridepublicintdeleteTask(Tasktask){SQLiteDatabasedb=this.getWritableDatabase();db.beginTransaction();db.delete(TABLE_TASK,taskId+" = ?",newString[]{String.valueOf(task.getId())});db.setTransactionSuccessful();db.endTransaction();Log.v("TaskDaoImpl: ",task.getId()+"-"+task.getTitle());tasks.remove(task);db.close();return0;}publicvoidinit(){tasks.removeAll(tasks);Log.v("TaskDaoImpl: ","init method");SQLiteDatabasedb=this.getReadableDatabase();Stringquery="SELECT * FROM "+TABLE_TASK;Cursorcursor=db.rawQuery(query,null);if(cursor.moveToFirst()){do{Tasktask=newTask();task.setId(Integer.parseInt(cursor.getString(0)));task.setTitle(cursor.getString(1));task.setNote(cursor.getString(2));Datedatetime=newDate(Long.parseLong(cursor.getString(3))*1000);Log.v("datetime ",datetime.toString());task.setDueDate(datetime);task.setPriorityLevel(Integer.parseInt(cursor.getString(4)));//get collaboratorsStringcollaboratorsS=cursor.getString(5);ArrayList<String>colaList=newArrayList<String>(Arrays.asList(collaboratorsS.split(",")));task.setCollaborator(colaList);//get statusif(Integer.parseInt(cursor.getString(6))==0){task.setCompletionStatus(false);}else{task.setCompletionStatus(true);}//set group idtask.setGroupID(Integer.parseInt(cursor.getString(7)));task.print();//add to array list - liststasks.add(task);}while(cursor.moveToNext());}}}
#ISSULE AND PROBLEM
In general, in order to use SQLiteHelper to make new table and database.
function named onCreate(SQLiteDatabase db) will be invoked to do that. In my
program, TaskGroupImpl instance is initialized before TaskDaoImpl, bug happend
here, when I make a new instance of TaskDaoImpl - ofcourse after TaskGroupImpl,
table named task would not be created or function named onCreate(SQLiteDatabase
db) is not invoked.
#Solution
I make an extra function to make new table manually. This function named
createTableIfNotExist(), it belong to TaskDaoImpl class - because it has a new
table which I want to make but not create automatically by SQLiteHelper.
When make call a instance of TaskDaoImpl, I also check to make a new table
name task. If it is exist, make no new table, if not, make a new table.
Main Class: cosc2010.assignment1.controller.ProgramLaucher
next line here(compulsory)
#2. Making file .class
This file is a compiled file of file.java. In order to make this file. Use the
following command on the terminal.
javac .path/to/file.java
In this case, my output is a file named ProgramLaucher.class
#3.Setting up folder for compile
In order to compile java source code, you need to add file manifest.txt and
compiled file file.class. For example in the case above, after make a new
directory, our directory should be
jar -cvfm ProgramLaucher.jar manifest.txt *.class
'c' refers to creating new archive file, in this case, it is
`ProgramLaucher.jar`'v' refers to verbose, while processing, all relevant details will be report on
the terminal screen
'f' refers to specified file .jar will be created - creating option is assigned
by `c` but, what and where to create is assigned by `f`'m' refers to manifest file
I am now introducing a simple way to download video from Youtube by conkeror and an extra terminal program name cclive. This program take role to catch the link of youtube video and download it to assigned directory. In addition, you can choose type of video to download, of course, it also depends on the source.However, I am not going to further to that point.
What you need is: cclive, conkeror-spawn-helper
Firstly, you need to install cclive. if you are using Fedora, you can install it by this simple command on the terminal.
sudo yum install cclive -y
Then, you open your conkeror file init.js, and append it with the following lines
//download video from youtube using ccliveinteractive("download-video-2-music","Download current playing video.",function(I){varpath=I.buffer.current_uri.path;path=path.substr(9,30);I.minibuffer.message("Downloading video to folder Music ");shell_command_blind("cclive -d /home/nguyenvinhlinh/Music \"https://www.
youtube.com/watch?v=\""+path);});interactive("download-video-2-downloads","Download current playing video.",function(I){varpath=I.buffer.current_uri.path;path=path.substr(9,30);I.minibuffer.message("Downloading video to folder Downloads");shell_command_blind("cclive -d /home/nguyenvinhlinh/Downloads \"https:
//www.youtube.com/watch?v=\""+path);});
You can active these functions by M-x download-video-2-download, M-x download-video-2-music or assign these function to hot keys, for example:
By default, conkeror users may not use backspace to delete previous characters when they do simple task in google document, perharp also for other google product. The solution is that you have to enable quote mode in conkeror