【ANDROID STUDIO】Periodic Work Request Work Manager

 package com.example.wordmanager


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

companion object {
const val KEY_COUNT_VALUE = "key_count"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
//setOneTimeWorkRequest()
setPeriodicWorkRequest()
}

}

private fun setPeriodicWorkRequest() {
val periodicWorkRequest = PeriodicWorkRequest.Builder(DownloadingWorker::class.java,16,
TimeUnit.MINUTES)
.build()
WorkManager.getInstance(applicationContext).enqueue(periodicWorkRequest)
}

private fun setOneTimeWorkRequest() {
val workManager = WorkManager.getInstance(applicationContext)
val data: Data = Data.Builder()
.putInt(KEY_COUNT_VALUE,125)
.build()
val constraints = Constraints.Builder()
.setRequiresCharging(true)
.build()
val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java)
.setConstraints(constraints)
.setInputData(data)
.build()
val filteringRequest = OneTimeWorkRequest.Builder(FilteringWorker::class.java)
.build()
val compressingRequest= OneTimeWorkRequest.Builder(CompressingWorker::class.java)
.build()
val downloadingWorker= OneTimeWorkRequest.Builder(DownloadingWorker::class.java)
.build()
val paralleWorks = mutableListOf<OneTimeWorkRequest>()
paralleWorks.add(downloadingWorker)
paralleWorks.add(filteringRequest)
workManager
.beginWith(paralleWorks)
.then(compressingRequest)
.then(uploadRequest)
.enqueue()
workManager.getWorkInfoByIdLiveData(uploadRequest.id)
.observe(this, Observer {
textView.text = it.state.name
if(it.state.isFinished) {
val data = it.outputData
val message = data.getString(UploadWorker.KEY_WORKER)
Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
}
})
}

}
package com.example.wordmanager

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*

class DownloadingWorker(context: Context, params: WorkerParameters) : Worker(context,params) {


override fun doWork(): Result {
try {

for (i in 0..300) {
Log.i("MYTAG", "Downloading $i")
}

val time = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = time.format(Date())
Log.i("MYTAG","Completed $currentDate")

return Result.success()
} catch (e: Exception) {
return Result.failure()
}
}

}

【PYTHON】collect the data using a SQL query

engine = create_engine('sqlite:///chinook.db')


query = """SELECT SUM(Total) as Total , strftime('%m-%Y', InvoiceDate) as 'month-year', BillingCountry

FROM invoices

WHERE BillingCountry="USA"

GROUP BY strftime("%m-%Y", InvoiceDate);

"""


with engine.connect() as connection:

  sql_df2 = pd.read_sql_query(query, connection)


sql_df2.head()


# convert to datetime for better plotting

sql_df2['month-year'] = pd.to_datetime(sql_df2['month-year'])


sns.lineplot(data=sql_df2, x='month-year', y='Total', hue='BillingCountry')

plt.xlabel('Year')

[ VISUAL STUDIO C# ] calendar USING MONTHCALENDAR

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;


// make sure that using System.Diagnostics; is included

using System.Diagnostics; 


namespace Template

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void pictureBox1_Click(object sender, EventArgs e)

        {

            if (groupBox1.Visible == false)

            {

                groupBox1.Show();

            }

            else { groupBox1.Hide(); textBox1.Text = null; }

        }


        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)

        {

            textBox1.Text = monthCalendar1.SelectionStart.ToString();

        }

    }

}


【Visual Studio Visual Csharp】Tray Icon

 using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace showTrayC { public partial class Form1 : Form { NotifyIcon notify = new NotifyIcon(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { notifyIcon1.Visible = true; notifyIcon1.BalloonTipIcon = ToolTipIcon.Info; notifyIcon1.BalloonTipText = "Application working..."; notifyIcon1.BalloonTipTitle = "TrayIcon example application"; notifyIcon1.ShowBalloonTip(2000); } private void Form1_Load(object sender, EventArgs e) { notifyIcon1.Visible = false; } } }

【PYTHON】Boxplots and Boxenplots

 import pandas as pd


df = pd.read_csv('itunes_data.csv')

df['Minutes'] = df['Milliseconds'] / (1000 * 60)

df['MB'] = df['Bytes'] / 1000000

df.drop(['Milliseconds', 'Bytes'], axis=1, inplace=True)


import matplotlib.pyplot as plt


df['Minutes'].plot.box()

plt.show()


df['Minutes'].plot.box()


import seaborn as sns

_ = sns.boxenplot(y=df['Minutes'])


# plot multiple columns at once

sns.boxenplot(data=df[['Minutes', 'MB']])


# save figure for book

f = plt.figure(figsize=(5.5, 5.5))  # this changes the size of the image -- more on this is chapter 5

f.patch.set_facecolor('w')  # sets background color behind axis labels

sns.boxenplot(y=df['Minutes'])

plt.tight_layout()  # auto-adjust margins

plt.savefig('B17030_05_02.png', dpi=300)


sns.boxenplot(y=df['Minutes'])

plt.yscale('log')


#@title Default title text

# save figure for book

f = plt.figure(figsize=(5.5, 5.5))  # this changes the size of the image -- more on this is chapter 5

f.patch.set_facecolor('w')  # sets background color behind axis labels

sns.boxenplot(y=df['Minutes'])

plt.yscale('log')

plt.tight_layout()  # auto-adjust margins

plt.savefig('B17030_05_03.png', dpi=300)


df['Minutes'].plot.box()

plt.yscale('log')


df['Minutes'].plot.box()

plt.yscale('log')


# another way to use a log scale

df['Minutes'].plot.box(logy=True)


df['Minutes'].describe()


【GAMEMAKER】Key Mapped

Information about object: obj_MapKey

Sprite: spr_Map
Solid: false
Visible: true
Depth: 0
Persistent: false
Parent:
Children:
Mask:
No Physics Object
Create Event:
execute code:

Mapping = false
scr_MapNames()
//you cannot use the variable "kd"
//if you want to use it, change the variable name in the scripts

//don't forget to check each of my instances' creation codes.
//go to the room I'm in, and ctrl+RightClick one of my instances.
//then click "Creation Code." You can see a few of my variables there.
//This is so each instance of me has different variable values.
Mouse Event for Left Released:
execute code:

//only this key is mapping
obj_MapKey.Mapping = false
Mapping = true
Draw Event:
execute code:

draw_set_halign(fa_center)
draw_sprite(sprite_index,-1,x,y) //draw the box
draw_text(x-48,y+8,draw_string) //draw the description
draw_text(x+112,y+8,draw_mapped) //draw the key
draw_set_halign(fa_left)
//draw an outline
draw_line(x-96,y,x+160,y)
draw_line(x-96,y,x-96,y+32)
draw_line(x-96,y+32,x+160,y+32)
draw_line(x+160,y,x+160,y+32)

//if waiting for remap, draw remap info
if Mapping {
 //draw_background(bg_White,272,238)
 draw_set_halign(fa_center)
 draw_text(400,260,"Press Desired Key for Action:")
 draw_text(400,276,draw_string)
}

Key Release Event for <any key> Key:
execute code:

if Mapping {
 scr_MapSet() //remap the key pressed
}

Information about object: obj_Player
Sprite: spr_A1_W_D
Solid: true
Visible: true
Depth: 1
Persistent: true
Parent:
Children:
Mask:
No Physics Object
Create Event:
execute code:

image_speed = 0 //don't animate yet
Step Event:
execute code:

//handle movement
//notice how it checks each key based on variable
//check the room creation code to see these variables initialized
//the variables are reset (remapped) using scr_MapSet - the execute string

if keyboard_check(global.DownKey) {
 //move; set sprite; animate sprite
 y += 4; sprite_index=spr_A1_W_D; image_speed = .4
}
if keyboard_check(global.LeftKey) {
 x -= 4; sprite_index=spr_A1_W_L; image_speed = .4
}
if keyboard_check(global.RightKey) {
 x += 4; sprite_index=spr_A1_W_R; image_speed = .4
}
if keyboard_check(global.UpKey) {
 y -= 4; sprite_index=spr_A1_W_U; image_speed = .4
}

//if he's not moving
if !keyboard_check(global.DownKey) && !keyboard_check(global.LeftKey)
&& !keyboard_check(global.RightKey) && !keyboard_check(global.UpKey) {
 image_index = 0 //place on first frame of sprite (standing)
 image_speed = 0 //stop animation
 //image_single is no longer supported
}

///////////
//Set Key//
///////////
var kk;
kk = keyboard_lastkey
if kd[kk] != "" { //make sure the key has a name
 draw_mapped = kd[kk] //set the drawing name to the name
 if(mapped_var == "global.UpKey"){
    global.UpKey = kk
 }
 if(mapped_var == "global.DownKey"){
    global.DownKey = kk
 }
if(mapped_var == "global.RightKey"){
    global.RightKey = kk
 } 
 if(mapped_var == "global.LeftKey"){
    global.RightKey = kk
 } 
 //execute_string(mapped_var+" = "+string(kk)) //set the variable to the key
 Mapping = false
}

//////////////////////////
//define each key's name//
//////////////////////////
/*
This is pretty much just a collection of names for the keys.
This way, the user knows what key each thing is set to.
*/
var m;
for (m = 0; m <= 255; m += 1) { //set all keys to nameless
 kd[m] = ""                     //only named keys can pass
}
kd[8] = "Backspace"
kd[13] = "Enter Key"
kd[16] = "Shift Key"
kd[17] = "Control Key"
kd[18] = "Alt Key"
kd[19] = "Pause/Break"
kd[27] = "Escape Key"
kd[32] = "Space Key"
kd[33] = "Page Up"
kd[34] = "Page Down"
kd[35] = "End Key"
kd[36] = "Home Key"
kd[37] = "Left Arrow"
kd[38] = "Up Arrow"
kd[39] = "Right Arrow"
kd[40] = "Down Arrow"
kd[45] = "Insert Key"
kd[46] = "Delete Key"
for (m = 65; m <= 90; m += 1) { //the letter keys
 kd[m] = chr(m)+" Key" //"A Key", "Z Key"
}
for (m = 96; m <= 105; m += 1) { //the numpad keys
 kd[m] = "Numpad "+string(m) //"Numpad 0", "Numpad 9"
}
kd[106] = "Multiply Key"
kd[107] = "Add Key"
kd[109] = "Subtract Key"
kd[110] = "Decimal Key"
kd[111] = "Divide Key"
for (m = 112; m <= 123; m += 1) { //the F keys
 kd[m] = "F"+string(m-1)+" Key" //"F1 Key", "F12 Key"
}

【Visual Studio Visual Csharp】Threading

 using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace threadC { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Thread first_thread = new Thread(new ThreadStart(first_thread_procedure)); Thread second_thread = new Thread(new ThreadStart(second_thread_procedure)); first_thread.Start(); second_thread.Start(); first_thread.Join(); } public void first_thread_procedure() { Thread.Sleep(500); MessageBox.Show("Hello from first thread :) ... "); } public void second_thread_procedure() { Thread.Sleep(1000); MessageBox.Show("Hello from second thread :) ... "); } } }

【PYTHON】Bitcoin data analysis

 itunes_df['Seconds'] = itunes_df['Milliseconds'] / 1000


itunes_df['len_byte_ratio'] = itunes_df['Milliseconds'] / itunes_df['Bytes']


genre_dict = {'metal': 'Metal', 'met': 'Metal'}

itunes_df['Genre'].replace(genre_dict)


itunes_df['Genre'].apply(lambda x: x.lower())


# the above is the same as this

def lowercase(x):

  return x.lower()


itunes_df['Genre'].apply(lowercase)


# but using built-in functions is almost always faster

itunes_df['Genre'].str.lower()


# this is a common sentiment analysis library; polarity is positive/negative sentiment,

# subjectivety is subjective/objective rating.

from textblob import TextBlob

test = TextBlob("Textblob is amazingly simple to use. What great fun!")

test.sentiment


test.sentiment.polarity


# it would be better than apply to use a list comprehension to get sentiment of track names, like this

itunes_df['Track_sentiment'] = [TextBlob(x).sentiment.polarity for x in itunes_df['Track']]


# but, if we wanted to mix polarity and subjectivity into one column, it would be best to use apply:

def pol_sub_mix(x):

  tb = TextBlob(x)

  return tb.polarity * tb.subjectivity


itunes_df['Track_pol_sub_mix'] = itunes_df['Track'].apply(pol_sub_mix)


# delete these columns

itunes_df.drop(['Track_pol_sub_mix', 'Track_sentiment'], inplace=True, axis=1)


# currently doesn't work with python 3.9

import swifter

itunes_df['Genre'].swifter.apply(lambda x: x.lower())


itunes_df.to_csv('cleaned_itunes_data.csv', index=False)


itunes_df.groupby('Genre').mean()['Seconds'].sort_values().head()


btc_df = pd.read_csv('bitcoin_price.csv')

btc_df.head()


btc_df['symbol'].unique()


btc_df.drop('symbol', axis=1, inplace=True)


btc_df['time'] = pd.to_datetime(btc_df['time'], unit='ms')


btc_df['time'].dtype


btc_df.info()


btc_df.set_index('time', inplace=True)


btc_df.head()


btc_df[['close']].plot(logy=True)


f = plt.figure(figsize=(5.5, 5.5))

btc_df.iloc[-3000:][['close']].plot(logy=True, figsize=(5.5, 5.5))

f.patch.set_facecolor('w')  # sets background color behind axis labels

plt.tight_layout()  # auto-adjust margins

plt.savefig('B17030_04_11.png', dpi=300)


btc_df2 = pd.read_csv('bitcoin_price.csv', index_col='time', parse_dates=['time'], infer_datetime_format=True)


date_parser = lambda x: pd.to_datetime(x, unit='ms')

btc_df2 = pd.read_csv('bitcoin_price.csv', index_col='time', parse_dates=['time'], date_parser=date_parser)

btc_df2.head()


btc_df.loc['2019']

【ANDROID STUDIO】 Query Parameter Retrofit With Kotlin Coroutines

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.liveData
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Response

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retService = RetrofitInstance
.getRetrofitInstance()
.create(AlbumService::class.java)
val responseLiveData: LiveData<Response<Albums>> = liveData {
//val response = retService.getAlbums()
val response = retService.getSortedAlbums(3)

emit(response)
}
responseLiveData.observe(this, Observer {
val albumsList = it.body()?.listIterator()
if (albumsList != null) {
while (albumsList.hasNext()) {
val albumsItem = albumsList.next()
val result = " " + "Album Title : ${albumsItem.title}" + "\n" +
" " + "Album id : ${albumsItem.id}" + "\n" +
" " + "User id : ${albumsItem.userId}" + "\n\n\n"
text_view.append(result)
}
}
})

}
}

package com.example.myapplication

import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query

interface AlbumService {
@GET("/albums")
suspend fun getAlbums() : Response<Albums>
@GET("/albums")
suspend fun getSortedAlbums(@Query("userId") userId:Int) :Response<Albums>

}

【FLUTTER ANDROID STUDIO and IOS】Sqlite CRUD

 import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'model.dart';
import 'dataBase.dart';
import 'itemCardWidget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: Brightness.dark,
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: Colors.blue,
)),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final DbManager dbManager = new DbManager();

Model model;
List<Model> modelList;
TextEditingController input1 = TextEditingController();
TextEditingController input2 = TextEditingController();
FocusNode input1FocusNode;
FocusNode input2FocusNode;

@override
void initState() {
input1FocusNode = FocusNode();
input2FocusNode = FocusNode();
super.initState();
}

@override
void dispose() {
input1FocusNode.dispose();
input2FocusNode.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sqlite Demo'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return DialogBox().dialog(
context: context,
onPressed: () {
Model model = new Model(
fruitName: input1.text, quantity: input2.text);
dbManager.insertModel(model);
setState(() {
input1.text = "";
input2.text = "";
});
Navigator.of(context).pop();
},
textEditingController1: input1,
textEditingController2: input2,
input1FocusNode: input1FocusNode,
input2FocusNode: input2FocusNode,
);
});
},
child: Icon(
Icons.add,
color: Colors.white,
),
),
body: FutureBuilder(
future: dbManager.getModelList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
modelList = snapshot.data;
return ListView.builder(
itemCount: modelList.length,
itemBuilder: (context, index) {
Model _model = modelList[index];
return ItemCard(
model: _model,
input1: input1,
input2: input2,
onDeletePress: () {
dbManager.deleteModel(_model);
setState(() {});
},
onEditPress: () {
input1.text = _model.fruitName;
input2.text = _model.quantity;
showDialog(
context: context,
builder: (context) {
return DialogBox().dialog(
context: context,
onPressed: () {
Model __model = Model(
id: _model.id,
fruitName: input1.text,
quantity: input2.text);
dbManager.updateModel(__model);

setState(() {
input1.text = "";
input2.text = "";
});
Navigator.of(context).pop();
},
textEditingController2: input2,
textEditingController1: input1);
});
},
);
},
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}

class Model {
int id;
String fruitName;
String quantity;

Model({this.id, this.fruitName, this.quantity});

Model fromJson(json) {
return Model(
id: json['id'],
fruitName: json['fruitName'],
quantity: json['quantity']);
}

Map<String, dynamic> toJson() {
return {'fruitName': fruitName, 'quantity': quantity};
}

}

import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

import 'model.dart';

class DbManager {
Database _database;

Future openDb() async {
_database = await openDatabase(join(await getDatabasesPath(), "ss.db"),
version: 1, onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE model(id INTEGER PRIMARY KEY autoincrement, fruitName TEXT, quantity TEXT)",
);
});
return _database;
}

Future insertModel(Model model) async {
await openDb();
return await _database.insert('model', model.toJson());
}

Future<List<Model>> getModelList() async {
await openDb();
final List<Map<String, dynamic>> maps = await _database.query('model');

return List.generate(maps.length, (i) {
return Model(
id: maps[i]['id'],
fruitName: maps[i]['fruitName'],
quantity: maps[i]['quantity']);
});
}

Future<int> updateModel(Model model) async {
await openDb();
return await _database.update('model', model.toJson(),
where: "id = ?", whereArgs: [model.id]);
}

Future<void> deleteModel(Model model) async {
await openDb();
await _database.delete('model', where: "id = ?", whereArgs: [model.id]);
}
}

import 'package:flutter/material.dart';
import 'dataBase.dart';
import 'model.dart';

class ItemCard extends StatefulWidget {
Model model;
TextEditingController input1;
TextEditingController input2;
Function onDeletePress;
Function onEditPress;

ItemCard({this.model,
this.input1,
this.input2,
this.onDeletePress,
this.onEditPress});

@override
_ItemCardState createState() => _ItemCardState();
}

class _ItemCardState extends State<ItemCard> {
final DbManager dbManager = new DbManager();

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Name: ${widget.model.fruitName}',
style: TextStyle(fontSize: 15),
),
Text(
'Quantity: ${widget.model.quantity}',
style: TextStyle(
fontSize: 15,
),
),
],
),
Row(
children: [
CircleAvatar(
backgroundColor: Colors.white,
child: IconButton(
onPressed: widget.onEditPress,
icon: Icon(
Icons.edit,
color: Colors.blueAccent,
),
),
),
SizedBox(
width: 15,
),
CircleAvatar(
backgroundColor: Colors.white,
child: IconButton(
onPressed: widget.onDeletePress,
icon: Icon(
Icons.delete,
color: Colors.red,
),
),
)
],
),
],
),
),
),
);
}
}

class DialogBox {
Widget dialog({BuildContext context,
Function onPressed,
TextEditingController textEditingController1,
TextEditingController textEditingController2,
FocusNode input1FocusNode,
FocusNode input2FocusNode}) {
return AlertDialog(
title: Text("Enter Data"),
content: Container(
height: 100,
child: Column(
children: [
TextFormField(
controller: textEditingController1,
keyboardType: TextInputType.text,
focusNode: input1FocusNode,
decoration: InputDecoration(hintText: "Fruit Name"),
autofocus: true,
onFieldSubmitted: (value) {
input1FocusNode.unfocus();
FocusScope.of(context).requestFocus(input2FocusNode);
},
),
TextFormField(
controller: textEditingController2,
keyboardType: TextInputType.number,
focusNode: input2FocusNode,
decoration: InputDecoration(hintText: "Quantity"),
onFieldSubmitted: (value) {
input2FocusNode.unfocus();
},
),
],
),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blueGrey,
child: Text(
"Cancel",
),
),
MaterialButton(
onPressed: onPressed,
child: Text("Submit"),
color: Colors.blue,
)
],
);
}
}

Thank You Substack Subscribers

Watch now (4 mins) | I had some drama with YouTube, but it's because of You that I can pay my bills. ͏     ­͏     ­͏     ­͏     ­͏     ­...

Contact Form

Name

Email *

Message *