Golang Net.IP to IPv6 (from MySQL) as Decimal(39,0) Conversion? - mysql

I have a database that stores IPv4 and IPv6 addresses as decimal(39,0). I need to convert a Golang Net.IP to this format. I have done it for IPv4 as follows:
func ipv4ToInt(IPv4Addr net.IP) int64 {
bits := strings.Split(IPv4Addr.String(), ".")
b0, _ := strconv.Atoi(bits[0])
b1, _ := strconv.Atoi(bits[1])
b2, _ := strconv.Atoi(bits[2])
b3, _ := strconv.Atoi(bits[3])
var sum int64
sum += int64(b0) << 24
sum += int64(b1) << 16
sum += int64(b2) << 8
sum += int64(b3)
return sum
}
I am trying the same with IPv6:
func ipv6ToInt(IPv6Addr net.IP) Int128 {
bits := strings.Split(IPv6Addr.String(), ":")
var arr [4]int64
var arr1 [4]uint64
for i := 0; i < 4; i++ {
arr[i], _ = strconv.ParseInt(bits[i], 16, 64)
}
for i := 0; i < 4; i++ {
arr1[i], _ = strconv.ParseUint(bits[i], 16, 64)
}
int1 := arr[0]
for i := 0; i < 4; i++ {
int1 = (int1 << 16) + arr[i]
}
int2 := arr1[0]
for i := 0; i < 4; i++ {
int2 = (int2 << 16) + arr1[i]
}
var IPv6Int Int128
IPv6Int.H = int1
IPv6Int.L = int2
return IPv6Int
}
Where int128 is
type Int128 struct {
H int64
L uint64
}
The result should look like:
42540578165168461141553663388954918914
from the IPv6 addr:
2001:470:0:76::2
Thanks!
EDIT, ANSWER:
Thanks to the people in #go-nuts, the answer is as follows:
func ipv6ToInt(IPv6Addr net.IP) *big.Int {
IPv6Int := big.NewInt(0)
IPv6Int.SetBytes(IPv6Addr)
return IPv6Int
}
The same works for IPv6, just do IP.To4() first.

Thanks to the people in #go-nuts, the answer is as follows:
func ipv6ToInt(IPv6Addr net.IP) *big.Int {
IPv6Int := big.NewInt(0)
IPv6Int.SetBytes(IPv6Addr)
return IPv6Int
}
The same works for IPv4, just do IP.To4() first.

Related

mysql query with C

I am writing a program where the user is giving random 10 bytes which I am storing in a buffer. Then search the hexadecimal string in a MySql database.
unsigned char buffer[10]; //Example:- {23, 181, 185, 192, 101, 156, 61, 247, 206, 204}
//convert each byte into 2 digit hexadecimal characters and store it in an array.
unsigned char hex_bytes[21];
for(int i = 0, l = 0; i < 10; i++) {
int decimal_num = buffer[i];
int quotient, remainder;
char hex_num[10];
quotient = decimal_num;
int j = 0;
while(quotient != 0) {
remainder = quotient % 16;
if(remainder < 10) {
hex_num[j++] = 48 + remainder;
}
else {
hex_num[j++] = 87 + remainder; //hex_num[j++] = 55 + remainder;
}
quotient = quotient/16;
}
for(int k = j-1; k >=0; k--) {
hex_bytes[l++] = hex_num[k];
}
}
printf("Ticket no. = %s\n", hex_bytes);
//------------------------------------------------------------------//
//Querying the Database
unsigned char query1[256];
uint32_t nos[10000];
MYSQL_RES *result;
//unsigned char* hex_str = "17b5b9c0659c3df7cecc"; <-----
//sprintf(query1, "SELECT sn FROM fixit_log WHERE rn = '%s'", hex_str); <-----
sprintf(query1, "SELECT sn FROM fixit_log WHERE rn = '%s'", hex_bytes);
mysql_query(con, query1);
if(mysql_errno(con) != 0) {
printf("stderr: %s\n", mysql_error(con));
mysql_close(con);
return;
}
result = mysql_store_result(con);
int k = 0;
for(int i =0; i < sr_nos_size; i++) {
MYSQL_ROW row = mysql_fetch_row(result);
printf("--sn: %2s\n", row[0]);
}
}
My Database looks like this:
sn rn
123456 17b5b9c0659c3df7cecc ///hexadecimal string of the given example as stored in the database
123457 17b5b9c0659c3df7cecc
123458 17b5b9c0659c3df7cecc
If I hardcode the hexadecimal string(comment out // part), I am getting the proper output. But if I run the program as above I am don't get any output.

retrieving data from json response from an API

I'm trying to get data from json response by storing it in some structs (Airport + coordinates) but I don't know how to deal with that since I'm not good enough with maps and interfaces. The code is showing no errors but MapofAirports is completely empty here is the code:
package main
import (
//"api/client"
//"api/client/clienterrors"
//"api/client/openstreetmap"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
)
type Coordinates struct {
Longitude string `json:"lon"`
Latitude string `json:"lat"`
}
type Airport struct {
Co Coordinates `json:"location"`
IATACode string `json:"id"`
Distance float64 `json:"distance"` // distance to coordinates in kilometer
}
func GetCoordinatesFromURL(url string) (float64, float64) {
parts := strings.Split(url, "=")
lat0 := strings.Split(parts[2], "&")
lon0 := strings.Split(parts[3], "&")
lat1, _ := strconv.ParseFloat(lat0[0], 64)
lon1, _ := strconv.ParseFloat(lon0[0], 64)
return lat1, lon1
}
func CalcDistance(lat1 float64, long1 float64, lat2 float64, long2 float64) float64 {
var latitude1 = lat1 * math.Pi / 180
var latitude2 = lat2 * math.Pi / 180
var longitude1 = long1 * math.Pi / 180
var longitude2 = long2 * math.Pi / 180
var R = 6371.0
var d = R * math.Acos(math.Cos(latitude1)*math.Cos(latitude2)*math.Cos(longitude2-longitude1)+math.Sin(latitude1)*math.Sin(latitude2))
return d
}
func main() {
var Locations []Airport
Locations = make([]Airport, 0)
var url = fmt.Sprintf("https://api.skypicker.com/locations?type=radius&lat=40.730610&lon=-73.935242&radius=250&location_types=airport&limit=3&sort=id&active_only=true")
UrlLat, UrlLon := GetCoordinatesFromURL(url)
resp, err := http.Get(url)
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var airportsJsonResponse interface{}
err = json.Unmarshal(body, &airportsJsonResponse)
MapofAirports, ok := airportsJsonResponse.([]interface{})
if ok {
lenAiroMap := len(MapofAirports)
locationsMaps := make(map[int]map[string]interface{})
for i := 0; i < lenAiroMap; i++ {
locationsMaps[i] = MapofAirports[i].(map[string]interface{})
}
var coords Coordinates
for i := 0; i < lenAiroMap; i++ {
if longitude, ok0 := locationsMaps[i]["lon"].(string); ok0 {
if latitude, ok1 := locationsMaps[i]["lat"].(string); ok1 {
coords = Coordinates{longitude, latitude}
}
}
code := locationsMaps[i]["id"].(string)
latFromCoordinates, _ := strconv.ParseFloat(Locations[i].Co.Latitude, 64)
lonFromCoordinates, _ := strconv.ParseFloat(Locations[i].Co.Longitude, 64)
dist := CalcDistance(latFromCoordinates, lonFromCoordinates, UrlLat, UrlLon)
Locations = append(Locations, Airport{
Co: coords,
IATACode: code,
Distance: dist,
})
}
}
LocationsJson, err := json.Marshal(Locations)
if err != nil {
log.Fatal("Cannot encode to JSON ", err)
}
fmt.Fprintf(os.Stdout, "%s", LocationsJson)
}
screenshot of json response
in the screenshot this is the json response we have, and I'm processing like this:
{ locations[],meta,last_refresh,results_retrieved } ==> location : { id , location + distance(calculated with a function) }
Change this line MapofAirports, ok := airportsJsonResponse.([]interface{}) to this
MapofAirports, ok := airportsJsonResponse.(map[string]interface{})
If you place a break point at this line you will see type of airportsJsonResponse is map[string]interface{}.
And you will have to change this lines into key value iteration
for i := 0; i < lenAiroMap; i++ {
locationsMaps[i] = MapofAirports[i].(map[string]interface{})
}
in to sth like below :
lenAiroMap := len(MapofAirports)
locationsMaps := make([]map[string]interface{},lenAiroMap)
for i, value := range MapofAirports["locations"].([]interface{}) {
converted := value.(map[string]interface{})
locationsMaps[i] = converted
}
this is my last update and while running the program it panics at unmarshaling step
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strconv"
"strings"
)
type Coordinates struct {
Longitude string `json:"lon"`
Latitude string `json:"lat"`
}
type Airport struct {
Co Coordinates `json:"location"`
IATACode string `json:"id"`
Distance float64 `json:"distance"` // distance to coordinates in kilometer
}
type Response struct {
Locations []Airport `json:"locations"`
// add all the other fields you care about
}
func GetCoordinatesFromURL(url string) (float64, float64) {
parts := strings.Split(url, "=")
lat0 := strings.Split(parts[2], "&")
lon0 := strings.Split(parts[3], "&")
lat1, _ := strconv.ParseFloat(lat0[0], 64)
lon1, _ := strconv.ParseFloat(lon0[0], 64)
return lat1, lon1
}
func CalcDistance(lat1 float64, long1 float64, lat2 float64, long2 float64) float64 {
var latitude1 = lat1 * math.Pi / 180
var latitude2 = lat2 * math.Pi / 180
var longitude1 = long1 * math.Pi / 180
var longitude2 = long2 * math.Pi / 180
var R = 6371.0
var d = R * math.Acos(math.Cos(latitude1)*math.Cos(latitude2)*math.Cos(longitude2-longitude1)+math.Sin(latitude1)*math.Sin(latitude2))
return d
}
func main() {
var url = fmt.Sprintf("https://api.skypicker.com/locations?type=radius&lat=40.730610&lon=-73.935242&radius=250&location_types=airport&limit=3&sort=id&active_only=true")
UrlLat, UrlLon := GetCoordinatesFromURL(url)
resp, err := http.Get(url)
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
res := &Response{}
if err := json.Unmarshal(data, res); err != nil {
panic(err)
}
fmt.Println(res.Locations)
for i, item := range res.Locations {
latt,_ := strconv.ParseFloat(item.Co.Latitude, 64)
lonn,_ :=strconv.ParseFloat(item.Co.Longitude, 64)
res.Locations[i].Distance = CalcDistance(latt,lonn , UrlLat, UrlLon)
}
fmt.Println("after calculate distance")
fmt.Println(res.Locations)
}
what's wrong with that ?

Implementing Dijkstra's algorithm with C++ STL

I have implemented the Dijkstra's algorithm as follows
#include <iostream>
#include <bits/stdc++.h>
#include<cstdio>
#define ll long long int
#define mod 1000000007
#define pi 3.141592653589793
#define f first
#define s second
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define vfor(e, a) for (vector<ll> :: iterator e = a.begin(); e != a.end(); e++)
#define vfind(a, e) find(a.begin(), a.end(), e)
#define forr(i, n) for (ll i = 0; i < n; i++)
#define rfor(i, n) for (ll i = n - 1; i >= 0; i--)
#define fors(i, b, e, steps) for(ll i = b; i < e; i += steps)
#define rfors(i, e, b, steps) for(ll i = e; i > b; i -= steps)
#define mp make_pair
using namespace std;
void up(pair<ll, ll> a[], ll n, ll i, ll indArray[]) {
ll ind = (i - 1) / 2;
while (ind >= 0 && a[ind].s > a[i].s) {
swap(a[ind], a[i]);
indArray[a[ind].f] = ind;
indArray[a[i].f] = i;
i = ind;
ind = (i - 1) / 2;
}
}
void down(pair<ll, ll> a[], ll n, ll i, ll indArray[]) {
ll left = 2 * i + 1;
ll right = 2 * i + 2;
ll m = a[i].s;
ll ind = i;
if (left < n && a[left].s < m) {
ind = left;
m = a[left].s;
}
if (right < n && a[right].s < m) {
ind = right;
}
if (ind != i) {
swap(a[i], a[ind]);
indArray[a[i].f] = i;
indArray[a[ind].f] = ind;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// cout << setprecision(10);
ll n, m;
cin >> n >> m;
vector<pair<ll, ll>> a[n];
forr(i, m) {
ll u, v, w;
cin >> u >> v >> w;
a[u].pb(mp(v, w));
a[v].pb(mp(u, w));
}
ll parent[n];
parent[0] = -1;
pair<ll, ll> dist[n];
forr(i, n) {
dist[i] = mp(i, INT_MAX);
}
dist[0].s = 0;
ll ind[n];
iota(ind, ind + n, 0);
ll ans[n];
ans[0] = 0;
bool visited[n];
fill(visited, visited + n, false);
ll size = n;
forr(i, n) {
ll u = dist[0].f;
visited[u] = true;
ll d1 = dist[0].s;
ans[u] = dist[0].s;
swap(dist[0], dist[size - 1]);
size--;
down(dist, size, 0, ind);
for (auto e : a[u]) {
if (visited[e.f]){
continue;
}
ll v = e.f;
ll j = ind[v];
if (dist[j].s > d1 + e.s) {
dist[j].s = d1 + e.s;
up(dist, size, j, ind);
parent[v] = u;
}
}
}
stack<ll> st;
forr(i, n) {
ll j = i;
while (j != -1) {
st.push(j);
j = parent[j];
}
while (!st.empty()) {
cout << st.top() << "->";
st.pop();
}
cout << " Path length is " << ans[i];
cout << '\n';
}
}
This implementation is correct and giving correct output.
As it can be seen every time I select the node with lowest key value(distance from source) and then I update the keys on all the adjacent nodes of the selected node. After updating the keys of the adjacent nodes I am calling the 'up' function as to maintain the min heap properties. But priority queue is present in the c++ stl. How can I use them to avoid the functions up and down.
The thing is I need to be able to find the index of the node-key pair in the mean heap whose key needs to be updated. Here in this code I have used a seperate ind array which is updated every time the min heap is updated.
But how to make use of c++ stl
Like you implied, we cannot random-access efficiently with std::priority_queue. For this case I would suggest that you use std::set. It is not actually a heap but a balanced binary search tree. However it works the desired way you wanted. find, insert and erase methods are all O(log n) so you can insert/erase/update a value with desired time since update can be done with erase-then-insert. And accessing minimum is O(1).
You may refer to this reference implementation like the exact way I mentioned. With your adjacency list, the time complexity is O(E log V) where E is number of edges, V is number of vertices.
And please note that
With default comparator, std::set::begin() method returns the min element if non-empty
In this code, it puts the distance as first and index as second. By doing so, the set elements are sorted with distance in ascending order
% I did not look into the implementation of up and down of your code in detail.

Pass stream to function

vector<bool> retroswap (vector<bool> v)
{
reverse(v.begin(), v.end()) ;
for (int i = 0 ; i < v.size() ; i++)
{
if (v[i] == 0)
{
v[i] = 1 ;
} else {
v[i] = 0 ;
}
}
v.insert(v.begin(), 1) ;
return v ;
}
// Overloading the + operator
vector<bool> operator+ (vector<bool> gds, vector<bool> rs)
{
for (int i = 0 ; i < rs.size() ; i++)
{
gds.push_back(rs[i]) ;
}
return gds ;
}
ostream& operator<< (ostream& out, vector<bool> v)
{
for (int i = 0 ; i < v.size() ; i++)
{
out << v[i] << endl ;
}
return out ;
}
vector<bool> generate_dragon_sequence (vector<bool> v, int n, ostream& out)
{
if (n==1)
{
return v ;
}
vector<bool> rs = retroswap(generate_dragon_sequence(v, n-1, out)) ;
out << generate_dragon_sequence(v, n-1, out) + rs ;
return generate_dragon_sequence(v, n-1, out) + rs ;
}
Above is my code that i am doing for my school project. I have a question regarding passing ostream objects to functions. I am constructing a recursive function which generates larger and larger vectors according to an algorithm. All I want to do is to output the final vector product using the stream object
Hence, in int main(), if I were to write generate_dragon_function(v, n, cout), it will output the final vector to the console.
I was wondering how I could do it? Thank you so much guys!

Divide function

I need to write the divide function in the Jack language.
my code is:
function int divide(int x, int y) {
var int result;
var boolean neg;
let neg = false;
if(((x>0) & (y<0)) | ((x<0) & (y>0))){
let neg = true;
let x = Math.abs(x);
let y = Math.abs(y);
}
if (y>x){
return 0;
}
let result = Math.divide(x, y+y);
if ((x-(2*result*y)) < y) {
if (neg){
return -(result + result);
} else {
return (result + result);
}
} else {
if (neg){
return -(result + result + 1);
} else {
return (result + result + 1);
}
}
}
this algorithm is sub-optimal since each multiplication operation also requires O(n) addition and subtraction operations.
Can I compute the product 2*result*y without any multiplication?
Thanks
Here's an implementation of (unsigned) restoring division (x/y), I don't actually know Jack though so I'm not 100% sure about this
var int r;
let r = 0;
var int i;
let i = 0;
while (i < 16)
{
let r = r + r;
if ((x & 0x8000) = 0x8000) {
let r = r + 1;
}
if ((y ^ 0x8000) > (r ^ 0x8000)) { // this is an unsigned comparison
let x = x + x;
}
else {
let r = r - y;
let x = x + x + 1;
}
let i = i + 1;
}
return x;
You should be able to turn that into signed division.