jeudi 28 février 2019

Possible way to push files automatically into a host

I have been using 000webhost for hosting my website. The only problem is that when i create a new file in my local system , each time i should upload it into my host manually. Is there any possible why to upload or push file automatically into 000webhost ? or is it possible to sync my folder, Does that function is done with 000webhost ? Any other suggestions ?




Retrieving data from database tables that relay on parent table to generate a JSON object

I have created tables with this structure: enter image description here

and I am trying to retrieve a game data with all its information and build a JSON object from PHP. I achieved this but I am not confident with my approach.

here is my php code:

enter image description here

please share your thoughts on how to make this better or if you have tips regarding ERD / PHP code.




Engagespot API returns invalid identifier when I send a notification

I am trying to create one to one user notification system using PHP and Engagespot. The user is logged in and I called Engagespot.identifyUser() function. After that If I send notification to this identifier it says invalid identifier.

This is my API call.

POST /2/campaigns HTTP/1.1
Host: api.engagespot.co
Api-Key: XXX

{
   "campaign_name":"Test Campaign",
   "notification":{
       "title":"Hey XYZ, Message only for you.",
       "message" : "How are you",
       "icon":"http://mywebsite.com/icon.png",
       "url":"https://mywebsite.com"
   },
   "send_to":"identifiers",
    "identifiers" : ["daniel"]   
}

Any idea why this doesn't work?




Angular 6 internationalisation that changes directions

I am working on a website using Angular 6 that should be presented in English and in Arabic, the problem is that these two languages are written on the opposite sides which the Angular Translate does not provide! Any help ?




Localhost page cannot be found using node-static

I am trying to serve static files using node-static. Later I intend to run this as windows service using nssm. I have run this before but don't know why, it doesn't work now.

Below is my code:

var http = require('http');

var nStatic = require('node-static');

var fileServer = new nStatic.Server(); ---> I also tried new nStatic.Server('filepath')
//setting middleware

http.createServer(function (req, res) { 
        fileServer.serve(req, res);
}).listen(9000);

I start the server using node server.js on command prompt. This is what I see

http://localhost:9000

node -v 10.15.2 npm -v 6.4.1

Can anyone please tell me what is that I am doing wrong ?




Can I pass data from drop to dragend using DragEvent?

I have been using DragEvent.dataTransfer to pass data to drop handler but unfortunately dataTransfer doesn't let me to do the same when I am trying to pass data to dragend handler (security reasons). Is there a way to send data from drop to dragend using DragEvent?




Can I send a file to Whatsapp from a weblink?

Is it possible to create something like a "Send to my Whatsapp"-Button on a webpage?

I want to share an Audio-file which users should be able to download via Whatsapp in the most convenient way ... they shouldn't need to type their phone number in a field or something like that ... a single click button would be best!

(Sorry, if that question is trivial or was already answered here ... I am no programmer and I won't do it myself ... so I just want to know, if that's possible in general)

Many thanks in advance




How to access separate html file from WSGI python

To create a simple web server using WSGI and when i'm running this code through this "A server error occurred. Please contact the administrator" in my browser.

My Code

main.py

import os
from wsgiref.simple_server import make_server


def application(environ, start_response):
    # Mimetype
    ctype = 'text/html'

    # Directory
    dir = environ["SCRIPT_FILENAME"][:environ["SCRIPT_FILENAME"].rindex("/")]
    # Get File Contents
    file_contents = b""
    with open(dir+"/main.html", "rb") as file:
        file_contents = file.read()

    # Add Dynamic Content
    response_body = b"This is a header!".join(
        b"".join(
            file_contents.split(b"%(HEAD)")
        ).split(b"%(HEADING)")
    )

    # Heading
    status = '200 OK'
    response_headers = [
        ('Content-Type', ctype), ('Content-Length', str(len(response_body)))
    ]

    # Send Response
    start_response(status, response_headers)
    return [response_body.encode('utf-8')]


httpd = make_server('localhost', 8080, application)
# Now it is serve_forever() in instead of handle_request()
httpd.serve_forever()

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>

<h1>Hello, Python WSGI Application</h1>

</body>
</html>

Both file main.py and main.html contains into the name of "app" directory. I couldn't detect actual problem what happened here.

Thanks.




Update value of a Recyclerview with Webservice response

I have a complex problem here.

I initialize my RecyclerView with some datas but asynchronously I'm getting data from my Webservice and I want to use those data in order to have them in my RecyclerView but it's "too late" because my RecyclerView is already initialized.

Here is some code :

First of all I'm initializing my Recyclerview with some datas

JSONArray medias; <- Global variable
ServiceProvider serviceProvider = new ServiceProvider(); <- Global variable where I'm doing my request

for (int j = 0; j < 3; j += 1) {
     JSONObject newElem = new JSONObject();
     newElem.put("path", "test");
     newElem.put("state", "ongoing");
     newElem.put("name", "element " + j);
     medias.put(newElem);
     serviceProvider.addMedia(getActivity(), new CallbackInterface() {
      @Override
      public void callbackaddMedia(Boolean success, JSONObject obj) {
         if (success && obj != null)
         {
            //Here I want to use the response object like
            //Update medias item state by obj.optString("state");
         }
      }
   });
   initRecyclerView();
}

private void initRecyclerView(){
    adapter = new DocumentsAdapter(getActivity(),false, medias, this);
    LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());

    binding.recyclerAll.setLayoutManager(mLayoutManager);
    binding.recyclerAll.setItemAnimator(new DefaultItemAnimator());
    binding.recyclerAll.setAdapter(adapter);
}

And like I said , Asynchronously I'm calling a Webservice which send me this response :

{
    "success": true,
    "mediaId": "307",
    "state": "success"
}




Looking for static site generator/CMS for multiple web servers

I bought Raspberry Pi and I want to use it as a web server for a simple blog. Also, I want to try implement load balancing somehow and create somewhere a mirrored version of my blog - in case the Raspberry fail or turn off, for example. I'm wondering which site generator will be good for something like this - I need something with easy post deployment. The possibility of installing graphic CMS will be nice, too. I'm thinking about Ghost or Hugo, but I'm not sure if these two are good choice.




What are the best ways to convert this dynamic url to static url in php? [on hold]

how to change a dynamic url to static?




How to get what people search on google and post search text to my website search box

So this is the thing i want when someone type battery 12v on google, when google shows results to add search text to my website search, so when user enter my webshop he get listed products that matches users search on google. google search result




Microsoft Web Deploy is not correctly installed on this machine(v3 or higher is recommended)

i'm trying to publish an asp.NET web api in .NET 4.5 to a windows server 2016 from Visual studio 2017 for the first time.

i'm following this microsoft tutorial and managed to get to the last part(where you actually press "publish" in VS2017).

Then this pops up after entering credentials for the windows server and it makes no sense(at least i think). "microsoft web deploy is not correctly installed on this machine. V3 or higher is recommended".

errorMessage

Even though i can clearly see that web deploy is installed on my windows server 2016. enter image description here

I have also installed the recommended server configuration for web hosting providers, and web deploy 3.6 shows up in programs and features.

I've tried reinstalling, i've tried only having web deploy 3.5, i've tried with recommended server configuration and without, i've tried installing more windows features that might have anything to do with web hosting.

I don't know where to go from there, except maybe ditching web deploy and choosing another route.

Any inspiration is appreciated.




Cyberduck user group and file permission

I'm new to web development and unsure about how to deploy a Silvestripe website with correct file permissions.

Does Cyberduck keep the same file permissions as on the local computer when uploading files? (this assumes not changing preferences in Cyberduck)

How is the group handled when creating files on the remote host? On my local computer the files have group "staff" but I need them to be "www-data" on the remote host.




Empty html with 200 response while scraping

So, I’m currently working on a web scraper/crawler using pyqt4 (QNetworkAccessManager) and I’m getting some weird response.

I am receiving an empty html with no error in an incremental way. So, the first response works, then 2 blank html then a response then 4 blanks etc.

Is it possible that the website uses some defense mechanism? (I am making those requests with random interval from 10 sec to 30)

Thank you for your time




git init. Fatal: cannot stat... Not a directory

Trying to initialize a git repository and receive error -

fatal: cannot stat '.../.git/description': Not a directory.

So I do 'ls -a' and see that it created my .git folder, but it's empty. So I figure it out, and go inside it and create a directory called "description". Then I climb out of the .git folder back into my project folder, and attempt git init again. This time it gives me the same error with a different directory name (since it found 'description', i assume). So I try the same thing with that folder. Upon my next attempt, I get the same error regarding yet another missing folder. Now I don't know too much about what's supposed to be in the .git folder, but I have come to the conclusion that I am not supposed to be responsible for the creation of these subfolders within .git... Anyone know what may be wrong? Below is my .gitconfig file's contents:

[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[core]
askpass = git-gui--askpass

I found this question, but the OP here just didn't know how to view the .git folder: git init will not create git directories for me

I have not found anything else directly relating to my issue yet.




Describe the full technology stack for a senior web developer

I'm just beginning my web-development path, and want to know what should I learn to become senior web developer.

Here's my learn-to list:

  • Html: HTML5 API
  • CSS: (+flexbox +css-grid), SASS, SCSS, LESS, STYLUS
  • JavaScript: (+ES6), JQuery, Ajax, Angular.js, React.js, Vue.js, Backbone.js, D3.js
  • Grunt, Gulp
  • WordPress, Magenta, Drupal, Joomla
  • node.js
  • PHP: Laravel,YII2
  • Ruby
  • .NET
  • Git, GitHub, CVS
  • DB: SQL, MySql, NOsql (memcached, redis), MongoDB
  • WebPack, Docker
  • UI/UX
  • Photoshop, Illustrator
  • Command line

Please correct my mistakes and add your knowledge.

p.s. Maybe I'm wrong somewhere, but don't judge strictly, I'm just a junior :)




Site design framework [on hold]

I want to display the name of the CSS pages in this way, what can I do?

enter image description here




Change Javascript frameworks on demand

I am new to web development. I am a C++ developer. I worked on a project where we were using different graphics libraries. Based on the systems environment variable we decide which library to use. I want this kind of design where we can change Javascript framework based on some settings. As technology is changing very fast Can we design such a way that we can change frameworks used in our web application will easily changeable? Is there any tool which can handle this or a design/architecture we can follow to achieve this.




postMessage Crossdomain Problems in iFrame https:// and https://www

I implemented a Cross-Domain IFrame. On my Main Page i'm using this function:

window.addEventListener("message", receiveMessage, false);

    function receiveMessage(event)
    {
      var origin = event.origin || event.originalEvent.origin; 

      if (origin !== "https://www.domain.xy" && origin !== "https://domain.xy")
        return;

      $('#gbook').height(event.data + 30);
    }

On the Page that should be used inside the IFrame I implemented the following Code:

var height= getAbsoluteHeight('body');
parent.postMessage(
       height, 
       "https://www.domain.xy"
);

Now when I'm opening my Page with the URL "https://www.domain.xy" everything works fine. But as soon as I try to open it by "https://domain.xy" (without the "www.") the Browser throws an exception:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.domain.xy') does not match the recipient window's origin ('https://domain.xy').

I already made it work with a workaround by posting two Messages (one Message to "https://domain.xy" and one Message to "https://www.domain.xy"). The result of this is the same Error but at least it works.

Is there a proper solution for this?




Screenshot is incorrect (web page)

I make a small website with a constructor, a button on it, clicking on it to take a screenshot of the page and elements to send to the mail appear. When working with the site in the browser on the computer, the screenshots are made normally and everything works. When working with a site from a mobile device, misunderstandings begin. Some of the screenshots are done entirely, the other part is done half or third. Part of the screenshots is generally done.

<head>
.....
  <style type="text/css">
    input, button {
      font-family: Arial; 
      font-size: 16px;
    }
    .page {
      padding: 20px;
    }
    form {
      margin: 10px; 
      padding: 10px;
    }
    input, button {
      border-radius: 20px;
    }
    input {
      background: #fff; 
      border: solid #ddd 1px; 
      padding: 7px 15px;
    }
    input:hover {
      border-color: #ccc;
    }
    input:focus {
      border-color: #bbb;
    }
    button {
      background: #f44; 
      border: none;
      color: #fff; 
      cursor: pointer; 
      padding: 8px 16px;
    }
    button:hover {
      background: #44f;
    }
    .hide {
      display: none;
    }
    canvas {
      display: none;
    }
  </style>
</head>
<body>
.....
        <form class="order hide">
          <input type="text" name="name" placeholder="Name">
          <input type="text" name="phone" placeholder="Telephone">
          <input type="text" name="email" placeholder="Email">
          <button type="submit">Send</button>
        </form>

        <div class="page">
          <button class="open-order">Send</button>
        </div>
      </td>
    </tr>
  </table>

<script type="text/javascript" src="html2canvas.min.js"></script>
  <script type="text/javascript">
    let path = window.location.protocol + '//' + window.location.host + window.location.pathname + 'save.php';

    function Order (elem) {
      let screen = null;
      function open () {
        elem.classList.remove('hide');
      }

      function screenshot (canvas) {
        document.body.appendChild(canvas);
        screen = canvas.toDataURL('image/png').replace(/data:image\/png;base64,/, '');
      }

      function send (e) {
        e.preventDefault();
        var data = new FormData(elem);
        data.append('image', screen);
        let xhr = new XMLHttpRequest;
        xhr.onreadystatechange = function (){
          if (this.readyState == 4) {
            if (this.status == 200) {
              console.log('Success. Image ' + this.responseText + ' saved');
            } else {
              console.log('Fail. Error: ' + this.responseText);
            }
          }
        };
        xhr.open('POST', path, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(data);
      }

      html2canvas(document.body)
      .then(screenshot)
      .then(open);
      elem.onsubmit = send;
    }

    document.querySelector('.open-order').onclick = function () {
      let order = new Order(document.querySelector('.order'));
    };
  </script>
</body>

Maybe I forgot something and someone will notice




Opencast customization

i'm using Opencast to develop a video web portal.

I'm new to using Opencast and finally after one day i installed it on my machine and it runs correctly.

I installed it on Ubuntu 18.10 by following the "Installation from source" guide on the official OpenCast website.

Now i'd like to know how this application could be customized.

I need to change the logo and colors on the home page for users. I cannot see any html or css files to edit.

Thanks you in advance




How to read build.prop values using Angular?

I found a library called PlatformJS which returns on Samsung Galaxy S series device with their codename. But there are lot of devices which aren't in the list. I am using Redmi Note 4 right now. So question is how to detect its name(Redmi Note 4) and codename (mido).




Count number of values inside an array mongo PHP

I need to get the total number of array elements that are present inside the products array . So far i have tried using the $size=>$products approach but since technically there are two arrays only the value i get is 2 but i want to count the inner elements as well so that the desired result comes out to be 3.

I know i need to use $unwind but i cant figure out the approach.

{  
   _id:2,
   card_pay:3998,
   count:4598,
   orders:2,
   products:[  
      [  
         {  
            product_id:{  
               $oid:"5c63d418ae1db123d8048276"
            },
            amount:2499,
            quantity:1,
            status:1
         },
         {  
            product_id:{  
               $oid:"5c46f7f329067970211471a0"
            },
            amount:200,
            quantity:2,
            status:1
         }
      ],
      [  
         {  
            product_id:{  
               $oid:"5c63d3afae1db123d8048273"
            },
            amount:1499,
            quantity:1,
            status:1
         }
      ]
   ]
}




which is the best framework for Single Page Website?

I'm familiar with HTML, CSS and JavaScript, wish to build a single page application (website). But I'm delimma in choosing a framework for learning to Kickstart my project. Which Framework is best AngularJS, VUE JS, ReactJS or any other. Please help to choose a better option.




A critical error has occurred due to the outdated version of the browser. Update your browser as soon as possible

When ever i open my WordPress site Prestige Bloom i am redirected to some other site by google chrome here is the Screenshot of error enter image description here

Please open my site and give me the solution to it i will be very thank full to you.




How to fix Laravel public files url redirect to double WWW?

When i try to access the resource on the browser like below

Before

It automaticly Became like this and causing error

After


It is working fine without www. but i need to load the web with www. Any advice?

Here is my .htaccess

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]




mercredi 27 février 2019

How to upload file from local machine to the browser using python?

I am using python to upload a file from my local disk to the web browser for an automation work. The folder name is "docs" which is in C directory. Docs folder contains 2 files "textnex.txt" and "safe.txt" so i want "textnext.txt" to upload on a web page. Here is my python code as below:

    # os for file management
import os
# Build tuple of (class, file) to turn in
submission_dir = r'C:\Users\Sonu\docs'
dir_list = list(os.listdir(submission_dir))
for directory in dir_list:
    file_list = list(os.listdir(os.path.join(submission_dir, 
directory)))
    if len(file_list) != 0:
        file_tup = (directory, file_list[0])

print(file_tup)

When i run this code it is not printing the files. I want textnex.txt to be uploaded on the web page. Have a look at the screenshot for the current result which is very weird to me. Can anyone help me here? Thanks in advance. Its showing .anaconda and navigator. I am confused




What are sources available to get features of web application development technologies

I’m building an app which collects features of different web application technologies. What sources I can use to get features of different technology solutions like elastic search, Java, angular, Apache.

example

java ==> robust, secure, multithreaded elastic-search => Scalable Map/Reduce model, REST based

I'm trying to automate the process of indexing features of technology solutions in to a database so It would be better if the source is a website or forum.




Remove cookie method doesn't work when I have a % symbol in cookie value

We have a cookie called gstid which holds a value "hh%d@gmail.com"

$.removeCookie('gstid', { path: '/' });

Interestingly remove cookie returns false when there a is % symbol in my cookie value. But for all other cookie values it returns a true. Any thoughts on why it goes wrong with a % ?. How do I handle this scenario for a %.

You could set a cookie using any plugin and place this snippet on a chrome console.

Thanks in advance.




Trying to display X-Code App on portfolio website; How would I do this

I built a few apps recently on x-code and am interested in displaying them on my portfolio site. I've scoured the web for a way to do this, but came up short. I'm looking to display them with interactivity similar to a live demo, but can't figure it out besides a simple screen recording. I'm using adobe portfolio, but could host the app demo anywhere. Let me know. Thank you in advance




Redis: How to count number of incorrect attempts ( when password is incorrectly entered)

When entering the wrong password, it should count no of times it is entered wrongly and then it should restrict more than "n" attempts where n is a pre-defined number, using redis.




Object null POST method Web API

I need your help with an extremely troublesome problem with the web API

When I use Postman to test the POST method of my API and I switch to debug mode, the object received by the method is always null

enter image description here

Here is the code of my DTO :

public class CharacterDTO
{
        public int Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

And finally the JSON I'm sending with Postman:

{
    "FirstName" : "John",
    "LastName" : "Snow"
}

If you ever need it, here is the request that Postman makes:

POST /api/characters HTTP/1.1
Host: localhost:49463
Content-Type: application/json
cache-control: no-cache
Postman-Token: 1e303be2-f318-4104-b189-5142fa6ddad6
{
    "FirstName" : "John",
    "LastName" : "Snow"
}
------WebKitFormBoundary7MA4YWxkTrZu0gW--

And the full screenshot of my Postman request :

enter image description here

I hope you have a solution for me because it's just unbearable I can't do anything.




Bash script to press button on webpage?

I have a webpage with many rows in a table, each with a print button at the end of the row (see below). I want to create a bash script that will be able to "press" these buttons and cause the PDF to download. Every button links to a different PDF, so I can't use curl to just call that URL. Ideas?

The button on the website looks like so:

<a class="button_std" href="#" onclick="window.open('/store/V1/V1637299/ecg/V1637299_20100104072532.pdf','print','resizable=yes,menubar=no,scrollbars=yes')"><span id="7996">Print</span></a>

enter image description here




IIS/DMZ - Site Slow

We have a DMZ setup that our web requests come in on. This website has pages that take around 15-20 seconds to load and when website traffic rises the site comes to a crawl.

From my reading so far it looks like the problem is all the requests coming to the website from the DMZ use the same ip address and since IIS process's each request from the same ip sequentially the site slows down. Does this sound accurate?

What would be a solution?




How to show an alert when 3 different button are clicked?

How can I show an alert when the user has clicked in 2 or 3 different buttons? For example when onclick() changes the src of an image. When 3 images are active => show alert




Modele Binding error when POST method called Web API

I come to post here after reading a lot of topics about the same mistake I have now.

I have a WEB API that works in GET but not in POST. When I send him JSON with POSTMAN, I get an error message in the ModelState which is ModelError ModelBinding

This is my model class:

public class Employee
{
        [DataMember]
        public int ID { get; set; }
        [DataMember(IsRequired = true)]
        public string FirstName { get; set; }
        [DataMember(IsRequired = true)]
        public string LastName { get; set; }
}

Here is the Post method of the controller of my API :

public IHttpActionResult Post([FromBody]Employee emp)
{
            if (!ModelState.IsValid)
                return BadRequest("Invalid data");

            ...
            return Ok();
}

In this controller, I pass in my if and it returns "invalid data" to me

I tried everything, I removed the[DataContract] in my model, but nothing works.

Here is an example of the JSON I am sending:

{
    "FirstName" : "John",
    "LastName" : "Malon"
}

Thank you in advance for your help!




Are there really any free website templates to use? [on hold]

So I have been looking around and as a back-end developer who doesn't want to spend too much time making sites from scratch I looked for some templates to just give me that head start so I could make the front-end part faster than I would usually spend creating from scratch.

It seems all website templates have copyrights and cannot be recreated with purchasing, normally I wouldn't have an issue paying but aren't there some free ones that can get the job done without having to worry about copyrights? Or should I just spend a day or so creating websites from scratch instead.




How can detect tab key in onclick method in html?

I have a select in HTML:

<select name="departamento" id="departamento" onclick="console.log('1')">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

When a user presses the Tab key when the cursor is on an option the output in the console is 1.

I don't want that. I want to prevent the execution of onclick when user presses the Tab key. The solution can be in jQuery or Javascript.




Webhosting with Apache

As a school project for the second semester we have to program a website and then upload it to a web server that the teacher then can see it. The programming isn't any big problem any more, but I don't know very much about web servers. After some research I found out that the web server Apache is free, but there are still some things not completely clear for me. Does this mean that I don't have to pay any money to host a website with Apache? I heard that there are web servers which have to be rent for a specific amount of time. Why wouldn't everyone just use Apache or other free web servers instead? Thanks in advance for answering my questions.




Formatting a menu bar to fit the same length as the logo bar

so im making a nav bar and i would like it to fit under my logo with the same width however the nav bar seems to be shorter in width compared to the logo there making it look funny

here is the css for the logo bar:

.logo{
overflow: hidden;
text-align: left;
position: relative;
margin : 0px 100px ;
height : 60px ;
background-color: white;
color:#1F6C8B;
font-family: Arial;

}

and here is nav bar css

.topnav {
overflow: hidden;
text-align: center;
position: relative;
margin : 0px 100px ;
height : 50px ;
font-family: Arial;

}

.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 10px 20px;
text-decoration: none;
font-size: 20px;
background-color: #1F6C8B;
height : 25px ;

}




Runs on localhost:4000 but not on ec2-ip:4000

I have a nodejs app running on port 4000. I have developed it in my Vagrant box running Ubuntu 16.04 where I am able to curl both http://localhost:4000 and http://vagrant-IP:4000.

However, when I replicate the same set-up on an EC2 instance, I am able to curl only on http://localhost:4000 and not on http://ec2-public-IP:4000.

In both cases server is listening on 0.0.0.0 and CORS is enabled. (Here, vagrant-IP and ec2-public-IP are actual IPv4 addresses). How can I fix this?




Server showing data instead of gui

while searching for a chess web project in c# i found this one: https://github.com/sshipsey/WebChess. It seemed like just what i needed, but when i ran the server and tried connecting using localhost:8080 it showed me the chess pieces data instead of the chess GUI. No idea if i am not connecting correctly or if there's a problem with the code. Can anyone help? .Data shown when connecting




How to get it using javascript regular expressions?

When there is such a sentence

var str = "blah blah blahblahblahblahblahblah blahblah test(abc; zxc; 100; 305.0)"

I want to get the value '305.0' when there is a 'test' word. How to get it using javascript regular expressions?




If condition if the field $exists inside $group in mongo

I have a mongo collection in which i need to group the data by payment_id,further i need to get the total_payable amount. The total_payable amount is made of total_payable+extra_book_price. Normal Addition is working but i want to target a scenario in which the extra_book_price that is inside a detail array is empty. So far i have tried $exists and ifNull but they don't work .

Any help is appreciated.

Also if extra_book_price does not exist i need to return the total_payable only.

[
  '$match'=>[
                          'bookfair_id'=>110
                        ]
],
[
  '$group'=> [
                       '_id'=>'$payment_id',
                           'card_pay'=> ['$sum'=> '$total_payable' ],
                           'count'=>[
                                         '$sum'=>[
                                                        '$cond'=> [ 
                                                            'if'=> ['$ifNull'=>['$extra_books_detail',true]], 
                                                            'then'=>['$total_payable'],
                                                            'else'=>['$add'=> ['$total_payable','$extra_books_detail.total_payable'] ]
                                               ]
                                             ]
                                ] 
                                    ]
                                ],



ASP.NET conditional yes/no messagebox

I have an asp:Button that fires a code behind function on the OnClick event. In that OnClick event several things happen, and among those things I do a check in the database for if I need to ask the user a yes or no question. For that I need a message box. First I did it like this:

protected void MyButton_Onclick(object sender, EventArgs e)
{
    // lots of stuff happening
    bool iNeedToAskTheUser = INeedToAskTheUser(stuff);
    if (iNeedToAskTheUser) 
    {
        DialogResult result = MessageBox.Show("Do you want to fix all objects?", "Fix objects", MessageBoxButtons.YesNo);
        if (result == DialogResult.Yes) // do stuff
    }
    // some other stuff
}

This works fine locally but not when deployed, so I figure I would need to use ScriptManager.RegisterStartupScript instead. I could just add javascript on the ASPX page that fires up a dialog and saves the response in a hidden control that I can then look at, but I don't want to fire up the dialog unless I have to, which I check for before I do the DialogResult in the code above. So I can't do that immediately when the user clicks the button.

Is there any way I can use ScriptManager.RegisterStartupScript in "the middle" of my _OnClick code so that I can choose whether or not to actually show the button, and then also know if the user clicked yes or no, (preferably) without doing a postback?




How do service like Squarespace or Spotify automatically setting up for thousands of sites?

Do they create a cluster multiple web server containers, or create a containers for each website ? And how do they automatically update the proxy server configuration ?




Change page after login

i'm trying to develop an interface for a db but I am not very practical in php. What I would like to do is showing the homepage after loggin in. However, the redirection does not work.

Desired behavior: 1) index.php -> login form / login credential

2) the credential login is sent to authenticate.php and if everything is correct, the homepage is viewed

Current behavior: Once the credentials are sent, authenticate.php does not change the page in homepage.php but remains a blank page.

authenticate.php

<?php require_once ('connect.php');
ob_start();
session_start();

// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');
}

if ($stmt = $connect->prepare('SELECT username, password FROM user WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    $stmt->store_result();

    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($username, $password);
        $stmt->fetch();
        $hash = hash('sha256', $_POST['password']);

        // Account exists, now we verify the password.
        if (hash_equals($password, $hash)) {
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['username'] = $_POST['username'];

            header('Location: homepage.php');
            $output = ob_get_clean();
        } else {
            echo 'Incorrect username and/or password!';
        }

    } else {
        echo 'Incorrect username and/or password!';
    }
    $stmt->close();

} else {
    echo 'Could not prepare statement!';
}
?>

connect.php

<?php
$config = parse_ini_file('pathToFile...\credential.ini');
$connect = @mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
unset($config);
?>




mardi 26 février 2019

Database server for log in and log out timekeeping hosting?

I am fairly new to hosting and server handling. I have been working for companies as a developer and every time I finish developing, my seniors take care of all the deployment to their servers (I am off limit to the servers).

Now, my situation changes when I got a job on a small company and they task me to develop a time keeping for them to be used because they use manually. They have two separate offices and needed the same database to store the employee time-in and time-outs. My question is what kind of hosting server should I use for in this scenario that is also ideal(Cloud or traditional web hosting or any suggestions)?

The database I am using for development is MySQL 5.7 and I used Laravel 5 as the web application to parse all the employee's time logs.

Thank you for answering me.




Redirect https from root directory to sub directory

I want to redirect from https://www.example.net to https://www.example.net/dd but I cannot find any solution to do this.




What is the best NoSql db for stored encrypted personal information?

I develop web app, which working with personal information. I plan to stored that inside NoSql database on separate server. What can you recommended me?




MVC Website intermittent behavior of not reaching sometimes

I have a ASP.Net MVC Website Hosted on IIS on couple of servers with load balancers, it a very simple page when it opens it logs user details in DB and show the view.

Issue is: It becomes unreachable sometime and pages are never opened. I have to restart APP Pool to get back on track and then it happens again.

What I have tried:

  1. Made sure all DB connection are properly handled, any connection that gets opened are surely closed
  2. Have put Recycle of APP Pool based on volume of RAM
  3. Went through IIS logs and checked that request have reached there or not
  4. There are other application also running on Server but the problem is isolated to this website
  5. There are global users, issue persist of different global area

What I think it can be:

  1. Might be possible that Load Balancer is never diverting my request
  2. My request getting lost in between networks and layer

This is Production environment and we are not facing this issue in ACC or Dev.

What else I can go ahead and check?




Error: unable to reflect System.web.configuration.machinekeySection with local iis

I am running an asp.net 3.5 web application with visual studio 2017. Everything working fine when i am running using IIS express but with classic pipeline. But I changed the settings (project properties-->Web-->Servers --> local iis; Created virtual directory as well) to run using local iis it is giving me the error "unable to reflect System.web.configuration.machinekeySection" . I am using IIS 7.5 and windows 7

I tried creating the machine key(both validation and decryption key) in iis but still issue persists.

Do anyone have any idea?? Please help here :)

Attaching the error description image here

enter image description here




PHP user register page will not add values to MySQL table

I have a login and register page on my website along with a mysql table called 'user' which stores the username, password, and email. Here is the php included in my register page:

<?php
        if(isset($_POST['submit_btn']))
        {

            $username = $_POST['username'];
            $password = $_POST['password'];
            $cpassword = $_POST['password'];
            $email = $_POST['email'];

            if($password==$cpassword)
            {
                $query= "select * from user WHERE username='$username'";
                $query_run= mysqli_query($con,$query) or die(mysql_error());

                if(mysqli_num_rows($query_run)>0)
                {
                        // there is already a user with the same username
                        echo '<script type="text/javascript"> alert("User already exists, please try a different username") </script>';
                }
                else
                {
                    $query= "insert into user values('$username','$password','$email')";
                    $query_run = mysqli_query($con,$query) or die(mysql_error());

                    if($query_run)
                    {
                            echo '<script type=text/javascript"> alert("User Registered, return to login page to login") </script>';
                    }
                    else
                    {
                        echo '<script type="text/javascript"> alert("Error!") </script>';
                    }
                }

            }
            else{
            echo '<script type="text/javascript"> alert("Passwords do not match") </script>';   
            }
        }
    ?>

Pressing the sign up button will redirect me to the login page but doesn't add the fields to the database. As you can see, I've inserted (mysql_error()); at any point things could go wrong, yet a never receive an error code. Strangely enough, if a manually add a user to my database and then try to create a new user through the register page using the same credentials, I will trigger the error saying that user has already been registered. This obviously means I have some kind of connectivity with the DB, I'm just not able to add to it. I have already checked the MySQL user privileges and the user should be allowed to write to the database. I'm assuming I have a problem with my php, but I suppose it could potentially be a MySQL issue as well. If anyone could assist me I would greatly appreciate it.

Edit: Here's my statement linking the page to my config.php file:

<?php
    session_start();
    require_once('dbconfig/config.php');
?>




Which script am I missing when trying to install framework7 custom build?

npm ERR! missing script: build-core:prod

I'm receiving the above error when trying to run the custom build for framework7 - https://framework7.io/docs/custom-build.html

I have gone through each step however I am running into this problem in cmder and I'm unsure why.

The error occurs at step 7 if this info is of any value

Any help would be appreicated.




Why is there a line through the social sharing boxes?

I'm currently hosting a website called "Ultradapt" - can be found at www.ultradapt.com. And I am in the process of setting up some social sharing buttons to generate more traffic.

However, I've stumbled onto a problem regarding the social sharing buttons. If you take a look at the website above, there is a white line through the buttons. Why is this line showing, and how do I disable it?

Thank you so much for your help in advance. I'm truly thankful!




how to send http request in golang to my own server

I'm writing a simple webserver in golang that gets/creates/edits/deletes a simple text file. I've written the function handlers and I'd like to test them by sending a request to the appropriate url and checking to see what happens. My code is as below:

func createHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name := vars["name"]
    body, _ := ioutil.ReadAll(r.Body)
    fmt.Fprint(w, name)
    ioutil.WriteFile(name, []byte(body), 0644)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/textFiles/{name}", createHandler).Methods("POST")
    log.Fatal(http.ListenAndServe(":8080", r))

    var url = "http://localhost:8080/textFiles/testFile.txt"
    var text = []byte(`{"title":"this is an example."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(text))
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    client.Do(req)
}

Once this code is run, however, no new file is created. I've been googling but I can't find anything on this type of problem, where I'm sending a request to the server that I'm building within the same file. Help appreciated.




design a back-end website,i don't know which language i choose?

i have a project to design a website like this www.digistyle.com and i'm in a back-end team. i don't know how should i start and what language is the best for back-end? i asked many people some one said

php

and others said

django

i don't know anything about this languages and i should start learning from beginning. the only language i code is c#. so now i want your help to give me your experiences about back-end.




Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\xampp\htdocs\MyLogin\includes\login.inc.php on line 17 [duplicate]

This question already has an answer here:

i have created a login form and on that form i have signed up as a user and when i try logging in i get - Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\xampp\htdocs\MyLogin\includes\login.inc.php on line 17, i have tried removing and adding ; or } but this doesn't seem to be fixing the problem. I have entered the code below for the login file.

<?php

session_start();

if (isset($_POST['submit'])) {

  include 'dbh.inc.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

// Error handlers
// Check if the inputs are empty
if (empty($uid) || empty($pwd)); {
  header("Location: ../index.php?login=empty");
  exit();
}else {
  $sql = "SELECT * FROM users WHERE user_uid = '$uid'";
  $result = mysqli_query($conn, $sql);
  $resultCheck = mysqli_num_rows($result);
  if ($resultCheck < 1) {
    header("Location: ../index.php?login=error");
    exit();
  } else {
    if ($row = mysqli_fetch_assoc($result)) {
      // Dehashing the password for the user
      $hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
      if ($hashedPwdCheck == false){
        header("Location: ../index.php?login=error");
        exit();
      }elseif ($hashedPwdCheck == true) {
        //Log in the user into the website here
        $_SESSION['u_id'] =$row['user_id'];
        $_SESSION['u_firstname'] =$row['user_firstname'];
        $_SESSION['u_lastname'] =$row['user_lastname'];
        $_SESSION['user_email'] =$row['user_email'];
        $_SESSION['u_uid'] =$row['user_uid'];
        header("Location: ../index.php?login=success");
        exit();
      }
    }
  }
} else {
  header("Location: ../index.php?login=error");
  exit();

}




How to use background-images with scss + Parcel.js

I'm trying to use parcel.js and scss to usea background-image but getting a Uncaught SyntaxError: Unexpected token < 7d6454d814b6ce2e1592d3937c337ef3.js:1 Error

Or at times getting: Cannot read property 'js' of null

Here is my scss:

.hero{
  background-image: url('../../images/2ndpaper.jpg');
}

Here is my js:

import "../styles/index.scss";
import paperbg from "../images/2ndpaper.jpg";

Here is my package.json:

 {
  "name": "development",
  "version": "1.0.0",
  "description": "CB PC - Web Development",
  "main": "index.js",
  "scripts": {
    "dev": "parcel src/index.html",
    "build": "parcel build src/index.html --out-dir prod"
  },
  "keywords": [
    "client",
    "website"
  ],
  "author": "Designs by Harp",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-proposal-class-properties": "^7.3.0",
    "parcel-bundler": "^1.11.0"
  },
  "dependencies": {
    "bootstrap-4-grid": "^2.4.1",
    "gsap": "^2.0.2",
    "jshint": "^2.10.1",
    "sass": "^1.17.2"
  }
}

What could be wrong? Thank you.




How to get to a specific part of my website which is 1 page?

I am wondering how to get to a specific part on my website such as the about section, or the portfolio / contact part.

I've tried the # method but doesn't seem to work.

Any suggestions / pointers?

Many thanks

Website: https://swpropertyadvancements.com




How to send video to the iis web directory

I already have built the IIS Web. But, I have no clues about how to send mp4 video format from another computer via IP address to the server root directory. Then, I think the FFmpeg software will useful to me. But, I have a lot of troubles on those instructions. Have any solution? Please give some suggestions, I will very thank you.




Like4Like Website coding but what should i know?

Wanted to make an website where you can like others posts, get points, and spend them to get yourself likes. What coding language would be the best and what are the things i need for that? Im a good Solo-worker just need these things to know ^^




Is there any free API that can give me live or per minute currency values

Is there any free API that can give me live or per minute currency values, I've used currency layer but it doesn't provide per minute currency rates, Also the Base currency cannot be changed in the free plan.




Virtual hosts not working on MAMP5 & Mac OS

I went through many threads and tutorials and can't find an answer to my problem. I use Mac OS Mojave and MAMP 5.2. It seems like everything is configured correctly but my virtual hosts are not working.

httpd.conf

# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

https-vhostsconf

NameVirtualHost *:8888

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:8888>
    ServerName dev.local.com
    DocumentRoot /Applications/MAMP/htdocs
    ServerAlias dev.local.com
</VirtualHost>

<VirtualHost *:8888>
    DocumentRoot /Applications/MAMP/htdocs
    ServerName localhost
</VirtualHost>

<VirtualHost *:8888>
    DocumentRoot   "/path/www/public/"
    ServerName     example.dev
    ServerAlias    www.example.dev 

    <Directory "/path/www/public/">
        Options       All
        AllowOverride All
        Require       all granted
    </Directory>
</VirtualHost>

<VirtualHost *:8888>
    DocumentRoot   "/path2/public/"
    ServerName     example2.dev
    ServerAlias    www.example2.dev 

    <Directory "/path2/public/">
        Options       All
        AllowOverride All
        Require       all granted
    </Directory>
</VirtualHost>

And finally /etc/hosts

127.0.0.1       localhost
127.0.0.1       example.dev
127.0.0.1       example2.dev

MAMP is configured to use port 8888 for Apache and 8889 for MySQL. The error I get when accessing example.dev:8888 or the other address is a 404 not found. What am I missing?




What is the best web hosting provider for linux

what is the best web hosting service for hosting website has more than 11000 files counted and high database connections per second




Code with Python: Should i choose a framework or go with core python to develop web? Which is the native DB for Python web?

I am the student of final year can you suggest me some Python web projects? I want to learn python and build my final year project in Python but I've no idea how to work with python so please guide me and answer my following questions please

Should i choose a framework or go with core python to develop web? Which is the native DB for Python web? e.g MySQL is native DB for PHP. Which Web framework of Python should choose and why?




Can't browse the subdomain after visiting a couple of pages of the website made with laravel

I developed this website using Laravel 5.5 for my research group and uploaded it to my university web host. The website's address is in the format of xxxx.cse.yyyy.edu .

When I browse some pages of this website it gets inaccessible and I can't even access the cse.yyyy.edu subdomain anymore for a while (usually after 10-12 hours). I can ping the IP address of the CSE subdomain but can't ping the domain address (possibly a DNS issue?). Although I am not sure, I think restarting my local router makes the website accessible again.

The only thing out of the ordinary about the website is the insecure login page that is not using https at the moment. Other than that, everything is just straightforward laravel code adopted from the original laravel documentations.

I'd be happy to provide more information but I don't really know what kind of info I should be providing here.

What do you think might be causing this problem? Thank you in advance!




How do I set specific position plotly graph in website?

I am using library plotly to show graphs in a website. In my case, I am putting four pies side by side and all positions are not correct.

I need to put text and number inside pie, as is show in picture above:

enter image description here

It´s clear that text inside graphs in middle of page is in perfect position, but text and number of graphs in page side are in incorrect position. When I is codding it, I use a code structure like below:

var number = {
  font: {
    size: 32,
    color: '#ddd',
    family: 'verdana'
  },
  showarrow: false,
  text: 'string',
  x: 0.375,
  y: 0.50
};
var text = {
  font: {
    size: 11,
    color: '#ddd',
    family: 'verdana'
  },
  showarrow: false,
  text: 'string',
  x: 0.375,
  y: 0.35
};

As in Plotly I need just to use page position in [0,1] scale, I divided page in eight parts and put text and number of second graph in 0.375. It´s perfect! Nothing wrong if I change resolution page.

But, when I set position of first and last graphs (page side: 0.125 and 0.875), does not work. I am trying do some calculation in function of dimensions page or text lenght, but isn´t working well and when I change resolution page (expansive website) this error increases. Being that it was expected be not necessary do it.

How can I solve it?




get/set logonHours by using C# web api 2.0

I would like to enable/disable logonHours for particular user by using Web api 2.0 ,tried with code, everything is working fine set/get other than that logonHours, please help me out.

DirectoryEntry("LDAP://test.com","Administrator", "tesT.123$")) {

            using (DirectorySearcher objAdSearcher = new DirectorySearcher(objRootEntry))
            {
                objAdSearcher.Filter = "(&(objectClass=user)(samAccountName=" + username + "))";

                SearchResult objResult = objAdSearcher.FindOne();

                if (objResult != null)
                {
                   objResult.GetDirectoryEntry().Properties["title"].Value = "Test"; //its working fine.

                    byte[] logonHours = new byte[] { 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0 };
                    //byte[] logonHours = new byte[] {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 };
                    objResult.GetDirectoryEntry().Properties["logonHours"].Value = logonHours; //its not working, also not throwing any error
                    objResult.GetDirectoryEntry().CommitChanges();


                }
            }
        }

Thanks in advance




Polymer paper-slider variable size steps

I would like to create a paper-slider element with ticks at values specified in an array of integers, with non-constant step sizes between the ticks. How would I go about doing this?




lundi 25 février 2019

I want to host my java web application on aws

my java web application is on localhost. i have created one variable with localhost link and use this variable to go another jsp page, so what should i write to replace localhost variable to host on AWS?




Web application throwing error(ERR_EMPTY_RESPONSE) codeigniter website

I can see lots of suggestions to resolve this but as am new to this would like to get a easy straight forward view to solve this issue.

MY URL contains https before the domain name. Also some of the pages were working in the site where only few where I used to get data from API is throwing this error

The xxxxxx page isn’t working

xxxxxx didn’t send any data.

ERR_EMPTY_RESPONSE

many thanks.




How to allow web hosting in EC2 with Linux AMI (port 80 rule added)

I've added rules for port 80 for http and even 443 for https but the url returns this site can't be reached. Do I need to configure the firewall somehow?

Also for url I used the public DNS address, I also tried the domain returned by host [public ip] command. Both didn't allow access.

Any help will be greatly appreciated, thanks!




How to implement the authorization through token and roles, in WEB API C #, SOAP architecture, through the use of repositories with stored procedures

How can I implement the authorization through token and roles, in WEB API C #, SOAP architecture, through the use of repositories with stored procedures and dependency injection?

public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                string autenticationToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodeautenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(autenticationToken));
                string[] userNamePassworArray = decodeautenticationToken.Split(':');
                string username = userNamePassworArray[0];
                string password = userNamePassworArray[1];

                LoginModel model = new LoginModel();

//validate user credentials and obtain user roles (return List Roles) //validar las credenciales de usuario y obtener roles de usuario

            model.Roleslist = _serviceUsuario.ObtenerRoles(username, password);

            if (model.Roleslist !=null)
            {
                //this line takes a list of roles and divides them with a comma.
                string ListRoles = string.Join(",", model.Roleslist.Select(x => x.Roles));

                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);

                //ClaimsIdentity oAuthIdentity = await model.Roleslist.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
                //ClaimsIdentity cookiesIdentity = await model.Roleslist.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

                //it does not work
                var authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, ListRoles);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Current.Request.Cookies.Add(authCookie);

                //  HResult = 0x80004002 Message = You can not convert an object of type 'System.Security.Claims.ClaimsIdentity' to the type 'System.Web.Security.FormsIdentity'.
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                string userData = ticket.UserData;
                string[] roles = userData.Split(',');
                HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "El nombre de usuario o la contraseña no son correctos.");
            }
        }
    }




How to open a webpage located on a server that has another network in my laptop

I'm working on my laptop on my company network, when I want to open this specific webpage I should go Remote Desktop to the Server then open this Webpage.

Note the server working on another Network and need login access.

so I ask if I can make shortcut or away to access to this webpage from my laptop without entering remote desktop.




How can i record a stream with a dahua cam?

I am using Django. The problem is that i need to start and stop a recording with a Dahua cam from a function in Django and later save that recording in a model, Dahua has an API to get and set its configuration, but not to directly start and stop a recording. To show the stream in HTML5 we use the following code.

<div class="h-50 border border-right-0 border-left-0">
    <div id="vxg_media_player1" class="vxgplayer h-100 w-100" 
    url="rtsp://username:password@192.168.1.108/cam/realmonitor? 
    channel=1&subtype=1" aspect-ratio latency="3000000" autostart controls 
    avsync debug></div>
    </div>

A JS Framework exists ( WEB RTC ), but it only works with a video tag.




Google maps postal color selection inline my website

does anyone know a good example how you can set areas by color in google maps and leave them in your website?

For example all postal codes (8802MA, 8802RX, 8802MC, 8802RZ, 8802PW, 8802PX, 8802RC, 8802PZ, 8802RD, 8802RT, 8802RB, 8802RS, 8802MD, 8802PK, 8802PP, 8802ME, 8802RA, 8802NV, 8802NX, 8802RE, 8802NW, 8802NT, 8802RG, 8802CN, 8802CP, 8802CM, 8802CL, 8802CK, 8802CJ, 8802DL, 8802RK, 8801ER, 8801ER, 8801EX, 8802PV, 8802RH, 8802NJ, 8801DA, 8801GD, 8802MG, 8802RP) in a given color?




Why does same cookie key set by two tabs are not overwritten?

So please ignore underlying details of why I am doing it. Open Tab 1 then Tab 2 both making ajax request every 5 seconds.

Tab 1: domain.com/a.jsp : Set-Cookie: sec-token=12345; max-age=28800; Secure; HttpOnly
Tab 2: domain.com/b.jsp : Set-Cookie: sec-token=ABCD; max-age=28800; Secure; HttpOnly

Shouldn't Tab 2 have overwritten cookie value set by Tab 1 ? I assume yes but I see that both tab 1 and tab 2 keep sending their related cookies that were set by their respective urls.

I have checked this in chrome and FF. Looking at chrome Settings > Cookies, I see both cookies are listed for sec-token with their own related path and values.




WordPress installation error while using apache24

I was trying to install WordPress on localhost but I am not using Xampp or Wampp. Instead of it I was trying to install it using Apache and MySQL separately. But when I ran the URL for the installation i.e. http://localhost/wordpress/ , it asked for the site title, username, and password. I filled the form data and clicked next button. But at the next screen no install button was appeared instead of it A blank screen appeared. I have attached a screenshot. Please let me know, whats the problem with it?enter image description here




What language should I learn to pull information from a third party site in real time

I want to develop a website that pulls information from a particular third party site in real time. I want to select certain products from this website, post them on my own site, but want the user to be able to filter through the products based on the current information provided from the third party site (i.e. brand, size, availability) I know HTML, CSS and Javascript but unsure on which backend language I would need to learn to develop this function. Any help would be greatly appreciated!




ReactJs security

I have just started learning authorization and authentication in react, and I'm writing this after finishing my first simple login system using JWT, as most of you know you store a token in the browser and then you compare it with the saved tokens in your backend now when that validation is done truly I set Authenticated Boolean to true and gain access to the website, after finishing that simple system I checked react dev tools and I found out that I can just change the boolean to true and bypass all of the authentication work!

And I have searched online for resources and tutorials to fix that massive problem but didn't find what was I looking for all I found is how to setup Authentication or protect a router similar to the way I did, but not deeply secured.

So can anyone recommend a course or tutorial paid or free to learn more about security and authentication?




How to set other site on canvas in html 5?

i want open google.com in my website like browser , i can set website on canvas ? or have any way to solve ?

<img id="scream" src="https://www.google.com/" alt="The Scream" width="220" height="277">




How to use the Embedded Apache Derby?

I've read through the entire documentation. I already have a complete rest api project with 2 classes and some hard coded data in my java backens. All api methods are functional. I need to implement the embedded Apache Derby database to make it fully functional.

I've set the derby home and derby install paths as well as added the derby.jar to my project. Added the dependency for gradle as well. How do I create the database and connect it with my get, post, delete and patch methods?




Set a python virtual environment to a ubuntu user?

Is it possible to activate a python virtual environment for everything a user do ? I have a webapp executing python code, and I would want the www-data user used by the apache host to use a specific python venv (It would solve a struggle for libraries).




Update include(file.php) by ajax

I need to execute include(file.php) which echo some data every time I press the button. Tried to call it from ajax

$.ajax({
    type: 'get',
    url: 'link/file.php',
    data: {
      'update': 1
    },
 });` 

But it doesn't update (only on page refresh). Can I somehow update this php echo every time I recieve get request or press the button? Thank you!




Implement Deposit and Withdrawal functionality

How can i implement Deposit and Withdrawal functionality for registered users on a website (ASP.NET). If you can provide any urls to a possible online payment processor would be great. I've looked into the major (paypal, amazon and etc) gateway payment processors and all i can find is documentation for only credit card payment.




unable to fetch the details from related tables in laravel (using with)

am trying to fetch userName from user table and productName from products table in my ProductReview.php but its returning null

ProductReview.php

       class ProductReview extends Model
    {
        protected $table = 'product_review';

        protected $fillable = ['review_id','user_id','order_id','product_id','region','vendor','verified_order',
                               'star_rating','date_of_review','review_title','review_message','published',
                               'relevance','order_id','order_item_id','order_type','order_number','source_of_review',
                               'created_at','updated_at','published_by'];

        public function pName(){
            return $this->hasOne('App\Models\Product','product_id');
        }
        public function uName(){
            return $this->hasOne('App\Models\User','id');
        }



        function getAllAdminReviews($data){

          $reviews = ProductReview::select('product_review.*,'product_id','user_id')
                      ->with(['pName' => function($pr){
                                $pr->select('product_name');      
                            },
                           'uName' => function($un){
                                $un->select('user_name');        
                            } 
                          ]);
return $reviews;
        }

        }

Product.php

  public function pName(){
        return $this->belongsTo('App\Models\ProductReview','product_id');
    }

User.php

   public function uName(){
        return $this->belongsTo('App\Models\ProductReview','id');
    }

output:

pName:null uName:null rest of the things is printing fine

thanks in advance




How I can build a full functional file manager with user management?

I am struggling in developing a web app where user can sign up and manage their files like google drive. How should I proceed to accomplish it. I want to use flask if it's possible with it.I searched about it but unable to find a perfect solution. Can you help me out or point out to some useful resources.

Thanks




Is there a way to use android's DetectedActivity class in website?

I am working on a progressive development application where I want to use android's DetectedActivity class. Is it possible.




Сreating a web interface for accessing the database

Good day. I hope for your help.

I will soon have a thesis defense and i need to create a web interface to access the database.

I compared all the main current products and i cant decide what is missing in this area.

There are lightweight (Adminer, phpLiteAdmin), there are for certain databases (PosgreSQL - pgAdmin 4, MySQL/MariaDB - phpMyAdmin) and so on...

My questions:
1) What do you think is missing in these products and i could implement it in my project? I thought about security and focus on it, as well as the simplicity of the UI.
2) What tools are best to use?
3) Which database to focus on or do under any like Adminer?




Apache FOP - is there a way to embed font programatically?

When creating a PDF using Apache FOP it is possible to embed a font with configuration file. The problem emerges when the app is a web application and it is necessary to embed a font that is inside WAR file (so treated as resource).

It is not acceptable to use particular container's folder structure to determine where exactly the war is located (when in configuration xml file we set tag to ./, it is set to the base folder of running container like C:\Tomcat\bin).

So the question is: Do anyone know the way to embed a font programatically?




dimanche 24 février 2019

Getting the particular (pre-formatted) text (from a website) using JSoup

I'm new to JSoup, and I want to get the text written in this specific HTML tag:

<pre class="cg-msgbody cg-view-msgbody"><span class="cg-msgspan"><span>**the text I want to get is present here, how can I get it using JSoup?**</span></span></pre>

Any help would be appreciated.

Thanks!




Unsupported operation: _Namespace while using dart io on web

I am trying to use dart-io to read and write file. I am getting below exception.
Uncaught Error: Unsupported operation: _Namespace
    at Object.dart.throw (dart_sdk.js:4537)
    at Function.get _namespacePointer [as _namespacePointer] (dart_sdk.js:49364)
    at Function._namespacePointer (dart_sdk.js:47224)
    at Function._dispatchWithNamespace (dart_sdk.js:47227)
    at io._File.new.open (dart_sdk.js:47342)
    at new io._FileStreamConsumer.new (dart_sdk.js:47186)
    at io._File.new.openWrite (dart_sdk.js:47468)
    at refresh (main.dart:15)
    at refresh.next (<anonymous>)
    at runBody (dart_sdk.js:22264)
    at Object.async.async (dart_sdk.js:22292)
    at main.refresh (main.dart:13)
    at Object.dart._checkAndCall (dart_sdk.js:4731)
    at Object.dart.dcall (dart_sdk.js:4736)

Code I used final output = io.File('output.txt').openWrite(); output.write(output_data);

Could you please help me in fixing it.
Or any other way to read and write files using dart in a web application.




PHP slideshow PREV and NEXT buttons not working

array( 'image' => $image1, 'title' => $image1_title, 'description' => $image1_desc, 'link' => $image1_link ), 'slide2' => array( 'image' => $image2, 'title' => $image2_title, 'description' => $image2_desc, 'link' => $image2_link ), 'slide3' => array( 'image' => $image3, 'title' => $image3_title, 'description' => $image3_desc, 'link' => $image3_link ), 'slide4' => array( 'image' => $image4, 'title' => $image4_title, 'description' => $image4_desc, 'link' => $image4_link ), 'slide5' => array( 'image' => $image5, 'title' => $image5_title, 'description' => $image5_desc, 'link' => $image5_link ) ); /*check if exist slide*/ $check_exist_slide = 0; foreach($kitter_slider as $slide => $value) { if (!empty ($value['image'])){ $check_exist_slide = 1; } } ?>
<!--slider-->
<section id="slider-bg-wrapper" class="full-width-wrapper">

    <?php if($data['md_enable_slider_background']){?>
    <div id="slider-bg-overlay">
        <div id="slider-bg-overlay1"></div>
        <div id="slider-bg-overlay2"></div>
    </div>
    <?php }?>

    <div id="slider-shadow">
        <div class="fixed-width-wrapper">
            <div class="box_skitter box_skitter_home maxx-theme" id="slider-wrapper">
            <?php if($check_exist_slide == 1) {// check if any slide image added in theme option, return custom slide?>
                <ul>
                    <?php foreach($kitter_slider as $slide => $value) {
                        if (!empty ($value['image'])) {?>

                        <li>
                            <?php if (!empty ($value['link'])) { ?>
                            <a href="<?php echo $value['link']; ?>" title="<?php echo $value['title']; ?>">
                                <img src="<?php echo $value['image'];?>" width="940" height="370" alt="<?php echo $value['title']; ?>"/>
                            </a>
                            <?php } else { ?>
                                <img src="<?php echo $value['image'];?>" width="940" height="370" alt="<?php echo $value['title']; ?>"/>                        
                            <?php } ?>

                            <?php if (!empty ($value['title'])) { ?>
                            <div class="label_text">
                                <h1><?php echo $value['title'];?></h1>
                                <p><?php echo stripslashes($value['description']) ?></p>
                            </div>
                            <?php }?>
                            </li>
                        </li>
                    <?php }?>
                    <?php }?>

                </ul>

            <?php }?>
            </div>

        </div>
    </div>

    </script>


</section>
<!--/slider-->    

<!--main content-->
<div id="main-content-wrapper" class="fixed-width-wrapper home-page" >

    <!--Content-->
    <div class="entry-content" >
        <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <!--post entry-->
        <article class="post-entry" id="post-<?php the_ID(); ?>">
            <?php the_content();?>
            <?php wp_link_pages(
                array(
                    'before' => '<div class="link-pages"><strong>'.__('Pages:', 'framework').'</strong> ', 
                    'after' => '</div>', 
                    'next_or_number' => 'number',
                    'nextpagelink'     => __('Next &rarr;', 'framework'),
                    'previouspagelink'     => __('&larr; Prev', 'framework')
                )
            );?>
        </article>
        <!--/post entry-->
        <?php endwhile; endif; ?>    
    </div>
    <!--/Content-->


</div>
<!--/main content-->

<div class="clear"></div>




how to use json data in website, what kind of database should I use?

I am trying to create a website in which a visitor can click a state in the US map and it gives you a statistics and information about the candidate that ran in the state's election in a given year. I already have a image map and I will add a java script function that takes year and the race's district as arguments.

I am trying to do this in django and Google App Engine and I mainly code in python.

I have put gathered and put together those data in .json file thinking that I can do something similar toopen("path.json", "r") in python and just pass the data. But I am not quiet sure how do it to and whether its even possible to do such thing. As I did some googling, I am starting to wonder if I need to use database. Should I use database and if I have to, RDB or NoSQL? In addition, how should I feed the data in json to the database.

json file looks like this

{
  "AL": {
    "api_version": "1.0",
    "pagination": {
      "count": 7,
      "pages": 1,
      "per_page": 100,
      "page": 1
    },
    "results": [
      {
        "party": "REP",
        "last_f2_date": "2015-12-09",
        "election_districts": [
          "00"
        ],
        "load_date": "2018-02-17T09:16:20+00:00",
        "party_full": "REPUBLICAN PARTY",
        "first_file_date": "2015-12-09",
        "office": "S",
        "incumbent_challenge": "C",
        "district_number": 0,
        "office_full": "Senate",
        "candidate_status": "N",
        "active_through": 2016,
        "candidate_id": "S6AL00336",
        "state": "AL",
        "election_years": [
          2016
        ],
        "federal_funds_flag": false,
        "incumbent_challenge_full": "Challenger",
        "flags": "S6AL00336",
        "district": "00",
        "cycles": [
          2016,
          2018
        ],
        "last_file_date": "2015-12-09",
        "has_raised_funds": true,
        "name": "BOWMAN, MARCUS",
        "operating_expenditure": 770.0,
        "primary_votes": "[19707]",
        "primary_sahre": "[0.0253026573760578]",
        "general_votes": "[' ']",
        "general_sahre": "[' ']"
      },
      {
        "party": "DEM",
        "last_f2_date": "2015-04-03",
        "election_districts": [
          "00"
        ],
        "load_date": "2018-02-17T09:16:20+00:00",
        "party_full": "DEMOCRATIC PARTY",
        "first_file_date": "2015-04-03",
        "office": "S",
        "incumbent_challenge": "C",
        "district_number": 0,
        "office_full": "Senate",
        "candidate_status": "P",
        "active_through": 2016,
        "candidate_id": "S6AL00302",
        "state": "AL",
        "election_years": [
          2016
        ],
        "federal_funds_flag": false,
        "incumbent_challenge_full": "Challenger",
        "flags": "S6AL00302",
        "district": "00",
        "cycles": [
          2016,
          2018,
          2020
        ],
        "last_file_date": "2015-04-03",
        "has_raised_funds": true,
        "name": "CRUMPTON, RONALD (RON) STEVEN",
        "operating_expenditure": 33668.0,
        "primary_votes": "[153897]",
        "primary_sahre": "[0.560802119355885]",
        "general_votes": "[748709.0]",
        "general_sahre": "[0.358672615888139]"
      },




my question is about How to call web api in wordpress web sites?

I want to make a WordPress web site and use my web API above so that the total information is saved in my database I tried to do my API in WordPress but did not get any solution.




Webgl unity build won't play Video

I have used video player to play video, everything works fine in unity but when I build it and run on firefox or any other browser,the video won't play. I have tried different settings and different video formats but nothing seems to work. I don't get any errors.

I have an empty scene with camera and video player, no scripts. Just used video player and used play on awake to play the video. Works fine in playmode but won't work in webgl build.




How do I make my CSS border surround ONLY my link?

I have a CSS border that is around a link but it stretches all the way to left but I want it to surround only the link. My website is http://calvinhaworth.x10host.com/desktophome/. My HTML is

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Calvin Haworths Portfolio (Desktop) </title>
  <style type="text/css">
        div.cntr {
                text-align: center;
        }
        div.linkright {
                text-align: right;
                border: ridge 10px;
        }
        div.linkright:hover {
                border: 10px ridge blue;
        }
  </style>
  </head>
  <body>
        <div class = linkright> 
                <a href = "http://calvinhaworth.x10host.com/teamlife9thdesktop/">Team/Life Activities (9th grade)</a>
        </div>
        <div class = linkright>
                <a href = "http://calvinhaworth.x10host.com/biology9thdesktop/">Biology (9th Grade)</a>
        </div>
        <div class = cntr>
                <img src = "https://res.cloudinary.com/calvinhaworth/image/upload/v1550969360/LogoMakr_3X5LlB.png">
        </div>
        <div class = cntr>
                <h1>Welcome to my portfolio. Click the wrong link? Go to the <a href = "http://www.calvinhaworth.x10host.com">main page</a>. </h1>
        </div>
        <div class = cntr>
                <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3066.160904221107!2d-104.76233648462336!3d39.78094427944419!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x876c641a5240b78b%3A0x4166849d10c9bfd2!2sDr.+Martin+Luther+King+Jr.+Early+College!5e0!3m2!1sen!2sus!4v1547568093508" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
        </div>
  </body>
</html>



Can console.log Object but cannot assign to var

So I have a section of code to read/parse a php file. The object looks like {plan{...}, catalog{...}}. I assign the first index of the object to a var and pass it into a new function

 if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        let inputPlan = {};
        inputPlan = (myObj['plan']);
        getInputs(inputPlan);
}

In the function getInputs, I try to parse the "plan" object which is in the format of {student: "sam", age : "15", ...}.

 function getInputs(inputPlan){

        console.log(inputPlan["student"]);
        var student = inputPlan["student"];     
}

I can grab the "student" key of the object and I print it out to the console getting "sam". However, when I attempt to assign it to a variable, I get a cannot read property "student" of undefined. I'm not sure why this is happening as the console seems to be reading the specified key without a problem?

Thank you




How to save TRANSACTION details, exactly for logged in user??? in Phpmyadmin

In my WEB-SITE user Registration information and Transaction details saves in one database, But After user logged in and make online payment in Website, In PhpmyAdmin Transaction details saves to New line with unknown Name, Surname etc. in database table.

How to define that Transaction belongs to logged in user.??

1- Column: After registration 2- Column: Transaction Details saved to new column




Sidebar menu close (Width:0) when click on body or swipe slide

I am trying to make a vertical slide menu for the mobile version. This side menu is open and close when I click specific button like (Openbtn) (Closebtn) and clicking anywhere in body tag including menubar.

I need a javascript code for side menu close when I clicked in body outside menubar (Side menu). Also it willbe helpful if is possible to close when I swipe menubar (side menu).

Below is my example for your reference:

function openNav() {
  console.log("open");
  document.getElementById("toggle_menu").style.width = "250px";
}

function closeNav() {
  document.getElementById("toggle_menu").style.width = "0";
}

document.addEventListener("click", function(){
  if( parseInt( $('#toggle_menu').css('width') ) > 0 ){
    document.getElementById("toggle_menu").style.width = "0";
  }
});


// For Child dropdown menu
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
  this.classList.toggle("active");
  var dropdownContent = this.nextElementSibling;
  if (dropdownContent.style.display === "block") {
  dropdownContent.style.display = "none";
  } else {
  dropdownContent.style.display = "block";
  }
  });
}
.toggle_menu {display:block; width:250px; top:0px; height:100%; background-color:#fff; box-shadow: 0 5px 5px rgba(0,0,0,.2);position: fixed; overflow-x: hidden; transition: 0.5s; z-index:1000;}
.title {width:100%; height:80px;}
.toggle_menu ul {list-style:none; margin:0; padding:0;}
.toggle_menu ul li {width:100%; height:40px; cursor:pointer;}
.toggle_menu ul li a {text-decoration:none; color: #666666; font-size:14px; display:block; padding: 10px 0px 0 50px; font-size: 14px; font-family:sans-serif;}
.toggle_menu ul li .sub-arrow:after { content:'\203A'; font-size:24px; color:#666666; float:right; margin-top:-20px; margin-right:30px; transform:rotate(90deg); -webkit-transform:rotate(90deg); -moz-transform:rotate(90deg); }
.toggle_menu ul li:hover {background-color:#E8E6FF;}
.toggle_menu ul .dropdown-container {display:none; background-color: #E2E1FB;} 
.toggle_menu ul .dropdown-container a:before{ content:'\203A'; font-size: 15px; margin-right:10px; color: #666666; }

.closebtn {
  position: absolute;
  height:40px;
  width:50px;
  color:#000;
  border-radius:50%;
  text-align:center;
  padding-top:10px;
  border:6px solid #307DFE;
  font-size:24px;
  font-family: Arial, Helvetica, sans-serif;
  background: #70A9FE;
  right:10px;
  top:10px;
}
.closebtn:hover {border:6px solid #FF9900;}             
<span id="menu_bar" onClick="openNav()">Menu</span>

<!-- Slide Menu -->
<div class="toggle_menu" id="toggle_menu">
            <div class="title"><a href="javascript:void(0)" class="closebtn" onClick="closeNav()">X</a> </div> 
      <div class="sidenav">
        <ul>
          <li><a href="#">Home</a></li>
          <li class="dropdown-btn"><a href="#">Men's</a><span class="sub-arrow"></span></li>
            <ul class="dropdown-container">
              <li><a href="">Traditional Wear</a></li>
              <li><a href="">Top Wear</a></li>
              <li><a href="">Bottom Wear</a></li>
              <li><a href="">Footwear</a></li>
              <li><a href="">Bags</a></li>
              <li><a href="">Accessories</a></li>
             </ul>
          <li class="dropdown-btn"><a href="#">Women's</a><span class="sub-arrow"></span></li>
             <ul class="dropdown-container">
                <li><a href="">Traditional Wear</a></li>
                <li><a href="">Westen Wear</a></li>
                <li><a href="">Footwear</a></li>
                <li><a href="">Lingerie</a></li>
                <li><a href="">Bages</a></li>
                <li><a href="">Jewellery</a></li>
                <li><a href="">Accessories</a></li>
             </ul>
        </ul>
      </div>
</div>



what language should i use for my project? [on hold]

i want to make my one solid project that contains Crud and other features for my portfolio.it's kind of investment for my future.I want to build the project to refresh my brain.so i can build websites easily after i get graduated.I learned basics of pure php and laravel.But i also want to learn node js and react at the same time.I'm thinking that learning php agin is not worth because in profesional environment.Companies will only need framework master because it's best for production, i think that nodejs will take php down from the best server side language in 5 years and i'm interested to learn more about ui/ux at the same time.So what do u think guys?




Chart.js canvas and chart width gets overwritten when redrawn

My charts that I made with chart.js grow each time when I redraw them and I have no idea why. My code for the chart cavas is:

let tempChart = document.getElementById("tempChart").getContext('2d');
let pressureChart = document.getElementById("pressureChart").getContext('2d');
let O3Chart = document.getElementById("O3Chart").getContext('2d');
let PM1Chart = document.getElementById("PM1Chart").getContext('2d');
<canvas id="tempChart"></canvas>
<canvas id="pressureChart"></canvas>
<canvas id="O3Chart"></canvas>
<canvas id="PM1Chart"></canvas>

This is the code I call each time when I want to draw or redraw a chart:

function createChart(chartLabels, chartData, chart, label, backgroundcolor, beginAtZero, borderColor) {

    let LineChart = new Chart(chart, {
        type: 'line',
        data: {
            labels: chartLabels,
            datasets: [{
                label: label,
                data: chartData,
                backgroundColor: backgroundcolor,
                pointRadius: 0,
                borderColor: borderColor
        }]
        },
        options: {
            responsive: false,
            scales: {
                yAxes: [{
                        ticks: {
                            beginAtZero: beginAtZero
                        }
                }
                ]
            }
        }
    })

}

The CSS of the canvas before I run createChart once:

    width: 45%;
    padding: 20px 20px;
    border-bottom: 1px solid #dedede;

CSS after I run createChart:

    display: block;
    height: 341px;
    width: 683px;

I have tested this code with empty and full arrays for my labels and data and in both instances the chart grows each time I call the createChart function.




Firebase signs out user after signing in

I have the problem that my firebase hosting website has an /account route which dynamically loads a content page, depending on if the user is signed-in or not. For detecting the users state, I am using firebase auth's onAuthStateChange callback:

firebase.auth().onAuthStateChanged((user) => {
    console.log("authstate changed:"+user);
    let pagereq = new XMLHttpRequest();
    if (user) {
        console.log(user.email);
        user.getIdTokenResult(true).then((idtokenres) => {
            if(idtokenres.claims.admin){
                console.log("user is admin");
            }
        });
        pagereq.open("GET","./account-management/management.html",true);
        logout.addEventListener("click",handleLogout());
    } else {
        logout.parentNode.removeChild(logout);
        pagereq.open("GET","./account-management/login/login-page.html",true);
    }
}

When the user is signed in a dynamically loaded login form appears and enables a sign in with an email and a password. The user now enters his credentials and hits 'sign in'. The content area reloads due to the callback and shows a console page. Here comes the problem. When the user signs in, onAuthStateChanged is called twice: first sucessful with the exact user-Object and second with user = null. The console page dynamically loads a script after the console page itself is loaded. In the script, there also is an onAuthStateChanged function which will be called normally. Here, the callback is called only once and user also is null. Why is that and how can I workaround this problem? I can only imagine why onAuthStateChanged in the /account page gets called twice(The dynamically loaded and the pages script both recieve the same callback), but not why the user-Object null at the second call and also null in the dynamically loaded script.




Testing the Web Annotation Data Model in Protege

I want to test the Web Data Annotation Model. Is there any possibilty to test the Web Data Annotation Model in Protégé in any kind of way?




Why there's no output coming on my python idle or vistual studio code? [on hold]

Python its always been this blank even though i put some otherr codes, there no output coming out what should i do?




samedi 23 février 2019

Logging in from google to logging in from websites

I had logged in from Google on "udemy" and subscribed for some paid course, all that is working fine but now if I have to log in from the "udemy" itself and use the already paid content how can I do so? I do not want to log in from my google account but simply from the website, If I sign up there for a new account then I could not able to access the purchased course which I want to access, what could be the steps to make my job done.

thanks.




How to identify Kali custom image in AWS

How do I detect if all of a sudden Kali Linux instance is initiated by an attacker in my AWS account.

I know that there is a guard duty signature that identifies pen testing done using Kali Linux but this signature does not work if some body uses a custom image ( not the default kali Linux image available in market place ) . How do I detect if some one uses a custom image ? Or any customisation done on base AWS image to have Kali running ? Would here be any specific Cloud trail log that says custom image was built and it resembles Kali ?




How to load a website faster in chrome, Firefox, cyberfox browser?

I need to make loading a (https://onlinebooking.sand.telangana.gov.in/Masters/Home.aspx ) website faster within 0.01sec. . Pls help me




How to Show Closest Location to Visitor using JavaScript

I'm currently in the process of redoing my company's website. It would be really cool to, as soon as someone loads any page of our new site, display the location that is either closest to them, or within the business' service radius (±20mi) in the top bar beside a location pinpoint icon. I've been searching for a few days now about how to find a way to make this possible, and JavaScript seems to be the only way to accomplish this. I'm new to JS, so I'm not sure of the best way to accomplish it.

I've been looking into the Geolocation JS functionality, but I cannot get it to work for the life of me. Here is what I have so far:

var location = document.getElementById("nearestLocation");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    location.innerHTML = "Geolocation is not supported by this browser.";
  }
}


function distance(lat1, lon1, lat2, lon2, unit) {
        var radlat1 = Math.PI * lat1/180
        var radlat2 = Math.PI * lat2/180
        var theta = lon1-lon2
        var radtheta = Math.PI * theta/180
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
                dist = 1;
        }
        dist = Math.acos(dist)
        dist = dist * 180/Math.PI
        dist = dist * 60 * 1.1515
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist
    }

    var data = [{
        "lat": "36.5983825",
        "lng": "-82.1828577",
        "location": "Bristol, VA"
    }, {
        "lat": "36.7053664",
        "lng": "-81.999551",
        "location": "Abingdon, VA"
    }, {
        "lat": "35.9120595",
        "lng": "-84.0979276",
        "location": "West Knoxville, TN"
    }, {
        "lat": "35.8718708",
        "lng": "-83.5642387",
        "location": "Sevierville, TN"
    }];

    var html = "";
    var poslat = position.coords.latitude;
    var poslng = position.coords.longitude;
    
    for (var i = 0; i < data.length; i++) {
        // if this location is within 0.1KM of the user, add it to the list
        if (distance(poslat, poslng, data[i].lat, data[i].lng, "K") <= 0.1) {
            html += "<li>Nearest Location: <i class='icon-location'></i>" + data[i].location + "</li>";
        }
    }
    
    $('#nearestLocation').append(html);
<html>
<body>
<head>
</head>
<button onclick="getLocation()">Find Your Local Honey Do</button>
<div id="nearestLocation"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</body>
</html>

This is my attempt at fusing:

https://www.w3schools.com/html/html5_geolocation.asp

and:

How to find nearest location using latitude and longitude from a json data

I've tried to use the info found on the following sites as well, but to no avail:

https://diveintohtml5.info/geolocation.html

How to display the nearest latitude and longitude to my location using javascript?

Most of the stuff I can find either only pulls the info and doesn't show me how to change info based upon the result, displays a map, or is broken and doesn't work

We have 14 locations, and getting their Long/Lat is not a problem.. It's getting the visitor's location either on-load or on-click. Retaining this info would be cool via cookies after they click on it, but it's not necessary. I just want to be able to show them the closest location to them, or make it a link directly to the location's page.

The internet has not proven helpful in helping me accomplish this.

I am aware of the ability to use PHP IP Recall to get an idea of location, but that's not precise enough for our liking, especially with mobile phones, when 70% of our web traffic comes from mobile devices.

Any assistance that can be provided will be greatly welcome!