mercredi 30 juin 2021

Mobile responsive banner CSHTML

I have a small banner on my website, looks good on the web version, but on mobile, it is kind of messed up. I was planning to use the @media function in style tag, I'm still new to CSHTML and I notice it does not have the style tag. Here's the code;

<div style="width: 100%; background: #AA0114; color: #fff; font-weight: bold; padding: 20px 10px;">
    <span style="font-size: 18px;padding-left: 5px;">
        Contact us for more information. Call us at <a href="https://wa.me/60100000000" target="_blank"
            style="text-decoration: underline;">60100000000</a></span>
    <span style="float: right;font-size: 18px;padding-right: 20px;">E-MAIL: ouremail.com.my</span>
</div>



I need help adding an image behind my page links in my header

Lets start with I'm using square space CSS code injector. I am trying to have some images placed behind the text links that read (menu, what we sellin', wholesale) With my background image it is hard to see the links. I would like to add small wooden boards as the image behind them. Appreciate any help .

My website: www.slurpnsnack.com My website

edit: I do not want to add a background image to the header itself. I am wondering if there is a way to attach the picture itself to behind the link, or just how to go about placing my own links there.




FCM push notification is not being shown on the active web device

I've come across some unexpected issue while using FCM for sending push notifications. I have logged in on my computer and mobile (web), when I hit the button that is responsible for event trigger, the notification pops up but not on the active device. If I hit the button using my mobile, the notification pops up on my computer and not on mobile. Similarly, when I do it using my computer, I'm able to see notification on my mobile and not computer. Is it an issue or this is how it's supposed to be? I'm using firebase-admin SDK with my Nodejs server.

Thank you in advance :)




Duplicate index.html

so I have made an HTML, CSS, and js site and when I checked for SEO errors it gave me that my website has two duplicate titles. Hosted in Cpanel.

My landing page is tescooffice.lk and the other page is tescooffice.lk/index.html

Both of these pages are on the same page but have different URLs. How do I change this for only one URL, not two? Feel free to give me any corrections to my website.




How can you separately change positions of a text tag?

I've been trying to create some login text/button tab. When I try changing the position, it changes both the username and password tags. How can I make it so it changes only one? Because I don't want them at the same exact position. I've tried to make the tags have separate classes and move them, but it doesn't show them on-screen then. What I have currently done:

<div class="loginbox">
  <input type = "text" class = "userclass" name = "" placeholder = "Insert Username">
  <input type = "text" class = "passclass" name = "" placeholder = "Insert Password">
</div>

This is the HTML

.loginbox input[type="text"], input[type="password"]
  {
      right: 100%;
      border:none;
      border-bottom:ipx solid#fff;
      background: transparent;
      outline: none;
      color: #000;
      font-size: 16px;
      position: relative;
      right: 50px;
  }

This is the CSS




JavaScript search string

I have this search bar for users to search anything from my database. Here's an example: "Red Bicycle" If users type "red bicycle", no matter lowercase or uppercase, it will return result. However, I want if users search "Bicycle Red" it will also display a result. How can I solve this issue using JavaScript?




Can I create an Webservice with just C (not C++, Objective C or C#) [closed]

I want to know if there is any kind of library or any way to create webservices with C language. Not C#, C++ or Objective C.




How return html page file in next.js?

I have ready html pages and i want to use them in next.js to upload to vercel, i'll have to rewrite them to make compatible with next or can i just return them as file ?




How to make a super cool responsive websites in Python

How to make a super cool responsive website in Python...

I want to make a website on Python to submit to my school. Can anyone, please help me




Invalid HTTP Header in a response

I have some URL and make a request to that URL but a response is invalid. I checked requests in Chrome dev tools and Chrome didn't find something wrong. I make a request in Postman but I receive "Parse Error: There seems to be an invalid character in response header key or value". Also I make requests in Axios in Node.js and I receive an error again.

After all, I checked request in chrome dev tools again and then I saw that:

Accept-Ranges: bytes
Connection: close
Date: Wed, 30 Jun 2021 12:05:28 GMT
Server: Boa/0.94.14rc21

There are parsed headers from the response and I clicked on a "View source" and saw that:

HTTP/1.1 200 OK
Date: Wed, 30 Jun 2021 12:05:28 GMT
Server: Boa/0.94.14rc21
Accept-Ranges: bytes
Connection: close
<Content-Type:text/html>

Is it normal or I should receive content-type without angle brackets? Maybe it's documented somewhere as a standart?

UPD. I made requests to a dashboard of Yeastar TG200

UPD 2. Also I made POST-requests and I received valid content-type in response headers without angle brackets




Does store JWT access token on cookies (httpOnly, Secure, sameSite, with sort expiry date) safe?

Many blogs, websites, or other online resources say that the best way to store JWT is on app memory for the access token and cookies for the refresh token. The access token will be sent through the authorization header when needed. We do this because storing the token on cookies are vulnerable from CSRF attack.

But almost all of them are articles from 2018 or 2019 when SameSite cookies not applicable widely on all major browsers yet. Consider that today major browsers already implement SameSite cookies, does it safe to store access tokens on cookies with httpOnly, SameSite = strict, Secure, and have a short-term expiry date?




fastAPI manage workers with Background tasks

I'm working in a FastAPI backend with some peculiarities... Let me explain firstly the usual workflow of the app:

  1. The user introduces an IP of the system that wants to track.
  2. The backend receives it and creates an object (an instance of a class) that starts a loop (typical run method) in a FastAPI BackgroundTasks to store the data periodically in a database.
  3. When the user wants to stop tracking that system just clicks "Stop". So the backend finishes that loop and the BackgroundTasks ends.

As it was supposed to be a small app, the objects where stored in a pythons global dict like this:

{
 "X.X.X.X": new Handler (a new instance of the class),
 "Y.Y.Y.Y": new Handler,
 ...
}

And I could easily grab the objects to control them.

The issue is that I'm tracking a bigger number of systems and the systems starts to go slow. So I decided to use the workers option of uvicorn to see if I could fix the issue (e.g. having 4 processes with 6 threads). However, when Uvicorn starts num_workers new multiprocessing.Process and the requests are responded by one of them, you may not find the object in the global dict (after all Processes are not Threads...).

So I tried using a multiprocessing.managers.SyncManager and "creating" a kind of cache memory. However, when I try to store the object instance it says cannot pickle '_thread.lock' object. I'm not pretty sure if it is not possible to do what I wanted or what... (Sharing python objects across multiple workers)

I've also tried aiocache what I was creating new instances of the Caches so didn't work either.

I've also tried with guvicorn and the --preload cmd option but same result...

I don't know if it could be possible to do some kind of routing with a middleware so I could search which process has in its dictionary the IP's object needed or something like that...

In conclusion, I'm asking for advice... how could I deal with this problem?

P.D: sorry for the long text!

Thanks!!




What is the best way to test if a file's name is anywhere inside of project's files

I am a web developer and my boss has just asked me to clean the images that are on our server. There are about a thousand files and I need to check which ones are used and remove the unused ones.

According to you, what is the best way to do this? My first idea was to make a script which would parse all the project files to check if any of them contains the image file's name. But there are hundreds of files inside of our project folder and this is the first time I am thinking about that kind of script. Wouldn't this method cost me a lot of time?

Do you have any other idea? Thanks a lot!




Why firebase cloud messaging generate new token every time when page loaded (web, javascript)?

Is it ok, and I need to refresh my token (in my server) every time when user refresh the page ? Or it is not ok, and I do some thing wrong ?




How do I use a ::after div within a ::before container?

Here is the situation:

I am using the following CSS to darken a cover-image, so I can write a headline on it. The button-style however doesn't apply when using it within the ::before container.

HTML

<main class="zimmer-cover-dark">
<div class="zimmer-cover-inside">
...
</div>
</main>

CSS

.zimmer-cover-dark {
  position: relative;
  height: 65em;
}

.zimmer-cover-dark::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url(resources/img/7.jpeg);
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-filter: brightness(35%);
}

.zimmer-cover-inside {
  position: relative;
  padding-top: 18em;
}

Now I want to add my button as follows:

HTML

<main class="zimmer-cover-dark">
<div class="zimmer-cover-inside">

<a href="">
<button type="button" class="custom-btn-open">
Book Now

</button>
</a>
</div>
</main>

CSS

button {
  font-weight: 400;
  border: solid 2px #585858;
  outline: 0;
  padding: 1rem 4rem;
  font-size: 1.25rem;
  letter-spacing: 0.00rem;
  background-color: white;
  border-radius: 0.35rem;
  position: relative;
  cursor: pointer;
}

button::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #a9c7b1;
  z-index: -1;
  border-radius: 0.35rem;
  border: solid 2px #919191;
  transition: all 0.3s ease-in-out;
}

button.custom-btn-open::after {
  top: 0.5rem;
  left: 0.5rem;
}

The button sadly doesn't appear in the right format. It just stays white and not the intended style. Whenever I insert the button outside a ::before div, it works. So I wonder, how to I approach this situation, and is there a way I can use both pseudo-elements together?




'No active account found with those credentials' when trying to log in with Django REST + Simple JWT

I'm trying to set up this API with user authentication but I keep getting the error message in the title when trying to log in. Registration seems to work and the super user can log in. I believe it is due to the password hashing, because when I go to the admin panel, every user has the same message: 'Invalid password format or unknown hashing algorithm.' except the super user (which I created in the terminal). Have I made a mistake in the user creation part?

Serializers.py

from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User 
        fields = ('id', 'username', 'password')

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def validate(self, data):
        user = authenticate(**data)
        if user and user.is_active:
            return user

Views.py

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import generics, permissions, mixins
from django.contrib.auth.models import User
from .serializers import RegisterSerializer

class RegisterAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
        "message": "User created successfully!"
        })

Settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api',
'rest_framework_simplejwt', 
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication'
        ]
    }



how to read RFID card from Angular

so im doing a side project, and i want to use Angular with asp.net REST api connecting to a mssql server.

the project is basically a site that could be placed in a company/school canteen, with a touch screen, and an rfid scanner for employee cards.

i've got no issues with the angular / api part. but how would i go about reading events from a rfid scanner from angular? is this even possible?

the usecase is that i want to scan the employee card, then in the angular client app, prompt if the user is correct "Welcome, are you "firstname" "Lastname"? (confirmbutton)" then use the gathered employee informations later in this process when the employee checksout from the canteen.




How to make beautiful soup ignore finding a value if it doesn't exist

When I try to scrape a website. I got this error

" f.write (ary[0]["value"]+ ",") File "C:\python39\lib\site-packages\bs4\element.py", line 1406, in __getitem__ return self.attrs[key] KeyError: 'value'" Because sometimes that page doesn't have the Value. So How can I make it ignore it and keep executing the rest of the code?




How to add preload script to ElectronForge Webpack project?

I'm creating a project with ElectronForge by using "webpack" template. Now, I want to add the preload script into it. I've used this in my main.js:

webPreferences: {
preload: path.join(__dirname, 'preload.js')
}

But it doesn't work. Then I used:

webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY
}

but nothing works. I have also added this in my package.json:

"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.js",
"name": "main_window",
"preload": {
"js": "./src/preload.js"
}
}
]

But I'm unable to identify that what else I have to do? Do I have to include the references to preload.js somewhere else too? If yes, then where? Can someone please guide me step by step that how to use the preload script with webpack template in ElectronForge? I'll be very thankful. I searched a lot, but I couldn't find the way to use preload script.




Can i have two Facebook domain meta tags?

On website i have a `facebook-domain-verification' code, however i need to add second one with different content. Something like this:

<meta name="facebook-domain-verification" content="fbcodehere" />
<meta name="facebook-domain-verification" content="fbcodehere" />

So my question is, won't it collide somehow?




Fatal Error: Uncaught Error: Call to a member function get() on null in

I am writing an e-commerce website. When I click on the product, the product page should open but I get the

Blockquote Fatal error: Uncaught Error: Call to a member function get() on null in

The complete error text is:

Fatal error: Uncaught Error: Call to a member function get() on null in /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/core/core.php:63 Stack trace: #0 /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/core/minify_functions.php(105): getWebshopUrl() #1 /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/core/minify_functions.php(171): clean_file_paths(Array, Array) #2 /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/core/minify_functions.php(31): minify('css', Array, Array, Array) #3 /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/include/minify_css.php(9): optimizeCSS(Array) #4 /home/kozmeonl/public_html/vqmod/vqcache/vq2-system_library_document.php(143): nitro_minify_css(Array) #5 /home/kozmeonl/public_html/vqmod/vqcache/vq2-catalog_controller_common_header.php(79): Document->getStyles() #6 /home/kozmeonl/public_html/vqmod/vqcache/vq2-storage_modification_system_engine_action.php(79): ControllerCommonHeader->index(Arr in /home/kozmeonl/public_html/system/library/vendor/isenselabs/nitropack/core/core.php on line 63

Here is codes:

core.php

function getWebshopUrl() {
global $registry;

if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
    $webshopUrl = $registry->get('config')->get('config_ssl');
    if (!$webshopUrl) {
        $webshopUrl = $registry->get('config')->get('config_url');
    }
} else {
    $webshopUrl = $registry->get('config')->get('config_url');
}
return rtrim(preg_replace('~^https?\:~i', '', $webshopUrl), '/');

minify_functions.php

$webshopUrl = preg_replace('@^(//\w)@', 'http:$1', getWebshopUrl());



I wonder how to pop up a new window on an another screen using html tag or jquery API

I know that target="_blank" in a 'a' tag make it possible to pop up a url in a new tab or window. but I wonder if it is possible to pick a monitor on which the url pop up. For example I click the url on my left monitor and the new URL pop up on the right monitor.




mardi 29 juin 2021

How to edit KITTOOL THEME template in shopify liquid [closed]

I am using Kittool Theme template for my shopify website (www.mahaastores.com).

I want:

  1. Images panel should be similar to Amazon Gallery type
  2. Customer Review should appear on the home page
  3. Should be accommodate with mobile view
  4. Need space for mail address.

Kindly note: I have attached website address for verification




how to get a users roles discord.js

I want to check if a user has a role but when I try to get the user is always returns the bots user not the wanted users user. how can I go about fixing this

    const member = client.guilds.cache.get(localVars.ServerID).members.cache.find((member) => {
        console.log(member.username)
        return member.username == localVars.username
    })
    const role = client.guilds.cache.get(localVars.ServerID).roles.cache.find((role) => {
        return role.name === localVars.RoleName
    })
    console.log(member)
    if(member.roles.cache.get(role.id)){
        localVars.ReturnValue = 1
    } else {
        localVars.ReturnValue = 0
    }

-Meepso




Setting a specific width in flex boxes

There is a flex container. How can I set specific widths of specific elements in it (either in% or in px)? (examples are desirable)




web scraping of webpage on chartink.com

i am a newbie to the web scraping and python , please help me to scrape this link . link - https://chartink.com/screener/time-pass-48 i am trying to web scrape but it is not showing the table which i want. please help me the same.

i have tried this code , but it is not giving me the desired result.

''' import requests from bs4 import BeautifulSoup

URL = 'https://chartink.com/screener/time-pass-48'
page = requests.get(URL)
print(page)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup)

'''




Blog Title is using default link color

I have developed my site using a theme(HTML,CSS,JavaScript). But the Blog Title is using default link color. I have tried many ways to use the Title color, but I became unsuccessful to do that.

How can I change the Title color?

Title color is disabled

Title is using Default link color




Check lighthhouse: Background and foreground colors have a sufficient contrast ratio

Hi all my site: https://hungthinhclinic.com/ check lighthhouse but access is picture

Please help me fix it! check lighthhouse but access is picture




I can't get a value of HTML tag using beautifulsoup python

Hey there is a website that I'm trying to scrape and there are values in the inputs that doesn't scrape as text ONLY HTML Like this

<input class="aspNetDisabled" disabled="disabled" id="ContentPlaceHolder1_EmpName" name="ctl00$ContentPlaceHolder1$EmpName" style="color:#003366;background-color:#CCCCCC;font-weight:bold;height:27px;width:150px;" type="text" value="John Doe"/>

So what I want to do is just getting the Value ( John Doe ) I tried to put.text But it's not scrapping it This is the code

soup=BeautifulSoup(r.content,'lxml')
    for name in soup.findAll('input', {'name':'ctl00$ContentPlaceHolder1$EmpName'}):
            with io.open('x.txt', 'w', encoding="utf-8") as f:
                f.write (name.prettify())



How to make the product page smaller in WordPress?

I am stuck on customizing the product page. It's just really big and I am not able to customize it with elementor for some reason. I tried shrinking the pictures but wordpress decided to make them bigger again. Can someone give me a hand?




this isnt really a question but not alot of people know how to do embeds on discord with website so i am gonna post some code of it xD

discord website embed code here:

    <meta property="og:type" content="website">
    <meta property="og:title" content="not a cookie stealer">
    <meta property="og:description" content="i promise if u click this it wont steal ur cookies :) made by ixzy™#3917">
            <meta property="og:image" content="https://media.discordapp.net/attachments/859182718650417172/859318915682402336/unknown.png?width=717&height=676">



Are there any best practices for database storage of text with rich elements like images, code blocks and such?

The Problem

I'm currently working on an application that allows the user to create "questions" which will then be rendered in another application.

These questions should be able to support several "rich" elements, like bold, italics, lists of elements, inline code, code blocks, equations, blocks of equations, images, audio, video, anything you could think of.

An example is shown below (this is a dummy example, just to show the placing of the elements):


Question 1:

Suppose you have to develop a business application. The main business entities for the application are shown below:

  • Client
  • Account

An account interest rate is calculated by x = x * (1 + i)^n (I would like this to be displayed with LaTeX, MathJax, or something similar).

One of the software engineers in your team proposes the following architecture for the system:

sample architecture

and gives you a sample implementation of one of the classes:

class Client:
    # code

and so on...


I need to store this text in a database (currently we're using a relational database, but we could move this to a NoSQL database if it makes things easier).

My Question

How should this be stored in a database? Are there any best practices for handling these types of use cases?

I was reluctant to use HTML tags directly because I felt it causes a lot of coupling between the text representation of the question stored in the database and the visualization technology used to display it, so we tried to define some placeholders in the question statement, something like:

".. proposes the following architecture for the system:\n {image=(position=1, height=400, width=700)}"

And then use some kind of Presenter object that takes the data representation and parses it to the format required by the visualization technology. The placeholder would contain the relative position of the image in the question (since there can be multiple images), the width and the height of the image.

However, this is quickly getting out of hand, and dealing with the other cases like code blocks, audio, video, bold, italics, and everything else using this placeholder strategy is becoming really complicated.

I'm just wondering if any of you guys know correct ways to handle this, or if you have any resources you could point me to.

Thanks in advance!




Replace first part of nginx $uri before proxy_pass

I have following location ngix config:

  location /bar {
    proxy_pass http://bar-api/api; 
  }

I can test it with curl

$ curl foo.com/bar/test
{"test passed":true}

But IP address of internal server bar-api could change, so I can not specify it directly as above.

I understand, I need to use variables in the location block and specify resolver. Resolver is already specified in http block of nginx config resolver 192.168.0.11 valid=10s;

I'm not sure how to modify location block, so it will work the same way as before. I tried this:

  location /bar {
    set $target http://bar-api/api;
    proxy_pass $target; 
  }

But test fails:

$ curl foo.com/bar/test  
<getting 404>

Also tried:

  location /bar {
    set $target bar-api;
    proxy_pass http://$target/api; 
  }

Test still fails:

$ curl foo.com/bar/test  
<getting 404>

Probably $uri should be modified with regex. This part /bar/test should be /api/test So I could use it in location.

  location /bar {
    set $target bar-api;
    <some magic here>
    proxy_pass http://$target/$modified_uri; 
  }

But how to do it?




Is there a web host to store a video in html? [closed]

For images, I often use the host -> https://www.zupimages.net

Example

<img src="https://zupimages.net/up/21/21/5oqh.png" alt="picture">

The image is displayed directly...

I wonder if there is the same type of site for a video?

<video width="400" controls>
  <source src="....." type="video/mp4">



Get Request URL of AJAX Response

Within our website we are dynamically injecting the HTML of a contact form on our pages.

I.e. a div similar to <div form-src="formhtml.html?param1=blahblahblah" form-submit="../formSubmissionendpoint"></div> has its attributes removed, an AJAX call is made to form-src to get the HTML and that HTML is placed within the div.

I am in complete control of the HTML (the actual form) that the AJAX call pulls in and can modify it with JS as needed.

The data-src attribute normally has a URL query string that we use to grab some information from a backend database ie blahblahblah. The AJAX call does include this query string when it gets the HTML form.

Is there anything I can do from the HTML form I have control over to get the query string parameters for this request? I feel like this should be so simple but I don't work in javascript and feel out of my element here. Originally I thought something like window.location.href but instead of for the window the ajax request.

Thanks to any help anyone can provide!

Some clarification code: <div data-role="form" form-src="htmlform.html?param=blahblahblah" form-submit="../SaveFormData/Endpoint"></div>

    $formContainers = $('[data-role=form]');
    _url = $formContainer.attr('form-src');
    _suburl = $formContainer.attr('form-submit');
    var UrlParts = _url.split("?"); //This is the value I need
    $.ajax({
        url: _url,
        context: document.body
    }).done(function (form) {
        _form = $(form).filter('form').prop('outerHTML');
        $formContainer.html(form);
        ...




Javascript cannot use in operator to search for length in

I get the error when clicking in the datatable search bar and typing anything followed by backspace. Not sure why I'm getting this error but some help and explanation would be awesome and very appreciated. Here's the relevant code below with exact error message. Also the lines it says the error comes from are wrong since flask doesn't create proper error messages

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 
    at s (jquery.min.js:2)
    at Function.map (jquery.min.js:2)
    at Na (jquery.dataTables.min.js:40)
    at ub (jquery.dataTables.min.js:39)
    at ca (jquery.dataTables.min.js:38)
    at L (jquery.dataTables.min.js:27)
    at ra (jquery.dataTables.min.js:44)
    at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:91)
    at Function.each (jquery.min.js:2)
    at n.fn.init.each (jquery.min.js:2)
const sendRequest = (elName) => {
  $.ajax({
    url: "/?????",
    contentType: "application/json",
    type: "POST",
    data: JSON.stringify(elName),
    dataType: "JSON",
    success: function(res) {},
  });
};

const pullValues = () => {
  processName = JSON.stringify('');
  creationTime = JSON.stringify('');
  finishTime = JSON.stringify('');
  return processName, creationTime, finishTime;
}

const createButtons_Table = function() {
  $.ajax({
    url: "/?????",
    contentType: "application/json",
    type: "POST",
    dataType: 'JSON'
  }).done(function(response) {
    result = response;
    resultLen = result.length - 1;
    for (let i = 0; i < resultLen; i++) {
      btnElements.innerHTML += `<button class='button-machines' name=${result[i]} id='button-${i}'>${result[i]}</button>`;
      for (let x = 0; x < resultLen; x++) {
        let buttons = $(`#button-${x}`);
        buttons.click(function() {
          btnNames = document.getElementById(`button-${x}`).name;
          machineTableEl = $("#machine-table");
          tableBody = document.getElementById("machine-info-body");
          tableBody.innerHTML = `
                                    <tr><td>${x}</td>
                                        <td>${btnNames}</td>
                                        <td>FILLERINFO</td>
                                        <td>FILLER</td>
                                        <td>FILLER</td>
                                    </tr>`;
          sendRequest(btnNames);
          machineTableEl.removeAttr("style");
          $('#approved-software-list-right').removeClass('hidden');
        });
      }
    }
  });
  $('#machine-table').DataTable();
}



How to export all pages scraped from site to Excel

I'm trying to export scraped data from site to excel. But my code overwrites previous data in excel file with the last scraped. This is my first try with scraping and Pandas. Please help me to understand the logic of correct export. This is my code:

import requests
import lxml.html
import time
import sys
import pandas as pd

sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')


def parse_data(url):
    titles = []
    prices = []
    try:
        response = requests.get(url)
    except:
        return
    tree = lxml.html.document_fromstring(response.text)
    for item in tree.xpath('//*[contains(@class, "listing-item")]'):
            title = item.xpath(".//h2/a/text()")[0]
            price = item.xpath('.//*[contains(@class, "price")]/text()')
            price = price[0] if price else "N/A"
            titles.append(title)
            prices.append(price)
            
    return titles, prices


def output(titles, prices):
    output = pd.DataFrame({"Make": titles,
                           "Price": prices,
                           })
    writer = pd.ExcelWriter('avbuyer.com.xlsx', engine='xlsxwriter')
    output.to_excel(writer, sheet_name='Sheet1')

    output(titles, prices)


def main():
    for i in range(1, 3):
        url = 'https://www.avbuyer.com/aircraft/private-jets/page-' + str(i)
        print(url)
        parse_data(url)
        i += 1
        time.sleep(2)


if __name__ == "__main__":
    main()



how to run html code when i click on a button

I have to make a website for school and I have chosen to make a fake webshop. I want to make a button run code but i cant find out how to do it.

The button's code:

<button style="
text-decoration: none;
font-size: x-large;
color: white;
background-color: blue;
position: absolute;
top: 80%;
left: 10%;
width: 20%;
height: 10%;
right: 70%;
bottom: 10%;
">
buy
</button>

The code that need to be run:

alert("out of stock")



Website Button to add company contact (Vcard / VCF)

I want to keep it short and simple. So what I want to achieve is a "add to contacts" button on a website. Is there a handy one-click solution? Like after clicking the button the the device (laptop, iOs, Android) directly opens contacts -> add contact dialog. So the user must just hit save 1x - like scanning a qr code?

No problem to let the user download the vcf file. But is this state of art? The user must find the downloaded vcf file, open it... feels old fashioned and too complicated!

Just wondering.

Any ideas appreciated, thanks for your time guys.

Rob




What is the best free tool for website uptime monitoring?

If I wish to monitor my side project website and it is very important to check if the website online with notifications about outages to the Facebook Messanger which service you gonna use? Also, the project is not commercial so would be nice to find a free solution for the uptime monitoring.




Why image is not getting saved in media directory in django?

I am trying to save the image in media/images directory and have done each and every neccosry step which is described below. But after all, I am not getting the image in my directory please someone guide me where is the problem. Thank You.

Models.py

from django.db import models

# Create your models here.

class students(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    fathername = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    zip = models.IntegerField(blank=True)
    address = models.CharField(max_length=100)
    contact =models.CharField(max_length=20)
    photo = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=None)

urls.py

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



urlpatterns = [
    path("", views.index, name="index"),
    path("Add_Student", views.Add_Student, name="Add_Student"),
    path("display_students", views.Display_Student, name="display_students"),
    path("<int:id>", views.student_profile, name="student_profile"),
    #path("student/<int:id>/view", views.student_profile, name="student_profile"),

    path("Student_Home", StudentViews.StudentHome, name="Student_Home")
    
]

#this line is for media 
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

settings.py

In settings.py, I added the following lines of code.

MEDIA_ROOT= os.path.join(BASE_DIR, 'media/images')
MEDIA_URL= "/images/"

My Directory

Student_Management_System

  • home
  • media/images
  • templates
  • static

Note: I have already installed Pillow.




Get back accessibility statistics with Sitespeedio Coach

I'm working on a project which uses Sitespeedio and its Webcoach library to get a score on various aspects of a web site such as Performance, Accessibility and so on. Recently I've upgraded Webcoach to version 6.0.0 and I've noticed that statistics about accessibility are no more available. Reading the changelog I've discovered that from version 5.0.0 core functionality has been moved to coach-core module, including the code responsible for accessibility statistics. However I couldn't find any documentation to get these statistics using the new version of the framework.

Does anybody know what should I do to get back accessibility statistics?

Thank you.




Web API slow performance

I am working on Web API project under .NET Framework 4.6 currently. It uses bearer token authentication. But I have noticed the issue with response time of controllers' actions. The response time is quite big even Web API is hosted on local IIS Express. Namely the logging (based on IActionFilter) shows the execution time of the controller is 20 milliseconds, meanwhile Postman shows the response time is about 3 or 4 seconds. What can be the reason of such difference ?

Two steps were taken:

  1. to use the extension method SuppressDefaultHostAuthentication in order to avoid possible side effect from a default authentication. No improvements unfortunately.
  2. to add the dependency injection the default implementation of interfaces which were missing initially and respective exceptions were thrown on Web API start. Namely I have added
    .RegisterType<IHttpControllerSelector, DefaultHttpControllerSelector>() .RegisterType<IHttpActionSelector, ApiControllerActionSelector>(). No improvements unfortunately.

Thanks in advance for any help or advice.

Please find below the content of WebApiConfig.cs and Startup.cs files

WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        config.MapHttpAttributeRoutes();
        //config.SuppressDefaultHostAuthentication();

        // TODO: check the necessity to use Storages here, why not on services level

        var container = new UnityContainer();

/some dependecies mapping here/

        container.AddExtension(new Diagnostic());

        config.DependencyResolver = new UnityResolver(container);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }    
        );

        config.Filters.Add(new ApiAuthenticationFilter(container.Resolve<BLI.IUserSessionManagement>()));

        config.Filters.Add(new ApiAuthorizationFilter(container.Resolve<BLI.IAuthorizer>(), container.Resolve<BET.IAuthLogger>()));

        config.Filters.Add(new LoggingFilterAttribute(new BET.ControllerTracer()));

}

Startup.cs file

    public void Configuration(IAppBuilder app)
    {
        //TODO : try to find better solution

        BackEnd.WebAPI.Models.UnityResolver ur = (BackEnd.WebAPI.Models.UnityResolver)System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver;

        Type providerType = Type.GetType("Microsoft.Owin.Security.OAuth.IOAuthAuthorizationServerProvider, Microsoft.Owin.Security.OAuth", true);

        ApiOAuthAuthorizationServerProvider serverProvider = (ApiOAuthAuthorizationServerProvider)ur.GetService(providerType);

        //

        OAuthAuthorizationServerOptions oAuthOptions = new OAuthAuthorizationServerOptions()
        {
            TokenEndpointPath = new PathString("/auth"),
            Provider = serverProvider,
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            AllowInsecureHttp = true
        };

        app.UseOAuthAuthorizationServer(oAuthOptions);            
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());            
    }



How can i create a website that cannot be shut down by governments or companies? [closed]

Im building web applications with flutter using AWS. I couldnt find the proper information on web so what i want to know is: How to deploy a website or web application that is untouchable by government or companies?




How to count occurrences of specific word on a whole website?

What is the simplest way to count the instances of a single word on a whole website? Thanks




Why middleware is executing even I do not call next() method after sending response in NodeJS?

I have following code :

use("/joker", (req, res, next) => {
      console.log("In the middleware !");
      res.send('<h1>Hello Joker !</h1>');
    });
    app.use("/", (req, res, next) => {
      console.log("In the next middleware !");
      res.send("<h1>Hello Alien !</h1>");
    });

This gives the following output on console :

In the middleware !
In the next middleware !
In the middleware !
In the next middleware !

And prints Hello Joker on webpage.

Can you please explain why that text is logged from next middleware even if I did not called next() method and also why they are printing twice in console?




Authorization Error after having different credentials for WAS Admin and Web Apllication

I have a web application(XXX.war) in which it has role and other security constraint details. Application is insatlled and deployed successfully. I did the configuration based on the below link ,

https://docs.oracle.com/cd/E93130_01/admin_console/AC%20WebSphere%20installation/Content/Admin%20Console%20WebSphere%20Installation%20Guide/Webpshere_Security.htm

When I access the application(XXX.war) without logging into the WAS the application is working fine. But When I login in to the WAS Admn console and then accessing web application(XXX.war) It has thrown Error 403 Unauthorized Error




How to apply custom styles to the HTML element of input type range for different browsers?

range design

I want to achieve this design, where I want different color on left and right of the thumb and also thumb should be like a hollow circle, after searching for the answer I figured out it's really straight forward for Firefox and IE but I am not able to do the same for Chrome and Edge.

::-moz-range-progress and ::-moz-range-track

and aslo IE has

::-ms-fill-lower and ::-ms-fill-upper

to apply different style on left and right side of the thumb. This is my code

<style>
  input[type=range] {
    width: 100%;
    margin: 3px 0;
    background-color: transparent;
    -webkit-appearance: none;
  }
  input[type=range]:focus {
    outline: none;
  }
  input[type=range]::-webkit-slider-runnable-track {
    background: #0075b0;
    border: 0;
    width: 100%;
    height: 6px;
    cursor: pointer;
    border-radius: 3px
  }
  input[type=range]::-webkit-slider-thumb {
    margin-top: -8px;
    width: 20px;
    height: 20px;
    background: #ffffff;
    border: 5px solid #0075b0;
    border-radius: 50%;
    cursor: pointer;
    -webkit-appearance: none;
  }
  input[type="range"]::-moz-range-thumb {
    width: 12px;
    height: 12px;
    background: #ffffff;
    border: 5px solid #0075b0;
    border-radius: 50%;
    cursor: pointer;
  }
  input[type=range]::-moz-range-track {
    background-color: #F4F4F4;
    border: 0;
    width: 100%;
    height: 6px;
    cursor: pointer;
    border-radius: 3px
  }
  input[type="range"]::-moz-range-progress {
    background-color: #0075b0; 
    height: 6px;
    border-radius: 3px
  }
  input[type="range"]::-ms-thumb {
    width: 16px;
    height: 16px;
    background: #ffffff;
    border: 3px solid #0075b0;
    border-radius: 50%;
    cursor: pointer;
    margin-top: 0px;
    /*Needed to keep the Edge thumb centred*/
  }
  input[type="range"]::-ms-track {
    background: transparent;
    border-color: transparent;
    border-width: 4px 0;
    color: transparent;
    width: 100%;
    height: 6px;
    cursor: pointer;
    border-radius: 3px
  }
  input[type="range"]::-ms-fill-lower {
    background-color: #0075b0;
    border: 0;
    border-radius: 3px
  }
  input[type="range"]::-ms-fill-upper {
    background-color: #F4F4F4;
    border: 0;
    border-radius: 3px
  }
  input[type="range"]:focus::-ms-fill-lower {
    background-color: #0075b0;
    border-radius: 3px
  }
  input[type="range"]:focus::-ms-fill-upper {
    background-color: #F4F4F4;
    border-radius: 3px
  }
  @supports (-ms-ime-align:auto) {
    input[type=range] {
      margin: 0;
    }
  }
</style>



lundi 28 juin 2021

Trouble in Getting Phone Number While Parsing the data inside the script

Code

import requests
from bs4 import BeautifulSoup as bs
my_url='https://www.olx.com.pk/item/oppo-f17-pro8128-iid-1034320813'


with requests.session() as s:
    r=s.get(my_url)
    page_html=bs(r.content,'html.parser')
    safe=page_html.findAll('script')
    print("The Length if Script is {0}:".format(len(safe)))
    for i in safe:
        if "+92" in str(i):
             print(i)

Query

Image 1

Image 2

I Want To Get that phone number that is actually present in windows.state using python script but I donot know how to parse the window.state.Will be very Thankful If you assist me that problem. Thanks in Advance!




Click in puppeteer not working inside ul tag

Below is the portion of html code of the webpage i am scraping using puppeteer. The id's are starting with numericals.

<div class="inner-menu">
   <ul class="module" style="float: left">
      <li id="0" class="moduleclass"><a class="active" href="/eu/alt/dashboard.htm">Home</a></li>
      <li id="4" class="moduleclass"><a class="" href="/eu/stu/studentBasicProfile.htm">Student</a></li>
      <li id="6" class="moduleclass"><a class="" href="/eu/exm/viewStudentExamDefinition.htm">Exam</a></li>

      <li id="7" class="moduleclass">
         <a class="" href="/eu/res/semesterGradeCardListing.htm">Result</a>
      </li>

   </ul>
</div>

I need to click on li with id 7. I tried using the code

await page.waitForSelector("#\\37 ");
await page.click("#\\37 ");

But it is not working.




Live progress status reporting using AJAX and PHP

Good day everyone, I'm trying to create a live progress status report for my automatic course scheduler. Currently, I tried using session variables to achieve my expected functionality but still no luck. Also, some progress report messages aren't displaying and the session variable doesn't seem to update. I would like to seek for help or advice to the stated problems.

For further information, I included below my code and expected and actual results. Thank you

Expected Result for Progress Status Reporting When The System is Automatically Scheduling Courses:

  • [Automatic Course Scheduler]: Initiating to schedule courses that have conflict...
  • [Automatic Course Scheduler]: All courses are successfully scheduled
  • [Automatic Course Scheduler]: Initiating to schedule courses that have no conflict...
  • [Automatic Course Scheduler]: All courses that have no conflict are now all scheduled.

Actual Result for Progress Status Reporting When The System is Automatically Scheduling Courses
Image of Actual Result

CODE:

Javascript (JQuery Lib)

$('.left-section').on('click', '#sp-auto-courses', function(){

            
            $.ajax({
                url: 'application_layer/automated_course_scheduler.php',
                type: 'post',
                success: function(response,status){

                }  

            });
            getProgress();
            function getProgress(){

                $.ajax({
                url: 'application_layer/schedulingLogRealTime.php',
                type: 'post',
                success: function(response,status){
                    if(response.length > 0){
                            
                                $('.schedulinglogs').append(response);
                                getProgress();
                        }else{
                                $("#sw-select-date").val("0").change();
                                    $('#table-responsive').empty();
                                    $('#table-responsive').load('application_layer/course-pagination.php');
                        }

                                

                    }  

                });



            }
        
    


    });

PHP

schedulingLogRealTime.php

<?php
session_start();

if (isset($_SESSION["acs_progress"]) && strlen($_SESSION["acs_progress"]) > 0) {
    sleep(1);
    echo $_SESSION["acs_progress"];
    unset($_SESSION["acs_progress"]);


}
?>

automated_course_scheduler.php

<?php 

require "dbcaller.php";

$timeslotpos = 1;
$inValues = array();
$scheduledTimeslot = array();
//$commaSeparatedInValues = "";
$coursePrioritization = false;
$processResult = array();
$selectWhereNoConflict = array();

$messageLog = array();
//SPREAD CONFLICT CONSTRAINTS DETECT
$spreadConflict = "true";
$selectAllCourseThatHaveConflict = $db->query("Select DISTINCT courses.Course_ID from courses INNER JOIN course_conflict ON course_conflict.Course_ID = courses.Course_ID WHERE CDataset_ID = 1 AND NOT EXISTS (SELECT Course_ID from examination_schedule WHERE course_conflict.Course_ID = examination_schedule.Course_ID)");

//CHECK If There Are Room Scheduled
$queryIfThereAreScheduledRooms = $db->query( "Select RoomID from examination_schedule Where ExamEvent_ID=1 AND RoomID !=0");

if($queryIfThereAreScheduledRooms->numRows() == 0){

    if($selectAllCourseThatHaveConflict->numRows() > 0){
        $coursesThatHaveConflict = $selectAllCourseThatHaveConflict->fetchAll();    
         storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: #8B8000;display: inline'>Initiating to schedule courses that have conflict... </p></p></div>");
             
         
                foreach($coursesThatHaveConflict as $row){

                    //CHECK IF THERE ARE SCHEDULED
                    $get_dataIfThereAreScheduled = $db->query("Select TimeslotPos, ExamScheduleID, Timeslot_ID from examination_schedule WHERE ExamEvent_ID=1 AND Course_ID=0")->fetchArray();
                    foreach($get_dataIfThereAreScheduled as $data){

                            $scheduledTimeslot[] = $data;   
                    }

                            
                    //NEED TO KNOW THE COURSE CONFLICT OF THE COURSES
                    $queryConflict = $db->query("SELECT course_conflict.ConflictCourse FROM course_conflict INNER JOIN courses ON course_conflict.Course_ID = courses.Course_ID WHERE courses.CDataset_ID = 1 AND course_conflict.Course_ID= ?", $row['Course_ID'])->fetchAll();

                    foreach($queryConflict as $row2) {

                            $inValues[] = $row2['ConflictCourse'];
                        
                
                    }
            
                    if($spreadConflict == "false"){
                         $selectWhereNoConflict = $db->query("Select DISTINCT timeslot.Timeslot_ID from timeslot WHERE ExamEvent_ID=1 AND NOT EXISTS (SELECT Timeslot_ID from examination_schedule WHERE timeslot.Timeslot_ID = examination_schedule.Timeslot_ID AND examination_schedule.Course_ID IN (".rtrim(str_repeat("?,", count($inValues)), ",").") AND examination_schedule.ExamEvent_ID=1) ORDER BY STR_TO_DATE (timeslot.Date, '%M %e, %Y'),  STR_TO_DATE (CONCAT(timeslot.Start_Time,' - ',timeslot.End_Time), '%l %p - %l %p') LIMIT 1;", $inValues);

                    }else if($spreadConflict=="true"){


                         $selectWhereNoConflict = $db->query("Select DISTINCT timeslot.Timeslot_ID from timeslot WHERE ExamEvent_ID=1 AND NOT EXISTS (SELECT Timeslot_ID from examination_schedule WHERE timeslot.Timeslot_ID = examination_schedule.Timeslot_ID AND examination_schedule.Course_ID IN (".rtrim(str_repeat("?,", count($inValues)), ",").") AND examination_schedule.ExamEvent_ID=1) AND NOT EXISTS (Select examination_schedule.Timeslot_ID from examination_schedule WHERE timeslot.Timeslot_ID = examination_schedule.Timeslot_ID AND examination_schedule.ExamEvent_ID=1) ORDER BY STR_TO_DATE (CONCAT(timeslot.Start_Time,' - ',timeslot.End_Time), '%l %p - %l %p') LIMIT 1;",  $inValues);   

                        if($selectWhereNoConflict->numRows() == 0){
                            $selectWhereNoConflict = $db->query("Select DISTINCT timeslot.Timeslot_ID from timeslot WHERE ExamEvent_ID=1 AND NOT EXISTS (SELECT Timeslot_ID from examination_schedule WHERE timeslot.Timeslot_ID = examination_schedule.Timeslot_ID AND examination_schedule.Course_ID IN (".rtrim(str_repeat("?,", count($inValues)), ",").") AND examination_schedule.ExamEvent_ID=1) ORDER BY STR_TO_DATE (CONCAT(timeslot.Start_Time,' - ',timeslot.End_Time), '%l %p - %l %p') LIMIT 1;", $inValues);  

                            storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]:  <p style='color: red;display: inline'>Not Enough Timeslot To Equally Spread Each Course: Finding Best Timeslot for ".$row['Course_ID']."</p></p></div>");      
                             

                    

                        }   
                    

                    }

                     if($selectWhereNoConflict->numRows() > 0){
                            $newTimeslotPos = 0;
                            $timeslotId = $selectWhereNoConflict->fetchArray();
                        
                            if(in_array($timeslotId['Timeslot_ID'], array_column($scheduledTimeslot, 'Timeslot_ID')) AND !empty($scheduledTimeslot)){
                                
                                    foreach($scheduledTimeslot as $data){

                                        $updateRowWithCourse = $db->query("UPDATE `examination_schedule` SET `Course_ID`= ? WHERE ExamScheduleID= ?", $row['Course_ID'], $data['ExamScheduleID']);
                                        break;
                                    
                                    }
                                    //$commaSeparatedInValues = "";         
                            }else{

                        
                                $selectCurrentTimeslotPos = $db->query("SELECT COALESCE(MAX(TimeslotPos), 0) as CurrentTimeslotPos FROM examination_schedule WHERE ExamEvent_ID=1 AND Timeslot_ID= ?", $timeslotId['Timeslot_ID']);

                                if($selectCurrentTimeslotPos->numRows() > 0){
                                    $currTimeslotPos = $selectCurrentTimeslotPos->fetchArray();
                                    $newTimeslotPos = $currTimeslotPos['CurrentTimeslotPos'] + 1;
                                }else{
                                    $newTimeslotPos = 1;
                                }

                                $insertCourse = $db->query("INSERT INTO `examination_schedule`(`Course_ID`, `Timeslot_ID`, `ExamEvent_ID`, `TimeslotPos`) VALUES (?,?,'1',?)", $row['Course_ID'], $timeslotId['Timeslot_ID'], $newTimeslotPos);
                                //      $commaSeparatedInValues = "";
                            }
                                
                     }else{
                         storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: red;display: inline'>Cant Schedule Course ID: ".$row['Course_ID']." due to many conflicts</p></p></div>");
                         
                

                     }  

                    $inValues = array();
                    //$commaSeparatedInValues = "";
                    $coursePrioritization = true;
                    $scheduledTimeslot = array();
                    $selectWhereNoConflict = "";

            }

            
                storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: green;display: inline'>All courses are successfully scheduled</p></p></div>");
                 
    
    }else{
            $coursePrioritization = true;
            
             storeMessageToSession("<div ><p style='display: inline'>[Auto Course Scheduler]:  <p style='color: green;display: inline'>All courses that have conflict are already scheduled.</p></p></div>");
             


    }
        

    if($coursePrioritization == true){
            
            $selectAllUnscheduledCourse = $db->query("Select DISTINCT courses.Course_ID from courses WHERE CDataset_ID = 1 AND NOT EXISTS (SELECT Course_ID from examination_schedule WHERE courses.Course_ID = examination_schedule.Course_ID)");

                if($selectAllUnscheduledCourse->numRows() == 0){

                     storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: green;display: inline'>All courses that have no conflict are already scheduled.</p></p></div>");
                     


                }else{

                         storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: #8B8000;display: inline'>Initiating to schedule courses that have no conflict... </p></p></div>");
                         
                        $unscheduledCourses = $selectAllUnscheduledCourse->fetchAll();
                        foreach($unscheduledCourses as $row){

                                //CHECK IF THERE ARE SCHEDULED (REFRESH)
                                $get_dataIfThereAreScheduled = $db->query("Select TimeslotPos, ExamScheduleID, Timeslot_ID from examination_schedule WHERE ExamEvent_ID=1 AND Course_ID=0")->fetchArray();
                                foreach($get_dataIfThereAreScheduled as $data){

                                        $scheduledTimeslot[] = $data;   
                                }

                                $newTimeslotPos = 0;
                                $timeslotId = array();


                                    
                                $timeslotId = $db->query("Select DISTINCT timeslot.Timeslot_ID from timeslot WHERE timeslot.ExamEvent_ID=1 ORDER BY RAND() LIMIT 1;")->fetchArray();                    

                                if(in_array($timeslotId['Timeslot_ID'], array_column($scheduledTimeslot, 'Timeslot_ID')) AND !empty($scheduledTimeslot)){
                                            
                                    foreach($scheduledTimeslot as $data){

                                        $updateRowWithCourse = $db->query("UPDATE `examination_schedule` SET `Course_ID`='".$row['Course_ID']."' WHERE ExamScheduleID=?", $data['ExamScheduleID']);
                                        break;
                                
                                    }

                                                    
                                }else{

                                        $selectCurrentTimeslotPos = $db->query("SELECT COALESCE(MAX(TimeslotPos), 0) as CurrentTimeslotPos FROM examination_schedule WHERE ExamEvent_ID=1 AND Timeslot_ID= ?", $timeslotId['Timeslot_ID']);
                                        if($selectCurrentTimeslotPos->numRows() > 0){
                                            $currTimeslotPos = $selectCurrentTimeslotPos->fetchArray();
                                            $newTimeslotPos = $currTimeslotPos['CurrentTimeslotPos'] + 1;
                                        }else{
                                            $newTimeslotPos = 1;
                                        }

                                        $insertCourse = $db->query("INSERT INTO `examination_schedule`(`Course_ID`, `Timeslot_ID`, `ExamEvent_ID`, `TimeslotPos`) VALUES (?,?,'1',?)", $row['Course_ID'], $timeslotId['Timeslot_ID'], $newTimeslotPos);


                                }

                            $scheduledTimeslot = array();
                        }


    

                     storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: green;display: inline'>All courses that have no conflict are now all scheduled. </p></p></div>");
                     
                            

                }
                    
    }

}else{

    storeMessageToSession("<div><p style='display: inline'>[Auto Course Scheduler]: <p style='color: red;display: inline'>The system can't initiate the automatic course scheduler due to some rooms are scheduled </p></p></div>");
    


}


function storeMessageToSession($message){


    session_start();
    $_SESSION["acs_progress"] = $message;
    session_write_close();

}

?>



How can I design an application for logo design on textile garments?

I would like to know how I can create an interface in html or in some tool to be able to design a web page that allows me to make a design of a textile garment that allows me to change colors and add a logo. I have knowledge in html css laravel

I attach the example of a page that performs these servicesExample




HTML Logic Form Obfuscating Password

I'm attempting to troubleshoot a login issue on an old system that noone here is very familiar with. We have what we believe to be the admin password, but it isn't working. I'm just grasping, but I thought maybe a browser issue, considering how old the system is, so I tried using Postman to see what kind of response I get, which resulted in a failure.

However, I'm noticing now that they seem to be using some method to obfuscate the password, and I don't really understand what it's doing.

The login form method is this.

<form method="post" name='login' action="/?language=en" onsubmit="document.getElementById('submit').disabled = true; document.getElementById('pass').value = CJMaker.makeString(document.getElementById('pass').value);" >

and the CJMaker file contains this.

function CJMaker(e)
{}function _CJMaker_makeString(val)
{if (val == null)
{return val;}var size = val.length;var retVal = new String();var conVal = new String();for (var i = 0; i < size; i++)
{var current = val.charCodeAt(i);current = current^4;conVal += String.fromCharCode(current);}for (var i = size - 1; i >= 0; i--)
{retVal += conVal.charAt(i);}return retVal;}CJMaker.makeString = _CJMaker_makeString;

So it looks like it's just using char codes, and I suspect that the password in the database isn't the actual password, but instead is whatever this would create.

I'm afraid I just do not understand this well enough to reverse it. I'm sure it's simple to some of you javascript guys though.

Can anyone tell me more about what this is doing?




How to detect which values are normal for the regular website response time?

What is website normal response time ? How to detect which values is normal for the regular website? What is the best wayto mesure my page reposnse time ?




Mi css se dañó solo

¿alguna idea de como arreglo esto?¿Y tambien porque pasó? Tristemente no usé repositorio enter image description here




Does anyone know a base64 website decoder?

I knew some time ago a website like (example):

https://base64decode/?VGVzdA==

All you had to do was put the encoded code after the "?"

And it returns on blank page with only the decoded text "Test". Does anyone know this site?

Sorry if I'm expressing myself badly, I don't really have the words to explain. Thank you.




How do I filter a list through a formatted web scraping for loop

I have a list of basketball players that I want to pass through a web scraping for loop I've already set up. The list of players is a list of the 2011 NBA Draft picks. I want to loop through each player and get their college stats from their final year in college. The problem is some drafted players did not go to college and therefore do not have a url formatted in their name so every time I pass in even one player that did not play in college the whole code gets an error. I have tried including "pass" and "continue" but nothing seems to work. This is the closest I gotten so far:

from bs4 import BeautifulSoup
import requests 
import pandas as pd 
headers = {'User Agent':'Mozilla/5.0'}

players = [
   'kyrie-irving','derrick-williams','enes-kanter',
   'tristan-thompson','jonas-valanciunas','jan-vesely',
   'bismack-biyombo','brandon-knight','kemba-walker,
   'jimmer-fredette','klay-thompson'
]
#the full list of players goes on for a total of 60 players, this is just the first handful

player_stats = []

 for player in players:
    url = (f'https://www.sports-reference.com/cbb/players/{player}-1.html')
    res = requests.get(url)
    #if player in url:
        #continue
    #else:
        #print("This player has no college stats")
#Including this if else statement makes the error say header is not defined. When not included, the error says NoneType object is not iterable       
    soup = BeautifulSoup(res.content, 'lxml')
    header = [th.getText() for th in soup.findAll('tr', limit = 2)[0].findAll('th')]
    rows = soup.findAll('tr')
    player_stats.append([td.getText() for td in soup.find('tr', id ='players_per_game.2011')])
    player_stats

graph = pd.DataFrame(player_stats, columns = header)



Is there a way to scrape UI of an app, then display the data with some changes? (Scrape FROM Android TO web)

I want to (very quickly) port an app to web.

The UI is very simple (almost archaic, to be honest). It's all text with one or two buttons per screen.

I'm looking for a way to do the following things:

  1. Read the text on screen.
  2. Send touch events from the buttons in the browser to buttons in the app.

Best case: no emulator and no app UI.




Create public status page with uptime monitoring statistics

Is it safe to create public uptime monitoring statistics page for the users, like this https://app.upzilla.co/statistics/6178




Bootstrap Text Align on the basis of breakpoints

Consider the code:

import React from 'react'
import DarkPattern from '../Assets/dark-pattern.jpg'

const Profile = () => {
    return (
        <div>
            <section className="bg-dark text-light  text-center ">
            <img src='https://i.pinimg.com/originals/ba/c1/37/bac13770cdea801e72852d8dc7160295.png' className='profile-img' alt='profile-img' />
           
                <div className="row px-5 w-75 mx-auto" >
                <div className="text-start col-md-6 col-md-4">
                    <h1>Name</h1>
                    <p>Tag</p>
                </div>
                <div className="text-end col-md-6 col-md-4 ">
                    <h1>Level</h1>
                    <p>Score</p>
                </div>
                </div>
            </section>
        </div>
    )
}

export default Profile

With the output: enter image description here

and in mobile mode: enter image description here

What I want to do in mobile mode is to make the text-align center only on mobile mode. I want to left column to text-align-start and the right to text-align-end. Any ideas??

P.S. Only bootstrap, don't wanna use the CSS Media Queries.




How to make div which fills 100% of ANT

i have very strange issue. I am trying to make div component to fill 100% height of it's parent ANT component. When i try to do like this nothing happens child div doesnt appears at all.

<Tabs
  defaultActiveKey="messages"
  type="card"
  size="large"
  centered
  onChange={(tabKey) => activeIconHandler(tabKey)}
  style=
 >
   <div style=>
   </div>
 </Tabs>

When i replace Tabs with div everything works fine. This code works great.

<div style= >
  <div style=>
  </div>
</div>

Can anyone please explain how to do it with Tabs i really need it for app design and can't refuse from using it. As well i wen't through all ANT documentation and still don't understand. I am using React and ANT framework.




Can I Deploy a Web API and Website Project to same domain?

I have an older ASP.NET Website project I've been maintaining need to add a simple API to it. I got this working in Visual Studio 2019 and am able to browse to the website as well as hit the API. However when I try to deploy this to the final production domain on Godaddy I get the error "The directory '/App_Code/' is not allowed because the application is precompiled.".

I know the Web API project should not have an "App_Code" as that project compiles into on .DLL file.

Is this a publishing setting issue?




How to implement Flask flash Function

I'm hosting a website locally and I'm having trouble implementing the flash functionality in Flask, to display messages to the user interface if they have logged in and if they have logged out, I've been watching a few tutorials to try n fix my problem but I keep getting a 500 Internal Server Error when I refresh the website, but don't get the error when I erase the code in my html n py files. I've been making use of Flask logics in my html files n been extending my header file to all the files, so I don't know why I'm getting this error.

Anybody to assist??




I'm curious about apple homepage

Apple several websites have several scroll animation and I've found out that some devices does not working with the animation.

So I'm wondering, is Apple show the animation only that devices enough performance for animation?




How can I administrate the roles on my project? [closed]

I'm working on a project and I have reached the last part of it. I'm wondering what is the best way to administrate the roles of the users in the website ?! note that the website have more than 20 role (not only admin and users) I used to accomplish this on my previous training projects using if statement with attached database or any other unreasonable way.




this block has encountered an error and cannot be previewed only on medias blocks

guys. I just installed the last version of WordPress (5.7.2) on my computer by using Xampp.

All seem to go well except when I want to add a block related to media only.

Before this, I got some problems with the admin panel which was displayed as a white screen. I searched on youtube and found a solution by adding :

define('CONCATENATE_SCRIPTS', false);

under the comment :

/* That's all, stop editing! Happy publishing. */

Please can you help me??




Web Data fetch is not updating

I am beginner at VBA. I have done the below code by referring to lot of articles found online.

I am trying to fetch API data from a website. It is taking the first fetch and I need the data to be fetched every 5 mins. But it is not refreshing at all. What can I do? Can anyone have a look at the code and advise?

I am using the below code to get the JSON data and later I am extracting using a JSON parser.

Sub FetchOptionChain()
        
        Dim Json As Object
        Dim webURL, webURL2 As String, mainString, subString
        Dim i As Integer
        Dim j As Integer
        Dim k As Integer
        Dim l As Integer
        Dim dtArr() As String
        Dim request, request2 As Object
        Dim HTML_Content As Object
        Dim requestString As String
        
        webURL2 = "https://www.nseindia.com/"
        webURL = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"
        
        subString = "Resource not found"
        
        Set HTML_Content = CreateObject("htmlfile")
        
        'Get the WebPage Content to HTMLFile Object
        With CreateObject("msxml2.xmlhttp")
        .Open "GET", webURL2, False
        .send
        
        End With

FetchAgain:
        
        With CreateObject("msxml2.xmlhttp")
        .Open "GET", webURL, False

        
        'Found online that I have to add the below to remove the cached results. Adding this is hanging the excel and it never comes out of it. Excel is hanging here
        
        .setRequestHeader "Content-Type", "application/json"
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"

        .send
        
        mainString = .ResponseText

        
        
        
If InStr(mainString, subString) <> 0 Then

' Data has not been fetched properly. Will wait two seconds and try again.

Application.Wait (Now + TimeValue("0:00:2"))
GoTo FetchAgain



How to bring origin/master to latest commit without pushing to remote?

I want to make this happen without any pushing to the remote repository.

From this: commit (HEAD -> master)

        `commit (origin/master)`

To : commit (HEAD -> master, origin/master)




Electron - Restrict Internet Access for Renderer

navigate" event of a window's webContents to restrict navigation to certain domains, however this does not cover everything, for example the Fetch API. Is there any way to restrict the sources from which an app me fetch resources or make HTTP requests to?




Bad request when trying to login to website using C#

Good morning,

I am trying to login into this website "https://ift.tt/3hiAWCe" and later get some information of a bunch of products (which are locked behind the Login) on this website.

This is the code I wrote with help of the internet.

string username = "email";
string password = "password";
string formUrl = "https://www.da-shi.de/account";
string formParams = string.Format("email_address={0}&password={1}", username, password);
string cookieHeader;

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}

using (WebResponse resp = req.GetResponse())
{
    cookieHeader = resp.Headers["Set-cookie"];
}

string SitemapURL = "https://www.da-shi.de/wasserpfeifen/shizu/alu/7579/shizu-shisha-light-922-black";
string pageSource = WebRequest_(cookieHeader, SitemapURL);

static string WebRequest_(string cookieHeader, string getUrl)
{
     string pageSource;

     WebRequest getRequest = WebRequest.Create(getUrl);
     getRequest.Headers.Add("Cookie", cookieHeader);
     WebResponse getResponse = getRequest.GetResponse();
     using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
     {
          pageSource = sr.ReadToEnd();
     }
     return (pageSource);
}

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(pageSource);

It returns the Error "Bad Request" and I dont know why...

What am I doing wrong?




dimanche 27 juin 2021

Can I use css/js from dependent module drupal?

I have two modules on Drupal 7. I want to make dependent module load css/js files from other module.

Parent module info:

name = mymodule
description = ParentModule
core = 7.x
version = «7.x-1.0»
configure = admin/config/content/mymodule
files[] = mymodule.module
scripts[] = mymodule.js
stylesheets[all][] = css/main.css
stylesheets[all][] = css/mobile.css

Dependent module info:

name = mysecondmodule
description = DependentModule
dependencies[] = mymodule ; here I inject dependences
core = 7.x
version = «7.x-1.0»
configure = admin/config/content/mysecondmodule

Main module is dependent. All what I want, to create "parent" module, that will contain only css files (and nothing else) that could be loaded from my main and other modules. I know the best way is Themes, but I need that.




how to make svg curve at one end

im using svg for circular progress bar , i want to make one end curve not the both end . how is this possible ? how can i implement one end curve in svg? enter image description here

svg {
  height: 80vh;
  margin: 10vh auto;
  border: 1px solid red;
  display: block;
  transform: rotate(-90deg);
}

svg circle {
  stroke-width: 10;
  fill: transparent;
}

#outer {
  stroke: lightgrey;
}

#inner {
  stroke: blue;
  animation: value 2.5s linear forwards;
  stroke-linecap: round;
}

@keyframes value {
  0% {
    stroke-dasharray: 0 100;
  }
  100% {
    stroke-dasharray: 90 100;
  }
}
<svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle id="outer" cx="50" cy="50" r="40" />

  <circle id="inner" pathLength="100" cx="50" cy="50" r="40" />
</svg>



How can I Implement this functionality of paid subscription for paid blog posts? [closed]

So, I am making a blog website using HTML, CSS, PHP, MySQL. Now I want to add a functionality to my website with which all the visitors of my website can read certain blogs. But to read all the rest of the blogs they have to signup and subscribe to a 1 month/6 month/12-month plan. After the subscription is confirmed by the admin they can easily read all the blogs on my website. And if anyone is trying to read a certain 'paid' blog then they will get a restriction error'. I have figured out how to add the payment and other stuff but what I am struggling with is how I can block public visitors who aren't signed up from viewing paid content. How can I do that?




Return The Records Of Myself And Other Users?

I have this query. It works but it is not returning records for the logged in user, only the users they follow. I want it to do both: return the users own posts plus people they follow on the site

(the code below just duplicates the logged in users own posts)


$FetchFollowing = $db->fetchAll("SELECT  xf_social_feeds.*, xf_user_follow.* 
    FROM xf_user_follow
   JOIN xf_social_feeds
     ON xf_user_follow.follow_user_id = xf_social_feeds.user_id_feeds
    WHERE xf_user_follow.user_id = '$uid'
      OR xf_social_feeds.user_id_feeds = '$uid' 
    ORDER by id DESC LIMIT $DefaultLoadLimit");

I could just put the user in the followers table when they register but i'm hoping to try to find a better solution first even if i have to ask on here




Javascript, fetch a url instead of a direct file path

This works fine:

fetch("./xml/Stories.xml").then((response) => {
  response.text().then((xml) => {
    xmlContent = xml;

But I would like to get my data from a website which has a link that only displays the xml, how would I go about retrieving the data through a link instead of a direct file path?

I.E:

fetch("https://Example.com/").then((response) => {
  response.text().then((xml) => {
    xmlContent = xml;



Is there any way to remove an element from iframed website?

So, I need to add https://www.rapidtables.com/tools/notepad.html in my website and I need to remove the header of their website. Is there any way?




How to run premade javascript files in a website?

I do have simple coding skills. I don't know too much about web development, only the very basics. I usually code in python and never have to use JavaScript or HTML.

So I made a game using Godot. And I exported my game with the html5 export.

It gave me

  • index.html
  • index.js
  • index.pck
  • index.wasm
  • favicon and PNG

I uploaded my game on itch.io, and they just needed a zip file of the above, but now I want to host the game on my own website.

I want to know the both methods of running the code in a small box on the website kind of like how it plays on itch and a way of playing just the app on the whole web page.

Likewise, I did try to research this online, but currently what I lack is how to describe this issue? Because all I search is how to run index.html file or how to implement that HTML in another HTML.

Which as you can guess gave me varied results from which none of them solved the issue and I realized that describing my issue here would be the best thing to do.

Oh, and I'm not going to make only games, so please don't give an answer that works specifically for games.




Trying catch and html tags with regex

I'm trying to catch and with regex format. This is my code: linkregex = re.compile(b'<[link|a] [^>]href='|"['"][^>]?>') but that isn't catching both... any ideas?




is there anyone that can guide me on Cryptocurrency game website [closed]

I need an answer to this quick

I have a project about crypto gaming website can you help me with the requirement need to develop a crypto game website




Error pushing to heroku main after some changes

ERROR

Compiled slug size: 586.5M is too large (max is 500M).
remote:  !     See: http://devcenter.heroku.com/articles/slug-size
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: 96c6f109f09404a40b71aa170bdedba7a3f9b173
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version 96c6f109f09404a40b71aa170bdedba7a3f9b173
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to mathewsjoy.
remote:
To https://git.heroku.com/mathewsjoy.git
 ! [remote rejected] main -> main (pre-receive hook declined)

Ive adding some extra files to my code 1 json, 1 html, 1 png and 2 python, words.pkl,classes.pkl and also chatbot_model.h5. Once i had finished with this I had tryed to do my normal push to github (was a success) and then git push heroku main. But i get the error shown above I have no branches, updated my requirements.txt and done everyone how i normally do it. But iam getting this error. No idea how on earth to fix this tried a few things like git status. But no luck, hope someone can help.

My website works fine like normal, but this commit wont go through.




How to disable redirection of http to https (Nginx, CertBot)

Im trying to not redirect http to https....

I tried to research but found nothing...

BTW I DID BOTH THIS COMMANDS TO MAKE NEW FILE INSTEAD OF USING DEFAULT FILE ON SITES ENABLED:

sudo touch /etc/nginx/sites-available/imallbd
sudo nano /etc/nginx/sites-available/imallbd

then:

sudo ln -s /etc/nginx/sites-available/imallbd /etc/nginx/sites-enabled/imallbd

This is my sites-enabled file

server {

    server_name imallbd.com;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # For API
    location /api {
        alias /var/www/imallbd/api/public;
        try_files $uri $uri/ @api;
            location ~ \.php$ {
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_pass   unix:/run/php/php7.4-fpm.sock;
         }
    }

    location @api {
      rewrite /api/(.*)$ /api/index.php?/$1 last;
    }

    # For FrontEnd -> GraphQL
    location /{
        proxy_pass http://localhost:3001;
        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;
    }

    location /admin{
        proxy_pass http://localhost:3000/admin;
        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;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/imallbd.com/fullchain.pem; # managed >
    ssl_certificate_key /etc/letsencrypt/live/imallbd.com/privkey.pem; # manage>
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot




}
server {
    if ($host = imallbd.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;

    server_name imallbd.com;
    return 404; # managed by Certbot


}

pls help!!! btw when i go to my website it gives me 502 bad gateway... ik thats not the question im asking but if you can give me some help tips or the answer i would be so grateful :)

when i run:

sudo nginx -t

   nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
   nginx: configuration file /etc/nginx/nginx.conf test is successful

If you want more details or information i can give, just tell me on the comments!

THANKS IN ADVANCE!!!




best Public API for weather [closed]

Hello Guys can you tell me which is the best Public API for weather because i want to create a weather web app for just fun but i don't know which is the best API




Pop up box is cutting off [closed]

Pop up box issue

Above page has a link called delegate, when its clicked, it opens up a pop up box. Issue is that pop up box is cutting off.

Not sure how to show it completly.




Why is there a difference between preview of website when viewing http and https?

I have an unclear situation. I have updated my website with html and css content and when I am viewing the http version the website shows up as coded in the CSS file, but when I am viewing the https version the CSS code doesn't apply what I have updated.

So, I have my website here -> This the http version and the Contact section items should have 15 px padding around them, to look more nice and viewable. But when I'm looking at the https version, they look as the initial version, without the stylesheet update. -> https version

Why is this happening?




Django pagination last page is empty

I get empty page errors trying to Page my posts. I have 7 posts but I get a blank page error when I want to go to Page seven and i can't see my last post.

    new_list = list(zip(yeni_ders_tarih, yeni_ders_saat, yeni_ders_ismi,yeni_ders_ogretmen, 
    yeni_derslik, yeni_yoklama))

    paginator = Paginator(new_list, 1)
    
    sayfa = request.GET.get('post')

    page7 = paginator.page('7')
    page = page3.object_list 

    try:
        listeler = paginator.page(post)
    except PageNotAnInteger:
        listeler = paginator.page(1)
    except EmptyPage:
        listeler = paginator.page(1)

Also, I can get page seven manually.

return render(request, 'pages/ogrenci-profil.html', context={
'new_list':listeler,
'page':page
})

This is my template.html

<tbody>
      

This is manually get page seven

This is my page seven error




Visualizing The Data You Sended To a Website

This is my first question on Stack Overflow. And the question is: How can I visualize the data I sended to a website? Can I use the developer tools for Opera GX? I want is to visualize what data I send to facebook.com while logging in. This way I can use the Python Requests module to log in using Python.




Setting.py Configuration for Production mode and Deployment

What I want to do is make all necessary changes in settings.py for Production purpose.When I set DEBUG=True,Everything works all right but when I set DEBUG=False,It makes me feel so tired and depressed.I have been trying for many days but could't figure out.Setting DEBUG=False, Static files runs and some don't but mediafiles completely stop working and i get Server Error (500) in some of the pages.And,I know the fix is in settings.py but don't know how to?


import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = ')osa2y(^uk4sdghs+#(14if-)b1&6_uo@(h#0c%sci^a#!(k@z'

DEBUG = False

ALLOWED_HOSTS = ['dimensionalillusions.herokuapp.com','127.0.0.1']


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    #CUSTOM  APPS
     'EHub.apps.EhubConfig',
     'EBlog.apps.EblogConfig',

     'EDashboard.apps.EdashboardConfig',
     
     'mptt',
     'ckeditor',
     'taggit',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    

    'whitenoise.middleware.WhiteNoiseMiddleware', 
        
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Dimensionalillusions.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        
        'DIRS': [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates'),],
        '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 = 'Dimensionalillusions.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}



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',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/staticfiles/'  


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


STATIC_ROOT=os.path.join(BASE_DIR, 'static')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_ROOT =os.path.join(BASE_DIR, 'staticfiles/mediafiles')  
MEDIA_URL ='/mediafiles/'  


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587

EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''






Import IIFE function from another file

I got a JS file from the server that contains an IIFE function and returns a function, my question is, How I can import it to my main JavaScript file and calling the returned function.

My IIFE file look like this:

var MyIIFE = function() {
    return function(i) {
      return i;
    }
}();

Thanks!




Front-end data is mismatching with back-end data

My front-end data from endpoints look like this:

{"code":200,
 "data":{"id":2,"信任他人程度":"","公平感知能力":"",
         "冒险程度":"","冷酷无情程度":"","反社会人格障碍":"",
         "受害者敏感性":"","受虐受害史":"","对照组编号":"1002",
         "心理理论能力":"","情感操纵":"","情绪智力":"",
         "慷慨程度":"","敌意":"","特质愤怒":"","状态愤怒":"",
         "瑞文智力测验分数":"","疼痛共情能力":"","皮质醇晨起":"7.89",
         "皮质醇睡前":"3.7","皮质醇觉醒反应":"4.69","睾酮":"",
         "社会支持":"","精神病态程度":"","脑电偏侧化睁眼":"0.129831813",
         "脑电偏侧化闭眼":"0.140590362","黑暗人格":""},
 "message":"请求成功",
 "success":true}

My back-end data come from controller looks like this:

KetiTwoGroupOne{id=2, 对照组编号=1002, 脑电偏侧化睁眼=0.129831813, 
                脑电偏侧化闭眼=0.140590362, 皮质醇睡前=3.7, 皮质醇晨起=7.89, 
                皮质醇觉醒反应=4.69, 睾酮=, 冒险程度=, 心理理论能力=, 
                公平感知能力=, 疼痛共情能力=, 慷慨程度=, 信任他人程度=, 
                瑞文智力测验分数=, 冷酷无情程度=, 精神病态程度=, 情感操纵=, 
                黑暗人格=, 受虐受害史=, 反社会人格障碍=, 社会支持=, 
                敌意=, 特质愤怒=, 状态愤怒=, 受害者敏感性=, 
                情绪智力=, 大脑数据指标=../static/ketiTwoDetainees/1_sub3316.bmp} 

They are defined in the same URL with /ketiTwoGroupOne/detail?id=2, could I get to know why they are different in data schema?

I assume that they come from the same data source and the same URL defined.




samedi 26 juin 2021

Is there an alternative to table-cell in CSS?

Whenever I want to align my divs horizontally I use table-cell as float:right/left is not working well for me

These are my divs which I want to align

Here's the CSS for it:

.left-cell {
    display: table-cell;
    width: 86% !important;
    position: relative;
    padding-left: 2vw;
    padding-right: 2vw;
}

.right-cell {
    display: table-cell;
    position: relative;
}

This works fine for most resolutions. Although my colleagues feel that this is not right as we are using table-cell without any table at all.

Is this considered bad practice? If yes, what are some alternatives to this as float is not working well for me?




How to add these specific effects as shown in this portfolio on home page?

so my question here is how to add or which library should I use to add these kinds of effects that are shown in this portfolio - https://patrickheng.com/ over the home page?

Like that ball spongy effect when we hover the mouse over it.

Thanks, any help would be appreciated.

Portfolio - https://patrickheng.com/




Site not updating, and in hostinger/filezilla it did update

I'm trying to update files - I'm using hostinger to host my website, if from the browser I'm accessing the website without https, it shows the website after the update, but if not - it doesn't, I really don't know what it can be, also I've tried from my phone, restarted the internet.. idk I'm really stuck.




NameError: name '_validate_student_' is not defined

I recently imported the LMS project from GitHub. The project is mainly created in Flask. I installed all the required modules and then trying to run the application. I seted the Flask to >>set FLASK_APP=run.py. On flask_run, it gives the following error. I'm not getting how to fix it. Looking forward for suggestions to resolve this error.

  • Serving Flask app 'run' (lazy loading)
  • Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
  • Debug mode: off
Traceback (most recent call last):
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Ali\AppData\Local\Programs\Python\Python38-32\Scripts\flask.exe\__main__.py", line 7, in <module>
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 321, in __init__
    self._load_unlocked()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\Users\Ali\Documents\flask_app\run.py", line 19, in <module>
    from application import app
  File "C:\Users\Ali\Documents\flask_app\application\__init__.py", line 6, in <module>
    import application.students
  File "C:\Users\Ali\Documents\flask_app\application\students.py", line 9, in <module>
    @validate_student
NameError: name 'validate_student' is not defined

C:\Users\Ali\Documents\flask_app>flask run
 * Serving Flask app 'run' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
Traceback (most recent call last):
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Ali\AppData\Local\Programs\Python\Python38-32\Scripts\flask.exe\__main__.py", line 7, in <module>
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 321, in __init__
    self._load_unlocked()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\Users\Ali\Documents\flask_app\run.py", line 19, in <module>
    from application import app
  File "C:\Users\Ali\Documents\flask_app\application\__init__.py", line 6, in <module>
    import application.students
  File "C:\Users\Ali\Documents\flask_app\application\students.py", line 9, in <module>
    @validate_student
NameError: name 'validate_student' is not defined

C:\Users\Ali\Documents\flask_app>flask run
 * Serving Flask app 'run' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
Traceback (most recent call last):
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Ali\AppData\Local\Programs\Python\Python38-32\Scripts\flask.exe\__main__.py", line 7, in <module>
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 321, in __init__
    self._load_unlocked()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "c:\users\ali\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\Users\Ali\Documents\flask_app\run.py", line 19, in <module>
    from application import app
  File "C:\Users\Ali\Documents\flask_app\application\__init__.py", line 6, in <module>
    import application.students
  File "C:\Users\Ali\Documents\flask_app\application\students.py", line 7, in <module>
    app = Flask(_validate_student_)
NameError: name '_validate_student_' is not defined

My Code Is:

from application import app
from flask import render_template, session, redirect, request, flash, escape
from functools import wraps
from flask import Flask
from helper_functions import *

app = Flask(_validate_student_)
@app.route('/students/')
@validate_student
def student_home():
    return render_template('/students/index.html', classes=getStudentClasses())

@app.route('/students/classes/')
@validate_student
def student_classes_home():
    return render_template('/students/classes.html', classes=getStudentClasses())

@app.route('/students/classes/join/', methods=['POST'])
@validate_student
def student_class_join():
    insert_db("INSERT INTO roster (people_id, class_id) VALUES (?, ?);", [session['id'], request.form['id']])
    flash("You joined the class with an id of %s" %(request.form['id']))
    return redirect("/students/classes")