mardi 31 décembre 2019

Green background appearing on Iphone (Safari and Chrome) for png images

I'm testing a website in production on Iphone and this morning the .png images of our team members started appearing with a green background (no css or anything applied). I am using Cloudinary CDN for image hosting and serving.

The original images don't have this background and show up correctly on every android device and desktop browser i have tested.

Here is a screenshot:

html

Do you have any ideia what is causing this.

Thanks in advance.




How to have two different text elements moving randomly on a page in Javascript

So I've been reading this post which I found is the closest to what I want. Basically, I want two different text elements (two different words) moving around the page randomly and also bouncing off each other when they come in contact.

I have tried to edit the code so that it's black and have only one text element. However how can I also include a second text element (a different word) moving randomly as well?

Also how can I change it to Roboto Mono font?

// Return random RGB color string:

function randomColor() {
  var hex = Math.floor(Math.random() * 0x1000000).toString(16);
  return "#" + ("000000" + hex).slice(0);
}

// Poor man's box physics update for time step dt:
function doPhysics(boxes, width, height, dt) {
  for (let i = 0; i < boxes.length; i++) {
    var box = boxes[i];

    // Update positions: 
    box.x += box.dx * dt;
    box.y += box.dy * dt;

    // Handle boundary collisions:
    if (box.x < 0) {
      box.x = 0;
      box.dx = -box.dx;
    } else if (box.x + box.width > width) {
      box.x = width - box.width;
      box.dx = -box.dx;
    }
    if (box.y < 0) {
      box.y = 0;
      box.dy = -box.dy;
    } else if (box.y + box.height > height) {
      box.y = height - box.height;
      box.dy = -box.dy;
    }
  }

  // Handle box collisions:
  for (let i = 0; i < boxes.length; i++) {
    for (let j = i + 1; j < boxes.length; j++) {
      var box1 = boxes[i];
      var box2 = boxes[j];
      var dx = Math.abs(box1.x - box2.x);
      var dy = Math.abs(box1.y - box2.y);

      // Check for overlap:
      if (2 * dx < (box1.width  + box2.width ) &&
          2 * dy < (box1.height + box2.height)) {

        // Swap dx if moving towards each other: 
        if ((box1.x > box2.x) == (box1.dx < box2.dx)) {
          var swap = box1.dx;
          box1.dx = box2.dx;
          box2.dx = swap;
        }

        // Swap dy if moving towards each other: 
        if ((box1.y > box2.y) == (box1.dy < box2.dy)) {
          var swap = box1.dy;
          box1.dy = box2.dy;
          box2.dy = swap;
        }
      }
    }
  }
}

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

// Initialize random boxes:
var boxes = [];
for (var i = 0; i < 1; i++) {
  var box = {
    x: Math.floor(Math.random() * canvas.width),
    y: Math.floor(Math.random() * canvas.height),
    width: 50,
    height: 20,
    dx: (Math.random() - 0.5) * 0.3,
    dy: (Math.random() - 0.5) * 0.3
  };
  boxes.push(box);
}


// Initialize random color and set up interval:
var color = randomColor();
setInterval(function() {
  color = randomColor();
}, 450);

// Update physics at fixed rate:
var last = performance.now();
setInterval(function(time) {
  var now = performance.now();
  doPhysics(boxes, canvas.width, canvas.height, now - last);
  last = now;
}, 50);

// Draw animation frames at optimal frame rate:
function draw(now) {
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < boxes.length; i++) {
    var box = boxes[i];
    
    // Interpolate position:
    var x = box.x + box.dx * (now - last);
    var y = box.y + box.dy * (now - last);
    
    context.beginPath();
    context.fillStyle = color;
    context.font = "40px 'Roboto Mono'";
    context.textBaseline = "hanging";
    context.fillText("motion", x, y);
    context.closePath();
  }
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
<!DOCTYPE html>
<html>
    <body>
    <head>
        <link rel="stylesheet" href="test.css">
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        
        
    </head>
    
    <canvas id="canvas"></canvas>
    


        <script src="test.js"></script>
        
        
        
        
    </body>
</html>



I want to make an web based expert system so which tools should i use?

I am making an expert system program but it must be web based so i don't know what technologies to use for an expert system as i don't have any experience regarding expert systems




How do I implement a sort of video playlist scrolling to my website? [closed]

Well as the questions says, I want to create a sort of video playlist to which the user can scroll through. It's similar to how Sky Sports does it like this: https://gyazo.com/5518b4aa29cb00519580ddf76373d84b How would I achieve this on my website that I am creating?




Firebase Dynamic Link attempts to open non-existing URI (/_/DurableDeepLinkUi/csreport)

We use Firebase Dynamic Links to generate short links that are sent via SMS and email.

A few notes:

  • These short links are not linked to an app
  • They are only intended to open a browser page

With that said, our infrastructure monitoring is indicating 404 errors on a strange URL: /_/DurableDeepLinkUi/cspreport

The strongest indicator that this is related to the Short Link is the fact that the long URL of our short link is in the request.headers.referer of the error stack.

Here are the error attributes and the error message:

Uncaught exception 'CHttpException' with message 'Unable to resolve the request "_/DurableDeepLinkUi/cspreport".'

url                             /_/DurableDeepLinkUi/cspreport
httpResponseCode                404
request.headers.User-Agent      Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
request.headers.contentLength   501
request.headers.host            
request.headers.referer         
request.headers.contentType     application/csp-report
request.method                  POST
response.headers.contentType    text/html

Here's an excerpt of how we generate our Dynamic Short Links:

$request_url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=" . $api_key;

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $request_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode([
        "dynamicLinkInfo" => [
            "domainUriPrefix" => $short_uri_prefix,
            "link" => $long_url,
            "androidInfo" => [
                "androidFallbackLink" => $long_url
            ],
            "iosInfo" => [
                "iosFallbackLink" => $long_url
            ],
            "navigationInfo" => [
                "enableForcedRedirect" => false
            ]
        ],
        "suffix" => [
            "option" => "SHORT"
        ]
    ]),
    CURLOPT_HTTPHEADER => [
        "Cache-Control: no-cache",
        "Content-Type: application/json",
    ],
]);

$response = curl_exec($curl);

Any idea what might be causing this 404? We have not been able to reliably reproduce it on any Android or iOS device we have internally.

We've reviewed the documentation provided by Google on this topic, to no avail: https://firebase.google.com/docs/reference/dynamic-links/link-shortener




record 10 minute audio file on browser

I am trying recording audio and upload it to php or nodejs server. I tried every answer given in other questions but ı couldn't do it. I need a tutorial that explain everything clearly.




Firebase javascript auth user displaying null even though user is signed in

I followed the Firebase docs for web development and I used the user.updateProfile method to add a displayName. After signing in, i used console.log(user) and it worked but when i called user.updateprofile, it reads user as null. Any solutions?

My code is attached

var button = document.getElementById("profile-button");
var username = document.getElementById("username-Box").value;

var user = firebase.auth().currentUser;

auth.onAuthStateChanged(user =>{
        console.log(user);
})


function updateProfile(){
        if (user != null){
                user.updateProfile({
                displayName : username
        }).then(user => {
                console.log("Updated Successfully");
                window.location.href="chatpage.html";
        }).catch(err =>{
                console.log(err);
                window.alert(err);
        });
        }else if(user == null){
                console.log("No user signed in");
        }
}



How can i deale wth static and media files in django without creating a virtual environnement?

Hello,

i want to use pictures in my application, and in the video i am following he used a virtual environment that i don't know how to create.

should i create a virtual environment ? if so , how to ?

if not , how can i use pictures without creating a virtual environment ?, and what are the the settings i have to do in the settings.py and urls.py files?

setting.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd0cn(*@vl*liejsapzk2yhoo!$iorw9-hx-43)%mi0g_rf#m$l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'custom.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'custom.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_in_env'),
]

STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_URL = '/media'
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path("",include('posts.urls')),
    path('admin/', admin.site.urls),
]


if settings.DEBUG:
    urlpatterns == static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
    urlpatterns == static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

cmd :

STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') NameError: name 'VENV_PATH' is not defined




Module parse failed: Unexpected token vanilla js

I have this app that im building.

https://jsfiddle.net/wvpysbnd/

vanilla js and bootstrap

webpack.config.js

const path = require('path')

module.exports ={
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
    }
};

package.json

{
  "name": "todolist",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "main": "main.js",
  "dependencies": {
    "bootstrap": "^4.4.1"
  },
  "devDependencies": {
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

I'm getting this error:

ERROR in ./src/index.js 28:26
Module parse failed: Unexpected token (28:26)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| 
>     static changeActivity = () =>{
|         activityPage.addEventListener('click', (e) =>{
|             e.preventDefault();

Even if I delete those lines, webpack seems to be stuck there.




How to create folder on a webpage using javascript or jquery? [closed]

I want to create a theme on webpage like windows where we can create new folder by pressing New folder button. It should be like a form input with name "New folder" or "New folder 2" which should be editable. Just like in windows file explorer




How come browsers don't support HEIF/HEVC?

Not that I understand much about this topic, but it seems like going forward, High Efficiency Image File (HEIF) will be a strictly superior image format to JPG. How come no browser is currently supporting it? Is this likely to change in 2020?

It's similar for High Efficiency Video Coding (HEVC). Only Safari currently supports it. Again, how come?




How to run this AJAX JAVA SCRIPT Coding?

My Source from W3 Schools : https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax_array

When I running this ajax example in w3 source it's running successfully.

When I try to execute the same code in my local its' not running .The code is below.

Is there I need any server for running this example.

ajax.html

<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>

<p id="demo"></p>

<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>

</body>
</html>

json_demo.txt

{
    "name":"John",
    "age":31,
    "pets":[
        { "animal":"dog", "name":"Fido" },
        { "animal":"cat", "name":"Felix" },
        { "animal":"hamster", "name":"Lightning" }
    ]
}

How to run this file in my local computer? Help me to begin my Ajax Learning......




How to Convert a Laravel Web app to Desktop application

How to convert a web application which has made with Laravel framework to Desktop Application?




lundi 30 décembre 2019

I really couldn't describe it in the title, it's better if you read the content inside

I'm having trouble doing PHP right now and I'm on the verge of going insane because I can't seem to show the data I want to show. All I get are errors and the "No tasks" I plan to echo out when there are no tasks available for the user (in my case I have tasks ready for the user in the database). If you guys could point out what's wrong with my code/db, it would be much of great help. Thanks :D

The code for the page function:

<?php

include("dbh.sys.php");
$user = $_SESSION['client_id'];
$sql = "SELECT * FROM incom_tasks WHERE taskUser=?;";
$stmt = $conn->stmt_init();

if(!$stmt = $conn->prepare($sql)) {
    echo '<p>SQL had an error!</p>';
} elseif($stmt = $conn->prepare($sql)) {
    //binder
    $stmt->bind_param("i", $user);
    //run!
    $stmt->execute();
    //get num rows
    $stmt->store_result();
    $num = $stmt->num_rows();
    $result = $stmt->get_result();
    if($num > 0){
        while($row = $result->fetch()){

        $points = $row['taskPoints'];
        $date = $row['taskDate'];
        $taskID = $row['taskID'];
        $sql = "SELECT * FROM tasks_list WHERE taskID=?;";
        $stmt = $conn->stmt_init();
        if(!$stmt = $conn->prepare($sql)) {
            echo '<p>SQL had an error!</p>';
        } elseif($stmt = $conn->prepare($sql)){
            $stmt->bind_param("i", $taskID);
            $stmt->execute();
            $stmt->store_result();

            $result = $stmt->get_result();

            while($row = $result->fetch()) {

                $name = $row['taskTitle'];
                $desc = $row['taskDesc'];

                //POINTS SUFFIX
                if($points == 1) {$pointsSuffix = "point";} else if($points > 1) {$pointsSuffix = "points";}

                echo('<div class="taskBox mdc-elevation--z1"><button class="material-icons taskCheck" title="Options..." onclick="markDone()">check_box_outline_blank</button><h2 class="taskName">'.$name.'</h2><p class="taskPoints">'.$points.' '.$pointsSuffix.'</p><p class="taskDesc">'.$desc.'</p><p class="taskDate">'.$date.'</p></div>');
               }    
            }
        }
    } else {
        echo '<p class="taskBox mdc-elevation--z1">No tasks for now!</p>';
    }
}

The code for the database handler:

<?php

$servername = "localhost";
$dbUsername = "root";
$dbPass = "";
$dbName = "climate_webapp";

$conn = mysqli_connect($servername, $dbUsername, $dbPass, $dbName);

if(!$conn) {
    die("Connection failed! ". mysqli_connect_error());
}

a picture of the database:

https://i.stack.imgur.com/45nhx.png




want to get data in php Dom::Xpath query after ajax call and ajax data is loaded on the site i am scraping?

i am getting data from Document Object Model query but how can i get data which is loaded through ajax while scraping through query.




Using v-for data as v-model value from object

I'm trying to add a default value to the radio button on page load. I'm looping over a json object by using v-for then trying to use the value in v-model of the radio group so that there would be a default value. For some the radio group doesn't take the v-for value. If I try to print out the current value in the v-for it works.

You'll notice that it prints out the value 3 above the radio buttons but the radio doesn't take that value 3 even though I tried to bind it with v-model

enter image description here

enter image description here




Opening my website without VS Code live server only shows a plain blank website on chrome

I have this problem that when i do not open my website through the help of VS Code, the website appears blank. Opening the main page

When opened, it shows nothing but a blank page




NGINX error - [emerg] "server" directive is not allowed here

I just installed nginx for my lab, in accidentally i deleted default file in /etc/nginx/site-available, then i copy the configuration on the internet, but it can not work with the new config, can someone help explain me what the error ?

here is the error that i got Nginx error

root@kali:/etc/nginx/sites-enabled# [emerg] "server" directive is not allowed here in /etc/nginx/sites-enabled/default:16^C
root@kali:/etc/nginx/sites-enabled# nginx -s reload
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-enabled/default:16

here is the default file in /etc/nginx/sites-available

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
            # proxy_pass http://localhost:8080;
            # proxy_http_version 1.1;
            # proxy_set_header Upgrade $http_upgrade;
            # proxy_set_header Connection 'upgrade';
            # proxy_set_header Host $host;
            # proxy_cache_bypass $http_upgrade;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
        #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}



accessing local webserver within lan/wlan from other pc/laptop/ smartphone

hi forum i built a web in my laptop and using XAMPP and able to access its page by typing example.com using the same laptop since i already set the 127.0.0.1 to example.com within vhosts.conf file and hosts in etc sub folder. but when i access it from my tablet it have to type the ip and all the url the page i want to access. for example when i access it from the laptop in which i installed the xampp i only type the example.com and was able to explore all the pages from the nav bar button but different when i access it from my tablet. i have to type the ip/example.com/public just to access the home page and the same with the others pages , for example i want to access the blog page from my tablet by clicking the blog nav button its direct me to ip/blog not example.com/blog or at least ip/example.com/blog. i already added my ip connection (wlan)within hosts file and set it to example.com also already set servername as example.com within vhosts.conf file. i am using windows 10. any one may help me how to resolve this issue. thank you




Can I revert a 301 forwarding in Godaddy?

So as a favor I was helping a colleague set up his new WP website. His old developer has started building the WP website within the same server under a different file path.

orginalwebsite.com and originalwebsite.com/wp/

Now my college wanted to forward the original website to redirect it to new wp website so he went in GoDaddy and did a domain 301 forwarding. After that was done and I told him it wasn't the right way to do things he went and deleted the forwarding.

The issue I am facing right now is that both domains don't open up anymore. Is there any way to fix this? He doesn't really care about SEO ranking at the moment, he just wants the website to be restored. I don't have a whole lot of experience on situations like this so any suggestions would be helpful.

I tried googling for any similar situations but Google only provides me articles that define what a 301 and 302 redirects are.

Thank you




How to limiting external API calls in PHP app

I have a PHP app that is overloading an external API with too many calls per minute. I need to limit it to only 20 calls a minute, but I can't seem to figure it out. I have researched the issue and found this and that, but there is a lack of proper documentation and I don't know how it would work. I understand that this is called "rate limiting", but I guess I skipped that in school.

My app is just sending cURL requests in a loop. I have several loops running in the program to gather all this information together. I could just limit the one loop with a timer for 20 per minute, but I have 17 loops running and I have loops within loops. Is it possible to just limit all the cURL requests within my PHP app with a single helper or something and not edit all my code?




Wonder how SSL certificate activated for 90 days

I found my subdomain got 90 days SSL certificate which I was not aware of. Could you please advise me on how it's possible? Issued by: Sectigo(formerly Comodo CA) -> cPanel, Inc. Certification Authority.




Hide Multiple Elements With The Same Id With JavaScript

I am trying to make a website with a control board with buttons that will toggle on or off if the target is on or not. Right now I am using an on and an off button to interfere with the target, I try to hide the button that is not "useable" if the target is off I don't want the off button to be shown, etc. I am trying to hide the button via a simple JavaScript piece, but unfortunately, it doesn't seem to be working. It only affects the button on top (I have about 18 buttons).

Thanks beforehand Best regards Max




PyQt5: Taking link to array in web browser

I have to take current link from user to an array and I use this in Back and Forward buttons.

import sys
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5 import QtNetwork
from PyQt5 import QtWebEngine
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

Links = ["https://www.google.com", "https://www.youtube.com", "https://www.facebook.com", "https://www.whatsapp.com"]

class MainWindow(QMainWindow):


    def __init__(self):
        super(MainWindow,self).__init__()

        self.browser=QWebEngineView()
        self.setCentralWidget(self.browser)
        self.adressbar=QtWidgets.QLineEdit(self)
        self.setWindowIcon(QtGui.QIcon('D:\Icons\Star.png'))
        self.browser.setUrl(QUrl('https://www.google.com'))
        self.adressbar.setGeometry(QtCore.QRect(0,0,1500,30))

        searchButton = QPushButton(self)
        searchButton.setIcon(QtGui.QIcon('D:\Icons\Search.png'))
        searchButton.setGeometry(QtCore.QRect(1500,0,30,30))
        searchButton.clicked.connect(self.search_button)

        backButton = QPushButton(self)
        backButton.setIcon(QtGui.QIcon("D:\icons\Back.png"))
        backButton.setGeometry(QtCore.QRect(1530,0,30,30))
        backButton.clicked.connect(self.back_button)

        homeButton=QPushButton(self)
        homeButton.setIcon(QtGui.QIcon("D:\icons\Home.png"))
        homeButton.setGeometry(QtCore.QRect(1560,0,30,30))
        homeButton.clicked.connect(self.home_button)

        forwardButton=QPushButton(self)
        forwardButton.setIcon(QtGui.QIcon("D:\icons\Forward.png"))
        forwardButton.setGeometry(QtCore.QRect(1590,0,30,30))
        forwardButton.clicked.connect(self.forward_button)

        youtubeButton = QPushButton(self)
        youtubeButton.setIcon(QtGui.QIcon("D:\icons\Youtube.png"))
        youtubeButton.setGeometry(QtCore.QRect(1620, 0, 30, 30))
        youtubeButton.clicked.connect(self.youtube_button)

        facebookButton = QPushButton(self)
        facebookButton.setIcon(QtGui.QIcon("D:\icons\Facebook.ico"))
        facebookButton.setGeometry(QtCore.QRect(1650, 0, 30, 30))
        facebookButton.clicked.connect(self.facebook_button)

        whatsappButton = QPushButton(self)
        whatsappButton.setIcon(QtGui.QIcon("D:\icons\Whatsapp.jpg"))
        whatsappButton.setGeometry(QtCore.QRect(1680, 0, 30, 30))
        whatsappButton.clicked.connect(self.whatsapp_button)

        self.showMaximized()

    def search_button(self):
        url = self.adressbar.text()
        self.browser.load(QtCore.QUrl(url))
        self.browser.QWebViewurl()
    def back_button(self):
        self.browser.back()
    def home_button(self):
        self.browser.setUrl(QUrl(Links[0]))
    def forward_button(self):
        self.browser.forward()
    def youtube_button(self):
        self.browser.setUrl(QUrl(Links[1]))
    def facebook_button(self):
        self.browser.setUrl(QUrl(Links[2]))
    def whatsapp_button(self):
        self.browser.setUrl(QUrl(Links[3]))

app = QApplication(sys.argv)
window=MainWindow()
window.show
sys.exit(app.exec_())

I mean when user enter facebook then google then youtube history array take this link and when user press backButton browser will enter google then facebook and if user press forwardButton when in facebook browser will enter google.

If you help me I can be happiest person in the world. Thank you




How can I repair my website project after reinstalling Windows?

Before reinstalling Windows 10 on my computer, I have backed up the Website's folder that was inside Wamp/www/ . After I've reinstalled Windows 10 and WAMP, I've copy/pasted the folder back to it's original location (the path remained the same). I've started WAMP with no issues, but when I've opened the index page and the other pages (PHP and HTML) all the CSS, JavaScript, PHP and images/videos resources were completely lost, only the HTML structure was displayed.

I've compared the latest backup with an older backup that I've found and I've noticed two things:

1) The resources and CSS files from inside the latest backup have been corrupted somehow, images/videos can't even be opened and all the CSS files, including bootstrap, are empty when opened. The file size appears unchanged though.

2) On the older version, everything is there as it should be, but the website only displays the image/video resources and not the CSS.

I've checked everything inside the HTML/PHP code and everything is where it was when it last worked. All paths remained the same, including the ones inside the "link rel=… "

PHP is installed and configured (I've tested it and it works). It's also the same version as before: 7.3.12 .

I have tried to manually recreate a page, but to no avail.

Is there a way to recover the integrity of the files of my website, or do I have to start over?




I need a PHP MVC CMS Routing Class or a small project to start with [closed]

I want to build a CMS website using PHP with MVC pattern, but I don't know how to start. Can someone give me a structured project folders or starter project with a routing class to start with, because I still have some problems, for example, I don't know when to display common views, or admin area views, etc.... Thank you!




jQuery Script to not Scroll to Top

Hi I was wondering how I would need to change this jQuery to make it NOT scroll to the top after reaching the bottom of the web page. Right now you get to the bottom and if you scroll down again it goes back to the top. How do I make it not do that and just stay at the bottom unless the user scrolls upwards?

  <script>
(function($){
  $(window).on("load",function(){

    if(!$(document).data("mPS2id")){
      console.log("Error: 'Page scroll to id' plugin not present or activated. Please run the code after plugin is loaded.");
      return;
    }

    $(document).data("mPS2idExtend",{
      selector:"._mPS2id-h",
      currentSelector:function(){
        return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight"));
      },
      input:{y:null,x:null},
      i:null,
      time:null
    }).on("scrollSection",function(e,dlt,i){
      var d=$(this).data("mPS2idExtend"),
        sel=$(d.selector);
      if(!$("html,body").is(":animated")){
        if(!i) i=d.currentSelector.call(sel);
        if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id");
      }
    }).on("keydown",function(e){ //keyboard
      var code=e.keyCode ? e.keyCode : e.which,
        keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40];
      if(code===keys[0] || code===keys[1]){
        if($($(this).data("mPS2idExtend").selector).length) e.preventDefault();
        $(this).trigger("scrollSection",(code===keys[0] ? 1 : -1));
      }
    });

    //mousewheel (https://github.com/jquery/jquery/issues/2871)
    var supportsWheel=false;
    function wheel(e){
      if (e.type == "wheel") supportsWheel = true;
        else if (supportsWheel) return;
      if($($(document).data("mPS2idExtend").selector).length) e.preventDefault();
      $(document).trigger("scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY < 0 || e.deltaX < 0) ? 1 : -1));
    };
    document.addEventListener('wheel', wheel, {passive: false}, false);
    document.addEventListener('mousewheel', wheel, {passive: false}, false);
    document.addEventListener('DOMMouseScroll', wheel, {passive: false}, false);

  });
})(jQuery);
</script>



Where would one start doing 3D in the web?

I need to do some 3D in the browser. I've got no idea where to start. Wouldn't want to lose too much time looking for an appropriate solution.

For example I have the following picture in my mind - an area with ground and no boundaries one can move in in all directions, using keyboard and mouse, including up and down, filled with seaweed like plants growing up from the floor slightly swaying, joints on them should be interactive.

Would be grateful if you could orient me in the right direction.




A music player. A few audio files

I make a music player. I don't know what to do to play some music files. I would like an audio player in separate divs, if I click.play, another music file will be played. More precisely, if I click button.play in the first div audio-player, the music file music.mp3 is played, and if I click button.play in the second div audio-player, the music file music1.mp3 is played. Here's my code.

    <div class="audio-player">
        <audio src="music.mp3"></audio>
        <button class="play" autofocus>play</button>
        <div class="seek-bar">
            <div class="fill"><div class="handle"></div></div>
        </div>
    </div>
    <div class="audio-player">
        <audio src="music.mp3"></audio>
        <button class="play" autofocus>play</button>
        <div class="seek-bar">
            <div class="fill"><div class="handle"></div></div>
        </div>
    </div>
var audio = document.querySelector('audio');
var playBtn = document.querySelector('button.play');
var seekBar = document.querySelector('.seek-bar');
var fillBar = seekBar.querySelector('.fill');

var pointerdown = false;

playBtn.addEventListener('click', function(){
    if (audio.paused) {
        audio.play();
    } else {
        audio.pause();
    }
});

audio.addEventListener('timeupdate', function(){
    if(pointerdown) return;

    var p = audio.currentTime / audio.duration;

    fillBar.style.width = p * 100 + '%';
});

function clamp (min, val, max) {
    return Math.min(Math.max(min, val), max);
}

function getP (e) {
    var p = (e.clientX - seekBar.offsetLeft) / seekBar.clientWidth;
    p = clamp(0, p, 1);

    return p;
}

seekBar.addEventListener('pointerdown', function(e){
    pointerdown = true;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';
});

window.addEventListener('pointermove', function(e){
    if(!pointerdown) return;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';
});
window.addEventListener('pointerup', function(e){
    if(!pointerdown) return;

    pointerdown = false;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';

    audio.currentTime = p * audio.duration;
});



How do I emulate JavaScript console on website? [closed]

I am developing Learn-To-Code website which has JavaScript lessons. How do I execute code entered by user in textarea and validate it and also show its output to another readonly textarea?




what is best practices when you have big info on the same page? and What about using a wizard to split the page's content in multi steps? UX

what is best practices when you have big info on the same page? and What about using a wizard to split the page's content in multi steps? from UI UX perspectives




Golang http.handlefunc always match "/"

Code:

http.HandleFunc("/", api.Index)
http.HandleFunc("/list", api.FileList)

http.HandleFunc("/api/upload", api.UploadFile)
http.HandleFunc("/api/delete", api.DeleteFile)

http.Handle("/files", http.StripPrefix("/files/", http.FileServer(http.Dir(settings.FilesPath))))

http.ListenAndServe(":1234", nil)

Result 1:

http://localhost:1234/

http://localhost:1234/list

http://localhost:1234/files

match "/"

api.index (it's wrong for the second and third)

Result 2:

http://localhost:1234/api/upload

http://localhost:1234/api/delete

match "/api/xxx"

api.xxx (it's right)

env:

go 1.13.5 windows/amd64

What should I do to fix this problem?

Thanks very much




dimanche 29 décembre 2019

Laravel allow only one session per user

I am trying to allow only one session per user. So if someone tries to log in when he already logged in his user account, the user is not allowed to login. The second user can login only when the first user logged out from his account. help please




The user-agent field cannot appear in the request header of a python crawler

I want to write a crawler script, but the web side of the User restrictions, can not carry the user-agent field, this kind of how to do?And user-agent cannot be null,The user-agent field cannot appear in the request header.




Convert youtube videos to mp3 [closed]

First of all, I know it is irrelevant to put that question in that platform but I hope someone would respond positively. I was using ytmp3 converter to convert youtube videos but I wanna switch to other good websites except "flvto" or "Zamzar". So, it would be helpful if someone suggests a good website. Though, I know this is not a right platform for it but anyway.




How can I code all functionalities of the right-click menu

I've my code for a custom right-click menu, HTML:

<div class="EnderPage--Menu">
  <div action="RTPC">Reload</div>
  <!--<div action="DBASC">Cast</div>-->
  <div action="DBASP">Print</div>
  <div action="VPS">View page source</div>
  <!--<div action="EDT">EnderDevelopers Tools</div>-->
</div>

JS:

  $(document).bind("contextmenu",function(event){
    event.preventDefault();
    if(!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))){
      $(".EnderPage--Menu").finish().toggle(100).css({top:event.pageY+"px",left:event.pageX+"px"});
    }
  });
  $(document).bind("mousedown",function(e){
    if (!$(e.target).parents(".EnderPage--Menu").length>0){
      $(".EnderPage--Menu").hide(100);
    }
  });
  $(".EnderPage--Menu div").click(function(){
    $(document).on('keydown', function(event) {
      if(event.key == "Escape"){
        $(".EnderPage--Menu").hide(100);
      }
    });
    $(".EnderPage--Menu").hide(100);
    var EnderMenuACTION = $(this).attr("action");
    if(EnderMenuACTION == "RTPC"){
      RunURL(window["TheCurrentContent"]);
    }
    if(EnderMenuACTION == "DBASC"){//failed
      //cast.framework.CastReceiverContext.getInstance().start();
    }
    if(EnderMenuACTION == "DBASP"){
      setTimeout(function(){
        window.print();
      }, 100);
    }
    if(EnderMenuACTION == "VPS"){
      var source = '<!DOCTYPE html>\n<html itemscope="" itemtype="http://schema.org/WebPage" lang="en-US">\n';
      source += document.getElementsByTagName('html')[0].innerHTML;
      source += "\n</html>";
      source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;");
      source = "<pre>"+source+"</pre>";
      sourceWindow = window.open('','_blank');
      sourceWindow.document.write(source);
      sourceWindow.document.close();
      if(window.focus) sourceWindow.focus();
    }
    if(EnderMenuACTION == "EDT"){
      //I don't know how to code that!
    }
  });

CSS:

.EnderSelect--Menu div{
  padding: 10px;
  margin: 8px;
  border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
  border-radius: 100px;
  user-select: none;
}
.EnderSelect--Menu div:hover{
  background-color: var(--EnderSelect-HoverColor);
}
.EnderSelect-selected{
  background-color: var(--EnderSelect-HoverColor2);
}
.EnderSelect--Menu *{
  padding: 0px;
}
.EnderPage--Menu {/* Add a mobile version in full-screen */
  position: fixed;
  z-index: 99999999999;
  background-color: var(--EnderBar-BackgroundColor);
  border: 2px solid var(--EnderBar-BorderColor);
  border-radius: 15px;
  -webkit-box-shadow: 0px 2px 20px 2px var(--EnderBar-ShadowBoxColor);
  -moz-box-shadow: 0px 2px 20px 2px var(--EnderBar-ShadowBoxColor);
  box-shadow: 0px 2px 20px 2px var(--EnderBar-ShadowBoxColor),  0px 0px 0px 4px var(--EnderBar-ShadowColor);
  height: fit-content;
  width: fit-content;
  max-height: 60vh;
  color: var(--EnderBar-TextColor);
  overflow: hidden;
  content: none;
  display:none;
}
.EnderPage--Menu div {
  padding: 14px 10px;
  transition: all 0.1s ease-in;
  user-select: none;
}
.EnderPage--Menu div:hover {
  background-color: var(--EnderSelect-HoverColor);
}

I want to code all of the normal right-click menu functionalities in my own custom menu, But I don't seem to be able to get any code to open the developer console, to cast my website content, or to save the current opened page code in a file for the user. Are these things possible to code in JavaScript/jQuery or what?




Trying to populate list box with sql (php)

I am trying to populate a list box with data from a mysql databse.




Divi blog pagination not loading previous posts on Wordpress

In the divi editor builder, the "Older Entries" posts works loading six posts through pagination, but not on my published website: https://thezross.com/blog/

Any thoughts as to what the issue is?




Thymeleaf Dynamic Image

I have a SpringBoot application where the user can store a profile picture, save an image in C: / imgPerfil / concatenating or user id + the original image name, for example: "2teste.jpeg", I need to show this image in front using thymeleaf how to do this? The Path is saved inside the Object used in the variable photo, it is also displayed in the data by Ajax.`

var nome; var foto; $.ajax({ url: '/getPerfil', type: 'GET', success: function (perfil) { nome = perfil[0].nome; foto = perfil[0].foto; console.log(perfil[0]); $("#nomeUsuario").text(nome); $("fotoUsuario").attr('src', foto); } });

How to display this image?`




React - applying css via className to imported Component

I'm new to react and I have a quick question about styling imported components. I made a basic Title component that simply outputs the props passed. My Title.js file:

import React from 'react';
import '../App.css'

class Title extends React.Component{
    render(){
        return <h1>{this.props.prop}</h1>
    }
}

export default Title

I'm using it in my App.js file and trying to style it via a className

import React from 'react';
import Title from './components/Title'
import './App.css';

function App() {
  return (    
      <Title className = 'title' prop = 'Title!'/>    
  );
}

export default App;

my css:

.title{
  background-color: rgba(255, 0, 0, 0.2);
  text-align: center;
  margin-top: 100px;
  padding: 20px;
  border: solid black; 
}

This does not works, even if I apply an inline style to the Title tag. However it does works when I apply the className to the h1 tag within the Title.js file. Is it because everything written within the Title tag is just passed as a prop? If that's true how are third-party library components styled? Any help is much appreciated!




Scrape dynamic Website where content is loaded as you scroll. Python

I dont know the right term but I think "dynamic website" might do the trick.
By that I mean that as I scroll, resources are being loaded. I searched for solutions and I came across webdrivers, personally I dont like a whole browser being loaded, just for the purpose of scrolling down.
A different approach would be looking at the network tab and scraping the url, that I find there.

https://www.immowelt.de/liste/hamburg/wohnungen/mieten?prima=700&sort=relevanz&cp=1

However the content really gets loaded as I scroll.

the link that gets shown when I open the network tab and scroll down: https://www.immowelt.de/liste/getlistitems

Im new to web development so I dont get how these links that I see in the network tab can be named exactly identical but hold different values.




Hebrew TTS and speech recognition for web (javascript)

As part of my project I'm developing a web and I want to make the pages accessible for blind people, that's why I need to use TTS and speech recognition services with javascript.

I'm searching for TTS that works with Hebrew. I tried SpeechSynthesis but I didn't found any reference to Hebrew, the same thing happened with ResponsiveVoice.JS. The only option I found work with Hebrew is Google Cloud but this API doesn't work with javascript...

Is there any TTS api that knows Hebrew or legal way to import google Hebrew TTS with javascript for my web application?




Unable to set OS for Nodejs Library Compilex

I am using Compilex library of nodejs to build an online judge. I am using Ubuntu and installed the library using npm install compilex. By default the OS is set to be Windows inside the server.js file of the demo webpage( which is provided upon installing compilex).

(Source: Documentation of Compilex)

//if windows  
var envData = { OS : "windows" , cmd : "g++"}; // (uses g++ command to compile )
//else
var envData = { OS : "linux" , cmd : "gcc" }; // ( uses gcc command to compile )
compiler.compileCPP(envData , code , function (data) {
    res.send(data);
    //data.error = error message 
    //data.output = output value
});

Basically upon starting the server the library creates a temp folder and all the input data and executable files are stored in it. The hosting machine must contain the required compilers. I tried changing it from "windows" to "linux"(inside the server.js file) but it doesn't work. Even upon changing, the temp folder has .exe files.

How do I resolve this?




Complex electron apps without front end frameworks?

can we make really complex electron apps without using front end frameworks? frameworks like react and angular are particularly good, but I've used it and found it difficult to access the native node modules that make the purpose of electron futile.




Web Crypto API without ssl

I wrote a little webapp for secure message transfer to learn more about encryption, and wanted to show it to my friends and let them play with it a little, so I hosted it on my little server, and was shocked to find that the Web Crypto API (which I worked my ass off to get to work because it is not very specific in its error messages) REQUIRES SSL ( kinda defeats the purpouse of implementing your own encryption scheme in browsers)!

I already have another API running on that server with SSL, but instead of merging them I wanted to ask: Is there a way to circumvent the secure socket requirement of Web Crypto API, or is there another library out there which allows me to use the same or similar functions in a non-secure context?




Python - Scrapy - Navigating through a website

I´m trying to use scrapy to log into a website, then navigate within than website, and eventully download data from it. Currently I´m stuck in the middle of the navigation part. Here are the things I looked into to solve the problem on my own.

  1. Datacamp course on Scrapy
  2. https://www.youtube.com/watch?v=G9Nni6G-iOc
  3. http://scrapingauthority.com/2016/11/22/scrapy-login/
  4. https://www.tutorialspoint.com/scrapy/scrapy_following_links.htm
  5. Relative url to absolute url scrapy

However, I do not seem to connect the dots.

Below is the code I currently use. I manage to login (when I call the "open_in_browser" function, I see that I´m logged in). I also manage to "click" on the first button on the website in the "parse2" part (If I call "open_in_browser" after parse 2, I see that the navigation bar at the top of the website has gone one level deeper.

The main problem is now in the "parse3" part as I cannot navigate another level deeper (Or maybe I can but the "open_in_browser" does not open the webiste anymore, only if I put it after parse or parse 2). My understanding is that I put multiple "parse-functions" after another to navigate through the website. Datacamp says I always need to start with a "start request function" which is what I tried but within the youtube videos etc. I saw evidence that most start directly with parse functions. Using "inspect" on the website for parse 3, I see that this time href is a relative link and I used different methods (See source 5) to navigate to it as I thought this might be the source of error. Right now, I have run out of ideas what it could be which is why I ended up here :)

Thanks in advance for any help or tips.

import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser
from scrapy.crawler import CrawlerProcess


class LoginNeedScraper(scrapy.Spider):
    name = "login"
    start_urls = ["<some website>"]

    def parse(self, response):
        loginTicket = response.xpath('/html/body/section/div/div/div/div[2]/form/div[3]/input[1]/@value').extract_first()
        execution = response.xpath('/html/body/section/div/div/div/div[2]/form/div[3]/input[2]/@value').extract_first()
        return FormRequest.from_response(response, formdata={
                                                   'loginTicket': loginTicket,
                                                   'execution': execution,
                                                   'username': '<someusername>', 
                                                   'password': '<somepassword>'},
                                         callback=self.parse2)

    def parse2(self, response):
        next_page_url = response.xpath('/html/body/nav/div[2]/ul/li/a/@href').extract_first()
        yield scrapy.Request(url=next_page_url, callback=self.parse3)

    def parse3(self, response):
        next_page_url_2 = response.xpath('/html//div[@class = "headerPanel"]/div[3]/a/@href').extract_first()
        absolute_url = response.urljoin(next_page_url_2)
        yield scrapy.Request(url=absolute_url, callback=self.start_scraping)

    def start_scraping(self, response):
        open_in_browser(response)

process = CrawlerProcess()
process.crawl(LoginNeedScraper)
process.start() 



How do I avoid redirection after Ajax failed request?

I have the following Ajax request that is supposed to retrieve some data to insert inside a div:

$.ajax({
    url: "work/mywork.php",
    data: { data_string: JSON.stringify({pages_count: 2, page: 1}) },
    method: "GET",
    complete: function (response) {
        $("#slider").append(response.responseText);
        $("#slider").css({width:(2*100)+'%'});
        register_visualizers();
        pages_count = 2;
        low_end = 0;
        high_end = 1;
    },
    error: function(jqHXR,textStatus,errorThrown){
        console.log(errorThrown);
    }
});

But if it somehow fails to retrieve such data, it redirects me to work/mywork.php. I believe it has something to do with headers, but I don't know how to avoid such header being set or if It's something completly different.

I would appreciate some insight on this, I've already search the web for about 2 days and I coulnd't find anything usefull.

Thanks in advance.




/public folder doesn't load when run on localhost

I just cloned a repo of a completely functional website from GitLab and when I try to run it on my local using npm start, on my localhost, the browser cannot load images, CSS and JS files of the project. I just see the HTML framework. Need help urgently. I'm using ejs.




WCAG - How to make the screen reader read all the page automatically?

I need to have a screen in my app which all of it's content will be read using the screen reader automatically.

I tried to add role="dialog" aria-live="assertive" aria-atomic="true" and it didn't make it.

I also tried to use role="alert" aria-live="assertive" aria-atomic="true" it did read it, but using 'alert' as prefix.

How can I make it happened using no prefixes and additional info ?




JPA, nativeQuery The value is shown above

The code below is repository

 @Query
                (
                        value = "select min(id) as id, coalesce (sum(case when points > 0 then points end), 0) as points, userid" +
                                " from books" +
                                " where userid = ?1" +
                                " group by userid", nativeQuery = true
                )
        JamInfo findPlus(Long userid);

    @Query
            (
                    value = "select min(id) as id, coalesce(sum(case when points < 0 then points*-1 end),0)as points, userid" +
                            " from books" +
                            " where userid = ?1" +
                            " group by userid", nativeQuery = true
            )
    JamInfo findMinus(Long userid);

The code below is controller

JamInfo jamplus = jamInfoRepository.findPlus(id);
JamInfo jamminus = jamInfoRepository.findMinus(id);
model.addAttribute("jamplus", jamplus);
model.addAttribute("jamminus", jamminus);

If you print it like this, it will be unified with the value of jamplus written first. How can the two values ​​be output differently?




Is there any way for me to use my Web Hosting service to run my Python Script

I just made a discord bot for my friends discord server and I was wondering if there was any way for me to use my Web Hosting service Infinityfree.net to host and run the bot. And if so is there also a way to install python packages. I'd very much appreciate it if someone could help me out.




samedi 28 décembre 2019

Configuring Cookie in IIS 8.5

Is it possible to set a cookie in IIS?

Assuming a web system that provides web document edit; clients use installed MS Office applications and open an office file in the IIS folder via HTTP as WebDAV, Office sends OPTIONS/HEAD requests to the WebDAV folder.

This authentication can be processed by BASIC/NTLM. When the authentication finished successfully, I would like to do set-cookie.




Updating Google Maps Long/Lat

I am trying to update a store location by getting the lat/long of a marker on the google map. However I get this error:

UpdateStoreDAO.js:7 Uncaught TypeError: Cannot read property 'getPosition' of undefined
    at updateItemData (UpdateStoreDAO.js:7)
    at UpdateStore.js:68
    at IDBOpenDBRequest.request.onsuccess (indexedDB.js:38)

I'm not quite sure why it won't work as getPosition works for adding a store location to the map for a marker. It uses the same Google Maps API as my adding page does and the add page never threw me this error.

The code for the update function (DAO) is:

function updateItemData(marker) {
    //User input of item name
    var storeLocation = $('#txtStoreLocation').val();
    //Get latitude and longitude of current marker position
    var eventLat = marker.getPosition().lat();
    var eventLng = marker.getPosition().lng();

    //Create an item object combining name, desc and price attributes
    data.storeLocation = storeLocation;
    data.eventLat = eventLat;
    data.eventLng = eventLng;

    var data = {
        'storeLocation' : storeLocation,
        'eventLat' : eventLat,
        'eventLng' : eventLng
    }

    //Insert data into indexedDB database
    updateOne(data, function(lastID) {
        event.preventDefault();
        return false;
    });
}

The code for the update store js file is (if it's any help):

//mapCenter 
var mapCenter = new google.maps.LatLng(51.8979988098144,-2.0838599205017);
//geocoder will be used to convert geographic coordinates (current marker position)
// intop a human-readable address
var geocoder = new google.maps.Geocoder();
//An InfoWindow displays content (usually text or images)
//in a popup window above the map, at a given location.
var infowindow = new google.maps.InfoWindow();

function initialize(){
    // Initial map properties
    var mapOptions = {
        zoom: 15,
        center: mapCenter
    };

    //Create a map object passing the html div placeholder to hold google map
    myMap = new google.maps.Map(document.getElementById("mapInput"), mapOptions);

    //Create a draggable marker icon in the map
    marker = new google.maps.Marker({
        map: myMap,
        position: mapCenter,
        draggable: true
    });
}

//Retrieve Item information saved in database 
//show in the form
var urlParams = new URLSearchParams(window.location.search);
var itemID = urlParams.get('itemID');
$('#itemID').html("Item ID: " + itemID);

setDatabaseName('dbCatalogue', ['UsersObjectStore', 'ItemsObjectStore']);
setCurrObjectStoreName('ItemsObjectStore');
//Select One function to retrieve data of a specific item
var data;
startDB(function () {
    selectOne(itemID, function(result) {
        $('#txtStoreLocation').val(result.storeLocation);
        $('#txtEventLat').val(result.eventLat);
        $('#txtEventLng').val(result.eventLng);
        data = result;
    })
})



//The addDomListener will be triggered when the HTML page is loaded
//and will execture the initialize function above
google.maps.event.addDomListener(window, 'load', initialize);

//Event handler for form submit button
$('#formUpdateStore').submit(function(event){

    // cancels the deafult form submission and handle the event from javascript
    event.preventDefault();

    //Create an idexedDB database (the name of the database is dbFlogger) 
    // with two object stores - UsersObjectStore to store user data 
    // and ItemsObjectStore to store item data
    setDatabaseName('dbEvent', ['EventObjStore']);
    // For this example, we will store data in ItemsObjectStore
    setCurrObjectStoreName('EventObjStore');
    //startDB will create a connection with the database and
    //execute operations such as save item
    startDB(function () {
        updateItemData(data);
        alert("Store has been updated successfully!");
    });
});

I understand it's probably a lot to ask but any help would be appreciated!




how to do HTML google multilevel entry?

I wanted to ask a maybe dumb question but how do you guys set up an html website to look like this when searched on google?

Ive tried adding anchor tags to the meta tags, yes maybe quite dumb idea , well it didn't work, does anybody know how to? Thank you in advance

enter image description here




Django- using same html template for the same purpose but for different users- blog web

I'm working on a blog web app and I want to know if there is a way to make 1 html template called blog.html for example that its content is different for each user who made it? Like if I have 200 users who create a blog in my web app and I dont want to make for each of them a special template.. I mean I want every one to have his unique blog but using the same blog.html template and then I can direct to their own unique blog using different end to the path.. and i'll take that end from the model field of the user..

like I can iterate through user.name model field and set it as the end path.. like in the ListView.. and I want each end path will direct to the specific blog using the same html template but dynamicly.

Anyway thanks for helping and if there is some one who build web apps with Django and want to work together with me, ill glad to :)

Hope you understand my intention.




Website load in slowly and is taking too much time to open [closed]

From the last 10 days, my website occurred a loading problem.

  • Sometimes it loads in just a second (and works normally).
  • Sometimes it takes too much time.
  • Sometimes it don't load at all.

I've tried:

  • To upload a blank HTML-page and opened it in the webbrowser, but the result stays the same.
  • To asked my hosting admin about the problem, but he replied that the servers are running smooth and that there should be no problems. He said that the problem depends on the contents on my pages/files.

Although, the contents on my index page are the same as before and worked well before this problem.

If you know what could cause this problem, feel free to tell me! :)

Link to my website: https://www.learninghints.com




Tomcat Servlet, added a new image into /web/images folder, but /out/artifacts folder not updated when redeployed

I was trying to put a new image onto my jsp page, so I added a new image into the /web/images/ folder:anran-profile.png is the image added, and the image path is supposed to be used by a jsp. However, after I redeployed the servlet, the image did not show up, and when I checked the /out/artifacts/images/ folder, I found that the image was not in there either. the profile.jpg was an old image, and anran-profile.png did not appear here after redeployed. If I manually copy and paste anran-profile.png into /out/artifacts/images folder, the image shows up successfully. This seems to mean the browser is looking at the right place but the servlet did not put up the required image in time. Can anyone tell me why the redeploy did not update the images folder, and how can I solve it?




How do I implement zoom.js to turn.js?

The result should be as follows:

If I click on a random page of my turn.js magazine, it should zoom in and zoom out of the page. The best example how I imagine it is here




Cors problems when developing 2 different projects on a local machine

I am working on two different projects. One is the back end in NodeJS and the other one is front end in VueJS. VueJS project is configured in a way that it starts a local development server with hot reload. Everything works fine for a few API calls but then I get CORS problems because front end on port 8080 can't access the back end on port 8888.

I use Mozilla Firefox browser for development purposes.

What can be done to resolve the issue? I have only problems while developing.




Web scraping with Scrapy / BeautifulSoup -- Authentification required

I am logged in into a webpage with required authentification, however, if I try to web scrape the content, I'm just getting the HTML content of the login page. I tried to use basic authentification inside the scrapy shell like:

from w3lib.http import basic_auth_header
from scrapy import Request

auth = basic_auth_header(your_user, your_password)
req = Request(url="http://example.com", headers={'Authorization': auth})
fetch(req)

It did not work. I'll be still redirected to the login page. I can fully inspect the HTML content if I do it manually, but I'm not able to automate this. Any ideas? Maybe I need the CSRF token? I should note, that I'm a beginner and have not that much knowledge. I could miss something very obvious / important.




What library or open source tool should I use to add a panel documentation to a web application?

I’m developing a web application, it’s like survey app(step by step) where the user answer questions and at the end he get a result.

For some questions I’d like to add like a Panel Help or Panel documentation triggered on demand for the user. The documentation is to clarify the user how to respond the question




can't bind model on web api post

I can't bind list of string to my model.

My model:

    public class EditUserForm
    {
        [BindProperty]
        public string Id { get; set; }
        [BindProperty]
        public string Username { get; set; }
        [BindProperty]
        public string Email { get; set; }

        public List<string> ActualUserRoles { get; set; }

        public EditUserForm(IdentityUser user)
        {
            Id = user.Id;
            Username = user.UserName;
            Email = user.Email;
        }
        public EditUserForm()
        {

        }

    }

In view I have connected with ActualUserRoles field html code as below:

<div>
   <label for="user-actual-roles" class="control-label">Actual user roles:</label>
   <select asp-for="ActualUserRoles" multiple class="form-control text-center h-75" id="user-actual-roles">
   </select>
</div>

From jQuery AJAX I add dynamically (after page load) options to make it async.

But after I send form with it to controller like below:

        [HttpPost]
        [Route("Edit/{userId}")]
        public async Task<IActionResult> Edit(string userId, EditUserForm editUserForm)
        {
            //here editUserForm.ActualUserRoles is null, but anoter field like Email has proper value
            return View("some-view.cshtml", editUserForm);
        }

I'm using ASP.NET Core 2.2.7

Please help




What to use for building website with a lot of user input

I have built a couple of websites using Bootstrap and PHP. Running my own webshop using this and is good enough for me. This is very time consuming because everything needs to be coded by hand. I have received a request to create a website for registration of events. People need to be able to register with these events and the staff needs to be able to record and save what people consume. So it needs a lot of user input. Now if i would use the Bootstrap PHP way this will take a long time. What is an easier and better way of creating this kind of website? Looking into Node.js but im interested in what other ways are out there.

Thanks in advance!




How to include/require a portion of text from a file?

Each page of my website has a related famous quote before the footer. I would like to write all quotes in a html/txt/php file and from there include the relevant one on each page. When trying to use require or include, it doesn't work because they are designed to call the contents of a whole file, not just a portion of it. How can I accomplish this?




How to get html form data in android without using any database?

I build a login page using html and using form elements i put a text field for name and phone number i want to access the name and phone number in my android application but i don't know how so please could you help?




Combining a mobile application with your php website to send automated sms? [closed]

I’ve been learning about web development and one of my colleagues asked me if I could send sms from my website upon user registration. I thought of APIs but those are expensive and for business users and I want something that I can use for myself, something I could use personally and work on. I thought of an idea that maybe it’d be possible to first build an android app and then connect it to my website and whenever a user registers, it could directly send the message to my app and then the app could send the message as sms from the mobile phone. Is it possible, if yes. Could someone guide me to the right direction?




User friendly Web UI MongoDB

I am looking for a web interface to search for mongodb records. It should not use queries. Instead it should use a simple search.

For example a record has a column called "Name" and the name is "Thomas Anderson". In the search you should select the column and search for "ander".

Is anything like this existing?




How to fill table with Dropdown select?

I need a Project for school based on PHP and HTML with integration of SQL DB. We've got a DB with 2 tables: The first table contains shopId and shopName e.g.

shopId       shopName
1            McDonald's
2            Burger King
3            KFC

and the 2nd table contains productId, prodName, price and shopId from above:

prodId       prodName        price        shopId
1            BigMac          2$           1
2            Whopper         3$           2
3            Long Chicken    3$           2
4            Hot Wings       5$           3

Now I've created a HTML select/dropdown and filled it with the shopName. What should happen is: When I select a shop from the Dropdown, a HTML table below should fill up with the products which are available in the respective shop.

I hope someone could help me with that! I'm pretty new to PHP but our group doesn't care about that..




Cut between sections | CSS

Hello everyone I'm trying to create this cut between sections with css but I can't, I would appreciate any help or ideas to solve this. They are two sections with background-image and in the middle of them is wedge with a solid edge.

help img




How can i automate a expedia search with puppeteer

  1. This is the code to automate expedia search
async function run() {
  const browser = await puppeteer.launch({ headless: false }); //Launch browser
    // Open a new page and navigate to google.com
  const page = await browser.newPage(); //open a tab 
  await page.goto('https://www.expedia.com');  //Navigate to website URL
  const waitForLoad = new Promise(resolve => page.on('load', () => resolve()));
  await page.evaluate(() => {
  document.querySelector('#aria-option-1 > div > div.multiLineDisplay.details').click();
  });
  await waitForLoad;

}
  1. Thank you fo help !!



How can I show a loading animation in Django while the server is processing a view?

So I'm currently working on a Django project that has a view that takes quite a bit of time to load and it can be rather user unfriendly to keep the user wondering what's wrong with the website until the page loads.

My website works in way such that the user would have a url such as:

http://www.example.com/Name/JohnRichards

Saved to their bookmarks. Upon visiting the above URL the server should display a loading message (probably with a GIF and AJAX or JS) of a loading screen until the server finishes loading data and then display it.

Note: Just in case it matters, when he user goes to the above mentioned link, they won't be redirected there, rather, this would be their entry point since it's a url that they have saved in their bookmarks

What I thought would work is returning some sort of a loading template of sorts as soon as somebody visits the page, and then after the data processing has finished, I would return the final response. But I can't have two returns in a function.

The following is my urls.py file:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.index, name='index'),
    path('Name/'+'<str:Name>', views.NameInLink, name='NameInLink'),
]

And the following is my views.py file

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import NameForm
from . import DataProcessor
import time

def NameInLink(request, Name):
    UserData = DataProcessor.process(Name)
    return render(request, "UserData.html", {"UserData": UserData})

How could I add a loading screen of sorts between user using visiting the URL and the data processing finishing?




firewatch Parallax effect with another div above with content

I'm struggling to find a way to set the parallax effect with the mountains... on the top of the page and the div with the content of the website below it. I have tried with z-index and position but I haven't reached it.

Thanks for your replies.

<div id="parallax">
<img class="scene" data-modifier="30" src="https://s.electerious.com/parallaxscene/p0.png">
<img class="scene" data-modifier="18" src="https://s.electerious.com/parallaxscene/p1.png">
<img class="scene" data-modifier="12" src="https://s.electerious.com/parallaxscene/p2.png">
<img class="scene" data-modifier="8" src="https://s.electerious.com/parallaxscene/p3.png">
<img class="scene" data-modifier="6" src="https://s.electerious.com/parallaxscene/p4.png">
<img class="scene" data-modifier="0" src="https://s.electerious.com/parallaxscene/p6.png">
</div>
<div id="test">
    <font color="red">This is some text!asdfasd</font>
</div>

document.querySelectorAll('.scene').forEach((elem) => {

    const modifier = elem.getAttribute('data-modifier')

    basicScroll.create({
        elem: elem,
        from: 0,
        to: 519,
        direct: true,
        props: {
            '--translateY': {
                from: '0',
                to: `${ 10 * modifier }px`
            }
        }
    }).start()

})

body {
    height: 2000px;
    background: black;
}

.scene {
    position: absolute;
    width: 100%;
    transform: translateY(var(--translateY));
    will-change: transform;
}

https://jsfiddle.net/ufcqw2xh/




Cookie without SameSite Attribute

When I scanned a Particular web app using ZAP it displays mentioning the site has "Cookie without SameSite Attribute" I read that we can perform CSRF attack for this vulnerability. Can anyone explain to me how to do that?.




What are the most used technologies to create a website? [closed]

I would like to know what are the most used technologies for creating websites / web applications, I had remained with the use of Angular but I would like to be informed, thanks




vendredi 27 décembre 2019

Any more efficent ways to scrap JB HI-FI? This basically takes an entire day

My code is below. It takes around 10 secondes to search 1 website. I'm basically searching Jb HI-FI from a to z and pages 1 to 200. Then I'm saving the data into a list with the title of the item (eg. a TV) and it's respective price.

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup
import time

name = []
price = []

alpha = ['a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y']


for alphabet in alpha:
    for i in range(1, 200):

        url = 'https://www.jbhifi.com.au/?q=' + alphabet + '&hPP=36&idx=shopify_products&p=' + str(i)
        print(url)


        options = Options()
        options.add_argument('--headless')

        driver = webdriver.Firefox(options=options)
        driver.get(url)

        soup = BeautifulSoup(driver.page_source, 'lxml')

        ii = 0

        for item in soup.findAll("h4", {'class': 'ais-hit--title product-tile__title'}):
            ii = ii + 1
            name.append(item.get_text(strip=True))

        for item in soup.findAll(["span"], {'class': ['ais-hit--price price', 'sale']}, limit = ii):
            price.append(item.get_text(strip=True))

        driver.close()




It is possible to just use QT and WebAssembly (instead of HTML + CSS + JavaScript) to develop a front-end web?

I am a C++ programmer, but for some reason, I have to develop a website by myself(My own commercial project). I don't want to take a lot of time to study JavaScript and something else. It is possible to just use QT and WebAssembly (instead of HTML + CSS + JavaScript) to develop a front-end web?




Can the Signal protocol be used at own social networks? [closed]

I am a huge fan of www.signal.org and its excellent software. I actually now feel safe after some years with Facebook, disturbing my night sleep...

Just then I am wondering if it's possible to buy, or install/integrate the actual Signal Protocol and software so we can create our own safe messaging both at future social networks, and then also making a Messenger app, just like the excellent Signal app? (Facebook, WhatsApp, etc.)




How to connect Python code that relies on CSV data to a website?

I'm building a data analysis tool that I plan to turn into web format.

Currently, I have a massive CSV file that I have compiled and a large python script that uses this CSV file to analyze the data and output results.

What would be the most efficient way to port this to a web format? I was thinking about using Flask, but I'm not sure how to include the CSV file as a part of the website's code.

Appreciate any advice or insight!




ThenInclude with many to many in EF Core

I have the following tables:

public class ParentEntity
  {
    public long Id { get; set; }

    [ForeignKey("ParentId")]
    public List<PersonEntity> Persons { get; set; }
  }
public class PersonEntity
  {
    public long Id { get; set; }

    public long ParentId { get; set; }

    [ForeignKey("PersonId")]
    public List<FriendEntity> Friends { get; set; }
  }
public class FriendEntity
  {
    public long PersonId { get; set; }

    public long FriendId { get; set; }

    [ForeignKey("FriendId")]
    public PersonEntity Friend { get; set; }
  }

The Friend table is a many-to-many relationship between two rows of the Person table.

I want to get all parents with all persons and all their friends, which would look like this:

var entities = context.Parents
        .AsNoTracking()
        .Include(c => c.Persons)
        .ThenInclude(i => i.Friends)
        .ToList();

However this does not get the data from the Friends table.

If I inlcude the friends in a person query without the parent it works:

var entities = context.Persons
        .AsNoTracking()
        .Include(i => i.Friends)
        .ToList();

How can I make the first query to retrieve the firends of a person as well and what is causing this behavior?




What to put on my personal website as a software developer looking for a new job?

I'm a backend software developer and will shortly be looking to change jobs to a different company. I haven't started any applications yet, but I will be in the next month or so.

I have my own domain name (which uses my first and last name). I only really use this for Google Mail and so there's nothing on the website at the moment.

I'd like to put something on the domain website which will help me with my new job search. My criteria are:

  1. Can't be anything too personal - a lot of people can work out the website from my email address and I don't want them to have details that they wouldn't normally have. So having an online version of my CV is a big no no.
  2. I don't have any personal software development projects - Unfortunately I have nothing to present as a portfolio demo and nothing that I could knock up within my timescales. I also don't have anything noteworthy on my GitHub profile either.
  3. Forwarding to LinkedIn profile - seems a bit lazy but perhaps an absolute last resort usage if I can't think of anything else.
  4. Max few days to set up - I can probably spend a maximum of a couple of days to focus on it, so anything substantially more than this won't work for the immediate use.

Are suggestions that work with the above requirements?

Thanks in advance




how to embed online compiler to website and give the user grade base on his code(like in codility)?

I want to build a website that contains a programming question and an editor so that the user can enter his code and based on some test cases the user will get grade, I would love to get direction on how to implement it right. I looked for API's and found paid products like Sphere-Engine or ones that didn't work already like HackerRank API but I couldn't find any working API. Just to make it clear I don't need the output of the code I need to run some test case on the code and then to give a grade for those who succeed like in (Codility). Are there any API's I can use ? or tool that I can embed to my website ?




Constructor restrictions for Custom Elements in Web Components

In the W3C custom elements spec, it is mentioned that within the Custom element constructor:

The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods.

I am finding it difficult to understand what expectations are we violating. My initial guess was that using createElement to create a custom element does not invoke the Constructor behind the scenes, but that does not seem to be the case based on a proof of concept which I did.




Is there a way to access all the files used to get to a certain page on a website? [closed]

So, I'm working on a webshop and want to know all the files that are used to get to a certain page on that website. That includes different php files used for price filters, color filters, category filters, etc. I know there's a get_included_files() function, but some scripts generate URLs that are accessed as well during the 'journey' from one page to the other and I'd like to see those as well.

Maybe there's a way to set a starting point and record all the pages that are being visited? So basically a way to see the route you took to get somewhere.




Web Dev Backend: when not to use database

I'm working on a web project and I'm not sure if I need database or not. The following steps summarises what I want my project to do:

  1. The server makes API calls to Google Docs API to get the document data
  2. The server renders the document data and store it
  3. The client gets the document data from the server and it gets displayed on the browser
  4. If any changes to the Google Docs are noticed, the server repeats (1) and (2).

From my limited web development experience, I think I have two options:

  1. Store it in the server as a variable while the server is running (A hashmap to store key-value pairs of rendered documents)
  2. Store it in some sort of database (e.g. MongoDB, MySQL etc.)

My question is, how do I know what the most appropriate way of storing such data?

FYI, I'm using React and Node (Express.js) backend. And the rendered data of a single document would look something like this:

{
  lastModified: ...
  renderedHTML: "<html> ... "
}



I want to make this regexp [closed]

Which will accept all int value and in float accept only 0.5

like, Valid string = 1,1.5,2.5,21332.5,1213.5,2151

Not valid string = 15.55.5.5 ,12.2.1 ,12.2




How to Create Web Pages for Publishing Ontologies Written in OWL?

I am currently working on a project where I am looking for a way to display OWL ontologies on web pages. I have searched and I am currently trying out Drupal as it seems to have some related modules but nothing related to what I am looking to achieve.

Can anyone assist me in extracting/publishing OWL ontology data to web pages?




How to open remote IIS Website in Local machine

I developed a ASP.NET Core application and now I'm trying to publish to a remote IIS Server, just for testing. I published as File System and then moved the folder to the remote server.

What happens now is that I can't open the created Web Site. First tried to open it inside the remote server, but it doesn't have SQL Server Express to access to a localDB, so it always shows an error. I already tried to install it but it always stops working during the installation.

enter image description here

Then, I tried to access the site in my local machine. But it also doesn't open. I have the IP for the remote server configured in the "hosts" file. Do I have to configure the IP for the site too? And do I have to have SQL Server installed in the remote server too?

Thank you in advance!




(Web) Dynamic text specifications depending on font and text width

I have an order form for printing text to be used as stickers. As seen in the picture, I have options for text input, font, print count and an option to input text width in centimeters, not pixels. Depending on these parameters, I'd need to calculate the text's width and height in centimeters using HTML/JS/PHP and calculate the price used for the materials dynamically. Is there a platform like this maybe or something similar I could use or should I just build it from scratch? Line breaks are included. enter image description here




Domain name masking

I purchased a domain and redirected it to a vps of mine to host a website, but when I type the domain in the browser, the URL changes with the IP name of the machine. Is there a way to mask it? (the supplier is OVH)

Example: Typed url www.example.com New url 34.315.167.4:3000




User.IsInRole("Admin") returning always false in _Layout.cshtml

In layout.cshtml I am checking whether the current user is an admin or not. If so, then a different menu is shown. However, it is always returning false, even when logging in with an admin. I am using the code below:

@if (User.Identity.IsAuthenticated == false)
{
    <li><a href="\Users\Login">Log in</a></li>
    <li><a href="\Users\Register">Register</a></li>
}

else
{
    <li><a href="\Users\Logout">Log out</a></li>
    if (User.IsInRole("Admin"))
    {
        <li><a href="\Users\List">Users List</a></li>
    }
}



In AFrame I Want To Augment With Two Different Patters With Different Pattern Ratio Of 0.50 And 0.75

Hello I Want To Augment Two Video With Two Different Marker With Different Pattern Ratio - One with 0.50 Ratio And Another With 0.75 Ratio . If I Augment With Hiro And Kanji Then Its Working But If I augment with different pattern ration then its not working. As per the research i did, got something like defining the patternRatio in a-scene -

Tag - <a-scene arjs="patternRatio: 0.75">

.By Default PatternRation Will Be 0.50 .But as per my requirement I have 2 Different Pattern Ratio. So How To Define Two Different Values.

Pattern One (Hiro) - HIRO,

Pattern Two (Custom QR Code) With Ratio 0.75 - PATTERN,

Patt File For Custom QR Code - Pattern,

Please Edit The Code In GLITCH - AFRAME IMPLEMENTATION CODE,

Video 1 - VID 1 Video 2 - VID 2

My Implementation -

console.log("Hi Aframe");

// Vid Component
AFRAME.registerComponent("vidhandler", {
  schema: {
    target: { type: "string" }
  },
  init: function() {
    this.videoAsset = document.querySelectorAll(this.data.target);
  },
  tick: function() {
    if (this.el.object3D.visible == true) {
      if (!this.toggle) {
        this.toggle = true;
        for (let i = 0; i < this.videoAsset.length; i++) {
          this.videoAsset[i].play();
          console.log(this.videoAsset[i]);
        }
      }
    } else {
      if (this.toggle) {
        for (let i = 0; i < this.videoAsset.length; i++) {
          this.videoAsset[i].pause();
        }
        this.toggle = false;
      }
    }
  }
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Aframe Multi Pattern Ratio</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://aframe.io/releases/1.0.1/aframe.min.js"></script>
    <script src="https://raw.githack.com/jeromeetienne/AR.js/2.1.4/aframe/build/aframe-ar.js"></script>
    <script
      type="text/javascript"
      src="https://rawgit.com/donmccurdy/aframe-extras/master/dist/aframe-extras.loaders.min.js"
    ></script>

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css" />

    <!-- import the webpage's javascript file -->
    <script src="/script.js"></script>
  </head>
  <body>
    <!-- Marker Border patternRatio:0.75  -->
    <a-scene
      vr-mode-ui="enabled: false"
      artoolkit="sourceType: webcam; detectionMode: mono; maxDetectionRate: 90;"
      arjs="debugUIEnabled: false;detectionMode: mono_and_matrix; matrixCodeType: 3x3;"
    >
      <a-assets>
        <video
          muted
          id="vid1"
          response-type="arraybuffer"
          loop="true"
          crossorigin
          webkit-playsinline
          playsinline
          controls
        >
          <source
            src="https://cdn.glitch.com/e85b316e-eed9-4e96-814e-d12630bc00df%2Fvid_pointing_green.mp4?v=1577421630965"
            type="video/mp4"
          />
        </video>
        <video
          muted
          id="vid2"
          response-type="arraybuffer"
          loop="true"
          crossorigin
          webkit-playsinline
          playsinline
          controls
        >
          <source
            src="https://cdn.glitch.com/e85b316e-eed9-4e96-814e-d12630bc00df%2Fvid_pointing_blue.mp4?v=1577421651559"
            type="video/mp4"
          />
        </video>
      </a-assets>
      <!--   Marker Border    Pattern Hiro  -->
      <a-marker type="pattern" preset="hiro" vidhandler="target: #vid1">
        <a-entity position="0 0 0">
          <a-video
            width="2"
            height="2"
            rotation="-90 0 0"
            material="transparent:true;shader:flat;side:double;src:#vid1"
          ></a-video>
        </a-entity>
      </a-marker>
      <!--     Pattern Ration 0.75 -->
      <a-marker
        type="pattern"
        url="https://cdn.glitch.com/e85b316e-eed9-4e96-814e-d12630bc00df%2Fpattern-qr-code.patt?v=1577440081157"
        vidhandler="target: #vid2"
      >
        <a-entity position="0 0 0">
          <a-video
            width="2"
            height="2"
            rotation="-90 0 0"
            material="transparent:true;shader:flat;side:double;src:#vid2"
          ></a-video>
        </a-entity>
      </a-marker>

      <a-entity camera>
        <a-entity cursor="rayOrigin: mouse;fuse: false;"></a-entity>
      </a-entity>
    </a-scene>
  </body>
</html>



Need to implement a robust System which can uniquely identify multiple user logins at the same time

Need to give access to atmost only 'n' number of users....

Consider Situations like The user may access the website from system browser or android app and the user may clear cookies or the browser and app crashes...The system is able to handle all well..

The system should be preferably in ruby on rails...Any suggestions are welcome




Firebase cloud messaging still not work on Safari web push

recently i'm using FCM to send push notifications to ios, android devices and web also. But I saw the old question from 2017 that Safari doesn't work with FCM. So are there any alternative solutions? Thank for any helps




What can I do to make broken link checker not delete my images?

I'm an intern, And I was tasked to make a uploading system which the user can upload images and other kinds of file. I already made the system and it is working fine, The connection to the database works great and everything seems fine, I also publish it at 000webhost. Then, my boss came and told me to copy the url of the website and then paste in broken link checker. No broken links but when I refresh my system all the images are gone, Even in the database. He told me fix this and I have no idea what to do. He also told me that Google does check your website for broken links occasionally and if I don't fix this, The images in the future will be gone. Does anyone know how solve this issue?




jeudi 26 décembre 2019

java -java.nio.file.FileSystemException The process cannot access the file because it is being used by another process

 //for Image1
    Part part = request.getPart("pimage1");
    String fileNameAbsolute = extractFileName(part);
    String fileName= extractFileNameEnd(fileNameAbsolute);
    String savePath ="E:\\ecom2\\WebContent\\images\\" + File.separator + fileName ;
    System.out.println("filename is:"+fileName);
    String origPath="E:\\ecom2\\WebContent\\imageforE\\" + File.separator + fileName ;
  //String origPath="E:\\images\\"+ File.separator + fileName ;

    Path temp = Files.move 
            (Paths.get(origPath),  
            Paths.get(savePath));
    if(temp != null)  { out.println("File renamed and moved successfully"); } 
    else    { out.println("Failed to move the file");  } 

line 5 is printing correctly but after that path temp is not working , error is there the process cant access the file. how to close part object.




How to put text behind an image in CSS?

I am new to CSS and I want to put text "MOUNTAINS" behind the mountain in the background image. Like the below image.

Home section image

This is the existing code

HTML Code Part

<!-- Home -->
        <section id="home" class="col-md-12">
            <!-- Background Image -->
            <div id="home-img" class="col-md-12">

            </div>
            <!-- Home Content -->
            <div id="home-content">
                <h1 id="first-title">LOSANGELES</h1>
                <h1 id="second-title">MOUNTAINS</h1>
            </div>
        </section>

CSS Code Part

#home{    
    height: 100%;
    position: relative;
    padding: 0;
}

#home-img{
    background: url("../img/home/1.jpg");
    background-size: cover;       
    top: 50%;
    left: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -1;
}

#home-content{
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);    
    letter-spacing: 1px;
    line-height: 124px;
    color: #4d4d4d;
    font-family: 'Bebas Neue', cursive;
}

#home-content #first-title{
    color: rgb(77, 77, 77);
}

#home-content #second-title{
    color: rgb(65, 79, 107);
}

#home-content h1{
    font-size: 115px;
    margin-left: -25%;
    margin-top: -8%;
}

I am stuck with this. So can CSS expert help me to do this? Thank you




Beautiful soup 'find_all' function doesn't seem to scrap "find_all('div', class_ = 'ais-infinite-hits ais-results-as-block')"

I'm trying to scrape an Australian retailer "JB HI-FI".

from requests import get
from bs4 import BeautifulSoup
url = 'https://www.jbhifi.com.au/?q=a&hPP=36&idx=shopify_products&p=1'
response = get(url)
print(response.text)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)`
movie_containers = html_soup.find_all('div', class_ = 'ais-infinite-hits ais-results-as-block')
print(type(movie_containers))
print(len(movie_containers))`

Then I just got 0 for the length. But I can clearly see 'ais-infinite-hits ais-results-as-block' by using "inspect" from google chrome




Timeout occurs when serving deep learning models with django, gunicorn and Nginx

I was able to serve deep learning models on 4 2080TI GPUs based on django, gunicorn and Nginx. The majority of the latency is around 200ms, but several requests takes over than 2s to finish. It happens occasionally and is hard to reproduce under some specific setting. How to fix this problem?

BTW, the QPS is just 1~2, so it's not result from busy GPU/CPU usage.

Here is the Nginx log: nginx log