mercredi 28 février 2018

how to change format date in node.js

im newbie in node js, i create a web use node js, i show date from database, but i want to change the format date

this.editNewEvent = function(req, res) {
    var id = req.query.id;
    // var start_date = ;
    var dateFormat = require('dateFormat');
    // var day_start = dateFormat(start_date, "dd/mm/yyyy");
    connection.acquire(function(err, con) {
        if (err) throw err;
        con.query('SELECT id, event_code, event_name, id_type, event_category, description, start_date, end_date, location_name, longitude, latitude FROM transaksi_new_events WHERE id = "' + id + '" order by modified_at desc', function(err, rows) {
            con.release();
            if (err) {
                console.log(err);
            } else {
                obj = JSON.parse(JSON.stringify(rows));
                res.render('transaksi_new_event/edit', { obj: obj });
            }
        });
    });
};

in my web the date show '2018-03-01T17:00:00.000Z' i want change format to dd/mm/yyyy

my web view




Estágio em Desenvolvimento

gostária de saber da opinião de vocês em relação ao um caso que esta acontecendo comigo, sou estudante de CC e em pouco tempo de faculdade e muito estudo diário consegui o meu estágio em desenvolvimento voltado a Web.
Acontece que o sistema que estou desenvolvendo não pertence a 100% da empresa que me contratou como estágiario, e sim a associação de alguns gestores da minha empresa com alguns sócios externos. Ou seja, o sistema que desenvolvo é de uma futura empresa(que ainda não existe) que terá como seu primeiro produto o projeto que eu estou executando sozinho por enquanto(sobre a supervisão de meu gestor). A minha dúvida é, isso de alguma forma pode impactar de forma negativa no meu futuro? simplismente por não ter entrado em uma empresa grande e já consignada no mercado e ter desenvolvido sozinho um sistema como estágiario as empresas podem me olhar de forma "negativa" ? Gostaria da opinião de vocês, se isso de certa forma agrega algo ou pode me prejudicar posteriormente. Origado a todos que responderem.




gin gonic css not being loaded from the root of the page

I have set my CSS folder to be a static resource like so:

r.Static("/css", "./css/")

And I have a webpage like this:

r.GET("/u/:pid/:id", handleUser)

However I'm having an issue where the HTML file for the user page "user.html" is loading the css as "css/main.css", however gin handles this request:

localhost:8080/u/0/2

where the CSS is loaded like this:

localhost:8080/u/0/css/main.css

my project structure is:

css/
    main.css
templates/
    user.html
main.go

Am I doing something glaringly wrong here?




Why Did can't I send model? Spring Boot 2 - Thymealf

I can not open the registration page. If I delete the th:field page is displayed. How can I solve problem. I can not speak English well Thank you...

Error

 Whitelabel Error Page
    This application has no explicit mapping for /error, so you are seeing this as a fallback.
    Thu Mar 01 01:10:34 EET 2018
    There was an unexpected error (type=Internal Server Error, status=500).
    An error happened during template parsing (template: "class path resource [templates/register.html]")

Exception

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/register.html]")

Register HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Register</h3>
<form th:action="@{register}" method="post" th:object="${user}">

<input type="text"  th:field="*{username}">
<input type="text"  th:field="*{password}">
<input type="submit" value="Submit">
</form>
 </body>
</html>

Controller

@Controller
@RequestMapping("/")
public class UserController {

    @RequestMapping(value="", method=RequestMethod.GET)
    public String getHomePage()
    {
        return "home";
    }

    @RequestMapping(value="register",method=RequestMethod.GET)
    public String getRegisterPage(Model model)
    {
        model.addAttribute("user",new User());
        return "register";
    }

}




PhP Curl SFTP File Editing

I am trying to create a online editor for multiple server. I want to edit a custom file on a server and I need to get it via sftp. My current code looks like this:

<?php

$user="user";
$pass = 'pass';
$c = curl_init("sftp://$user:$pass@0.0.0.0/path/to/file/file.txt");
curl_setopt($c, CURLOPT_PORT, 3206);
curl_setopt($c, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);
//the next line is not working and from now on am I stuck
$text = file_get_contents($fh);

?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input 

type="submit" />
<input type="reset" />
</form>

I want to edit this file on the website and then reupload it to the sftp server in the same directory (overweite the existing one). I do not know how to continue. Thanks for the help.




Error To Many Redirects - ScriptResource.axd

We have a website built on SharePoint 2016. When you go to "https://www.ghcscw.com" it can find the ScriptResource.axd file and everything works fine. When you go to "https://ghcscw.com" its tries to find the ScriptResource.axd file multiple times returning a 302 and then fails. This breaks the SharePoint search functionality (I believe it's the ajax functionality).

Here are the specific errors. If anyone can help that would be greatly appreciated:

/ScriptResource.axd Failed to load resource: net::ERR_TOO_MANY_REDIRECTS /WebResource.axd Failed to load resource: net::ERR_TOO_MANY_REDIRECTS (index):230 Uncaught ReferenceError: Sys is not defined at (index):230 sp.init.js?rev=LHfxXsgcQykvazINslGeNQ%3D%3DTAG0:2 Uncaught ReferenceError: Type is not defined at sp.init.js?rev=LHfxXsgcQykvazINslGeNQ%3D%3DTAG0:2 sp.core.js?rev=mYpp5rntO3MT6rs6SRo%2BtA%3D%3DTAG0:2 Uncaught ReferenceError: Type is not defined at sp.core.js?rev=mYpp5rntO3MT6rs6SRo%2BtA%3D%3DTAG0:2 /favicon.ico Failed to load resource: net::ERR_TOO_MANY_REDIRECTS




How to publish MVC application

I need to find a newbie, beginner's step by step guide to deploying MVC application on IIS. I am using VS 2017, IIS 10 & Windows Server 2016. Application is developed and works in VS, but I cannot figure out how to deploy to IIS. There is a similar question at SO but it ends with the same question, where can I find a beginner's guide?




Need to create a webpage that compiles a code [on hold]

So I will try to be as specific as possible. I wrote a compiler with c++ that compiles pascal code. I wrote everything on Visual Studio, and only run it there. Basically, I want to make it an online compiler. I want to make a webpage that gets the input from the users(which in my case would be a pascal code), runs my code, gets the output from my program, and prints it out to the screen. How do I possibly create it? Thank you in advance.




Is there a limit to the resources allocated to child processes in windows?

I've programmed an asp.net application for displaying data from a manufacturing machine in real time in client browsers on a LAN. It relies on a separate C# web socket server application that continuously fetches data from the machine and sends it the client browser. When a client connects, the web socket application spawns a child process to serve the client. Each child process uses a separate port to communicate with its client. Each spawned process has two threads, one for listening for the disconnect message from the browser and another which executes in an infinite loop, constantly polling the manufacturing machine for data and sending it to the client as often as it can. All servers run on a windows 10 PC.

I've noticed that the rate at which data is displayed slows down with increasing numbers of clients. This effect was more pronounced with an earlier version of the web socket server that spawned threads instead of processes to serve the clients (which is why I changed it to use processes instead). When I look at the web socket server processes in Task Manager, I notice that their network utilization goes down with more clients (from 0.9 Mbps with one client to 0.7 Mbps with two), although their memory usage stays the same.

I suspect the problem is some limitation on the resources allocated to child processes spawned from the same parent. The reason I believe this is that when I start up separate web socket server instances manually (instead of having them spawned by a process) and then connect clients to them there is no slow down. I would like to know why the slowdown is occurring, and if there is a way to fix it.




get variable in ejs on submit on same page

getting data from post

app.post("/places", function(req, res) {
//Get all places from the DB
Place.find({}, function(err, places) {
    if(err) {
        console.log(err);
    } else {
        res.render("/places", {places: places});        
    }
});
});

i want something like if(variable is passed then below code will work on same page) otherwise i face errors "undefined variable places" if i render to a new page, get that variable it works fine, but i want on same page

 // ejs file
 <div class="row text-center">
     <% places.forEach(function(place) { %>
    <div class="col-md-4 col-sm-6">
        <div class="thumbnail">
            <img src="<%= place.image %>">
            <div class="caption">
                <h5><strong><%= place.name %></strong></h5>     
            </div>  
        </div>
    </div>
    <% }); %>       
</div>




How to Save scrapped data to a CSV file in python

This is My Web scrapping code that uses beautiful soup module.. i need the save the data that is getting printed as a csv files

import csv
import requests
from bs4 import BeautifulSoup
for i in range(907):      # Number of pages plus one 
url = "http://www.pga.com/golf-courses/search?page={}&searchbox=Course+Name&searchbox_zip=ZIP&distance=50&price_range=0&course_type=both&has_events=0".format(i)
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")

g_data1=soup.find_all("div",{"class":"views-field-nothing-1"})
g_data2=soup.find_all("div",{"class":"views-field-nothing"})


for item in g_data1:
     try:
                print item.contents[1].find_all("div",{"class":"views-field-counter"})[0].text
     except:
                pass  
     try:
                print item.contents[1].find_all("div",{"class":"views-field-course-type"})[0].text
     except:
                pass


for item in g_data2:
     try:
            print item.contents[1].find_all("div",{"class":"views-field-title"})[0].text
     except:
            pass
     try:
            print item.contents[1].find_all("div",{"class":"views-field-address"})[0].text
     except:
            pass
     try:
            print item.contents[1].find_all("div",{"class":"views-field-city-state-zip"})[0].text
     except:
            pass




Kotlin framework suggestions for developing a server + client application

guys. I've recently set as a development goal something to which google could not provide me with some accurate suggestions/answers. I hope that some of you guys can help here to get started somehow, as you may have already tried/experienced frameworks for kotlin. I intend to build a complete application that revolves around the idea of tasks and managing your free time/tasks. I know there are plenty of these around, but I want to build one myself to improve myself. These are the following keypoints of the application that I intend to build (I am kinda new to the web development life-cycle, I have read the basics about it and I intend to gain further knowledge by creating this app):

  • Build a back-end app that exposes web-services by REST, which I intend to deploy on a wildfly server. For this, I searched for several frameworks for web development in kotlin and the only one I could find (mature enough or the most suggested) is ktor. Questions:

    1) Can ktor be used to build the REST web-services?

    2) Are there any useful libraries/frameworks you suggest to be used in conjecture with ktor?

  • Build a front-end app that provides a UI to handle those web-services and use them.

    1)What are some popular kotlin-frameworks that are used for front-end development?

    2)Should I give up on front-end with kotlin framework and instead default to something more popular such Angular js?

A few points worth considerating:

  • After building the above, I intend to create an Android app to make use of the back-end app, sort of a 'light' version of the front-end app.
  • The back-end app must utilize Hibernate/JPA and connect to a PostgreSQL database.
  • Having no real-life experience in this web-development cycle, I ask these questions so that I may start with the most recent/popular/indicated frameworks and want to gain knowledge on best practices and don't start off on the wrong foot.
  • Kotlin must be the base language so that I may get accustomed to it. I have given it thought and decided I will go forward with it.
  • This is just an application that I will work for in my free time, nothing special, but I know it will be very time consuming.
  • If I have omitted something/forgot to mention something, please do mention it so that I may provide more details.



How to add floating text on the canvas along with mouse move events?

In the example given in

https://codepen.io/jkiss/pen/OVEeqK

html

<canvas id="nokey" width="800" height="800">
    Your Browser Don't Support Canvas, Please Download Chrome ^_^``
</canvas>

css

*{
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
html, body{
    height: 100%;
    margin: 0;
    padding: 0;
    background-color: #333;
    overflow: hidden;
}
canvas{
    background-color: #000;
}

js

var canvas = document.getElementById('nokey'),
   can_w = parseInt(canvas.getAttribute('width')),
   can_h = parseInt(canvas.getAttribute('height')),
   ctx = canvas.getContext('2d');

// console.log(typeof can_w);

var ball = {
      x: 0,
      y: 0,
      vx: 0,
      vy: 0,
      r: 0,
      alpha: 1,
      phase: 0
   },
   ball_color = {
       r: 207,
       g: 255,
       b: 4
   },
   R = 2,
   balls = [],
   alpha_f = 0.03,
   alpha_phase = 0,

// Line
   link_line_width = 0.8,
   dis_limit = 260,
   add_mouse_point = true,
   mouse_in = false,
   mouse_ball = {
      x: 0,
      y: 0,
      vx: 0,
      vy: 0,
      r: 0,
      type: 'mouse'
   };

// Random speed
function getRandomSpeed(pos){
    var  min = -1,
       max = 1;
    switch(pos){
        case 'top':
            return [randomNumFrom(min, max), randomNumFrom(0.1, max)];
            break;
        case 'right':
            return [randomNumFrom(min, -0.1), randomNumFrom(min, max)];
            break;
        case 'bottom':
            return [randomNumFrom(min, max), randomNumFrom(min, -0.1)];
            break;
        case 'left':
            return [randomNumFrom(0.1, max), randomNumFrom(min, max)];
            break;
        default:
            return;
            break;
    }
}
function randomArrayItem(arr){
    return arr[Math.floor(Math.random() * arr.length)];
}
function randomNumFrom(min, max){
    return Math.random()*(max - min) + min;
}
console.log(randomNumFrom(0, 10));
// Random Ball
function getRandomBall(){
    var pos = randomArrayItem(['top', 'right', 'bottom', 'left']);
    switch(pos){
        case 'top':
            return {
                x: randomSidePos(can_w),
                y: -R,
                vx: getRandomSpeed('top')[0],
                vy: getRandomSpeed('top')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'right':
            return {
                x: can_w + R,
                y: randomSidePos(can_h),
                vx: getRandomSpeed('right')[0],
                vy: getRandomSpeed('right')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'bottom':
            return {
                x: randomSidePos(can_w),
                y: can_h + R,
                vx: getRandomSpeed('bottom')[0],
                vy: getRandomSpeed('bottom')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'left':
            return {
                x: -R,
                y: randomSidePos(can_h),
                vx: getRandomSpeed('left')[0],
                vy: getRandomSpeed('left')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
    }
}
function randomSidePos(length){
    return Math.ceil(Math.random() * length);
}

// Draw Ball
function renderBalls(){
    Array.prototype.forEach.call(balls, function(b){
       if(!b.hasOwnProperty('type')){
           ctx.fillStyle = 'rgba('+ball_color.r+','+ball_color.g+','+ball_color.b+','+b.alpha+')';
           ctx.beginPath();
           ctx.arc(b.x, b.y, R, 0, Math.PI*2, true);
           ctx.closePath();
           ctx.fill();
       }
    });
}

// Update balls
function updateBalls(){
    var new_balls = [];
    Array.prototype.forEach.call(balls, function(b){
        b.x += b.vx;
        b.y += b.vy;

        if(b.x > -(50) && b.x < (can_w+50) && b.y > -(50) && b.y < (can_h+50)){
           new_balls.push(b);
        }

        // alpha change
        b.phase += alpha_f;
        b.alpha = Math.abs(Math.cos(b.phase));
        // console.log(b.alpha);
    });

    balls = new_balls.slice(0);
}

// loop alpha
function loopAlphaInf(){

}

// Draw lines
function renderLines(){
    var fraction, alpha;
    for (var i = 0; i < balls.length; i++) {
        for (var j = i + 1; j < balls.length; j++) {

           fraction = getDisOf(balls[i], balls[j]) / dis_limit;

           if(fraction < 1){
               alpha = (1 - fraction).toString();

               ctx.strokeStyle = 'rgba(150,150,150,'+alpha+')';
               ctx.lineWidth = link_line_width;

               ctx.beginPath();
               ctx.moveTo(balls[i].x, balls[i].y);
               ctx.lineTo(balls[j].x, balls[j].y);
               ctx.stroke();
               ctx.closePath();
           }
        }
    }
}

// calculate distance between two points
function getDisOf(b1, b2){
    var  delta_x = Math.abs(b1.x - b2.x),
       delta_y = Math.abs(b1.y - b2.y);

    return Math.sqrt(delta_x*delta_x + delta_y*delta_y);
}

// add balls if there a little balls
function addBallIfy(){
    if(balls.length < 20){
        balls.push(getRandomBall());
    }
}

// Render
function render(){
    ctx.clearRect(0, 0, can_w, can_h);

    renderBalls();

    renderLines();

    updateBalls();

    addBallIfy();

    window.requestAnimationFrame(render);
}

// Init Balls
function initBalls(num){
    for(var i = 1; i <= num; i++){
        balls.push({
            x: randomSidePos(can_w),
            y: randomSidePos(can_h),
            vx: getRandomSpeed('top')[0],
            vy: getRandomSpeed('top')[1],
            r: R,
            alpha: 1,
            phase: randomNumFrom(0, 10)
        });
    }
}
// Init Canvas
function initCanvas(){
    canvas.setAttribute('width', window.innerWidth);
    canvas.setAttribute('height', window.innerHeight);

    can_w = parseInt(canvas.getAttribute('width'));
    can_h = parseInt(canvas.getAttribute('height'));
}
window.addEventListener('resize', function(e){
    console.log('Window Resize...');
    initCanvas();
});

function goMovie(){
    initCanvas();
    initBalls(20);
    window.requestAnimationFrame(render);
}
goMovie();

// Mouse effect
canvas.addEventListener('mouseenter', function(){
    console.log('mouseenter');
    mouse_in = true;
    balls.push(mouse_ball);
});
canvas.addEventListener('mouseleave', function(){
    console.log('mouseleave');
    mouse_in = false;
    var new_balls = [];
    Array.prototype.forEach.call(balls, function(b){
        if(!b.hasOwnProperty('type')){
            new_balls.push(b);
        }
    });
    balls = new_balls.slice(0);
});
canvas.addEventListener('mousemove', function(e){
    var e = e || window.event;
    mouse_ball.x = e.pageX;
    mouse_ball.y = e.pageY;
    // console.log(mouse_ball);
});

I wanted to add my company name ("Welcome to AITeam") appear floating along with the dot and lines. I have a very less knowledge on front end development. Kindly suggest what modification to any of the scripts (css/js/html) can do the trick.




Span doesn't work

How i can change code? nodeValue is a string type and it's also write in replace word!

walk(document.body);

function walk(node)  
{

    var child, next;

    switch ( node.nodeType )  
    {
        case 1: 
        case 9:  
        case 11: 
            child = node.firstChild;
            while ( child ) 
            {
                next = child.nextSibling; 
                walk(child);
                child = next;
            }
            break;

        case 3: 
            handleText(node);
            break;
    }
}

function handleText(textNode) 
{
    var v = textNode.nodeValue;

    v = v.replace(/ddd/gi, '<span class="red">N</span>');
    v = v.replace(/fff/gi, '<span class="yellow">N</span>');
    v = v.replace(/ccc/gi, '<span class="green">N</span>');

    textNode.nodeValue = v;
}




Build website using html and css [on hold]

I'm going to build my first website as a graduation project actually I have learned html css php codeigneter and Java script.. I'm completely Scattered and I don't know how I should start in the first step... My project is about blood bank.. Please help me how I can started




Share on Facebook using dynamic meta tags not able to post to page or group

To share a page I use.

To share a page with dynamic tags, I used:

function shareOverrideOGMeta(overrideLink, overrideTitle, overrideDescription, overrideImage) {
FB.ui({
        method: 'share',
        href: window.location,
        action_properties: JSON.stringify({
            object: {
                'og:url': overrideLink,
                'og:title': overrideTitle,
                'og:description': overrideDescription,
                'og:image': overrideImage
            }
        })
    },
    function (response) {
        // Action after response
    });

}

But not able to post to specific page or group using this.

What change should be done to get that?




Downloading protected m3u8 video

Maybe this is not the right forum for this question but i'm trying to download video from this https://ucha.se/watch/1325/Zvuk link. When i use some tool it gives me always an error. I tried JDownloader, hd-video-convertor,free-ts-convertor. No one works. I found that the player is "flowplayer" and the video comes in .ts files. How to downlaod such kind a protected video?

How it looks like in dev tools image




C# Web application reloading Continously

I am Having a DropDownList with SelectedIndexchanged event and set autopostback='true'.If I don't give Update panel Page keeps on reloading.I dont want to use update panel.Page keeps reloading continously.Pls help...




Retrieving inaccessible .zip file download from archive.org site (maybe use wget)

Here is a archive.org link to the site:

https://web.archive.org/web/20130225110136/http://www.generation-game.com/Telechargement-1-2576-Sephizack-World-Version-1-0-Beta.html

I don't even know if the .zip file I want is hosted on the archive.org servers. So figuring that out would be the 1st step.

To download the .zip file, the page says I first have to "click the ad below" (the add that would presumably appear in the empty white box). Since the site is defunct and no longer has active ads, there is no ad to click on in order to activate the download of the file.

I tried searching the page source for the word zip to no avail.

I tried the command posted in this answer to no avail:

wget -r -l1 -H -t1 -nd -N -np -A.zip -erobots=off https://web.archive.org/web/20130225110136/http://www.generation-game.com/Telechargement-1-2576-Sephizack-World-Version-1-0-Beta.html

Perhaps I could recursively comb an archive of the entire web site for all .zip files somehow? Similar to what's asked in this post? I would love some assistance in doing so.




How can I send an image back to client instead of telling a client where the image is hosted at? Is it even possible?

How can I send an image back to client instead of telling a client where the image is hosted at? Is it even possible?

I just do not want to let the client know where the image is hosted at.




"No HTTP resource was found that matches the request URI" Web API routing issue

I have a Wep API service in an MVC Project and while publish on local IIS i can call services easily but when publish on server i found This Error "No HTTP resource was found that matches the request URI" while calling service is there any one can Help




How to create and access a folder structure in .Net core web API after hosting it on Docker

Currently I am using 1. Windows 7 2. Docker Toolbox 3. Visual studio 2017 4. Asp.net core 2.0 Web API

Problem:- First I have created an asp.net core 2.0 web API, which uses a physical path for reading files. It was running perfectly before hosting it to docker. Then I have enabled support for Docker, build and run the image. When i try to hit the URL it is giving me exception that "could not find the part of path"

You can see How I declared a path here. Is that right way to do this? Or do I need to make some changes to dockerfile?




backspace isn't working in number filed of html5 contact form in firefox

I am trying to fix some javascript error of contact form while user trying to enter the contact number they cant able to correct or cant able use backspace key in firefox only. In chrome it is working completely fine

here is my code

CG = (function(){
    var
    _isNumeric = function(evt){
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if(charCode >= 48 && charCode <= 57)
            return true;
        return false;
    },
    _isDecimal = function(evt){
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if((charCode >= 48 && charCode <= 57) || charCode==46)
            return true;
        return false;
    },
    _alphanumeric = function(evt){
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        return ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 32 || (charCode >= 48 && charCode <= 57));
    };
    return{
        isDecimal:_isDecimal,
        isNumeric:_isNumeric
    }
});

    $(document).ready(function(){
    $("input[type=text]").on("keypress",".isDecimal",function(e){
        return CG.isDecimal(e);
    });
    $(document).on("keypress",".isNumeric",function(e){
        return CG.isNumeric(e);
    });
    $(document).on("keypress",".alphanumeric",function(e){
        return CG.alphanumeric(e);
    });
    $(document).on("keypress",".isDecimal",function(e){
        return CG.isDecimal(e);
    });
})




mardi 27 février 2018

three.js autofit scene to window.onresize

Hey guys anyone have any experience auto-fitting an three.js scene to a window/html when it's resized?

Can't seem to find an approach that doesn't require having to competely refresh the page.

https://codepen.io/Samsy/full/emWppX/

(function() {
  var App;

  window.App = (function() {
    class App {
      constructor() {
        var fb, lin, plus, twt;
        this.init = this.init.bind(this);
        this.update = this.update.bind(this);
        this.renderScene = this.renderScene.bind(this);
        this.resize = this.resize.bind(this);
        fb = document.getElementById('facebook');
        twt = document.getElementById('twitter');
        lin = document.getElementById('linkedin');
        plus = document.getElementById('plus');
        fb.addEventListener('click', () => {
          return window.open("https://www.facebook.com/Pierre.de.miel", '_blank');
        }, false);
        twt.addEventListener('click', () => {
          return window.open("https://twitter.com/Samsyyyy", '_blank');
        }, false);
        lin.addEventListener('click', () => {
          return window.open("https://www.linkedin.com/profile/view?id=182449324&trk=nav_responsive_tab_profile", '_blank');
        }, false);
        plus.addEventListener('click', () => {
          return window.open("http://experiments.crma.ninja/repos/samuel-honigstein/", '_blank');
        }, false);
      }

      init() {
        this.scene = new THREE.Scene();
        this.camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100000);
        console.log(this.camera);
        this.camera.position.z = 7;
        this.camera.position.y = 1;
        this.renderer = new THREE.WebGLRenderer({
          width: window.innerWidth,
          height: window.innerHeight,
          scale: 1,
          antialias: false
        });
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.container = document.createElement('div');
        this.container.id = 'canvasGL';
        this.container.appendChild(this.renderer.domElement);
        this.camera.lookAt(new THREE.Vector3());
        document.getElementById('experience').appendChild(this.container);
        this.terrain = new Terrain(this.scene);
        this.scene.add(this.terrain.plane_mesh);
        return this.update();
      }

      update() {
        requestAnimationFrame(this.update);
        this.terrain.update();
        return this.renderScene();
      }

      renderScene() {
        return this.renderer.render(this.scene, this.camera);
      }

      resize(stageWidth, stageHeight) {
        this.camera.aspect = stageWidth / stageHeight;
        this.camera.updateProjectionMatrix();
        return this.renderer.setSize(stageWidth, stageHeight);
      }

    };

    App.prototype.canvasGL = null;

    App.prototype.container = null;

    App.prototype.scene = null;

    App.prototype.camera = null;

    App.prototype.renderer = null;

    App.prototype.geometry = null;

    App.prototype.material = null;

    App.prototype.mesh = null;

    App.prototype.gui = null;

    App.prototype.terrain = null;

    App.prototype.composer = null;

    App.prototype.render_pass = null;

    App.prototype.fxaa_pass = null;

    App.prototype.posteffect = false;

    App.prototype.meteo = null;

    App.prototype.skybox = null;

    return App;

  }).call(this);

  window.Terrain = (function() {
    class Terrain {
      constructor(scene) {
        this.init = this.init.bind(this);
        this.initGUI = this.initGUI.bind(this);
        this.buildPlanes = this.buildPlanes.bind(this);
        this.update = this.update.bind(this);
        this.scene = scene;
        this.init();
      }

      init() {
        this.uniforms = {
          time: {
            type: "f",
            value: 0.0
          },
          speed: {
            type: "f",
            value: this.options.speed
          },
          elevation: {
            type: "f",
            value: this.options.elevation
          },
          noise_range: {
            type: "f",
            value: this.options.noise_range
          },
          offset: {
            type: "f",
            value: this.options.elevation
          },
          perlin_passes: {
            type: "f",
            value: this.options.perlin_passes
          },
          sombrero_amplitude: {
            type: "f",
            value: this.options.sombrero_amplitude
          },
          sombrero_frequency: {
            type: "f",
            value: this.options.sombrero_frequency
          },
          line_color: {
            type: "c",
            value: new THREE.Color(this.options.wireframe_color)
          }
        };
        this.buildPlanes(this.options.segments);
        return this.initGUI();
      }

      initGUI() {
        this.gui = new dat.GUI();
        this.gui.values = {};
        this.gui.values.speed = this.gui.add(this.options, 'speed', -5, 5).step(0.01);
        this.gui.values.segments = this.gui.add(this.options, 'segments', 20, 800).step(1);
        this.gui.values.perlin_passes = this.gui.add(this.options, 'perlin_passes', 1, 3).step(1);
        this.gui.values.elevation = this.gui.add(this.options, 'elevation', -10, 10).step(0.01);
        this.gui.values.noise_range = this.gui.add(this.options, 'noise_range', -10, 10).step(0.01);
        this.gui.values.sombrero_amplitude = this.gui.add(this.options, 'sombrero_amplitude', -5, 5).step(0.1);
        this.gui.values.sombrero_frequency = this.gui.add(this.options, 'sombrero_frequency', 0, 100).step(0.1);
        this.gui.values.wireframe_color = this.gui.addColor(this.options, 'wireframe_color');
        this.gui.values.wireframe = this.gui.add(this.options, 'wireframe');
        this.gui.values.floor_visible = this.gui.add(this.options, 'floor_visible');
        this.gui.values.elevation.onChange((value) => {
          this.uniforms.elevation.value = value;
        });
        this.gui.values.wireframe.onChange((value) => {
          this.plane_material.wireframe = value;
        });
        this.gui.values.floor_visible.onChange((value) => {
          this.groundMaterial.visible = value;
        });
        this.gui.values.noise_range.onChange((value) => {
          this.uniforms.noise_range.value = value;
        });
        this.gui.values.speed.onChange((value) => {
          this.uniforms.speed.value = value;
        });
        this.gui.values.perlin_passes.onChange((value) => {
          this.uniforms.perlin_passes.value = value;
        });
        this.gui.values.sombrero_amplitude.onChange((value) => {
          this.uniforms.sombrero_amplitude.value = value;
        });
        this.gui.values.sombrero_frequency.onChange((value) => {
          this.uniforms.sombrero_frequency.value = value;
        });
        this.gui.values.wireframe_color.onChange((value) => {
          console.log('value');
          this.uniforms.line_color.value = new THREE.Color(value);
        });
        return this.gui.values.segments.onFinishChange((value) => {
          this.scene.remove(this.plane_mesh);
          this.buildPlanes(value);
          this.scene.add(this.plane_mesh);
        });
      }

      buildPlanes(segments) {
        this.plane_geometry = new THREE.PlaneBufferGeometry(20, 20, segments, segments);
        this.plane_material = new THREE.ShaderMaterial({
          vertexShader: document.getElementById('shader-vertex-terrain-perlinsombrero').textContent,
          fragmentShader: document.getElementById('shader-fragment-terrain').textContent,
          wireframe: this.options.wireframe,
          wireframeLinewidth: 1,
          transparent: true,
          uniforms: this.uniforms
        });
        this.groundMaterial = new THREE.MeshPhongMaterial({
          ambient: 0xffffff,
          color: 0xffffff,
          specular: 0x050505
        });
        this.groundMaterial.color.setHSL(0.095, 1, 0.75);
        this.materials = [this.groundMaterial, this.plane_material];
        this.plane_mesh = THREE.SceneUtils.createMultiMaterialObject(this.plane_geometry, this.materials);
        this.plane_mesh.rotation.x = -Math.PI / 2;
        return this.plane_mesh.position.y = -0.5;
      }

      update() {
        return this.plane_material.uniforms['time'].value = this.clock.getElapsedTime();
      }

    };

    Terrain.prototype.uniforms = null;

    Terrain.prototype.plane_mesh = null;

    Terrain.prototype.plane_geometry = null;

    Terrain.prototype.groundMaterial = null;

    Terrain.prototype.clock = new THREE.Clock(true);

    Terrain.prototype.options = {
      elevation: 1,
      noise_range: 2.14,
      sombrero_amplitude: 0.6,
      sombrero_frequency: 10.0,
      speed: 0.8,
      segments: 324,
      wireframe_color: '#e25cfe',
      perlin_passes: 1,
      wireframe: true,
      floor_visible: true
    };

    Terrain.prototype.scene = null;

    return Terrain;

  }).call(this);

  App = new window.App();

  App.init();

}).call(this);

^ Trying to implement this, but as if you see with above it doesn't match any resize events.




Can I use TLS 1.2 or 1.1 (if 1.2 is not available) in .net when calling a web servivce?

I would like to be able to use TLS 1.2, if a web service requires it, but also (for the time being) make calls using TLS 1.1 to services that do not support it.

Currently we are using ServicePointManager.SecurityProtocol to set this in our code. (.net 4.0) Is this already backwards compatible? Or is it an all or nothing thing? And if so, is there some way to OR things together?




Any way to pass data object from Java Cucumber TestRunner to step definition class other than using singleton?

I'm looking for an idea for how I can pass a data object (e.g. WebDriver) from the Java test runner class to a step definition class. Any suggestions?

I've seen one example where a static singleton class was employed, but I'd prefer something else.

My goal is to create the Web driver service in the test runner class, and somehow pass that to the step definition class.

Any ideas?




Why sometime the datatable does work and sometime it does work?

Please help me out, I am trying to fix this issue for 3 hours....I am new to html, so if I did anything wrong, please point out. Can anyone take look at my code, I did a web page host locally, I used datatable(jquery)to add some extra feature to my table on html. Now the problem is that sometime the datatable works, its css gets used. sometime it is not using the datatable 's css. I think it causes by the ordering of my import..

Here is my code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>QnAlist</title>
  <base href="/">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <!-- Optional theme -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">


  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">

  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>


</head>
<body>
  <app-root></app-root>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">




FLASK, Python- Unable to send data back to HTML from FLASK

I've been working on a Machine learning model for my college project lately. I've already written a keras model and saved it as hdf5 format. I've checked it running locally the saved model makes fine prediction. I want to run this model via a web application, hence I've been working on flask for the past couple of days. I've written code for flask app.py and index.html

app.py

from flask import Flask, render_template, request
from flask import request
import numpy as np
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from flask import jsonify
import os
import re
import sys

# init model directory
MODEL_DIR = './models'
result=''

#init Flask
app = Flask(__name__)

#load the compiled model.
print("Loading model")
model = load_model(os.path.join(MODEL_DIR, 'classifier_model.hdf5'))

scaler= MinMaxScaler(feature_range=(0,1))

#routing for home page
@app.route('/', methods=['GET','POST'])
def index():
if request.method == 'GET':
    return render_template('index.html')

if request.method == 'POST':
    weight=float(request.form('weight'))
    height=float(request.form('height'))
    gluc=float(request.form('glucose'))
    bp=float(request.form('bp'))
    age=float(request.form('age'))
    height=height/100
    bmi=weight/(height*height)
    predict_data=np.array([[gluc, bp, bmi, age],[103,80,19.4,22]])
    scaled_predict_data=scaler.fit_transform((predict_data))
    round_predict = 
model.predict_classes(scaled_predict_data,verbose=0)
    res=np.array_str(round_predict[0])

    return render_template('index.html', value=res)





if __name__ == '__main__':
    port= int(os.environ.get('PORT',8080))
    app.run(host='0.0.0.0', port=port,debug=True)

index.html

<html>
<head>
    <script >
      var value= 
    </script>

</head>>
<body>

  <form  method = "POST">
     <p>Weight <input type = "number" name = "weight" /></p>
     <p>Height(CM) <input type = "number" name = "height" /></p>
     <p>Glucose(mg/dL) <input type = "number" name = "glucose" /></p>
     <p>Blood Pressure <input type ="number" name = "bp" /></p>
     <p>Age <input type ="number" name = "age" /></p>
     <p><input type = "submit" value = "submit" /></p><br>
     Output: <br>
  </form>

 </body>
</html>

Now when I run the app.py code, everything runs fine and index.html is rendered but when I hit the submit button I get this error message: TypeError: 'ImmutableMultiDict' object is not callable

Any help would be highly appreciated. This is my college project and the submission date has already passed. Please Help. Thanks in advance.




: in angular2,i am very confused with this operator

Since i am new to angular 2 i am confused with this operator when to use : this operator for example: hero:Hero(what is the meaning of this statement)

onSelect(hero: Hero): void {
  this.selectedHero = hero;
}




get all set of lat long for a path between two points

how get all set of lat long for a path between two points ???

I will point put 2 points in a map and it will show the path and along with will return the overall lat long between the path in a sequence




Login to secure website with redirects Java / Jsoup

How do I go about reading and locating where I need to input login information in jsoup in order to access the web on a VPN? I'm interested in both an explanation of the steps/topics involved as well as the programming methodology with java (basically how to code this in java using jsoup). Note: with all the redirects, I have a hard time understanding what is happening and how/when/where to code in a jsoup-login.

Here's my workflow so far:

I have a target page, like the one below

[debug] status code 302 : https://centrale.landingnetwork.com/gp/stores/www.landingnetwork.com/gp/home/

When I navigate to this URL in java/jsoup, I get all kinds of redirects. Here's the trail of my redirects: (in order of which comes next)

[debug] status code 302 : https://centrale.landingnetwork.com/gp/stores/www.landingnetwork.com/gp/signin/gi-signin.html/123-1234567-1234567?ie=UTF8&landat=%2Fgp%2Fstores%2Fwww.landingnetwork.com%2Fgp%2Fhome%2F123-1234567-1234567&ort=1122334455.98765&rrt=1112223334.12121

[debug] status code 200 : https://wa.secureallnetwork.com/login?clienteId=Centrale-prod-wa&nonce=867:5309:867:5309:867:5309:867:5309:867:53099&redirect_uri=https%3A%2F%2Fcentrale.landingnetwork.com%3A443%2Fgp%2Fstores%2Fwww.landingnetwork.com%2Fgp%2Fsignin%2Fgi-landat.html%2F123-1234567-1234567%3Flandat%3D%2Fgp%2Fstores%2Fwww.landingnetwork.com%2Fgp%2Fhome%2F123-1234567-1234567&ort=1122334455.98765&rrt=1112223334.12121

[debug] status code 200 : https://wa.secureallnetwork.com/login?sif_profile=gi_profile_1&clienteId=Centrale-prod-wa&nonce=867:5309:867:5309:867:5309:867:5309:867:53099&redirect_uri=https://centrale.landingnetwork.com:443/gp/stores/www.landingnetwork.com/gp/signin/gi-landat.html/123-1234567-1234567?landat=/gp/stores/www.landingnetwork.com/gp/home/123-1234567-1234567

Now, I don't have a super big background in networking, but I can definitely follow along if explained well/thoroughly.

My issue: when I go through redirects, I don't know why my form posting code of my username / password doesn't work.

Here's my code so far, (two classes);

import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.UncheckedIOException;
import org.jsoup.nodes.Document;

public class App {
    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";
    public static final String LOGIN_FORM_URL = "https://centrale.landingnetwork.com/gp/stores/www.landingnetwork.com/gp/home/";
    public static final String USERNAME = "myusername";  
    public static final String PASSWORD = "mupassword";

    public static void main(String[] args) throws Exception {
        WebCrawler wc = new WebCrawler();

        // # Go to login page and grab cookies sent by server
        Connection.Response loginForm = wc.crawl(LOGIN_FORM_URL);

        // this is the document containing response html
        Document loginDoc = loginForm.parse();

        // save the cookies to be passed on to next request
        HashMap<String, String> cookies = new HashMap<>(loginForm.cookies());  

        // # Prepare login credentials
        String authToken = loginDoc.select("form").attr("class", "a-spacing-micro").first().attr("action");

        HashMap<String, String> formData = new HashMap<>();
        formData.put("usernameInputField", USERNAME);
        formData.put("passwordInputField", PASSWORD);

        Connection.Response homePage = wc.crawl("https://wa.secureallnetwork.com" + authToken, cookies, formData, Connection.Method.POST, true);
    }
}


import java.io.IOException;
import java.util.HashMap;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;

public class WebCrawler {
    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";

    public Connection.Response crawl(String URL) throws IOException {
        Response response = Jsoup.connect(URL).userAgent(USER_AGENT).followRedirects(false).execute();
        if (response.hasHeader("location")) {
            String redirectUrl = response.header("location");
            return crawl(redirectUrl);
        } else {
            return response;
        }
    }

    public Connection.Response crawl(String URL, HashMap<String, String> cooks, HashMap<String, String> dat, Connection.Method m, boolean follow) throws IOException {
        Response response = Jsoup.connect(URL).userAgent(USER_AGENT).cookies(cooks).data(dat).followRedirects(follow).method(m).execute();

        if (response.hasHeader("location")) {
            String redirectUrl = response.header("location");
            return crawl(redirectUrl);
        } else {
            return response;
        }
    }
}

When I print out the headers, they seem relatively straight forward, the only things that might stand out to me are, 'X-REQUEST-ID1'/'X-REQUEST-ID2' headers, set cookie session id, and a location. But I'm sure that's not where I'm having my main troubles at - I think it's more where I attempt to interact with the data over multiple web pages with jsoup.

To reiterate my question: How can I login pragmatically with java/jsoup to my website? A thorough explanation with details/examples/final code would be a glorious lesson if somebody would be willing to take the time!

Cheers




How to create offline web app with JavaScript that can read local file and parse?

I'm trying to create an app with a browser interface that allows users to input a text file and then parse it for certain phrases. I have all the logic/regex I need to do the parsing, I just don't know how to implement it into a webpage interface.

What I currently have uses node.js and only works when I run the command with node (not in the browser) and hardcode the path to the file on my local system.

const fs = require("fs");
const text = fs.readFileSync("C:\\Users\\bob\\Desktop\\test\\sample.txt", "utf-8"); 
const textByLine = text.split("\n"); 

//rest of script logic below

I've been researching things like require.js and browserify which from what I understand, allow you to use node.js on client side, but I'm not sure if this is what I need.

I sort of want to make an electron app, but I'd rather build it out as a webapp first.

Is this the best way to go about accomplishing what I'm trying to do?




Google OAuth error with Google+

I do some work with the Google OAuth Login and the Google+ API. I dont know, what I'am doing wrong, but there is a long error message displayed, when I'm running the script via PHP. First I show you the procedure. The User comes from the OAuth Login. Google send the authorization code to my Login.php script:

<?php
session_start();
include('g_client.php');
if(isset($_GET['code'])){

$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['EINGELOGGT'] = true;
$_SESSION['code'] = $_GET['code'];


header("Location: ./index.php");
}
else{
    echo "Fehler beim einloggen.";
}
?>
Then the script hand off to my index.php, where I request to the Google+ API:
include("g_client.php");
$plus = new Google_Service_Plus($client);
$_SESSION['access_token'] = $client->getAccessToken();

$me = $plus->people->get('me');
$name =  $me['displayName'];  

The g_client.php are the contain SECRETS and SCOPES:

include("../geheim.php");
require_once __DIR__.'/../vendor/autoload.php';

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setIncludeGrantedScopes(true);

$client->setScopes('https://www.googleapis.com/auth/userinfo.profile');
$client->setScopes('https://www.googleapis.com/auth/userinfo.email');
$client->setScopes('https://www.googleapis.com/auth/plus.me');  

So, it should work in my view, but then there is the error message:

<b>Fatal error</b>: Uncaught exception 'Google_Service_Exception' with message '{&quot;error&quot;: {&quot;errors&quot;: [{&quot;domain&quot;: &quot;usageLimits&quot;,&quot;reason&quot;: &quot;dailyLimitExceededUnreg&quot;,&quot;message&quot;: &quot;Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.&quot;,&quot;extendedHelp&quot;: &quot;https://code.google.com/apis/console&quot;}],&quot;code&quot;: 403,&quot;message&quot;: &quot;Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.&quot;}}' in /srv/dev-disk-by-label-MAIN1/WEB_MAIN/Projekt1/vendor/google/apiclient/src/Google/Http/REST.php:118Stack trace:#0 /srv/dev-disk-by-label-MAIN1/WEB_MAIN/Projekt1/vendor/google/apiclient/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')#1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')#2 /srv/dev-disk-by-label-MAIN1/WEB_MAIN/Projekt1/vendor/google/apiclient/src/Google/Task/Runner.php(17 in <b>/srv/dev-disk-by-label-MAIN1/WEB_MAIN/Projekt1/vendor/google/apiclient/src/Google/Http/REST.php</b> on line <b>118</b><br />

I hope you can help me! Thank you!




Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Hi Iam facing this eror in my andriod studio i also change the jdk location in file structure and i also upgrade the gradle version but cant fix the eror when i change the file structure and save ok it cant change plz help me enter image description here enter image description here




JMX Custom Monitor for Web App To Send data to APM Insight

I'm using a monitor web app called Applications Manager Insight, this App can monitor the activity and parameters of an Web app installed in a Applications Server, the only problem is that i want to monitor a considerable number of apps and for each app i need to purchase a license. As option i think is possible to develop a custom monitor to send information as Troughput, Memory Use, time elapsed to complete some task... and other parameters. I'm new in JMX, anybody has some idea if that i want to do is possible?

enter image description here




WebGL accurate timing

Is there a way to achieve accurate timing in WebGL, without having to rely on Javascript? That is, without the use of setInterval() or setTimeout() or requestAnimationFrame()? I need to perform a task periodically using WebGL and timing accuracies are very important. Unfortunately setInterval()/setTimeout() are not the most accurate methods to use to make a task run periodically. Therefore I was wondering whether or not WebGL methods exist to do this sort of thing (no Javascript)?

Thank you




How to implement a Switch Account feature in web architecture [Rails]?

I don't quite know where this question belongs or how to ask it, but I will try my best to try and explain.

Basically, a User can have multiple Unit's that they can use.

We are running into problems with the context of our application, where the Unit you are making requests to... is NOT the one that user thinks it is.

To exemplify, suppose the current_user has 2 Units.

#< Unit id: 1, name: "Happy Unit One", created: "2018-02-26 05:00:00 UTC">,

#< Unit id: 2, name: "Sad Unit Two", created: "2018-02-27 05:00:00 UTC">

When the user logs in, they will be directed to their home page /home/:unit_id for their last unit. So, for this case they will be redirected to /home/2. I decided that it will be useful to store this value in a current_unit_id variable, where we can access and reference it.

Take a look below:

Contextualising the navigation menu

current_unit_id is the foundation of our side nav. Meaning, if our curent_unit_id changes to 1... then, it Happy Unit One will be at the top. Makes sense right?

This is where things get funky

If a user clicks on a different unit through the navigation, it will update the current_unit_id and redirect them to THAT home page. BUT, imagine if their current_unit_id = 2 and they are on it's home page (/home/2) but they hardcode the URL: /home/1...

Now, they will be LOOKING at the Home Page of #< Unit id: 1, name: "Happy Unit One"> but their navigation will still have #< Unit id: 2, name: "Sad Unit Two"> because the current_unit_id did not update.

If you are suggesting, why don't we just update in on the /home/:unit_id GET request... (believe me, we tried this) the problem is that we have so many routes that are making use of /something/:unit_id and it doesn't make sense to to update current_unit_id on each of these requests.

Other examples I looked at.

I tried to look at the way Bitbucket contextualises their repo and branches.Bitbucket example

Over here, anywhere you go in the application, it will always be in the context of the random-repo repository. HOWEVER, if you change the highlight part of the URL to something like management it will understand and it will look like this after: enter image description here




What are 3 main differences and similarities between web service and web page?

As a new student, I am looking for bullet point answers regarding the main differences and similarities between Web Service & Web page.

Thanks




How can I make padding not move other elements down?

I am trying to make a row of three buttons. One of the buttons has a :hover property that makes its margin-top increase. This looks something like this:

button {
  position: relative;
  height: 45px;
  width: 150px;
  margin: 10px 8px;
  padding: 5px 5px;
  font-weight: 700;
  font-size: 15px;
  letter-spacing: 2px;
  color: #383736;
  border: 2px #383736 solid;
  border-radius: 4px;
  text-transform: uppercase;
  outline: 0;
  overflow:hidden;
  background: none;
  z-index: 1;
  cursor: pointer;
  transition: 0.15s;
}

button:hover {
  color: whitesmoke;
}

.btn:hover:before {
  right: 0;
}

.btn:before {
  content: "";
  position: absolute;
  background: #383736;
  bottom: 0;
  left: 0;
  right: 100%;
  top: 0;
  z-index: -1;
  transition: right .15s;
}

.btn2:hover:before {
  top: 0;
}

.btn2:before {
  content: "";
  position: absolute;
  background: #383736;
  bottom: 0;
  left: 0;
  top: 100%;
  right: 0;
  z-index: -1;
  transition: top .15s;
}

.continue {
  border-color: lime;
  color: lime;
}

.continue:before {
  content: "";
  background-color: lime;
}

.continue:hover {
  padding-top: 20px;
}

.continue:hover:before {
  content: "\2192";
}
<button class = "btn">
  HOVER
</button>

<button class = "btn2">
  HOVER
</button>

<button class = "btn continue">
  CONTINUE
</button>

When you hover the third button, it's padding-top changes and therefore the other two buttons move down. What can I do to make it so that this has the same effect, except the other two buttons don't move?




Get response body from Unity Web Request

How do you get the response body to a Unity Web Request?

I can get the response headers but it is not clear where to find the response body.




Web services Vs Socket io

Anyone has an idea about socket io vs web services? to advise me? I have a service application that calls every 10 sec or so on more than 100 devices to the server. Which technology should I adopt in order to have less problems and better server performance?Anyone?




Best technology for creating a log in form in page [on hold]

Obviously I want my page to have dynamic content and user registration/sign in forms.

I am a little fluent in NodeJS and PHP and I know how to create such website. My question is which technology is the safest and generally the best practice when creating such things? Node, PHP, perhaps Python or something entirely different? Any sources for common good practices regarding web development?




MVC radio button checked based on database field value

MVC app for logging time spent at clients. I have a radio with four choices: Regular, Overtime, Doubletime & Free In the create & edit form/View it is defined:

<span>Regular: </span> @Html.RadioButtonFor(model => model.EntryType, "RT", new { @ViewBag.RT })
<span> &nbsp;&nbsp; OverTime: </span> @Html.RadioButtonFor(model => model.EntryType, "OT", new { @ViewBag.OT })
<span> &nbsp;&nbsp; DoubleTime: </span> @Html.RadioButtonFor(model => model.EntryType, "DT", new { @ViewBag.DT })
<span> &nbsp;&nbsp; Free: </span> @Html.RadioButtonFor(model => model.EntryType, "0$", new { @ViewBag.ZT })

The "new ViewBag..." is not in the create part. In the Controller's Edit ActionResult I have:

ViewBag.RT = "";
ViewBag.OT = "";
ViewBag.DT = "";
ViewBag.ZT = "";
switch (timeEntryModel.EntryType)
{
            case "RT":
                ViewBag.RT = "@checked =  \"checked\"";
                break;
            case "OT":
                ViewBag.OT = "checked =  \"checked\"";
                break;
            case "DT":
                ViewBag.DT = "checked =  \"checked\"";
                break;
            case "ZT":
                ViewBag.ZT = "checked =  \"checked\"";
                break;
   }

This works, but is there a proper way to set the checked radio base on the value in the database or based on the value in a ViewBag entry?




c# web alerts unrecognized logins

I have an application in the C # language, in my web application, is it possible to identify if the login is being made from a strange machine? creating a list of machines recognized by login? I have tried methods to capture data from the browser through .js, thus generating a fingerPrint but without success, because it is not possible to identify the machine if it is in a network for example.

Here's an example where Google or Microsoft do this, I logged into my account on a computer that I had never used, so I get the notification and I can administer the machines that are recognized for my login.

Is it possible to implement this without installing plug ins on the user's machine? through only my WEB application?

1 - Alert

2 - Managment




Show json diff in my web application

I would like to show the difference between two JSON files in my web application. Similar to what notepad++ does, but I don't want the users to the edit the files.

How would I go about this ? Are there any JS libraries I could use ?

Example: enter image description here

Thanks!




How to read comport data in windows using PHP

I am trying to read serial com port in windows, Using php language but some class present like PhpSerial.php but in my case, its doesn't work. am using device it have microcontroller 8051, its send data to RS232 or USB port. I want to read data and store into mysql database.




Thymeleaf - delete with confirme modal

I want to delete the object from table. The problem is that I do not delete the object I click. I always delete the object above. what am I doing wrong?

home.html

<tr th:each="fgp : ${fingerprints}">
    <td><a th:href="@{'/home/'+${fgp.fingerprintId}+'/viewFingerprints'}"><button
                        type="button" class="btn btn-success">V</button></a> <a
                th:href="@{'/home/'+${fgp.fingerprintId}+'/editFingerprints'}"><button
                        type="button" class="btn btn-warning">E</button></a>

                <button type="button" class="btn btn-danger" data-toggle="modal"
                    data-target="#myModal"></button>

                <!-- The Modal -->
                <div class="modal fade" id="myModal">
                    <div class="modal-dialog">
                        <div class="modal-content">

                            <!-- Modal Header -->
                            <div class="modal-header">
                                <h4 class="modal-title">Are you sure?</h4>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>

                            <!-- Modal footer -->
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger"
                                    data-dismiss="modal">Close</button>
                                <a th:href="@{'/home/'+${fgp.fingerprintId}+'/deleteFingerprints'}"><button
                                        type="button" class="btn btn-success">Yes</button></a>
                            </div>
                        </div>
                    </div>
                </div>
            </td>

Controller

@GetMapping("/home/{fingerprintId}/deleteFingerprints")
public String deleteFingerprints(@PathVariable("fingerprintId") int id, Model model) {

    Fingerprints fingerprint = fingerprintRepository.findByFingerprintId(id);

    System.out.println("Fingerprint id: " + fingerprint.getFingerprintId());

    fingerprintRepository.delete(fingerprint);

    return "redirect:/home";
}




java spring microservice send realtime data/or dynamic variable to browser

I am new in Java Spring microservice architecture. I have a sensor that sends every second a value: for example a number=100, number=102, number=104, ..... during a 30 min.

I have simple code that takes data from sensor and returns a dynamic variable.

I can see it like this: log.info("Data from sensor: "+number);

And as a result we can see the output in the console:

Data from sensor: 100 Data from sensor: 102 Data from sensor: 104 .....

The question is What is a better way to show this variable using microservice architecture? What to write in Controller.class under @GETMAPPING ("/sampledata") For example, when we run a simple microservice, it will show us a static data. Browser: localhost:1234/api/sampledata . Browser will return us a final result "Hello, World!" or something like "{Client=Josh, age=20, Surname=Siemens}". But how to make the microservice, that will never stop and update the result? For example, once opened Browser: localhost:1234/api/sampledata and on display we see the dynamic results:

Data from sensor: 100 like Temperature: 36 C

in 1-2 seconds the value will change.

Data from sensor : 102 like Temperature: 36,2 C

Any ideas how is it possible to do it? Maybe not only spring, maybe javascript or something like that??




Use the site search that uses URL encryption

"Web of Science" encrypts its URL and I see, for example,

https://apps.webofknowledge.com/Search.do?product=UA&SID=F67qBATp491aEGteSXE&search_mode=GeneralSearch&prID=95259ca7-b2ab-4cc2-a40c-25af4052a989 

when I write "Linear Algebra".

I use Python 3 and I want to download all pages, given for this request, but I don't understand how to do it. Does any resources for work with sites like "Web of Science" exist?




Should I use MVC? [on hold]

I've got a web form project that will require a lot of users to input data to a sql server database, and then be presented with a set of answers from the massaged data in the database. The answers will be in the form of list views that the user will then be able to change the way the data is presented, to allow them to make informed policy decisions.

I've got 20 years of experience in designing ASP.Net web forms with C# to solve the kind of project. Would it be worth my while to teach myself MVC to complete this project, and if so, what advantages will it bring over Web forms?

I know this has been discussed at length before, and I ask your indulgence for yet another question of the same type. I have no peers to discuss this with on a face to face basis, and I would really appreciate some discussion on the subject. (Also please excuse my english, although it's my first language, I don't get to use it technically)




How do I map IIS virtual directory to a subdomain?

currently I have a website mapping as following

http://subdomain.domain.com/<virtualdir> to http://<IP Address>/<virtualdir> 

I want the virtual directory to be accessed with just the subdomain

http://subdomain.domain.com/ 

so that it points to http://<IP Address>/<virtualdir>

Im using IIS 10, windows server 2016.

What are my possible options?




When i try to get my JSON Object from the link, i am getting a error: No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]

The complete error:

Failed to load https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/joe0802?api_key=*****-********-****-****-****-************: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:58631' is therefore not allowed access.

I am using ASP.net to create a Analytics-Site...

My Webpage code:

@{
    ViewBag.Title = "Home Page";
}
<script src="~/Scripts/request.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<div class="row">
   <button onclick="getSummoner()">GET</button>

    <p id="result" />
</div>

My JS for the JSON request:

function getSummoner() {
    $.getJSON('https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/joe0802?api_key=RGAPI-80f8d1ee-cbc6-4a34-9a62-bd0429749221', function (data) {
        window.alert(data);
    }

    );

}




Content-type in a GET request header

I'm finding it hard to understand if there are any implications of asking for a content-type header for GET requests. I know that usually one should use accept header for GET, but what are the implications of using a content-type?




Using Resources file - webpage

First of all it's not a duplicate with any other questions (I already checked and tried every one of them)

Allright, so i created some Resources files for my "MultiLanguage" webpage and I'm using it in my aspx code part like <%Response.Write(Resources.Resources.dash13); % and/or <%$ Resources:Resources, dash13 %>. They both working fine for textboxes(as a Placeholder property not Text), classes ect. (For using these, i changed the text parts with these type of codes.)

But when I try to use them for Buttons I get the <%$ Resources:Resources, dash13 %> output on my page instead of getting the right text of the resource.(there is no placeholder for Buttons so i used "text" property.) What should i do?

edit: I just tried this Text="<%#Eval(Resources.Resources.dash13) %>". I don't get an error now. But on the webpage the button is empty. There is no output.




lundi 26 février 2018

Integrating an app and a website which features a user database

I am trying to create an app and website that have an integrated user database. The purpose is to create a mashup that combines several APIs from various websites to create a one stop user interface.

I am familiar with coding but I don't have the slightest clue where to start and what to use to make this work.

Any direction would be greatly appreciated, thanks!




Web service client - ways to make it

I have REST web service written using Spring Boot. Now I want to write www site which will be using this Web service. How should I write this client? I've been thinking about writing it using JavaScript to handle http requests and all stuff, but after searching for it in Google I'm confused and I don't know what to do. I've also thought about preparing data in Web service and just showing it in static HTML page. Which way is better? And why? Which technologies should I check?




How can i add a secure c++ compiler to my site? [on hold]

I want to add a c++ compiler on my site.I want to use php and i want to run cmd.executabils on server.I undertand that can be dangerous for my site.How can i implement a c++ compiler securely?




How can i host a web server using Xampp and Share it among users on my wifi network locally? Is this possible? [duplicate]

I can create & host a php server on my compute locally & use it from browser. But Is it possible to access this also from same wifi network i am using?




Find dates after today [Expess + mongoose]

I building a web application that lists events in chronological order and i only want to list future events from a specific date, however my mongoose queries keep returning and empty object. If i query all events, my code works fine, but when ever i add filters, it always returns an empty object.

my model:

const EventSchema = new Schema({
name: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
address: {
    type: String,
    required: true
},
date: {
    type: Date,
    required: true
},

start: {
    type: String,
    required: true
},
end: {
    type: String,
    required: true
},
url: {
    type: String,
    required: true
},
phone: {
    type: String,
    required: true
},
email: {
    type: String,
    required: true
},
img: {
    type: String,
    default: "noimage.jpg"
} });

my route

app.get('/events', (req, res) => {
Event.find({ date: { $gte: new Date(2018, 01, 01) } }).exec(function(err, events) {
    console.log(events)
    events.forEach(function(event) {
        const month = event.date.getMonth() + 1;
        const day = event.date.getDate();
        const year = event.date.getYear();
        event.formatDate = month + '/' + day + '/' + year;
        console.log(event.date.getMonth())
    });
    res.render('events', {
        events: events,
    })
}) });

mongodb object

{
"_id": {
    "$oid": "5a736236ee687920e2fb736f"
},
"img": "hauntedhouse.jpg",
"name": "Holloween Party",
"date": "2017-10-31",
"description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium hic molestiae cum eaque? Officia, temporibus, nobis! In labore quod, esse alias, quos, ex quae eius enim quisquam autem fugit consectetur.",
"address": "Lorenzo \u201cLore\u201d Garcia Park - 413 E. Clark Ave",
"start": "6:00 PM",
"end": "10:00 PM",
"phone": "555-555-555",
"email": "asdf@asdf.com",
"url": "http://www.test.com",
"__v": 0 }




Which Javascript technologie should I use server-side in this case?

These days I'm trying to get into the Javascript world and all of its frameworks and derivations. So far, I just tried client-side framework and I got really hooked by VueJS. Now I'm trying to learn server-side frameworks but I don't know which one is the best for my need. Let me explain why I'm so indecisive meanwhile there are a lot of documentation and similar questions asked. So I'm looking for a framework that:

  • can be coupled with VueJS
  • can be used with Typescript
  • could handle multiplayer game (developed with another framework such as http://lance.gg/)

I think that all frameworks or almost suit the first two criteria but for the last one I'm not sure about.

Also I saw NuxtJS but I'm not sure what it is for and if it could be something useful to learn. If someone could explain me what it does it would be nice.

I know that's a pretty general question and it might have been answered several times but I'd like to have personal feedback and advice. I don't mind about learning curve since I got the time to practice and learn. I'm just looking for the framework that suits the best my needs.

Thank you in advance.




How to rent your own space in a datacenter (not cloud provider)?

Is it even possible as a private person to rent a webspace? For example at interxion. How much would it cost? What do you get, do you get the hardware assigned and tell them what software you want to run on it or what? Do you know material how to read up on this? Is there open source software for virtualizing the hardware? Which datacenter are applicable for private persons?




How to login using more then one string in Asp.net..?

   string email = "value1 & value2";
    string password = "pass & pass1";
    if (TextBox1.Text == email & TextBox2.Text == password)
    {
        Session["id"] = TextBox1.Text;
        Response.Redirect("Dashboard.aspx");
        Session.RemoveAll(); 
    }
    else
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Sorry !! Email Id Or Password wrong ')", true);
    }

how to perform or operation in string email and password




Chart.js | Trouble refreshing line chart with "setInterval"

Wondering if anyone can help me out please.

I'm having trouble getting a Chart.js LineChart (with AJAX data) to refresh every "X" seconds. I've tried to put the code below in a function inside a setInterval and eventhough it does refresh, it redraws itself in a "zoomed-in" manner...

I want the chart to refresh itself every 10 seconds.

Code:

        $.ajax({
            type: "POST",
            url: '@Url.Action("ChartRT")',
            contentType: "application/json",
            dataType: "json",
            success:
            function (chartsdata_RT) {
                var aData = chartsdata_RT;
                var aLabels = aData.map(c => c.Period);
                var aDatasets1 = aData.map(c => c.FAILED);
                var aDatasets2 = aData.map(c => c.OTHER);
                var aDatasets3 = aData.map(c => c.DELIVERED);
                var aDatasets4 = aData.map(c => c.PENDING);
                var dataT = {
                    labels: aLabels,
                    datasets: [
                        {
                            label: "FAILED",
                            data: aDatasets1,
                            borderColor: '#ff0000',
                            backgroundColor: "rgba(255, 0, 0, 0.3)",
                            fill: 'true'
                        },
                        {
                            label: "OTHER",
                            data: aDatasets2,
                            borderColor: '#3366ff',
                            backgroundColor: "rgba(32, 162, 219, 0.3)",
                        },
                        {
                            label: "DELIVERED",
                            data: aDatasets3,
                            borderColor: '#009900',
                            backgroundColor: "rgba(0, 102, 0, 0.3)",
                        },
                        {
                            label: "PENDING",
                            data: aDatasets4,
                            borderColor: '#ff9900',
                            backgroundColor: "rgba(255, 153, 219, 0.3)",
                        }

                    ]
                };

                var ctx = $("#chart_last2hours").get(0).getContext("2d");
                ctx.canvas.height = "50";
                var myNewChart = new Chart(ctx, {
                    type: 'line',
                    data: dataT,
                    options: {
                        legend: {
                            display: true,
                            position: 'right',
                            fullWidth: false,
                            labels: {
                                fontColor: '#484848',
                                fontsize: 10,
                                boxWidth: 20,
                                padding: 5,
                                lineWideth: 0
                            }
                        }

                    }

                });
            }



        });




Inconsistent font spacing between specific letters

I'm using a font called Nunito. Specifically weights 600 and 700. This font is imported on my website using Google Fonts with this line of code

@import url('https://fonts.googleapis.com/css?family=Nunito:600,700');

Now, if I write letters ší on my website the spacing is weird as you can see here

my website

The code on my website is nothing but simple HTML. It may be worth mentioning that I'm using VueJS.

<h3>Největší</h3>

However, writing the same word inside Google Fonts displays spacing correctly.

same word but on Google Fonts

Frankly I have no idea why that is.

@import url('https://fonts.googleapis.com/css?family=Nunito:600,700');
<h3>Největší</h3>



What type of website is better for online marketing as well as digital marketing?

In a few word a visitor friendly website and information rich website is always better for Digital Marketing. You can follow some of these task below to get better result:

  • Make your Navigation Simple
  • Use Keywords on Different Location
  • URL Should be SEO Friendly
  • Keep your Content Unique and Update
  • Use Professional SEO Tools



Check page source of an app url

Please tell me the way to check the page source of an article from app in mobile. In chrome it is load url and check for the page source. Similarly from the app for a news article how to check for page source.




How to set bootstrap 4 navbar breakpoint in px

I have this code and i want set the bootstrap breakpoint to 1334 px. In screens with 1334 or smaller width i want force the mobile-view menu.

How I can do that ?




Putasync 400 Bad Request c# - google APi works

I want to sent a base64pdf, via http put. Unfortunatly I get the 400 bad request error.

I tried it with the google rest api and there it worked fine.

string finalURL = upURL + pdf.Id + "/signedpdf";
string json = "{ 'base64Pdf' : '" + pdf.Base64Pdf + "' }";
using (var client = new HttpClient())
{
     var response = await client.PutAsync(finalURL, new StringContent(json, Encoding.UTF8, "application/json"));
     if (response.IsSuccessStatusCode)
        return true;
}




Recommendations for web app deployment / source control

I'm involved in ongoing development of a Linux (Ubuntu) web application and using Git / bitbucket for source control. Until now deploying the web app has been manual. We would check out the code and then move the files to the appropriate directories.

We want to automate the deployment. One option is to use a source control directory structure that mirrors the deployment directory structure and check out the code directly. For example, our web pages could be in a /var/www/html directory, while our cgi bin scripts would be in the /usr/lib/cgi-bin directory. In that scenario, I assume we would cd / and checkout the code. We don't currently have that structure, and I don't want to change it unless it will be beneficial. Another option is to add a file that specifies where files are supposed to go (at the directory level) and have a script copy the files.

I'm sure there are better alternatives. Any advice is appreciated.

Thanks.




How to display data from Java program to webpage?

I want to know a way to display data from my java programm to my html file ! without using JEE ! Thanks




installing mail server on Ubuntu using docker and rainloop

i am setting up a mail server at link: https://mail.devlopersguide.com/ for that i am using dovecot to manage my imap and pop3 protocol and using rainloop as my web mail.

but after setting up i am unable to setup my mail account how can i setup my email account devcot.

i have tried all possible efforts but was unsuccessful.

guide followed from

https://notblog.org/install-mail-server




How to upload objects to my site

So I have made a website using Jquery, CSS, and HTML. Each user when they visit this site they create an object. I was wondering how I can allow the users to share this object on the website and let the visitors of the site see it.




How to make a checkbox relate to an entire div with JavaScript?

I am trying to make entire divs "checkable" in order to remove them in bulk in a JavaScript function. How can I associate an entire div to a particular checkbox, so when the checkbox is clicked, the entire div gets selected with JavaScript?




Only search for things wich are shown in frontend in Wordpress

I want to customize my Wordpress search. The problem is that I have for example news, where only the 6 newest of them are shown in my frontend. When I serach for it I see every news which has the post_status public in the database. Bit I only want to display the news I outpot un my frontend.

I possible way would be to simply change the post_status in my backend, but is there a way to automize this?




First steps in Hackathon

I have question I started learning programming and I plane get involved in hackathon someday. Have you some opinions on hackathon? Maybe someone was involved?




dimanche 25 février 2018

How to define one to many relation in java spring.?

I am trying to create an api to save locations for a user. I defined User entity and a Location entity. Defined it as a one to many relation to user entity and location entity.

But when I try to create a location for a user, I am getting this response :

url : http://localhost:8080/Locations/create

Request :

    {
"latitude" : 15645.00,
"longitude" : 154645.00,
"location" : "miraroad",
"user": {
    "id" : 6
}
}

Response :

    {
    "id": null,
    "location": "miraroad",
    "latitude": 15645,
    "user": null,
    "longitude": 154645
}

User id is not getting mapped to location created.

Code :

User :

    @Entity // This tells Hibernate to make a table out of this class
public class User {


      public User() {}

      public User(String email, String name) {
            this.email = email;
            this.name = name;
          }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name = "user_id")
    private Integer id;

    @Column(name = "name")
    private String name;

    private String email;

    private String number;


    @OneToMany(mappedBy="user")
    private List <Location> locations;

    public List<Location> getLocations() {
        return locations;
    }

    public void setLocations(List<Location> locations) {
        this.locations = locations;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

Location :

   @Entity
public class Location {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name ="loc_id")
    private Integer id;


    private String location;
    private double latitude;

    public Location() {}

    @ManyToOne(fetch = FetchType.LAZY)
    private User user;


       @Override
    public String toString() {
        return "Location [id=" + id + ", location=" + location + ", latitude=" + latitude + ", longitude=" + longitude
                + "]";
    }
    public double getLatitude() {
        return latitude;
    }
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }
    public double getLongitude() {
        return longitude;
    }
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
    private double longitude;
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public char[] getId() {
        // TODO Auto-generated method stub
        return null;
    }
}

LocationController :

@Controller    // This means that this class is a Controller
@RequestMapping(path="/Locations") // This means URL's start with /demo (after Application path)

public class LocationController {

        @Autowired // This means to get the bean called userRepository
                   // Which is auto-generated by Spring, we will use it to handle the data
        private LocationRepository locationRepository;
        private UserRepository userRepository;

         @RequestMapping("/create")
         @ResponseBody
         public Location create(@RequestBody Location location) {
           String locId = "";
           Location newLocation = new Location();
           try {
               User user = userRepository(location.getUser()); //Get the parent Object

               newLocation = new Location(); //Create a new Many object
               newLocation.setLatitude(location.getLatitude());
               newLocation.setLongitude(location.getLongitude());
               newLocation.setLocation(location.getLocation());
               newLocation.setUser(user);

               locationRepository.save(newLocation);
               locId = String.valueOf(newLocation.getId());

           }
           catch (Exception ex) {
            // return "Error creating the user: " + ex.toString();
               return newLocation;
           }
           return locationRepository.save(newLocation);
         }

        private User userRepository(User user) {
            // TODO Auto-generated method stub
            return null;
        }

        @GetMapping(path="/all")
        public @ResponseBody Iterable<Location> getAllLocations() {
            // This returns a JSON or XML with the users
            return locationRepository.findAll();
        }

}

What is hoing wrong here? I am new to web development and java. Can anyone help me out please?

Thank you..




Is there any plugin or scripts or any tool which can embed any desktop application in web page

Is there any plugin or script or tool available which can embed any desktop application into web page, like into iframe?

Which can be fully functional as we work with desktop app.

Please suggest is there any way to accomplish this?

Thanks




What is the best way to implement network in this case?

I'm planning to deploy a network mainly for downloading files, it serves internationally so CDN is required to boost user's download speed.

And here is the thing, the network should serve different files via a single url by some LOGIC,
like http://address/file
user A gets fileA from CDN_A
user B gets fileB from CDN_B

I'm thinking about write a CGI program in the center server, implement the LOGIC there, redirect the url http://address/file to http://static.Aaddress/fileA or http://static.Baddress/fileB.

It should work, right? And any better ideas?




How to code this phone app? [on hold]

Hello I'm coding a website app for phones and I'm new. The app is based in different tabs. In one of this tabs I would like to put an image with some information that I will modify probably every week and I would like to know what do you think is the best way to make this kind of app?

Thank you very much!




How to associate a domain bought in Weebly to Godaddy hosting?

I bought a domain in Weebly but my hosting is now in Godaddy, how could I configure my Weebly domain to address to Godaddy hosting?

Thanks in advance.




What is the best online station to develop ?

I need some online website, portal or station that I could use to develop some websites with a team any idea or suggestion?




Python Web Scraping td class span

New to Python and Web Scraping... I have been looking to scrape the highlighted section of code so I can retrieve the numbers 1.16, 7.50 and 14.67, but am having no joy in using a td, class, table-matches__odds pageSoup.find_all... anyone know what I'm missing here?

I'm using beautifulsoup 4.

jupyter notebook looking for all td




Why do some browsers render this unicode character using the wrong font, apparently at random?

I am developing a website which requires use of the unicode symbol "S with caron" (0x161). The website uses the free Palanquin font, which does support this character - however, some machines incorrectly render this particular character in a different font. For example:

Example of incorrect renedering

Note that in the incorrect example, the correct font is being used for other characters, even for those containing unusual diacritics. Crucially though, there is no obvious pattern about which machines are affected. Using browsershots.org, I have seen the issue occur on Chrome, Firefox, IE and Edge on both Windows and Linux - yet I have also seen the correct rendering on all of these browsers. I have also seen different outcomes on machines which are using the same version of the same browser.

I have tried pasting the character directly into the HTML as well as using the escape code &scaron;, both of which result in the same issue.

  • Does anyone have any idea what could be causing the issue?
  • Are there any suitable workarounds if it is not possible to rectify the issue?



How to load webpage content when HTTP POST triggers DOM changes?

Good afternoon,

I am writing a cross-site userscript for TamperMonkey. I am manipulating one page with jQuery and need to load information from another page using HTTP POST using GM_xmlhttpRequest. However, when accessing the requested page by browser, its DOM will be changed to its final state directly after the request. With the script's HTTP POST I only receive the HTML from before the change.

How could I get the page content from after the changes?




Is there a practice of purposefully going with very loose TDD workflow? [migrated]

Does TDD always mean to constantly add implementation inside Test-Develop loop? I saw once an efficient developer, who prototyped a part of big web app in Python. He did a few things in a day or two - wrote multiple broken/empty tests at once, as a way to describe system use cases - wrote only mocks and interfaces (abstract classes) for the code that might go into the above sketchy tests - wrote a few thin implementations inside rare the tests, in order to demo how interfaces and top-down api calls are connected

That look quick, and efficient to me. That gave a good understanding of how the design works and I believe that looked like a controllable experiment for him.

While I myself follow the TDD very standardly - add test/ add code/ add more asserts into test. I almost immediately jump into development of some function body. Is there a word/name for this efficient and broad development in TDD? Does it look more like a personal experience - or it's the part of TDD that I've somehow missed and practice it very literally instead of doing "smart code sketches"?




create output file and save it to users local machine using python

I have created a webpage which takes an audio file as input and sends it python script web.py. web.py should remove the tags of audio files and it should save the processed file to users local machine.I have done with removing tags to an audio file using pytaglib library but stuck with saving the file to local machine. I have used save method of pytaglib but it did not work.

<html>

 <body>

     <form action="web.py" method="post">

     <input type="file" name="songin" accept="audio/*">
         <input type="submit" value="EditSongInfo" name="kira">

     </form>
</body>

web.py

#!C:/Users/L/AppData/Local/Programs/Python/Python36-32/python.exe
import taglib
print("Content-Type: text/html\n")
form =cgi.FieldStorage()
song=taglib.File(form['songin'].value)
arrw=song.tags.keys()
for i in list(arrw):
      song.tags.pop(i)    
song.save()