text:
Q: Laravel Mix Vue 3 - Can't compile "TypeError: Cannot read property 'resolve' of undefined" I'm trying to upgrade my Laravel 8 with Vue 2 to Vue 3. I changed all the packages in my package.json to support the new Vue 3 dependencies. I can't even compile a simple test app with Vue 3. The error i'm getting when I try to build isn't giving me much information.
Any one know how to fix this error when I try to "yarn watch"?
λ yarn watch
yarn run v1.22.5
$ mix watch
[webpack-cli] TypeError: Cannot read property 'resolve' of undefined
    at Alias.register (c:\wamp\www\Stipender\node_modules\laravel-mix-alias\index.js:8:37)
    at Object.components.<computed> [as alias] (c:\wamp\www\Stipender\node_modules\laravel-mix\src\components\ComponentRegistrar.js:133:53)
    at Object.<anonymous> (c:\wamp\www\Stipender\webpack.mix.js:15:5)
    at Module._compile (c:\wamp\www\Stipender\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (c:\wamp\www\Stipender\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at module.exports (c:\wamp\www\Stipender\node_modules\laravel-mix\setup\webpack.config.js:4:5)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

package.json
{
    "private": true,
    "scripts": {
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "production": "mix --production"
    },
    "devDependencies": {
        "@babel/core": "^7.12.10",
        "@babel/helper-validator-option": "^7.12.11",
        "@babel/plugin-proposal-optional-chaining": "^7.12.7",
        "@babel/plugin-transform-runtime": "^7.12.10",
        "@babel/polyfill": "^7.11.5",
        "@babel/preset-env": "^7.12.11",
        "@fortawesome/fontawesome-pro": "^5.15.1",
        "@vue/cli-plugin-babel": "^4.5.10",
        "@vue/compiler-sfc": "^3.0.2",
        "babel-loader": "^8.2.2",
        "cross-env": "^7.0.3",
        "jquery": "^3.5.1",
        "laravel-mix": "^6.0.9",
        "lodash": "^4.17.20",
        "node-sass": "^5.0.0",
        "resolve-url-loader": "^3.1.2",
        "sass": "^1.32.2",
        "sass-loader": "^10.0",
        "vue-loader": "^16.1.2"
    },
    "dependencies": {
        "@vee-validate/rules": "^4.0.4",
        "admin-lte": "^3.0.5",
        "axios": "^0.21.1",
        "bootstrap": "^4.5.3",
        "chart.js": "^2.9.3",
        "dayjs": "^1.10.2",
        "laravel-mix-alias": "^1.0.2",
        "mitt": "^2.1.0",
        "moment": "^2.29.1",
        "owl.carousel": "^2.3.4",
        "popper.js": "^1.16.1",
        "primevue": "3.1.1",
        "simple-line-icons": "^2.5.5",
        "style-loader": "^2.0.0",
        "sweetalert2": "^10.13.0",
        "v-calendar": "^2.1.6",
        "vee-validate": "^4.0",
        "vue": "^3.0.5",
        "vue-recaptcha-v3": "^2.0.0",
        "vue-router": "^4.0.0-beta.13",
        "vue-slider-component": "^3.2.11",
        "vuex": "^4.0.0-rc.2",
        "wowjs": "^1.1.3"
    }
}

webpack.mix.js
const mix = require('laravel-mix');
require('laravel-mix-alias');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.alias({
    '@': '/node_modules',
    '~': '/node_modules',
})
    .autoload({ 'jquery': ['window.$', 'window.jQuery', '$', 'jQuery'] })
    .js('resources/website/js/Vue3test.js', 'public/website/js').vue()
    .sass('resources/website/css/app.scss', 'public/website/css')
    .copyDirectory('resources/website/images','public/website/images')
    .copyDirectory('resources/website/images','public/images')
    .copyDirectory('resources/views/emails/images','public/images/email')

    .sourceMaps();

A: Instead of mix.alias({...}), use the mix.webpackConfig.
However, for node_modules you don't need the aliases. For example, to import vue-property-decorator you just do:
import {Vue, Component} from 'vue-property-decorator';

For custom components located for example in /resources/js/, you can do the following:
(Note: I haven't verified with node_modules, but it should work if you replace resources/js with node_modules in the example below.)
mix.autoload({ 'jquery': ['window.$', 'window.jQuery', '$', 'jQuery'] })
    .js('resources/website/js/Vue3test.js', 'public/website/js').vue()
    .sass('resources/website/css/app.scss', 'public/website/css')
    .copyDirectory('resources/website/images','public/website/images')
    .copyDirectory('resources/website/images','public/images')
    .copyDirectory('resources/views/emails/images','public/images/email')

    .webpackConfig({
        resolve: {
            extensions: [".ts", ".tsx", ".js", ".jsx", ".vue", "*"],
            alias: {
                'vue$': 'vue/dist/vue.esm.js',
                '@': path.resolve(__dirname, 'resources/js/'),
                '~': path.resolve(__dirname, 'resources/sass/')
            },
        },
    })

    .sourceMaps();

Then in your tsconfig.json:
"compilerOptions": {
    "paths": {
      "@*": ["./*"]
    }
}

And you can then import components from /resources/js/components/ExampleComponent.vue like so:
import ExampleComponent from '@/components/ExampleComponent'


text:
Q: How to mock axios in outer function? How to mock HTTP responses from axios in outer function?
I have wrapper function for GET request in axios:
export const getRequest = async (
    url: string,
    queryParams: { [key: string]: string; } = {},
    headers: { [key: string]: string; } = {}
): Promise<IhttpResponse> => {
    const config: AxiosRequestConfig = {
        url: url,
        method: 'get',
        headers: headers,
        params: new URLSearchParams(queryParams)
    };
    const response = await axios(config);
    return {status: response.status, body: response.data};
}

This wrapper function called in other function:
export const getCards = async () => {
    const url = `${backendUrl}/card`;
    const res = await getRequest(url);
    return res;
}

And I have Jest test:
import {getCards} from "@/cards_api";
import axios from "axios";
jest.mock("@/http-methods.ts");

test("test one", async () => {
    (axios.get as jest.Mock).mockImplementation(() =>
        Promise.resolve({status: 200, data: {'key': 'value'} })
    );
    const r = await getCards();
    console.log(r);
});

But it falls with error TypeError: _axios.default.get.mockImplementation is not a function
How to correctly test getCards with mocked data?

A: you have to mock the axios module itself rather then your api module.
import axios from 'axios';
import { getCards } from '@/cards_api';

jest.mock('axios');

test("test one", async () => {
    axios.mockResolvedValue({ status: 200, data: { 'key': 'value' } });
    const { status } = await getCards();
    expect(status).toBe(200);
});

using the `jest-mock-axios' module might also be an option for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap 4 100vh container within auto-width column is overflowing I'm fairly new to bootstrap. I have a bootstrap 4 page with three columns. The middle column has a container where I've arranged 4 images in a grid. On large screens, I want this container to be as large as possible while still fitting in the screen (and preserving the aspect ratio of the images inside. I can accomplish something like this through trial and error by manually setting the column width (e.g. col-lg-5), but depending on the aspect ratio of the screen, the image container either does not fill the entire height, or overflows beyond the view. Allowing the column to be auto-width results in the column occupying 100% width (the images are large) which is not what I want. I was able to set the height of the image container to 100% using max-height: 100vh;, and I thought this should do the trick, but the rows inside that container don't scale to fit. Instead, there is overflow in the vertical direction.
Here is the example:

Column 1

Column 2

Column 3

https://www.codeply.com/p/x1EiL25vhm
Current:

Currently, the images are overflowing the container and I can't figure out how to get them to scale properly.
Desired outcome:

I would like the image container to always occupy 100% height with automatic width, until all available space is used on the sides. On small screens the three columns should stack vertically and column 2 will occupy 100% width.

A: A sorta hack that MAY work

*

*Smaller screen sizes need to be though through

*The reason why it will not expand after a certain width is that the inner
  making it
 will expand more

*Reason for max-height:46vh is to allow room for the Column 2 header. Maybe it is better to calc on the fly

Code

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Column 1

Column 2

Column 3


text:
Q: How to use CSS selector to find link by text I am using Java and Selenium to look at a page to see if there is a link with specific text and if not then I go to the next page and check.
My problem is that I can't find a way to find a link based on it's text, I can find them based on their URL but text doesn't seem to work.
This is what I do for the URL:
$("a[href*='foo']")

But when I try the same for text:
$("a[text*='bar']")

It finds nothing.
The only way I know to do this is to get all of the links and loop through them checking to see if the text contains the string I am searching for.
Is there a better way to do this?

A: You can't perform matches to text using CSS selectors.
You can use xpath:
//a[contains(text(), 'bar')]

or
//a[text() = 'bar']

A: While there's no css pseudo selector available for the content of an element, JQUERY implements the :contains in its selector:
$('a:contains("bar")')

Jquery :contains() Selector


text:
Q: Eclipse executa o xml buildfile do ANT 2 vezes, mesmo mandando executar apenas uma vez No netbeans, após algumas pesquisas, consegui editar o arquivo build.xml de modo a personalizar a forma como a IDE gerava meu jar e meu arquivo manifest. Tive que migrar uns projetos para o eclipse, e até achei a opção de construir jar,  mas preciso construir meu jar com algumas informações personalizadas.
Adicionei o arquivo build.xml como um ANT buildfile no meu projeto no eclipse, mas quando mando executá-lo, a IDE executa 2x, gerando 2 arquivos jars de uma vez.
Segue meu arquivo build.xml.
<?xml version="1.0" encoding="UTF-8"?>

<project name="GerOficios" default="makejar" basedir='.'>

    <target name="makejar">

        <property file="version_info.properties" />

        <property name="application.title" value="GerOficios_v6" />

        <property name="main.class" value="com/dfmachado/geroficios/View/ListaDeOficiosUI" />

        <buildnumber file="build.num" />

        <property name="build.version.num" value="${version.number}.${build.number}" />

        <tstamp>
            <format property="TODAY" pattern="dd/MM/yyyy - HH:mm:ss" />
        </tstamp>

        <property name="store.jar.name" value="GerOficios ${build.version.num}" />

        <property name="store.dir" value="store" />
        <property name="store.jar" value="${store.dir}/${store.jar.name}.jar" />

        <echo message="Packaging ${application.title} into a single JAR at ${store.jar}" />

        <mkdir dir="${store.dir}" />

        <jar destfile="${store.dir}/temp_final.jar" basedir="bin" filesetmanifest="skip">
            <zipgroupfileset dir="lib" includes="*.jar" />

            <manifest>
                <attribute name="Main-Class" value="${main.class}" />
                <attribute name="SplashScreen-Image" value="com/dfmachado/geroficios/View/image/minerva.png" />

                <attribute name="Build-OS" value="${os.name} version ${os.version} on ${os.arch}" />
                <attribute name="Java-Version" value="${javac.source}" />
                <attribute name="Implementation-Title" value="${application.title}" />
                <attribute name="Implementation-Version" value="${build.version.num}" />
                <attribute name="Built-By" value="${user.name}" />
                <attribute name="Built-Date" value="${TODAY}" />
            </manifest>
        </jar>

        <zip destfile="${store.jar}">
            <zipfileset src="${store.dir}/temp_final.jar" excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA" />
        </zip>
        <delete file="${store.dir}/temp_final.jar" />

    </target>

</project>

Apenas pra salientar, o eclipse gera o jar do jeito que gerava no netbeans, o problema é o xml ser executado 2 vezes e gerar 2 jars, mesmo eu dando comando apenas uma vez, como pode ser visto no print abaixo:

Após sugestão do @VictorStafusa, executei o ant via linha de comando no mesmo projeto e foi criado apenas um arquivo, aparentemente o problema é alguma configuração no eclipse, mas eu não consegui localizar nenhuma até agora.

A: Após perguntar no SOEn em simultâneo, consegui localizar a causa do problema. Basicamente era ter adicionado o arquivo buildfile do ant nas configurações do Builder do projeto. Como o eclipse, por padrão, compila o projeto automaticamente(até para agilizar a execução do mesmo), ao mandar executar o ant em separado, ele também executava a referencia ao buildfile que adicionei no builder.
A solução dada foi remover/desativar o arquivo build.xml das configurações do Builder do projeto:

E pra chegar ai o caminho é:

Project -> Right Click -> Properties -> Builders


text:
Q: Why it is called Gross and Net I can't find the right keywords to use in google search to find the reason behind on why the whole profit was called Gross and the remaining profit as Net.
I want to know the deeper meaning because I always forgot which is which.


text:
Q: Can't seem to get cin.getline to work help please? Trying to get cin to input to the array, I have the correct header for it but whenever I run the cin part it just skips it and does nothing, I want it to be able to cin a line of text with the spaces.
char a[2000];
cin.getline(a, 2000);
questionsArray[y] = a;

edit: this is within a switch statement although can't see how it would affect it?

A: Generally speaking, std::getline is the better choice, as it works on std::string directly:
#include <string>   // for std::string, std::getline()
#include <iostream> // for std::cin

// ...
std::string a;
std::getline( std::cin, a );


text:
Q: How to partially use Hazelcast with Spring Data? I have a somehow complex application, with a dozen of entities, some of them related in a several-layer hierarchy.
I am trying to introduce Hazelcast for one of the entities, Post. That is, I annotated the instance with @KeySpace, implemented Comparable, Serializable and made its repository, PostRepository extend KeyValueRepository, all as explain in this video https://www.youtube.com/watch?v=r0qlIPXkb-4.
This entity has relations to several other entities, for instance it has a property private List<PostComment> comments.
Now, when I fetch a post from PostRepository, I notice that Hibernate keeps printing the query to fetch it, several joins for the related entities as select ... from post post0_ left outer join post_comment.... I am assuming that Hibernate printing this means that is going to DB and not fetching the data from Hazelcast.
My question is, how do I configure that these entities are also cached by Hazelcast?

A: I think you'd also need to mark all related entities with @KeySpace. Otherwise it will always need to take the relationships directly from the database.
Here's a good Code Sample of adding Hazelcast as a layer in-between the application and database.
In other words, I don't think you can use Spring Data Hazelcast only for part of connected entities.


text:
Q: Working with primitives in XNA Perhaps I am trying to use XNA in a way that it was not designed, but I would very much like to be able to draw my own primitives and save them as a bitmap, or a texture2D, or anything that will hold a few 2d lines for me. My goal is to program a game where the textures are created procedurally, instead of just being loaded from the content manager.
If it helps to know, I've made a Shape class that stores polygons, and I probably could just tell spriteBatch to draw each line out, but I'm trying to optimize by storing commonly used shapes somewhere, instead.

A: You can use a RenderTarget for your task. Something like this:
// var to store your drawing
Texture2D newShape;

// drawing will be on this target
RenderTarget2D rt = new RenderTarget2D(GraphicsDevice, width, height);
SpriteBatch sb = new SpriteBatch(GraphicsDevice);

// set to render all to render target
GraphicsDevice.SetRenderTarget(rt);

GraphicsDevice.Clear(Color.Transparent);

sb.Begin();

// Draw what you want here.

sb.End()

// Return to drawing on "main" buffer
GraphicsDevice.SetRenderTarget(null);

// Save the texture you just drawn
newShape = rt;


text:
Q: I'm getting error while setting Notepad++ as the default Git editor for commits I've been trying to set Notepad++ as my default editor from Git-bash but when I run this command:
git config core.editor "notepad++ -multiInst -nosession"

I get this error:

fatal: not in a git directory

How can I do this?

A: You've forgotten something in your command in your Git :
if you're running x64 machine then try this command
$ git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

The exact location of notepad++ should be placed there with the necessary parameters.

A: git config by default affects the configuration for a specific repository. If you are not in a repository you will get the error you have seen.
If you want to make a user-wide configuration that is not specific to a  repository, use git config --global instead.
See: What is the difference between global and local configuration in git?


text:
Q: A. Find the height of the mountain; B. Find the distance to the nearest kilometre stone From the top of a mountain, in the same vertical plane is two consecutive kilometers stones on the level piece of ground the angles of depression to the kilometer stones are 42° 12 minutes and 23° 30 minutes respectively.
A. Calculate the hate of the mountain
B.  Calculate the distance to the nearest kilometre stone

A: Denote $\alpha = 42^{\circ}12'$, $\beta = 23^{\circ}30'$.
 $h - $ height; $d - $ distance to nearest km stone.
Then
$$\tan \alpha = \dfrac{h}{d}; \tag{1}$$
$$\tan \beta = \dfrac{h}{d+1}. \tag{2}$$
So :
$$
\dfrac{\tan\alpha}{\tan\beta} = \dfrac{h/d}{h/(d+1)}=\dfrac{d+1}{d} =1+\dfrac{1}{d}.
$$
And therefore
$$
d = \dfrac{1}{\dfrac{\tan\alpha}{\tan\beta} - 1}=\dfrac{\tan\beta}{\tan\alpha-\tan\beta}.\tag{3}
$$
Then $h$ can be found easily from $(1), (3)$.


text:
Q: ImportError: No module named 'nose' I tried to help('modules') and there was no nose module.
I even tried pip install nose, sudo pip install nose, and etc..
When ever I tried to install nose with command line, it will throw out
SyntaxError: invalid syntax.
Traceback (most recent call last):
  File "C:\Python34\plot_cluster_iris.py", line 31, in <module>
    from sklearn.cluster import KMeans
  File "C:\Python34\lib\site-packages\sklearn\cluster\__init__.py", line 6, in <module>
    from .spectral import spectral_clustering, SpectralClustering
  File "C:\Python34\lib\site-packages\sklearn\cluster\spectral.py", line 13, in <module>
    from ..utils import check_random_state, as_float_array
  File "C:\Python34\lib\site-packages\sklearn\utils\__init__.py", line 11, in <module>
    from .validation import (as_float_array, check_arrays, safe_asarray,
  File "C:\Python34\lib\site-packages\sklearn\utils\validation.py", line 17, in <module>
    from .fixes import safe_copy
  File "C:\Python34\lib\site-packages\sklearn\utils\fixes.py", line 18, in <module>
    from .testing import ignore_warnings
  File "C:\Python34\lib\site-packages\sklearn\utils\testing.py", line 36, in <module>
    from nose.tools import assert_equal

What should I do?

A: I think your pip3 and python3 versions are mismatched, possibly due to multiple versions of Python 3 installed.
Run pip3 --version to find the exact Python version that pip3 is associated with and the location of site-packages directory.
Then, run python3 and look at the location of site-packages using:
import site
site.getsitepackages()

If you see different directory locations then that's your problem - multiple versions of Python 3. If it is indeed the problem, remove both the versions, re-install the correct one and then install your packages.
I hope this helps!


text:
Q: How to change a simple func into recursive one in django rest API I have an object, which is able to have its own child, that child also has own child, and so on. All of them have the field total_amount_active_channels, which by default is 0. When I change this field in any object (in parents and child as well), the changes should affect in all previous parents.
For example:
A (parent): if changes = 0,  total_amount_active_channels =2
B (child of A): if changes = 0,  total_amount_active_channels =2
C (child of B): if changes = 1,  total_amount_active_channels =2
D ( child of C): if changes = 1,  total_amount_active_channels = 1

But anytime when I open any object, it should plus its own total_amount_active_channels+the total_amount_active_channels of its child.
Now it works with this code, but I want to remake it by recursion. I am not good at recursion!
my view:
class CircuitEditView(generics.RetrieveUpdateAPIView):
    lookup_field = 'pk'
    queryset = Circuit.objects.all()
    serializer_class = CircuitEdit
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated, IsOpuOnly,)

    def perform_update(self, serializer):
        a = bool(self.get_object().first)
        instance = serializer.save(created_by=self.request.user.profile)
        if a != instance.first:
            get_total_amount_active_channels(obj=instance.id_object, instance=instance)

my service.py:
def get_total_amount_active_channels(obj, instance):
    cir = instance.id_object
    while True:
        if cir.id_parent is None:
            if instance.first ==True:
                cir.total_amount_active_channels = int(cir.total_amount_active_channels)+1
                cir.save()
            else:
                cir.total_amount_active_channels = int(cir.total_amount_active_channels) - 1
                cir.save()

            break

        if instance.first == True:
            cir.total_amount_active_channels = int(cir.total_amount_active_channels) + 1
            cir.save()
            cir = cir.id_parent
        else:

            cir.total_amount_active_channels = int(cir.total_amount_active_channels) - 1
            cir.save()
            cir = cir.id_parent

models of Circuit:
class Circuit(models.Model):
    id_parent = models.ForeignKey('Circuit', on_delete=models.CASCADE, blank=True, null=True)
    num_circuit = models.CharField('Номер канала', max_length=100, blank=True, null=True)
    name = models.CharField(unique=True, max_length=100, blank=True, null=True)
    first = models.BooleanField('Используется/Не используется', default = False)
    customer = models.ForeignKey(Customer, related_name='circ_cust', on_delete=models.SET_NULL, blank=True, null=True)
    id_object = models.ForeignKey(Object, related_name='circ_obj', on_delete=models.CASCADE, blank=True, null=True)

model of Object:

    id_parent = models.ForeignKey('Object', on_delete=models.CASCADE,related_name='parents', blank=True, null=True)
    name = models.CharField('Название', max_length=100)

    num = models.CharField('Количество задейственных каналов', max_length=100, blank=True, null=True)

    amount_channels = models.CharField('Количество каналов', max_length=100, blank=True, null=True)
    total_amount_channels = models.CharField(max_length=25, blank=True, null=True)
    total_amount_active_channels = models.CharField(max_length=25, blank=True, null=True)

A: I would do my recursive approach like this:
def get_total_amount_active_channels(obj, instance):
    cir = instance.id_object

    # update this node
    if instance.first:
        cir.total_amount_active_channels = int(cir.total_amount_active_channels) + 1
    else:
        cir.total_amount_active_channels = int(cir.total_amount_active_channels) - 1

    cir.save()

    if cir.id_parent != None:
        # check for recursion
        get_total_amount_active_channels(obj, cir.id_parent)

Anyways, recursion could cause memory problems if the tree you're navigating is big enough and tends to be slower than iterative approaches. I would improve the iterative approach rather than implementing a recursive approach.
If you remove redundant code in your iterative approach, it could be great. I would do something like this:
def get_total_amount_active_channels(obj, instance):
    cir = instance.id_object
    while True:
        # update this node
        if instance.first:
            cir.total_amount_active_channels = int(cir.total_amount_active_channels) + 1
        else:
            cir.total_amount_active_channels = int(cir.total_amount_active_channels) - 1

        cir.save()

        if cir.id_parent is None:
            break
        else:
            cir = cir.id_parent


text:
Q: Unable to connect to failover cluster I have a 2 node failover cluster running on Windows 2008 R2.
The cluster is functioning and I can failover services between the two nodes. All was working fine last week but now nothing can connect to the cluster unless it is on the same subnet as the virtual ip for the resource.
For example:

*

*My machine (different subnet) can ping node 1 (10.255.1.1)

*My machine (different subnet) can ping node 2 (10.255.1.2)

*My machine (different subnet) cannot ping virtual ip (10.255.1.3)

*A server (same subnet) can ping node 1 (10.255.1.1)

*A server (same subnet) can ping node 2 (10.255.1.1)

*A server (same subnet) can virtual ip (10.255.1.3)

There is also nothing in the cluster validation report that suggests it could be causing this issue.
What could be causing this?
Any help would be greatly appreciated

A: see this:
http://support.microsoft.com/kb/244331/en-us#
Gratuitous ARP requests must be forwarded across networks so that all devices receive the updated MAC-to-IP address mappings. Contact your hardware manufacturer for information about how to change your switch or router's configuration so that gratuitous ARP requests are passed to all networks.

A: *

*Check route(s) from "different subnet" to "same subnet"

*Check firewall between "different subnet" to "same subnet"

In case you are pinging DNS names instead of IP's:

*Check DNS

A: try clearing the ARP table from the network end.
Also there could be issues with Ghost NICs if the machines are Virtual machines and if there is a NIC teaming implemented


text:
Q: Is the (inverse) image of an ideal also an ideal? How would you go about proving(or disproving) these two statements.  I feel like they are both true but am struggling with the proof technique/strategy of showing these statements.
If $ϕ: R → S$ is a ring homomorphism and $I$ is an ideal of $R$, then $ϕ(I)$ is an ideal of $S$.
If $ϕ: R → S$ is a ring homomorphism and $I$ is an ideal of $S$, then $ϕ^{−1}(I)$ is an ideal of $R$.

A: If $\Phi$ isn't surjective then the first statement is false; nonetheless $\Phi(I)$ is an ideal of $\Phi(R)$.
The second statement is true, $\Phi^{-1}(I)$ is a subgroup of $R$, now show that : $$\forall (r,x)\in R\times\Phi^{-1}(I),r\cdot x\in\Phi^{-1}(I).$$


text:
Q: Is the following statement mathematically well written? Assuming $\{A,Y,X\}$ are matrices, and $\{f(.),g(.),h(.)\}$ are functions with scalar outputs, and $\vec{x}_i$ is the $i$th column of $X$ and $x_{ti}$ denotes the $t$th row from the $i$th column of $X$.
I want to say that the function $f(Y)$ has its minimum if for each column $\vec{y}_i$ in $Y$ the corresponding $\vec{x}_i$ (based on the relationship $g(\vec{y}_i)\approx h(A,\vec{x}_i)$) has its non-zero entries $x_{ti}$ such that the related columns $t$ in $A$ have their non-zero entires $a_{st}$
with indices $s$ such that both of these two conditions hold:

*

*$\vec{h}_i=\vec{h}_s$

*$\|y_i-y_s\|_2^2$ is sufficiently small

I want to say the above in a clear, condensed mathematical way. I tried the following, but I'm not sure how good it is!
The function $f(Y)$ has its minimum if
$\forall \vec{y}_i$, $g(\vec{y}_i)\approx h(A,\vec{x}_i)$
such that
$\forall \vec{a}_t$, where $\vec{x}_{ti} \neq 0$ and $\forall s$, where $a_{st}\neq 0$, $\vec{h}_i=\vec{h}_s$ and $\|y_i-y_s\|_2^2\leq \epsilon$ for a sufficiently small $\epsilon >0$.


text:
Q: Spring 4 and JSF ViewScope In Spring 3 and JSF 2.0 when we wanted to use the JSF view scope we had to introduce custom ViewScope implementation and instruct Spring to pick it up through CustomScopeConfigurer.
Has Spring 4 made any progress in the JSF integration on this front? Or is it still needed to define custom ViewScope implementation to leverage view scope in spring managed beans?

A: Here is a confirmation from Spring staff of what @fischermatte mentioned: https://jira.spring.io/browse/SPR-6543


text:
Q: Node screenshot from chrome devtools is shifted to right Whenever I try to capture node screenshot from the chrome devtools, element which I want to capture is shifted to right in the screenshot. I am not sure why this happening, I tried googling this but I didn't get any fix. I have attached the screenshot of actual node and the screenshot taken from google devtools.
Actual Node

Screenshot taken from chrome devtool


text:
Q: jQuery find() -- loop through found elements? I'm attempting to apply some CSS to a set of elements using a data attribute each of them has. I'm going through the elements using jQuery's find, but I can't seem to use $(this) to apply any bespoke transformations to the individual elements:
$('#ajax-list').find('a .title').css('background', colours[$(this).attr('data-colour-id')]);

I'm trying to use $(this) to refer to a .title but it's not working. Is there a way to loop through the results of find() to affect each found element individually?

A: You can use the .css( propertyName, function(index, value) ) format to achieve this
$('#ajax-list').find('a .title').css('background', function(){
    return colours[$(this).attr('data-colour-id')];
});


text:
Q: Decrypt and OpenSSL encrypted file I'm trying to make an application on visual studio 2013 to perform the following linux command line task:

openssl enc -aes-192-cbc -d -nosalt -nopad -bufsize 16384 -in $file -K $aeskey  -iv $invec

I've read about openssl.net, but I can't get it work on my project (nuget errors due to framework version no matter the framework version I choose), so I've tried built in .NET libraries, but I don't know if I'm using the right ones. I'm a noob on encryption protocols and I've managed to do this:
Dim decypted As String
Dim rcsp As Rijndael
Dim fStream As IO.MemoryStream
Dim output As Byte()
Dim stream As CryptoStream

rcsp = Rijndael.Create()
rcsp.Key = Encoding.UTF8.GetBytes(sKey) <---- ERROR HERE ---->
rcsp.IV = Encoding.UTF8.GetBytes(sIV)

output = Convert.FromBase64String(sFileToDecrypt)
fStream = New IO.MemoryStream(output)
stream = New CryptoStream(fStream, rcsp.CreateDecryptor, CryptoStreamMode.Write)

The error I'm getting (translated from spanish) is something like: "the specified key does not have the valid size for this algorithm" on the line marked with the error.
My keys sizes are 24 bytes for the key and 32 bytes the initialisation vector; both hexadecimal.


text:
Q: set space between two cells in tableview? How to set spacing between two cells? My code is not working.
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 3)];/// change size as you need.
separatorLineView.backgroundColor = [UIColor whiteColor];// you can also put image here
[cell.contentView addSubview:separatorLineView];
cell.contentView.backgroundColor = [UIColor colorWithHex:@"#E8E8E8"];
cell.contentView.layer.cornerRadius= 6.0;
//    cell.contentView.layer.shadowOffset = CGSizeMake(-1, 1);
cell.contentView.layer.borderWidth = 1.0f;
[cell setLayoutMargins:UIEdgeInsetsMake(10, 10, 10, 10)];

A: You can create sections instead of cells, so that you have 1 cell per section.
And then in the TableView delegate method you can use this :
  // Set the spacing between sections
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return cellSpacingHeight
    }

A: This will help you!
write Inside UITableViewCell subclass
override func layoutSubviews() {
    super.layoutSubviews()

    contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, UIEdgeInsetsMake(10, 10, 10, 10))
}

A: Simplest solution is just add relevant constraint in your cell XIB/Storyboard


text:
Q: Увеличение переменной внутри цикла Подскажите, пожалуйста, как мне сделать, чтобы при каждой итерации j значение переменной k увеличивалось на 5? То бишь когда j=2, то k=5, а когда j=3, то k=10 и так далее.
        for (var j = 2; j < 5; j++) {
            if (number == j) {
                var k = 5;
                for (i = 0; i < 10; i++) {
                    if (i < k || i >= k + 5) {
                        console.log(123);
                    }
                }
            }
        }

A: Если правильно понял, то вот:

for (var j = 2, k = 5; j < 5; j++, k = k + 5) {
            if (true) {
              console.log(k);
                for (i = 0; i < 10; i++) {
                    if (i < k || i >= k + 5) {

                    }
                }
            }
        }


text:
Q: Google map geocoding stops, while executing recursively i am using following function to load latlng of addresses From an array to array about 40, but it stops after 10 iterations.
 loadStoreLatLong(40);

   function loadStoreLatLong(i){

    var paddress = store_locations[i]['address'] +','+store_locations[i]['postal_code'] + ', ' +store_locations[i]['district'] + ',' + store_locations[i]['country'];
    var  pgeocoder = new google.maps.Geocoder();

    pgeocoder.geocode( { 'address': paddress}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

        Storelatlong[i] = results[0].geometry.location;
        i--;

        if(i<0){

   clientLocation();

        }else{

   loadStoreLatLong(i);

    //var t = setTimeout("loadStoreLatLong("+(i)+")",1000);
    //jQuery('#map_canvas').text('Loading ... '+i);

        }
        }
    });
}

i am really stuck there, can any one help to figure it out, when i set time out 1000, this iterates fine 40 time, when i decrease the timeout, iterations also decreases and stop.    thanks

A: Geocoder of Google Maps API Javascript is not suite for much points. They denies continuous accesses in short time.
So please use REST version even if you have 40 points.
https://developers.google.com/maps/documentation/geocoding/

A: The client geocoder is not intended for geocoding lots of points on page load.  It is intended for geocoding user entered addresses.
It is asynchronous and is subject to a quota and rate limit.  The limits are set up such that you can geocode ~10 points quickly (depending on server load).
You should check the status returned, if it indicates that you are over the limit, delay for a period of time and retry.
See Andrew's answer to this question


text:
Q: i want to check different array position in my Linq query I am trying to count no of leaves condition year and month here is my LINQ query-
  leaves = ( from x in obj.Result
            where  (Int64.Parse(x.status) == 1 &&
                  ((x.start_date.Month == month &&
                    x.start_date.Year == selectedyear) &&
                   (x.end_date.Year == selectedyear || x.end_date.Month == month)))
          orderby x.user_id
           select x).ToList();

and I am getting a perfect result but now my start_date and end_date becomes
the array of dates, in that array multiple leaves dates are stored
now I want to check my all record within that array condition year and month
here is my model example
  public DateTime start_date { get; set; }
        public DateTime end_date { get; set; }

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

and here also leaves_Date would be a string  so someone has an idea that how can I set array in my LINQ query


text:
Q: How to pop up the modal div MVC I want to pop up my div class that contains user at password text box but nothings happen and I test also my function if its running correctly that's why I put alert in my function. This my code bellow. I try so many solution and yet still not show my div. Can any give me a best solution regarding this matter or other way to pop up the web form  without leaving my current page.
@model TBSWebApp.Models.User

@{
    ViewBag.Title = "UserLogin";
    Layout = "~/Layout/_webLayout.cshtml";
}

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <fieldset>

                    <button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
                        Sign-in
                    </button>

                                    <button type="button" class="close" data-dismiss="modal">
                                        ×
                                    </button>

Satya Login

                                    <form>

                                            <input class="form-control" type="text" placeholder="Login Username" id="inputUserName" />

                                            <input class="form-control" placeholder="Login Password" type="password" id="inputPassword" />

                                    </form>

                                    <button type="submit" class="btn btn-primary button button4">Sign</button>
                                    <button type="button" id="btnHideModal" class="btn btn-primary button button4">
                                        Hide
                                    </button>

    </fieldset>

        ©

I already solved my problem


text:
Q: Calling Facebook Workplace API I am playing around with Facebook's Workplace API. I have some experience working with Facebook's Graph API using the Graph API explorer, but I don't know how to call the API for workplace in the Graph API explorer. Or is there a separate Graph API explorer tool for Workplace?
Update 1
I have created the Workplace account using my domain email, but my Facebook account was created on my personal Gmail account. The Graph API explorer is opened in my personal Facebook account. Could this also be a problem?

A: This is how I am doing it. I am not using the Graph API explorer, but I am using postman.
Suppose you want to get the list of grp from the workplace.
With a GET req, enter the URL https://graph.facebook.com/community, and in the Headers section, add Authorization Bearer <access token>, press send, and you will see list of grps.
This is how I am doing it now.


text:
Q: Is it possible to create PostgreSQL Databases with dynamic names with the help of Golang? I use Go on my backend. I try to write a function which takes database name and creates PostgreSQL Database with this name. After this function should create tables in this DB (I have already created an sql script for this task)
So the main problem is that I don't understand how to write a function which will create a PostgreSQL Database. I had a thought to create one .sql file and somehow pass database name to this file (for example find string in .sql file, which looks like {{dbname}} and replace it with db name), but may be there is a better way?
Here is my .sql file which should create tables in new PostgreSQL Database
create table "reviews"
(
  review_id  uuid  not null
    constraint review_pk
      primary key,
  user_id  uuid  not null,
  rating  float,
  comment text,
  date  date  not null
);

create unique index reviews_review_id_uindex
  on "reviews" (review_id);

create unique index reviews_user_id_uindex
  on "reviews" (user_id);

create table "sections"
(
  section_id  uuid  not null
    constraint section_pk
      primary key,
  title  text  not null,
  color  text,
  created_at date not null,
  updated_at  date  not null,
  deleted boolean default false
);

create unique index sections_section_id_uindex
  on "sections" (section_id);

A: Try this,
 package main

import (
  "database/sql"
   "log"

   _ "github.com/lib/pq"
)

func main() {
    conninfo := "user=postgres password=yourpassword
    host=127.0.0.1 sslmode=disable"
    db, err := sql.Open("postgres", conninfo)

if err != nil {
    log.Fatal(err)
}
dbName := "testdb"
_, err = db.Exec("create database " + dbName)
if err != nil {
    //handle the error
    log.Fatal(err)
}

//Then execute your query for creating table
   _, err = db.Exec("CREATE TABLE example ( id integer,
   username varchar(255) )")

   if err != nil {
       log.Fatal(err)
   }

}

Note: All query statements don't support parameters in postgress, like ("create database $1", "testdb") won't work.


text:
Q: VBA store formatted text in clipboard I need to copy/store a string of text into the clipboard but need that text to be formatted (font type, color, weight, etc.)
Private Sub copyToCB(varText As String)
    Dim x As Variant
    x = varText

    CreateObject("htmlfile").parentWindow.clipboardData.setData "text", x
End Sub

The above does the job of storing the referred text into the clipboard but it's stored as plain text.  I'd like it to be e.g. bold and red.
I've been scouring the Internet literally for hours, to no avail.  You'd think this would be something straightforward but I'm at a total loss!

A: If you use the clipboard classes from @GMCB found at https://stackoverflow.com/a/63735992/478884
You can do this:
Sub TestCopying()
    CopyWithSomeFormatting "This should paste as red/bold"
End Sub

Sub CopyWithSomeFormatting(txt As String)
    Dim myClipboard As New vbaClipboard 'Instantiate a vbaClipboard object
    myClipboard.SetClipboardText _
        "" & txt & "", "HTML Format"
End Sub

Works for me at least when pasting to Word/Excel


text:
Q: How to process matrix kind of jasper report I'm using jasper reporting to display image in pdf.
Here's the template I'm using for this purpose.
<band height="130" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.HorizontalRowLayout"/>
            <image>
                <reportElement x="0" y="0" width="141" height="130" uuid="9908dc5a-89f7-460b-98b9-521c7aec57b5"/>
                <imageExpression><![CDATA[$F{imagePath}]]></imageExpression>
            </image>
            <image>
                <reportElement x="141" y="0" width="138" height="130" uuid="553c9f56-eb72-4f25-80b7-b315ba3a1dc4"/>
                <imageExpression><![CDATA[$F{productQrPath}]]></imageExpression>
            </image>
            <image>
                <reportElement x="279" y="0" width="138" height="130" uuid="b7f4ad17-e6c9-4f9e-a969-2fed6c6b41c9"/>
                <imageExpression><![CDATA[$F{imagePath}]]></imageExpression>
            </image>
            <image>
                <reportElement x="417" y="0" width="138" height="130" uuid="8d5156b6-5ebc-4681-9cff-b88b1e5e4afd"/>
                <imageExpression><![CDATA[$F{imagePath}]]></imageExpression>
            </image>
        </band>

Basically I want my op in this format https://www.anony.ws/i/2015/09/16/2.png
But I'm getting this kind of https://www.anony.ws/i/2015/09/16/3.png
it's obvious why i'm getting this kind as i'm using same placeholder in a single page.
even after using  JRTableModelDataSource i'm not getting op.
   JRTableModelDataSource dataSource = new JRTableModelDataSource(tbProducts.getModel());
JasperPrint print = JasperFillManager.fillReport(jasper, parameters, dataSource);

Please give me suggestion how i can achieve this.
PS
I don't have enough repo to post image kindly consider link.
EDIT
Even I tried with 2D array just for testing the confusion is how should be the template design.
String members[][] =
            {
              {"Larry", "Curly", "Moe" },
              {"Manny", "Moe", "Jack"},
              {"Huey", "Dewey", "Louie"}
            };
        JasperPrint print = JasperFillManager.fillReport(jasper, parameters, new JasperDataSourceBuilder(members));


text:
Q: Hibernate 6 @Type annotation I upgraded to Springboot 3.0 and in my hibernate entity class has something like:
    @Column(columnDefinition = "jsonb", nullable = false, updatable = true, name = "accounts")
    @Type(type = "jsonb")
    private ArrayList<Account> accounts;

But I'm getting the exception 'Cannot resolve method 'type' since upgrading to Springboot 3.0 and moving to Jakarta persistence.
I need a replacement for com.vladmihalcea.hibernate.type.json.JsonBinaryType;

A: I found the answer:
I had to use the lib:
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-60</artifactId>

and in the entity:
    @Column(columnDefinition = "jsonb", nullable = false, updatable = true, name = "accounts")
    @Type(JsonBinaryType.class)
    private ArrayList<Account> accounts;

A: In Hibernate 6, the mapping annotations are much more typesafe. You're usually required to specify Class references instead of stringly-typed names.

A: If you want to model JSON, I would suggest you to use @JdbcTypeCode(SqlTypes.JSON) which is how you model JSON with plain Hibernate ORM Core. Also see https://docs.jboss.org/hibernate/orm/6.1/userguide/html_single/Hibernate_User_Guide.html#basic-mapping-json


text:
Q: Email , Name are missing in Attribute mapping of AWS Cognito User pool - Sign in with Apple External Identity Provider I created a Cognito User pool and would like to integrate Sign in with Apple as External Provider.
Mapped Apple details as below

In the Attribute Mapping  Email, Name is missing like below

MFA is enabled(required) and Log in with email is selected, email is a required attribute on pool creation.
For User pool 1 email, names are missing in Attribute Mapping?

Created another user pool with MFA optional and Log in with username selected, email is a required attribute on pool creation.
for this user pool email, the name appears in Attribute Mapping?
User pool 2

May I know the reason why Email, Name are missing in Attribute mapping in the Case of User pool1?
Thank you

A: I faced the same issue few days back, try disabling and enabling the sign in with apple is what worked for me


text:
Q: What is Yihan's number? Problem:Haoyu gives Mingze and Yihan two different positive integers, and tells them that the product of their numbers is less than $2022.$ They are also aware that they have two different positive integers. They have the following conversation:
Mingze: I'm not sure whose number is larger.
Yihan: Me neither.
Mingze: Ah! Then my number is larger.
Yihan: Now I know your number!
What is Yihan's number?
$\textbf{(A)} ~41 \qquad \textbf{(B)} ~42 \qquad \textbf{(C)} ~43 \qquad \textbf{(D)} ~44 \qquad \textbf{(E)} ~45$
This question confuses me. Let's just say Mingze's number is $x$, while Yihan's number is $y$. I know that $xy<2022$, but then what? I don't know what to do with the conversation they had. Please enlighten me on how to solve this problem!

A: If Mingze's number were at least $45,$ he would know that Yihan's number must be smaller, or else the product would be at least $45\cdot 46 > 2022.$ Thus, his number is at most $44,$ and by the same reasoning, Yihan's is as well. In fact, Yihan's number is at most $43,$ since otherwise she would know that her number was larger. The only way that Mingze can then know that his number is larger is if it is either $43$ or $44.$ If Yihan's number were $42$ or smaller, she wouldn't be able to figure out which of $43$ or $44$ was Mingze's number, so her number must be $43,$ which is $\fbox{(C)}.$


text:
Q: React hook - onFocus and onBlur I have changed the code from components to hooks.
I'm completely new to it and i'm learning react
and i need help to change it to hooks
what should i do to make it work on functional react ?

*

*update:

*

*I have issued the solutions bellow but when i click on the input it takes me to the top of the page

  const [nameFocused, setNameFocused] = useState(true);
<FormGroup
                    className={classnames("mt-5", {
                      focused: nameFocused,
                    })}
                  >
                    <InputGroup className="input-group-alternative">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="ni ni-user-run" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input
                        placeholder="Your name"
                        type="text"
                        onFocus={(e) => setNameFocused(true)}
                        onBlur={(e) => setNameFocused(false)}
                      />
                    </InputGroup>
                  </FormGroup>

Not relevant:
<FormGroup
                    className={classnames("mt-5", {
                      focused: state.nameFocused,
                    })}
                  >
                    <InputGroup className="input-group-alternative">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="ni ni-user-run" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input
                            placeholder="Your name"
                            type="text"
                            onFocus={e => this.setState({ nameFocused: true })}
                            onBlur={e => this.setState({ nameFocused: false })}
                          />
                    </InputGroup>
                  </FormGroup>
``

A: I'll just tell you how to handle state with hooks, read the docs and try and figure out the other hooks on your own.
This is how you handle state with hooks. First, "declare" the state variable:
const [nameFocused, setNameFocused] = useState(false)

You'll have to import { useState } from react first. The const [..] part is array destructuring. Look it up if you're not familiar. Basically, how this works is, the useState hook returns an array of two things, the first one is the default value to the state variable, and the second is a function to set the state variable. And the value you pass into the useState function is treated as the default value. In this case, it's false. So, after this line of code, we have the nameFocused variable with the value false and the setNameFocused function to set the value of the variable.
Like I already mentioned, the setNameFocused function can be used to the set the value of the state nameFocused. So your onBlur and onFocus handlers will look like:
...
  onBlur={() => setNameFocused(false)}
  onFocus={() => setNameFocused(true)}
...

One important thing to note is that the hooks should always to called in the same order, ie the hooks should never be called in an if block or anything similar.

A: You should use useState hook in your component.
Here nameFocused is a state and setNameFocused is equal to this.setState({ nameFocused: ...}) in class component.
import { useState } from 'react'

...
   const [nameFocused, setNameFocused] = useState(false)

   return (
    <FormGroup
      className={classnames("mt-5", {
        focused: nameFocused,
      })}
    >
      <InputGroup className="input-group-alternative">
        <InputGroupAddon addonType="prepend">
          <InputGroupText>
            <i className="ni ni-user-run" />
          </InputGroupText>
        </InputGroupAddon>
        <Input
              placeholder="Your name"
              type="text"
              onFocus={e => setNameFocused(true)}
              onBlur={e => setNameFocused(false)}
            />
      </InputGroup>
    </FormGroup>

   )
...

A: import React,{useState} from "react"

1 change the class definition to a function definition and delete every this keyword.(command+shift+L) on vscode
let first_function = ()=>{...}

2 change the render() to return
3 group all your state into a single initial state variable[optional]
let initialState = {nameFocused:true || false}

4 Inside your functional component declare your states
let [state,setState] = useState(initialState)

5 when setting state with the useState hook
setState((previousState)=> ({...previousState, newState}))

example:
<Input
    placeholder="Your name"
    type="text"
    onFocus={e => setState((prev)=>({...prev, nameFocused: true }))}
    onBlur={e => setState((prev)=>({...prev, nameFocused: false }))}
  />

6 we have the useReducer hook , and with this you are free from the trouble of always keeping count of the previous state.
react doc react hooks(useReducer)


text:
Q: Kotlin, jackson: cannot annotate @JsonCreator in primary constructor I want to annotate with @JsonCreator using a primary constructor, something like this:
// error
@JsonCreator class User(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

But the @JsonCreator annotation gives an error "This annotation is not applicable to target 'class'".
Using a secondary constructor works, but is it the only (or best) way?:
// works, but is there a better way?
class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

A: What you describe here:
class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

is actually explicitly specifying the primary constructor. You can differentiate the primary from the secondary by looking at the class declaration:
class User constructor(/** **/) { // <-- primary

    constructor(/** ... **/) { // <-- secondary

    }

}

if the constructor is part of the class header it is a primary constructor, if it is part of the class declaration (it is after the {) it is a secondary one.


text:
Q: Prime Number Algorithm Can anyone tell me how to implement Sieve of Eratosthenes algorithm in C? I need to generate prime numbers but my algorithm is slow.
My code:
#include <stdio.h>

int prime(long int i)
{
    long int j;
    int state = 1;
    for(j=2;j<i;j++)
    {
        if((i%j)==0){state=0;break;}
    }
    return state;
}

int main()
{
    int t;
    long int m,n,i;
    scanf("%d", &t);
    while(t--) {
        scanf("%d %d", &m,&n);
        for(i=m;i<=n;i++)
        {
            if(i==1){
                //do nothing for 1
            } else{
                if(prime(i))printf("%d\n",i);
            }
        }
    }
    return 0;
}

t is the number of test cases m and n is the range between which prime are to be printed.

A: In my opinion, your algorithm slow because you calculate the inessential number.
try this code
int isPrime(int number){

    if(number < 2) return 0;
    if(number == 2) return 1;
    if(number % 2 == 0) return 0;
    for(int i=3; (i*i)<=number; i+=2){
        if(number % i == 0 ) return 0;
    }
    return 1;

}

A: Here is actually very simple code that use the Sieve of Eratosthenes algorithm. works for all positive int.
int is_prime(int n){
  int p;
  for(p = 2; p < n; p++){
    if(n % p ==0 && p != n)
      return 0;
  }
  return 1;
}

A: Marc B's link shows a nice and simple algorithm which is correct, written by NSLogan. I wrote a slight modification to it to show some size/speed tradeoffs. I thought I'd share for interest's sake.
First, the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <time.h>

#define USE_BITS

#ifdef USE_BITS
#define alloc_prime char *prime = calloc(i/8+1,sizeof(*prime));
#define set_not_prime(x) prime[x/8]|= (1<<(x%8))
#define is_prime(x) (!(prime[x/8]&(1<<(x%8))))
#endif

#ifdef USE_CHAR
#define alloc_prime char *prime = calloc(i+1,sizeof(*prime));
#define set_not_prime(x) prime[x] = 1
#define is_prime(x) (prime[x] == 0)
#endif

#ifdef USE_SIZE_TYPE
#define alloc_prime size_t *prime = calloc(i+1,sizeof(*prime));
#define set_not_prime(x) prime[x] = 1
#define is_prime(x) (prime[x] == 0)
#endif

int main(){
    int i;
    printf("Find primes up to: ");
    scanf("%i",&i);

    clock_t start, stop;
    double t = 0.0;

    assert((start = clock())!=-1);

    //create prime list
    alloc_prime;
    int c1, c2, c3;
    if(!prime){
    printf("Can't allocate %zu bytes.\n",i*sizeof(*prime));
    exit(1);
    }

    //set 0 and 1 as not prime
    set_not_prime(0);
    set_not_prime(1);

    //find primes then eliminate their multiples (0 = prime, 1 = composite)
    for(c2 = 2;c2 <= (int)sqrt(i)+1;c2++){
      if(is_prime(c2)){
        c1=c2;
        for(c3 = 2*c1;c3 <= i+1; c3 += c1){
          set_not_prime(c3);
        }
      }
    }

    stop = clock();
    t = (double) (stop-start)/CLOCKS_PER_SEC;

    //print primes
    for(c1 = 0; c1 < i+1; c1++){
        if(is_prime(c1))printf("%i\n",c1);
    }
    printf("Run time: %f\n", t); //print time to find primes

    return 0;
}

Since this uses sqrt, to compile use: gcc prime.c -lm
I've compared three different ways of storing the boolean variables that peoro suggested. One method actually uses bits, the second takes an entire byte, and the last uses an entire machine word. A naive guess about which is fastest might be the machine word method, since each flag/boolean is dealt with more 'naturally' by your machine. The timings to calculate the primes up to 100,000,000 on my machine were as follows:
Bits: 3.8s
Chars: 5.8s
M-words: 10.8s
It is interesting to note that even all the ugly bit-shifting necessary to represent a boolean with only one bit is still faster overall. My conjecture is that caching and locality-of-reference seem to outweigh the extra ~3 instructions. Plus, you end up using 1/nth the memory of the n-bit-machine-word method!

A: You need to create an array of booleans as big as the maximum prime number you want to find. At the beginning it's completely initialized to true.
The ith cell of such array will be true if i is a prime number, or false if it's not.
Start iterating from i=2: it's prime, then set to false any cell with an index multiple of 2. Go to the next prime number (i=3) and do the same. Go to the next prime (it's i=5: i=4 is not prime: array[4] was set to false while processing i=2) and do the same again and again.

A: Though it's very old post, Following is my try to generate the prime number using "Sieve of Eratosthenes" algorithm.
#include <stdio.h>

#define NUM 8000        /* Prime Numbers in the Range.  'Range + 2' actually. */

int main()
{
  int a[NUM] = {0};         /* Array which is going to hold all the numbers */
  int i , j;

  /* initializing array from 2 to given number + 2, assuming the first prime number is 2 */
  for(i = 2,j=0; i < NUM+2, j<NUM; i++, j++)
  {
    a[j] =i;
  }

  for(i = 0; i < NUM; i++ )
  {
    int num = a[i];

    /* If number is not 0 then only update the later array index. */
    if(num != 0)
    {
      for (j = i+1; j < NUM; j++)
      {
        if( (a[j]%num == 0) )
        {
            a[j]=0;
        }
      }
    }
  }

  for(i = 0; i < NUM; i++)
  {
    /* Print all the non Zero *Prime numbers* */
    if(a[i] != 0)
    {
      printf("%d \n", a[i]);
    }
  }

}

Hope this will help someone.

A: Fist step is to recognize that it's trivial to split it into arbitrary sized blocks; and that you do NOT need an array (or bitfield) for every number. For example, if you only care about numbers from 100000 to 110000, then to mark all numbers that are divisible by 3 as "not prime" you can do "for( index = 3 * (100000+3-1)/3; index < 110000; index += 3) {". For a more flexible example:
    for( value = 2; value < sqrt( block_end_value-1); value++ ) {
        for( index = value  * (block_state_value+value -1)/value; index < block_end_value; index += value ) {
            mark_not_prime(index - block_state_value);
        }
    }

The second step is to realize that you don't need to care about every number (and the for( value = 2; value < sqrt( block_end_value-1); value++) above is inefficient). For example, if you've already marked numbers that are divisible by 2 as "not prime" then there is no reason to care if numbers are divisible by 4, 6 or 8; and if you've already marked numbers that are divisible by 3 as "not prime" then there is no reason to care if numbers are divisible by 6, 9 or 12; and ... Essentially you only want to test if a number is divisible by another prime number. This means that to find prime numbers in the range 100000 to 110000 you first want to find prime numbers in the range 0 to sqrt(110000); and if you want to find prime numbers in the range 0 to sqrt(110000) you want want to find prime numbers in the range 0 to sqrt(sqrt(110000)); and ....
The third step is to realize that it can be accelerated by copying repeating patterns. You can create a 2-bit pattern (representing "is divisible by 2") and copy those 2 bits everywhere. In the same way you can create a 6-bit pattern (representing "is divisible by 2 or 3") and copy those 6 bits everywhere. In the same way you can create a 39916800-bit pattern (representing "is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10 and 11") and copy that 39916800-bit pattern everywhere. Of course nothing prevents you from pre-generating a pattern and storing it in your program's code.
The fourth step is to realize that multiples of 2 are too trivial to store and by not storing them you halve the memory consumption of all tables and patterns (and any stored/pre-generated pattern).
By combining the third and fourth steps above; a pre-generated pattern representing "is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10 and 11" will cost 19958400 bits, or about 2.38 MiB. On its own the first part of this pattern will also be usable for finding prime numbers from 1 to the first prime number that is larger than 11 (which in this case would be numbers from 1 to 13).
The fifth step is to realize that if you already have a pattern you can use it to find "N = the next "not marked yet" prime number", copy the existing pattern N times, then mark multiples of N as "not prime"; and end up with a larger pattern. For example; if you have a pattern representing "is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10 and 11", you'd skip over 12 (because its not prime according to the existing pattern); copy the pattern 13 times, then mark the numbers that are divisible by 13 as "not prime" and end up with a pattern representing "is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 and 13".
The sixth step is to realize that once you have a pattern large enough for the range you want, you can fill in the missing divisors without copying. For example, if you only want prime numbers in the range from 1 to 6227020800; then you can take a pattern representing "is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 and 13" and then mark numbers that are divisible by prime numbers in the range from 14 to 6227020800 as "not prime".
By combining all of the above; if you want to find prime numbers in the range 1000000000 to 11000000000; then you'd start by finding prime numbers in the range 1 to sqrt(11000000000); and to do that you'd copy a pre-generated pattern and extend it until you have a table that would be large enough to represent prime numbers in the range 1 to sqrt(11000000000); then copy that extended pattern and fill in the missing numbers to generate a table representing prime numbers in the range 1 to sqrt(11000000000); then create a table for prime numbers in the range 1000000000 to 11000000000 and initialise the memory by copying data from the "extended pre-generated pattern" into it, then use the table of prime numbers in the range 1 to sqrt(11000000000) to find prime numbers that haven't already been incorporated into the "extended pre-generated pattern" to find numbers that still need to be marked as "not prime" that you need to generate the table for numbers from 1000000000 to 11000000000.

A: Toomtarm Kung' answer is great, thank's a lot.
There's however still one caveat I stumbled upon: (i*i) may overflow for i>46340 on 32 bit and i>3037000499 on 64-bits, producing incorrect results, i.e. 2147483647 will not be recognised as a prime when using 32-bit integers.
To avoid the integer overflow, one can replace (i * i)<=number by i <= number / i
Now, to avoid a double division, the code may be written as follows:
int isPrime(int number){
    if(number < 2) return 0;
    if(number == 2) return 1;
    if(number % 2 == 0) return 0;
    int j;
    for(int i=3; ((j=number/i) >= i); i+=2){
        if(number - (j * i) == 0 ) return 0;
    }
    return 1;
}


text:
Q: Automatically open a btn-group dropdown and select first element I have the following bootstrap3 drop down menu:

                  Mark done

What I want to achieve is to automatically trigger the drop down and select the first item.
Here is the code I have so far (this code is part of an event handler):
    var menu = $(".dropdown-menu");
    menu.dropdown('toggle');
    menu.first().addClass("active");
    menu.first().focus();

This toggles and shows the drop down menu but does not set the first element to active, hitting tab navigates to something other than the menu items...
What is missing in my code to achieve this?

A: menu.first() returns the .dropdown-menu element itself. You want to select its first child, i.e. the first li, so do:
menu.children().first().addClass('active')


text:
Q: Livesearch - javascript clickable row I am still working on my live search function. It populates perfectly, but now I want to add the clickable row function, which works by itself but not when I integrate it with the other code.
http://www.fpmnky.com/
This is without the clickable code
http://www.fpmnky.com/index2.php
The live search doesn't work after I add the extra code for the clickable row.
This is with the code below:
  <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
  <script type="text/javascript" src="js/jquery.watermark.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script type="text/javascript">

  $(document).ready(function() {

  $("#airport").watermark("");

  $("#airport").keyup(function()
  {
  var airport = $(this).val();
  var dataString = 'keyword='+ airport;
  if(airport.length>1)

  {
  $.ajax({
  type: "GET",
  url: "ajax-search.php",
  data: dataString,
  beforeSend:  function() {

  $('input#airport').addClass('loading');

  },
  success: function(server_response)
  {

  $('#searchresultdata').html(server_response).show();
  $('span#faq_category_title').html(airport);

  if ($('input#airport').hasClass("loading")) {
   $("input#airport").removeClass("loading");
    }

  }
  });
  }return false;
  });
  });

  jQuery( function($) {
$('tr[href]').addClass('clickable').click( function() {
    window.location = $(this).attr('href');
}).find('a').hover( function() {
    $(this).parents('tr').unbind('click');
}, function() {
    $(this).parents('tr').click( function() {
        window.location = $(this).attr('href');
    });
});

$('tr[href]').css( 'cursor', 'pointer' );
$('tr[href]').hover(function() {
$(this).css('cursor','pointer');
});
  });

  </script>

I am guessing it is a formatting issue, I am still new to javascript/jQuery, so help me out here.
Thank you

A: You have an error on line 50.
$("#airport").watermark("");

This watermark function seems to cause a problem. Use Firefox and press strg+shift+k to see the error. On the first page, you don't have this error message. Because of this problem I think tat not all the JS is executed, and I think that's your problem.


text:
Q: Hibernate ошибка работы с БД в новом потоке Связка Hibernate + Spring.
Вызываю метод контроллера, в этом методе в новом потоке запускаю метод сервиса для обновления таблицы в БД.
Первый поток сразу прекращает свою работу (метод контроллера возвращает ответ, что все ок, заполнение таблицы стартовало).
Второй поток в цикле начинает заполнять данными таблицу БД.
Ф-ция слоя DAO для записи данных в таблицу следующая:
@Repository
public class AreaDAO extends BaseDAO<Area> {
    public AreaDAO() {
        super(Area.class);
    }

    public void updateArea(Long areaId, Long regionId){
        Session session = getSessionFactory().openSession();
        Query q = session.createQuery("update Area set region_id =:region_id"+
        " where id=:id and coalesce(is_deleted,0)<>1");
        q.setLong("region_id", regionId);
        q.setLong("id", areaId);
        q.executeUpdate();
        session.close();
    }

}

После пары итераций (пара записей в таблице все-же обновилась) на методе q.executeUpdate() происходит зависание и обновление таблицы БД прекращается.
После продолжительного подвиса в логах сервера появляется ошибка: org.hibernate.engine.jdbc.spi.SqlExceptionHelper Cannot get a connection, pool error Timeout waiting for idle object
Если же весь код я запускаю не в отдельном потоке, а в потоке метода контроллера, то таблица БД обновляется без проблем.
В чем может быть проблема такого поведения?

A: У вас выполняется DML-операция, но нет кода открытия и завершения транзакции. Из-за того, что вы работаете в отдельном потоке, скорее всего, транзакционность не может управляться контейнером прозрачно в этом случае, и надо делать это вручную. Попробуйте добавить transaction = session.beginTransaction() и transaction.commit() вокруг q.executeUpdate(). Также, следует сделать корректное освобождение ресурсов, т.к. сейчас это сделано неверно.
Оберните код в try/catch и добавьте блоки:
    } catch (Exception e) {
        if (transaction != null && transaction.isActive()) {
            transaction.rollback();
        }
        throw e;
    finally {
      if (session != null && session.isOpen()) {
        session.close();
      }
    }

После этих манипуляций, у вас могут возникнуть ошибки связанные с тем, что ручное управление транзакциями может не поддерживаться в вашем окружении. Но это отдельная тема и отдельный вопрос. Если проблема возникнет, можете начать её разбор с этого ответа https://ru.stackoverflow.com/a/486577/183597


text:
Q: Image uploading isnt working properly - Php I have this code:
$name="dsds"

    if(isset($_FILES))
        {
            $imagename = $_FILES['uploadimage'].$name;
            $imagetype = $_FILES['uploadimage'].$type;
            $imagesize = $_FILES['uploadimage'].$size;

            if($imagetype != "image/gif" || $imagetype != "image/jpg" || $imagetype == "image/png" || $imagetype == "image/jpeg")
            {
                $error = 'Please upload an image with JPG, PNG, GIF';
            }
            elseif($imagesize > 716800)
            {
                $error = 'Image Needs to be under 700kb only';
            }
            else
            {
                         $success = 'Uploaded';
                        }

But sometimes it uploads the image but it adds "Array" to the filename , and sometimes it doesnt work at all.

A: Found your mistake. I think you meant
$imagename = $_FILES['uploadimage']['name'];

and not
$imagename = $_FILES['uploadimage'].$name;

A: $imagename = $_FILES['uploadimage']['name'];
$imagetype = $_FILES['uploadimage']['type'];
$imagesize = $_FILES['uploadimage']['size'];

You have to use it like this, name, type and size are not variables but keys


text:
Q: Chrome: page loading is slow until DevTools(F12) shows My env: Chrome 96.0.4664.110 (Official Build) (64-bit) on windows 10
When I open a link in a new page, the page loading is  very slow. I can see the loading icon is running but the page keeps blank for a long time(10 seconds or more).
But when I press F12 to show the DevTools window, the page content loads immediately.
So what is the problem, and how to fix it? Many thanks

A: Same problem for me, finally I realised that it was activated Throttling under the Network tab, and it was selected "Slow 3G" mode,  don't know how it has been activated. As you can see there is an alert icon with the Network tab name


text:
Q: How to add Apache modules to MAMP I use MAMP PRO 4.1 on macOS Sierra
I want to use the following modules in my Apache config:

*

*groupfile_module

*ldap_module

*authnz_ldap_module

*suexec_module

*proxy_html_module

*xml2enc_module

*log_forensic_module

But they are not available by default in the"Servers & Services"->Apache-> modules.
I tried many ways to add them, but none worked, e.g.:

*

*copying them manually from the other Apache modules folder on my machine and adding to the config- the result is just "Apache server cannot be started" without any output to the log

I also created an issue for the MAMP team- http://bugs.mamp.info/view.php?id=5811
Help is appreciated.


text:
Q: Topology: A subset $F$ of $X$ is "closed" if $F' \in T$ It seems like I'm having a very hard time of understanding even the basics of topology. Might be that my problem is poorly worded, but if you understand it then I would greatly appreciate an explanation as simple as possible. Totally blank here.
Assume that $T$ is a topology on $X$. A subset $F$ of $X$ is closed if $F'\in T$ ($F'=X\setminus F$)and let $\mathcal{F}$ be the "family" of all closed sets. Show that

*

*$\emptyset, X\in \mathcal{F}$.

*If $G\subseteq \mathcal{F}$, then $\bigcap_{F\in G} F\in \mathcal{F}$

*If $F_1, F_2,...,F_n$ is a finite number of sets in $\mathcal{F}$, then $F_1 \cup F_2 \cup. . . \cup F_n\in \mathcal{F}$.

Now. I believe that I am supposed to show that the 3 properties of set topology and the statements above correlate, but I really don't know how to show this. Again, I can not stress how clueless I am on this, so the explain like im 5 solution to the procedure and theory is appreciated if possible.

A: I'll do the first two parts to get you started. The third part should be pretty easy after that.
I will continue to use your notation $A'$ for the complement of $A$, although this notation is somewhat nonstandard.
Also, I fixed your typesetting so $\mathcal{F}$ (note the fancy font) now refers to the family of all closed subsets of $X$, as opposed to $F$ to refer to a single closed set.
Part 1
Note that $\emptyset$ and $X$ are open. This is true for any topology, by definition. Since these sets are open, their complements are closed, again by definition. But $\emptyset' = X$ and $X' = \emptyset$. Therefore, $\emptyset$ and $X$ are closed, so they are in $\mathcal{F}$.
Part 2
Suppose $\mathcal{G} \subseteq \mathcal{F}$. This means that $\mathcal{G}$ is a collection of elements of $\mathcal{F}$. Each element of $\mathcal{F}$ is a closed subset of $X$. Therefore, $\mathcal{G}$ is a collection of closed subsets of $X$, and the notation $\bigcup_{F \in \mathcal{G}}F$ simply means the union of this collection.
More typical notation for this situation would be to say that we have a collection of closed sets $F_{\alpha} \subseteq X$, where $\alpha$ ranges over some index set, which we might call $I$. In this notation, $\bigcup_{f \in \mathcal{G}}F$ would instead be written as $\bigcup_{\alpha \in I}F_{\alpha}$. I introduce this notation because it is easier to work with, as it allows us to refer to individual sets $F_{\alpha}$.
So, each set $F_{\alpha}$ in our collection is closed, and therefore by definition each complement $F_{\alpha}'$ is open. Since any union of open sets is open, this means that $\bigcup_{\alpha \in I}F_{\alpha}'$ is open. But then by definition, the complement of this set, which is $\left(\bigcup_{\alpha \in I}F_{\alpha}'\right) = \bigcap_{\alpha \in I}F_{\alpha}$, is closed, and is therefore in $\mathcal{F}$. Since this is precisely what we needed to show, the proof for Part 2 is complete.
You should be able to do Part 3 quite analogously to Part 2.


text:
Q: addEventListener. Вывести переменную которая меняется Есть JSON
{"data":[{"id_brand":"1","name":"BMW"},{"id_brand":"4","name":"Hyundai"}]}

Есть функция для построения таблицы
`
jsonToTable(json) {
        this.Array = [];
        this.tableElement.innerHTML="";
        var tblHead = document.createElement("thead");
        var tblTr = document.createElement("tr");
        this.tableElement.appendChild(tblHead);
        tblHead.appendChild(tblTr);
        for (var key in json[0]) {
            var tblTh = document.createElement("th");
            tblTh.innerHTML = key;
            tblTr.appendChild(tblTh);
        }
        var tblBody = document.createElement("tbody");
        table.appendChild(tblBody);
        for (var i = 0; i < json.length; i++) {
            var tblTr = document.createElement("tr");
            for (var key in json[i]) {
                this.Array[this.Array.length] = document.createElement("td");
                this.Array[this.Array.length-1].innerHTML = json[i][key];
                var t = this.Array.length;
                //Здесь проблема
                this.Array[this.Array.length-1].addEventListener("click",function () {
                    console.log(key);
                },true);
                tblTr.appendChild(this.Array[this.Array.length-1]);
            }
            tblBody.appendChild(tblTr);
        }
        console.log(this.Array);
    }

`

Так вот при нажатие на колонку id_brand срабатывает функция в addEventListener

console.log(key);

И выводится 'name',хотя должно id_brand.
Я так понимаю, что это из-за того что key меняется в процессе выполнения цикла. Как исправить это?
ПС Функция в классе.

A: Когда выполняются обработчики кликов, переменная key имеет значение из последней итерации цикла - как Вы уже заметили. С вызовом функции, которая возвращает функцию-обработчик, происходит "захват" значения этой переменной - в виде параметра, и замыкание, созданное вокруг возвращенной функции-обработчика, видит правильное значение aKey из конкретной итерации цикла.
this.Array[this.Array.length-1].addEventListener("click", (function (aKey) {
  return function() { console.log(aKey); };
})(key), true);


text:
Q: How to properly extract a method in Java intelliJ? EDIT
I am trying to create a 2D platform-game in Java. I have a Player-class that has an update()-method:
public class Player {
...
...
...

    public void update(TileBlock[][] tb, ArrayList<MovingBlock> movingBlocks) {

        // checkBlockCollision(TileBlock[][] tb)
        // checkMovingBlockCollision(ArrayList<MovingBlock> movingBlocks)

        // Bounds for collision
        int x1 = (int) (x + width + GameState.xOffset);
        int y1 = (int) (y + height + GameState.yOffset);
        int x2 = (int) (x + GameState.xOffset);
        int y2 = (int) (y + GameState.yOffset);

        // Tile Block Collision
        for (TileBlock[] tileBlocks : tb) {
            for (int x = 0; x < tb[0].length; x++) {
                if (tileBlocks[x].getID() == 1) {

                    // Right collision
                    if (Collision.playerBlocked(new Point(x1, y2 - 2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1, y1 - 1), tileBlocks[x])) {
                        right = false;
                    }

                    // Left collision
                    if (Collision.playerBlocked(new Point(x2 - 1, y2 + 2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x2 - 1, y1 - 1), tileBlocks[x])) {
                        left = false;
                    }

                    // Top Collision
                    if (Collision.playerBlocked(new Point(x2 + 1, y2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1 - 2, y2), tileBlocks[x])) {
                        jumping = false;
                        falling = true;
                    }

                    // Bottom collision
                    if (Collision.playerBlocked(new Point(x2 + 2, y1 + 1), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1 - 2, y1 + 1), tileBlocks[x])) {
                        y = tileBlocks[x].getY() - height - GameState.yOffset;
                        falling = false;
                        topCollision = true;
                    }
                    if (!topCollision && !jumping) {
                        falling = true;

                    }
                } else if (tileBlocks[x].getID() == 2) {

                    // Right collision
                    if (Collision.playerBlocked(new Point(x1, y2 - 2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1, y1 - 1), tileBlocks[x])) {
                        reachedGoal = true;
                    }

                    // Left collision
                    if (Collision.playerBlocked(new Point(x2 - 1, y2 + 2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x2 - 1, y1 - 1), tileBlocks[x])) {
                        reachedGoal = true;
                    }

                    // Top Collision
                    if (Collision.playerBlocked(new Point(x2 + 1, y2), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1 - 2, y2), tileBlocks[x])) {
                        reachedGoal = true;
                    }

                    // Bottom collision
                    if (Collision.playerBlocked(new Point(x2 + 2, y1 + 1), tileBlocks[x]) ||
                            Collision.playerBlocked(new Point(x1 - 2, y1 + 1), tileBlocks[x])) {
                        reachedGoal = true;
                    }
                }
            }
        }

        // Moving Block Collision
        if (movingBlocks != null && !movingBlocks.isEmpty()){
            for (MovingBlock movingBlock : movingBlocks) {
                if (movingBlock.getID() != 0) {
                    // Right collision
                    if (Collision.playerMovingBlock(new Point(x1, y2 - 2), movingBlock) ||
                            Collision.playerMovingBlock(new Point(x1, y1 - 1), movingBlock)) {
                        right = false;
                    }
                    // Left collision
                    if (Collision.playerMovingBlock(new Point(x2 - 1, y2 + 2), movingBlock) ||
                            Collision.playerMovingBlock(new Point(x2 - 1, y1 - 1), movingBlock)) {
                        left = false;
                    }

                    // Top Collision
                    if (Collision.playerMovingBlock(new Point(x2 + 1, y2), movingBlock) ||
                            Collision.playerMovingBlock(new Point(x1 - 2, y2), movingBlock)) {
                        jumping = false;
                        falling = true;
                    }

                    // Bottom collision
                    if (Collision.playerMovingBlock(new Point(x2 + 2, y1 + 1), movingBlock) ||
                            Collision.playerMovingBlock(new Point(x1 - 2, y1 + 1), movingBlock)) {
                        y = movingBlock.getY() - height - GameState.yOffset;
                        falling = false;
                        topCollision = true;

                        // Move the player the same amount the block is moving
                        GameState.xOffset += movingBlock.getMove();
                    } else {
                        if (!topCollision && !jumping) {
                            falling = true;
                        }
                    }
                }
            }
        }

        topCollision = false;
        double moveSpeed = 2.5;

        if (right) {
            GameState.xOffset += moveSpeed;    // Move the tile-block to the left because the player is moving right
        }
         if (left){
             GameState.xOffset -= moveSpeed;    // Move the tile-block to the right because the player is moving left
         }
         if (jumping){
             GameState.yOffset -= currentJumpSpeed;
             currentJumpSpeed -= 0.1;           // Jump is slowing down at 0.1 pixel per call to update()
             if (currentJumpSpeed <= 0){
                 currentJumpSpeed = startSpeed;
                 jumping = false;
                 falling = true;
             }
         }
         if (falling){
             GameState.yOffset += currentFallSpeed;
             // Fall-speed
             double maxFallSpeed = 5;
             if (currentFallSpeed < maxFallSpeed){
                 currentFallSpeed += 0.1;
             }
         }
         if (!falling) { currentFallSpeed = 0.1; }  // So we fall again without going too fast in the start

        // Player/Enemy collision
        if (Collision.PECollision() && !invincible) {
            health--;
            invincible = true;
            startTime = System.currentTimeMillis();
        }
        if (invincible) {
            int deathDuration = 2000; //in milliseconds
            long duration = System.currentTimeMillis() - startTime;
            if (duration > deathDuration){
                invincible = false;
            }
        }
    }
}

This code works, but update() is very big. So I am trying to extract the two collision-methods, so that I only call them in update(). But when I try to change the code above to this:
public void update(TileBlock[][] tb, ArrayList<MovingBlock> movingBlocks) {

    checkBlockCollision(tb);
    checkMovingBlockCollision(movingBlocks);

    topCollision = false;
    double moveSpeed = 2.5;

    if (right) {
        GameState.xOffset += moveSpeed;    // Move the tile-block to the left because the player is moving right
    }
     if (left){
         GameState.xOffset -= moveSpeed;    // Move the tile-block to the right because the player is moving left
     }
     if (jumping){
         GameState.yOffset -= currentJumpSpeed;
         currentJumpSpeed -= 0.1;           // Jump is slowing down at 0.1 pixel per call to update()
         if (currentJumpSpeed <= 0){
             currentJumpSpeed = startSpeed;
             jumping = false;
             falling = true;
         }
     }
     if (falling){
         GameState.yOffset += currentFallSpeed;
         // Fall-speed
         double maxFallSpeed = 5;
         if (currentFallSpeed < maxFallSpeed){
             currentFallSpeed += 0.1;
         }
     }
     if (!falling) { currentFallSpeed = 0.1; }  // So we fall again without going too fast in the start

    // Player/Enemy collision
    if (Collision.PECollision() && !invincible) {
        health--;
        invincible = true;
        startTime = System.currentTimeMillis();
    }
    if (invincible) {
        int deathDuration = 2000; //in milliseconds
        long duration = System.currentTimeMillis() - startTime;
        if (duration > deathDuration){
            invincible = false;
        }
    }
}

private void checkMovingBlockCollision(ArrayList<MovingBlock> movingBlocks) {
    // Moving Block Collision
    if (movingBlocks != null && !movingBlocks.isEmpty()){
        for (MovingBlock movingBlock : movingBlocks) {
            if (movingBlock.getID() != 0) {
                // Right collision
                if (Collision.playerMovingBlock(new Point(x1, y2 - 2), movingBlock) ||
                        Collision.playerMovingBlock(new Point(x1, y1 - 1), movingBlock)) {
                    right = false;
                }
                // Left collision
                if (Collision.playerMovingBlock(new Point(x2 - 1, y2 + 2), movingBlock) ||
                        Collision.playerMovingBlock(new Point(x2 - 1, y1 - 1), movingBlock)) {
                    left = false;
                }

                // Top Collision
                if (Collision.playerMovingBlock(new Point(x2 + 1, y2), movingBlock) ||
                        Collision.playerMovingBlock(new Point(x1 - 2, y2), movingBlock)) {
                    jumping = false;
                    falling = true;
                }

                // Bottom collision
                if (Collision.playerMovingBlock(new Point(x2 + 2, y1 + 1), movingBlock) ||
                        Collision.playerMovingBlock(new Point(x1 - 2, y1 + 1), movingBlock)) {
                    y = movingBlock.getY() - height - GameState.yOffset;
                    falling = false;
                    topCollision = true;

                    // Move the player the same amount the block is moving
                    GameState.xOffset += movingBlock.getMove();
                } else {
                    if (!topCollision && !jumping) {
                        falling = true;
                    }
                }
            }
        }
    }
}

private void checkBlockCollision(TileBlock[][] tb) {
    // Tile Block Collision
    for (TileBlock[] tileBlocks : tb) {
        for (int x = 0; x < tb[0].length; x++) {
            if (tileBlocks[x].getID() == 1) {

                // Right collision
                if (Collision.playerBlocked(new Point(x1, y2 - 2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1, y1 - 1), tileBlocks[x])) {
                    right = false;
                }

                // Left collision
                if (Collision.playerBlocked(new Point(x2 - 1, y2 + 2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x2 - 1, y1 - 1), tileBlocks[x])) {
                    left = false;
                }

                // Top Collision
                if (Collision.playerBlocked(new Point(x2 + 1, y2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1 - 2, y2), tileBlocks[x])) {
                    jumping = false;
                    falling = true;
                }

                // Bottom collision
                if (Collision.playerBlocked(new Point(x2 + 2, y1 + 1), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1 - 2, y1 + 1), tileBlocks[x])) {
                    y = tileBlocks[x].getY() - height - GameState.yOffset;
                    falling = false;
                    topCollision = true;
                }
                if (!topCollision && !jumping) {
                    falling = true;

                }
            } else if (tileBlocks[x].getID() == 2) {

                // Right collision
                if (Collision.playerBlocked(new Point(x1, y2 - 2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1, y1 - 1), tileBlocks[x])) {
                    reachedGoal = true;
                }

                // Left collision
                if (Collision.playerBlocked(new Point(x2 - 1, y2 + 2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x2 - 1, y1 - 1), tileBlocks[x])) {
                    reachedGoal = true;
                }

                // Top Collision
                if (Collision.playerBlocked(new Point(x2 + 1, y2), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1 - 2, y2), tileBlocks[x])) {
                    reachedGoal = true;
                }

                // Bottom collision
                if (Collision.playerBlocked(new Point(x2 + 2, y1 + 1), tileBlocks[x]) ||
                        Collision.playerBlocked(new Point(x1 - 2, y1 + 1), tileBlocks[x])) {
                    reachedGoal = true;
                }
            }
        }
    }
}

The collisions are not registered and the player just falls through the map and out of bounds instead of landing on the blocks on the map, as intended. What is the correct way to extract the method here? All help is appreciated!

A: I found a mistake that may be causing your problem.
TLDR; Solution
In the already refactored code, you seem to only init your bounding values,
this part :
// Bounds for collision
int x1 = (int) (x + width + GameState.xOffset);
int y1 = (int) (y + height + GameState.yOffset);
int x2 = (int) (x + GameState.xOffset);
int y2 = (int) (y + GameState.yOffset);

where in the original code you seem to init them every time you go in the update() method.
So I believe you only have to move these inits where they belong to make it work.
Proper way to extract method in latest Intellij
Here is simple way to extract method from any code for Intellij:

*

*Select code you want to extract

*Right click, and then unfold Refactor

*Under Refactor, you should see Extract Method..., Left click it

*then, you only have to follow the wizard to set method name, every params etc

EDIT
You added comment while I was responding so, couldn't know you already tried auto method extracting; But first part of my message still remain valid to fix bug


text:
Q: how to form Mysql Join Query For Single Child multiple parent Relationship? Say I have tables T1,T2,T3,T4 like this below ERD

T1 - Dominant Table has 2 child tables (T2,T3),
T4 has 2 parent tables (T2,T3)
How to form a Left join query for this relationship in mysql


text:
Q: Sequencing sanity check The context of my question is the implementation of a simplistic stack-based virtual machine.  My implementation of the addition and multiplication operations looks like this:
    case OP_ADD: Push(Pop() + Pop()); break;
    case OP_MUL: Push(Pop() * Pop()); break;

Since addition and multiplication are commutative operations, it doesn't matter which order the Pop calls are evaluated as long as the side effects (i.e., updating the virtual machine's stack pointer) of the first Pop call (whichever one that is) will be completed before the other Pop call.
With subtraction and division, the order does matter, so we have to ensure we control which Pop is executed first.  For example, here's the implementation of the subtraction operation:
    case OP_SUB: {
        const auto subtrahend = Pop();
        const auto minuend = Pop();
        Push(minuend - subtrahend);
        break;
    }

I've heard vague claims that C++17 has tightened up the sequence-point and sequencing rules, but I've not heard details.  I'm no longer enough of a language lawyer to parse the spec confidently in this regard.
Do the changes in C++17 provide enough sequencing guarantees that subtraction could be implemented as a single expression as with addition and multiplication?  Are the order of the Pop() calls and their side effects defined, implementation-defined, or unspecified?

A: No.
One of the big changes was to certain operators, such as shift operators, which become left-to-right evaluated and this affects stream insertion. But the subtraction operator is not included.
And, honestly, even if that weren't the case, I'd still recommend the code you have now because it is clearly correct when read by a human, in a way that relying on esoteric sequencing rules never will be.