Giter VIP home page Giter VIP logo

code-reuse's Introduction

Code Reuse c#

My English is not good, have sympathy for me!!!

I.Getting number of week from the beginning of this year to now

First you need to use this

using System.Globalization;

Function:

       public static int LayTuanTrongNam(DateTime time)
        {
            CultureInfo myCI = CultureInfo.CurrentCulture;
            Calendar myCal = myCI.Calendar;
            CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
            return myCal.GetWeekOfYear(time, myCWR, myFirstDOW);
        }
  

How to use:

       int getNumberOfWeeksInYear = LayTuanTrongNam(DateTime.Now);
       // example today is 2/12/2018 then the result is 49
       getNumberOfWeeksInYear--;
       // if you want accurate you need to minus 1
      
       int getNumberOfWeeksInMonth = LayTuanTrongNam(new DateTime(DateTime.Now.Year, 1, DateTime.Now.Day));
       // set month to 1 if you want to get number of weeks in this month

II. Fixing injection mysql php

Function:

        public static String fixInjection(String s)
        {
            // for php $_GET method
            s = s.Replace("&", "%26");
            s = s.Replace("\\", "\\\\");
            // for prevent from injection query
            s = s.Trim().Replace("'", "''");
            return s;
        }

Example

  String name = fixInjection(@"/ 'Hello Nam & You' \");
     /* the result is:  
     / ''Hello Nam %26 You'' \\
     */
     

III. Algorithm for simplifying decimal to fractions

Function:

            public static String SimplifyingFraction(double n,double d)
        {
            double num = n / d;
            String s = DoubleToFraction(num);
            return s;
        }
    public static string DoubleToFraction(double num, double epsilon = 0.0001, int maxIterations =20)
    {
        double[] d = new double[maxIterations + 2];
        d[1] = 1;
        double z = num;
        double n = 1;
        int t = 1;

        int wholeNumberPart = (int)num;
        double decimalNumberPart = num - Convert.ToDouble(wholeNumberPart);

        while (t < maxIterations && Math.Abs(n / d[t] - num) > epsilon)
        {
            t++;
            z = 1 / (z - (int)z);
            d[t] = d[t - 1] * (int)z + d[t - 2];
            n = (int)(decimalNumberPart * d[t] + 0.5);
        }

        return string.Format((wholeNumberPart > 0 ? wholeNumberPart.ToString() + " " : "") + "{0}/{1}",
                             n.ToString(),
                             d[t].ToString()
                            );
    }

Example

String s= SimplifyingFraction(2,8);//Numerator is 2 and Denominator is 8, => s="1/4"
s= DoubleToFraction(0.25);//=>s="1/4"

Code Reuse JavaScript


Show html string on website (prevent XSS):

// 1:string,2:class in css
  function preventXSS(s,cl){
    s=s.replace("&","&amp");
    s="<pre class=\""+cl+"\">"+s.replace(/</g,"&lt")+"<pre>";
    return s;
    }

Example:

var s="<button>Click me</button>";
s=preventXSS(s,"YourCssClass");
document.write(s);
 

 

PHP XSS

             echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

 

Xamarin. Getting weather temp in LS city

  async Task GetWeatherTemp(String url)
        {   
            //GetWeatherTemp("https://api.openweathermap.org/data/2.5/weather?q=Lang%20Son&units=metric&appid=df2521d538fc3664cfeae4a6491e63c1");
            HttpClient client = new HttpClient();
            Task getStringTask = client.GetStringAsync(url);
            string urlContents = await getStringTask;
            int i= urlContents.IndexOf("\"temp\"");
            int a= urlContents.IndexOf("\"pressure\"");
            urlContents = urlContents.Substring(i);
            char[] c = urlContents.ToCharArray();
            string s = "";
            foreach (char item in c)
            {
                if (item == ',') break;
                else s += item;
            }
            s = s.Replace("\"temp\":", "");
            return Convert.ToInt32(s);
        }

Xamarin convert datatable from json

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Shared preferences

Application.Current.Properties ["id"] = someClass.ID;

if (Application.Current.Properties.ContainsKey("id")) { var id = Application.Current.Properties ["id"] as int; // do something with id }

Unity timer

IEnumerator Lose()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            //code
        }
           StopCoroutine("Lose");
           StartCoroutine("Lose");
    }
#php
  $dt=mysql_real_escape_string($dt);//prevent injection
        //$dt=str_replace("'","''",$dt);
        date_default_timezone_set('Asia/Ho_Chi_Minh').//
        $timezone = date_default_timezone_get();
        $date = date('Y-m-d H:i:s ', time());
        
    Opt("TrayIconHide", 1)

HTML Tab

Type
  `& emsp ;`
to add a single space. Type
  `& ensp ; `
to add 2 spaces. Type
  `& emsp ; `
to add 4 spaces.

https://i.imgur.com/x4OD9J0.png

https://www.google.nl/search?q=google+search+bar&hl=vi

get views youtube nodejs

const fs = require('fs');
const request = require('request');
const cheerio = require('cheerio');
const url = 'https://www.youtube.com/watch?v=QAoFlBW1TYg';

request(url,(error,
response,html) => {
	if(!error && response.statusCode==200){
		const $=cheerio.load(html);
		const dt=$(".watch-view-count");
		var views=dt.text().split(" ");
		views[0]=views[0].split('.').join("");
		var num=parseInt(views[0]);//+10;
		console.log(dt.text()+"\n"+num);
		fs.writeFile('index.html', html, function (err) {
		  if (err) return console.log(err);
 			 console.log('Written!');
		});
	}

});

set heroku timezone

heroku config:add TZ="Asia/Vientiane"

diskpart

https://daynhauhoc.com/t/usb-bi-chia-lam-2-o-f-va-g/87910 alt text alt text

code-reuse's People

Contributors

snightcoder avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.