text:
Q: Fetch request from Chrome extension results in 403 Forbidden Whenever I try to send a POST request from background.js of my Chrome extension I get 403 Forbidden error. If I execute the same code outside my Chrome extension it works normally. My API doesn't require any authentication.
Request code:
let formData = new FormData();
formData.append('message', "This is a test message.");

fetch('https://myapi.com/add', {
    body: formData,
    method: "post"
}).then(r => console.log(r));

Request response:

I also checked my Apache 2 access.log and everything seems to look normal:
x.x.x.x - - [13/Sep/2020:17:02:30 +0000] "POST add HTTP/1.1" 403 581 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"

Are there any Chrome extension policies that could block my request?
Do I need to add any special permissions to my manifest.json?
Do I need to make any changes to my API (take this as a reserve, because it works normally outside Chrome extension)?

A:
Edit: Read your server logs. The server is probably telling you exactly what the error is. Make sure debugging is enabled.

403 errors are not really emitted from a server without good reason - and that reason is usually specific to your application. A 403 is generally a permission issue: we know who you are, but you're not authorized to do what you're trying to do.
There might be a header present (or missing) which is preventing the request from making any changes (in your case, a POST request). For example, your server might be setting cookies to prevent CSRF attacks. Many times the server will not validate tokens on GET requests, which may explain why GET requests work in your case but not POST requests.
If you can search your server code, I'm willing to be there is something like this pseudocode:
if (requestIsMissingCSRFToken()) {
  throw new Error(STATUS.FORBIDDEN)
}

Edit: Some relevant links

*

*Django - Working with AJAX, CSRF, & CORS

*POST 403 Forbidden for Chrome extension with Django on the backend

*HTTP POST sent from app to Django Server returns 403 Forbidden

A: The problem was in Django REST framework. Apparently it has a few authentication classes enabled by default. Disabling/setting them to an empty array in settings.py will get rid of the annoying '403 Forbidden' error.
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
    ]
}

EDIT: I don't know how safe this is, but at least it works.

A: I just had the same problem. Thanks so much for posting this. I also work on a Chrome extension with Django backend.
For me deleting 'rest_framework.authentication.SessionAuthentication' from the 'DEFAULT_AUTHENTICATION_CLASSES' did it, but I kept the 'oauth2_provider.contrib.rest_framework.OAuth2Authentication'.
According to this medium article "rest_framework.authenication.SessionAuthentication' is only needed if you want to keep browsable API. I have CSRF and CORS enabled. So I think my setup is very secure.
Below is my settings.py file.
import os

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*xbmoy2yt4%l=od-dm*w$dxpl+rb(n#rmv0n&0x$a@+io!j+++'

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

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'audio.apps.AudioConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig',
    'rest_framework',
    'oauth2_provider',
    #'corsheaders',
]

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

ROOT_URLCONF = 'zeno.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'zeno.wsgi.application'
CORS_ORIGIN_ALLOW_ALL = True

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

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

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

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

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CORS_ORIGIN_ALLOW_ALL = False

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

STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, '..', 'static'),
)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        #'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    # 'DEFAULT_PAGINATION_CLASS': (
    #     'rest_framework.pagination.PageNumberPagination',
    # ),
    # 'DEFAULT_PERMISSION_CLASSES': (
    #     'rest_framework.permissions.IsAuthenticated',
    # ),
    #'PAGE_SIZE': 10
}

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', # To keep the Browsable API
    'oauth2_provider.backends.OAuth2Backend',
)

#STATIC_ROOT = os.path.join(BASE_DIR, "static/")
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'test.com']

AUTH_USER_MODEL = 'accounts.CustomUser'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
#EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails")


text:
Q: JavaScript Quote Generator with Options I`m working on a project and I have to build a quote generator with JavaScript.
The requirements for the project are below:

*

*Select the number of quotes generated (between 1 and 5)

*Choose between 2 types of quote generators (accordingly, you'll need two different sets of sentences)

*Once the quotes are generated, have the program generate new quotes or quit the program

I did 2 generators which are generating random sentences from 3 and 4 fragments. Those 2 generators are working from 2 different buttons
Select the number of quotes generated (between 1 and 5)- Trying to do that with 2 prompts and loop but not really working for the moment. The prompt appears but once the user types in the desired amount of quotes nothing happens.
Once the quotes are generated, have the program generate new quotes or quit the program - Thinking  of using another prompt
My js code:

var beg = [`Peter `, `Michael`, `Lorna`, `Diana`, `Maria`]
var mid = [`prefer`, `looks after`, `has`, `works with`, `is breeding`]
var end = [`dobermans`, `labradors`, `grate danes`, `french buldogs`, `rotweilers`]
function generateQuote() {
  var randomNumber1 = Math.floor(Math.random() * (beg.length));
  var randomNumber2 = Math.floor(Math.random() * (mid.length));
  var randomNumber4 = Math.floor(Math.random() * (end.length));
  for (let i = 0; i < beg.length + mid.length + end.length; i++)
    var randomQuote = beg[randomNumber1] + ` ` + mid[randomNumber2] + ` ` + ` ` + end[randomNumber4]
  document.getElementById('quoteDisplay').innerHTML = [randomQuote];
}
var begg = [`She `, `He`, `It`, `Maddie`, `Josh`]
var midd = [`likes`, `hates`, `loves`, `dislikes`, `adores`]
var midd1 = [`well- trained`, `nice`, `adorable`, `fluffy`, `goodlooking`]
var endd = [`animals`, `pets`, `dogs`, `cats`, `spiders`]
function generateQuote1() {
  var randomNumber1 = Math.floor(Math.random() * (begg.length));
  var randomNumber2 = Math.floor(Math.random() * (midd.length));
  var randomNumber3 = Math.floor(Math.random() * (midd1.length));
  var randomNumber4 = Math.floor(Math.random() * (endd.length));
  var randomQuote = begg[randomNumber1] + ` ` + midd[randomNumber2] + ` ` + midd1[randomNumber3] + ` ` + endd[randomNumber4]
  document.getElementById('quoteDisplay').innerHTML = [randomQuote];
}
var quoteNumber = prompt("How many quotes you would like to generate?", "1");
if (quotenumber != null) {}

Random Quote Generator

<button onclick="generateQuote() ">First type Quote</button>

<button onclick="generateQuote1() ">Second type Quote</button>

A: I think your problem is document.getElementById('quoteDisplay').innerHTML = [randomQuote]. randomQuote is a string not an array here so you could do document.getElementById('quoteDisplay').innerHTML = randomQuote.
Also consider using a for loop here if you want to generate multiple quotes. E.g. for(i =0; i < 5; i++) do quotesArray.push(randomQuote)

A: I think you supposed to have one button on HTML that will generate the quote with the function from the script:
<button id="btn1" onclick="getQuote()">Get New Quote</button>

and in your script.js you should use a different variable to generate the random function and add it to your HTMLPage OR console:
document.getElementById('').innerHTML = //add your fragments together here```

A: Use ES6 Template Literals to display your code on the webpage document.getElementById("text").innerHTML = "${beg[randomNumber1]} ${mid[randomNumber2]} ${end[randomNumber3]}";
and you can also check it on console: console.log("${beg[randomNumber1]} ${mid[randomNumber2]} ${end[randomNumber3]}")

A: Thanks a lot for your response. I removed the brackets and tried your solution but not sure if I get it right
Here is what I did:
function generateQuote() {
    var randomNumber1 = Math.floor(Math.random() *  (beg.length));
    var randomNumber2 = Math.floor(Math.random() *  (mid.length));
    var randomNumber4 = Math.floor(Math.random() *  (end.length));
    for (let i = 0; i < 5; i++) {
        quotesArray.push(randomQuote)
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: SharePoint Event receiver I have created a sharepoint item updating event receiver for a custom list. The event receiver checks certain condition and block the user from saving the item if the condition fails. TO display the warning, i have used
 properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.errormessage= "error";

Now it shows error message below the form in red font. I want to change the formatting of the text, and want to show the error message in bold characters. How can this be achieved, any help on this will be appreciated.
Thanks

A: if you inspect the html, you will find something that might help
span[role="alert"]
{
     font-weight:bold;
}

you can apply this css locally (CEWP) or globally (master page/alternatecssurl reference)

A: Use this one instead
properties.ErrorMessage = "Error";
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CanceWithRedirectUrl;
properties.RedirectUrl = "your custom error page"

You can find more information here


text:
Q: Passing in multiple options for argparse in Python I have been looking at argparse documentation but I am still confused how to use it.
I made a python script to get issues from either pmd, checkstyle, or findbugs after a code analysis. Theses issues are also categorized into severities such as major, blocker, and critical.
So I want to be able to pass in two arguments in the form python script.py arg1 arg2 where arg1 would be a combination of p,c,f which stands for pmd, checkstyle, or findbug and arg2 would be a combination of m,c,b which stands for major, critical, and blocker.
So for instance, if I write python script.py pf cb in the terminal, I would get pmd and findbugs issues of critical and blocker severity.
It would be awesome if someone can give me a general structure of how this should go.
Thanks.

A: Perhaps you'd rather let the user specify the flags more verbose, like this?
python script.py --checker p --checker f --level c --level b

If so, you can use append
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--checker', action='append')
>>> parser.add_argument('--level', action='append')

Then you get a parameter checker and level, both as lists to iterate over.
If you really want to use the combined flags:
for c in arg1:
    run_checker(c, arg2)

Assuming that you just pass the severity levels to the checker in some way.

A: You could try setting boolean flags if each option is present in an argument:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("pcf", help="pmd, checkstyle, or findbug")
parser.add_argument("mcb", help="major, critical, and blocker")
args = parser.parse_args()

# Use boolean flags
pmd  = 'p' in args.pcf
checkstyle = 'c' in args.pcf
findbug = 'f' in args.pcf

major = 'm' in args.mcb
critical = 'c' in args.mcb
blocker = 'b' in args.mcb

This would work using python script.py pf cb.
Also, just a helpful hint. If you place the following at the top of your python file and then make it executable with chmod +x script.py you can then call the file directly (using a *NIX operating system):
#!/usr/bin/env python
import argparse

...

Now run with ./script.py pf cb or even put it in your path and call script.py pf cb

A: https://stackoverflow.com/users/1401034/ewan is a good solution given your specification.  But a slight variation gives users more options, and might be clearer.
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--pmd', action='store_true')
parser.add_argument('-c', '--checkstyle', action='store_true')
parser.add_argument('-f', '--findbug', action='store_true')
parser.add_argument('-m', '--major', action='store_true')
parser.add_argument('-d', '--critical', action='store_true')
parser.add_argument('-b', '--blocker', action='store_true')

args = parser.parse_args()
print args

Sample runs:
1840:~/mypy$ python2.7 stack24265375.py -cfmd
Namespace(blocker=False, checkstyle=True, critical=True, findbug=True, major=True, pmd=False)
1841:~/mypy$ python2.7 stack24265375.py -h
usage: stack24265375.py [-h] [-p] [-c] [-f] [-m] [-d] [-b]

optional arguments:
  -h, --help        show this help message and exit
  -p, --pmd
  -c, --checkstyle
  -f, --findbug
  -m, --major
  -d, --critical
  -b, --blocker
1842:~/mypy$ python2.7 stack24265375.py --critical --major
Namespace(blocker=False, checkstyle=False, critical=True, findbug=False, major=True, pmd=False)

In this case, there are 6 optional, boolean flags.  The short, single letter versions can be strung together in any combination.  Except the necessary '-', this form can look just like the one using 2 positional arguments.  But they can be mixed and matched in any combination.  And the long form is self documenting.
The help display might be clearer if these 6 arguments were divided into 2 argument groups.
parser = argparse.ArgumentParser()
group1 = parser.add_argument_group('issue')
group1.add_argument('-p', '--pmd', action='store_true')
group1.add_argument('-c', '--checkstyle', action='store_true')
group1.add_argument('-f', '--findbug', action='store_true')
group2 = parser.add_argument_group('severity')
group2.add_argument('-m', '--major', action='store_true')
group2.add_argument('-d', '--critical', action='store_true')
group2.add_argument('-b', '--blocker', action='store_true')

args = parser.parse_args()
print args

with the help:
usage: stack24265375.py [-h] [-p] [-c] [-f] [-m] [-d] [-b]

optional arguments:
  -h, --help        show this help message and exit

issue:
  -p, --pmd
  -c, --checkstyle
  -f, --findbug

severity:
  -m, --major
  -d, --critical
  -b, --blocker


text:
Q: \title after \begin{document}: When to do it? My answer to Problem using \alert{} in Beamer title with metropolis theme solves an incompatibility problem between TiKZ and \title with \protect-ed contents in beamer documents.
Following code fails:
\documentclass{beamer}
\usepackage{tikz}

\title{Hello \protect\alert{World}!} %<- before \begin{document}
\begin{document}
\maketitle
\end{document}

and next one works
\documentclass{beamer}
\usepackage{tikz}

\begin{document}
\title{Hello \protect\alert{World}!}%<- after \begin{document}
\maketitle
\end{document}

If the title is \title{Hello World!}, there's no problem placing it in preamble.
I found the answer by trial and error and because I remembered some similar answer in TeX.SX. I would like to know why the error happens and why the solution works.
While I was writting this question Should I place \title, \author, \date in the preamble or after \begin{document}? appeared in my browser. My resume from it  is that it doesn't matter if title commands are declared in preamble or inside the document before \maketitle except when it matters. Then my question is when it matters? Only in beamer? when using \protect? when using TiKZ? Is there any general recipe?

A: Ultimately the issue here, I think, boils down to two things:

*

*If you use \title before \begin{document}, it ends up being incorporated in the PDF properties. After \begin{document} and such inclusion is too late.

*PDF properties are sensitive since they can handle some TeX-related macros, but not everything. And, the beamer class does a lot to allow for its overlay specifications and templates. Specifically, \alert and everything defined with an overlay specification under \newcommand-and-friends will surely cause issues if they end up in the PDF properties.
To examine (1), consider the following minimal examples:
exampleA.tex:
\documentclass{beamer}

\title{Hello world!}% title before \begin{document}

\begin{document}

\maketitle

\end{document}

exampleB.tex:
\documentclass{beamer}

\begin{document}

\title{Hello world!}% title after \begin{document}

\maketitle

\end{document}

Both yield the same output, but the PDF properties are different. exampleA.pdf yields

while exampleB.pdf yields

This is because beamer sets the document option \beamer@autopdfinfotrue by default in beamer.cls and calls
\ifbeamer@autopdfinfo%
  \g@addto@macro\beamer@firstminutepatches
  {
    \begingroup
      \let\beamer@saved@hook\pdfstringdefPreHook
      \pdfstringdefDisableCommands{%
        \let\\=\
        \let\newline=\\%
      }%
      \let\thanks=\@gobble%
      \hypersetup{pdftitle={\inserttitle\ifx\insertsubtitle\@empty\else\ - \insertsubtitle\fi}}
      \global\let\pdfstringdefPreHook\beamer@saved@hook
    \endgroup
  }
\fi%

in beamerbasetitle.sty. Note the call to \hypersetup{pdftitle={...}} that \inserts the title.
In support of (2), you can redefine \alert to not use an overlay specification nor templates (say, \def\alert#1{\textcolor{red}{#1}}) and see that the number of errors during compilation decreases (or it actually compiling).

The proposed solution here would be to distinguish between PDF-related content and TeX-related content using \texorpdfstring{<tex>}{<pdf>}:
\documentclass{beamer}

%\usepackage{tikz}% With or without tikz
\title{Hello \texorpdfstring{\protect\alert{world}}{world}!}

\begin{document}

\maketitle

\end{document}

Of course, you can also go overboard and use
\let\oldalert\alert% Store \alert in \oldalert
\let\alert\relax% Make \alert a null-op
\AtBeginDocument{\let\alert\oldalert}% Restore \alert at \begin{document}

or something similar for anything that may be problematic for inclusion in the PDF properties.


text:
Q: Using derived class for UserControl - how to eliminate blue-lining in xaml editor? I'm trying to use a C# class derived from UserControl as the base class for some xaml pages' layout root, so I can share some common functionality.  I.e. the backing class is like:
public class BaseView : UserControl
{
    // Some virtual functions I want in common ...
}

public class MyView : BaseView
{
    // Overidden functions ...
}

The xaml file then references the class like:
<jt:BaseView x:Class="ns.MyView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:jt="clr-namespace:ns"
    ...>
</jt:BaseView>

This seems to work when running, but in the xaml editor, the code is all underlined with blue squiggly lines, with a fly-over message of something like "Cannot create instance of BaseView".
If I don't do this, and use UserControl in the xmal, I get errors because the partial class generated from the xaml then has the UserControl base class and not my custom base class.
How do I get the editor to know about my custom base class (i.e. get rid of the blue underlines)?

A: The most common cause for a design time "Cannot create instance..." sort of error is that the constructor of the element is doing something that doesn't make sense or is unavailable at design time.


text:
Q: Connect to TFS using proxy I'm using the following code to connect to TFS
TfsTeamProjectCollection server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverName));
server.EnsureAuthenticated();

It works fine. Recently though we've moved from on-premises TFS to VSTS (in the cloud). The above still works, but a local proxy server has been setup to help speed up our connection. I can configure that by following the above code with this:
var versionControlServer = server.GetService<VersionControlServer>();
versionControlServer.ConfigureProxy(proxyName);

This seems to connect fine the first time. But, if I restart my app, the `EnsureAuthenticated' call fails with exception:
Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access mycorp.visualstudio.com\mycorp.
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.SendRequest()
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpRequestChannel.Request(TfsMessage message, TimeSpan timeout)
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, TimeSpan timeout, Object[]& outputs)
       at Microsoft.TeamFoundation.Framework.Client.LocationWebService.Connect(Int32 connectOptions, Int32 lastChangeId, Int32 features)
       at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.Connect(ConnectOptions connectOptions)
       at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.EnsureConnected(ConnectOptions optionsNeeded)
       at Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.EnsureAuthenticated()
       at Microsoft.TeamFoundation.Client.TfsConnection.EnsureAuthenticated()

To get it working again I've found if I quit Visual Studio I can then delete the folder "C:\Users\MyUser\AppData\Local\Microsoft\Team Foundation\6.0\Cache". When I run my app again, then it will connect ok. But, this workaround won't work in production.
How can I connect using the proxy and connect more than once?

A: After install Microsoft.IdentityModel.Clients.ActiveDirectory 2.28.3 package to my project (console application), then it is working fine.


text:
Q: VSTS Service Hooks - On Build Creation / Edition We are looking to add a service hook to call an API when any of our build definitions are edited or when someone creates a new build definition. In the list of options available for WebHooks, I only see an option "Build Complete" with respect to builds (as shown below).
Is there a way, we can add to the list of triggers on VSTS?

A: There isn't such feature available in VSTS now, there is a user voice that you can vote: add service hook for build definition create/delete/modify


text:
Q: How to configure cppcheck to detect memory leaks in linux souce code I want to try some open source static analysis tools to check their performance in detecting leaks on linux source code.I am starting with cppchecker.
In linux most of the memory allocation calls are made through functions like kmalloc(), kzalloc() and corresponding free function is kfree(). How can I configure cppchecker to track kmalloc calls instead of default malloc() call?There is something called creating a new config file where we can define user preferences but i cant figure out how to do that.
Also as a follow up to the above question does cppcheck performs interprocedural analysis for memory leak detection? What other open source static analysis tools I can use for this purpose?

A: I am a Cppcheck developer.
It is true that there are old builtin handling for kmalloc etc. A good start is to check the kernel with the builtin knowledge. No cfg file is needed.
However with a cfg file you can enhance cppcheck.
Here is a start:
<?xml version="1.0"?>
<def format="1">
    <memory>
        <dealloc>kfree</dealloc>
        <alloc init="false">kmalloc</alloc>
        <alloc init="true">kzalloc</alloc>
    </memory>
</def>

Save that text in a file with a name such as kernel.cfg and then use for instance --library=kernel to use that info during cppcheck analysis.
There are lots of missing info here in this cfg. If you use --check-cfg , Cppcheck will complain when it is confused during analysis and wants more cfg-info. It mainly needs noreturn information about functions and also if a function is "leak-ignore".
You can look in our official std.cfg file, for instance at the configuration for strcmp(). This configuration explicitly says that strcmp() is not noreturn. The configuration also has a "leak-ignore" attribute - because if you can pass a pointer to the allocated memory to strcmp() then the leaks-checker should ignore this because the strcmp() will not cause any deallocation etc.
Let us know if you have questions about how it works.

A: Are you quite sure that cppcheck is not already able to check for kernel allocation leaks?  The source code looks strongly like it treats kmalloc and so on just like malloc.  Look at the testmemleak.cpp file in the cppcheck repository for example and you see test cases that exercise a bad kmalloc.
As far as interprocedural analysis goes, I don't believe that cppcheck does this.  I speculate that GCC might be able to do a little based on the -flto flag, but I am not an expert.


text:
Q: reuse issue in UITableView I have UITableView which covers whole screen (480px).
Each cell is of height 300px.
I have total 5 rows.
Below is the code what I have used.
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
    }

    UIButton *myButton = (UIButton *)[cell viewWithTag:999999999];
    int i = indexPath.row+1;
    myButton.tag = i;
    myButton.titleLabel.text = [NSString stringWithFormat:@"B - %d", i];
    [myButton setTitle:[NSString stringWithFormat:@"B - %d", i] forState:UIControlStateNormal];
    NSLog(@"tag set is %d & text for button is =====B-%d====", i,i);
    [myButton addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

- (int) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

-(IBAction)btnSelected:(id)sender {
    UIButton *button = (UIButton *)sender;
    NSLog(@"my tag after click is ===%d", [button tag]);
}

Now when I run this code, I was expecting each cell will have B - 1 to B - 5 written. However after B - 3, all I see is B - 1 and B- 2.
NSLog says as below.
2013-07-28 23:31:34.281 NewTest[1783:11303] tag set is 1 & text for button is =====B-1====
2013-07-28 23:31:34.284 NewTest[1783:11303] tag set is 2 & text for button is =====B-2====

Now when I scroll fully down, I get NSLog as below.
2013-07-28 23:31:34.281 NewTest[1783:11303] tag set is 1 & text for button is =====B-1====
2013-07-28 23:31:34.284 NewTest[1783:11303] tag set is 2 & text for button is =====B-2====
2013-07-28 23:32:03.643 NewTest[1783:11303] tag set is 3 & text for button is =====B-3====
2013-07-28 23:32:03.719 NewTest[1783:11303] tag set is 4 & text for button is =====B-4====
2013-07-28 23:32:03.835 NewTest[1783:11303] tag set is 5 & text for button is =====B-5====

Now when tag and text are set properly why I see last two buttons as B-1 and B-2 instead of B-4 and B-5.
Any idea how to solve this problem?
Screenshot 1

Screenshot 2

Screenshot 3

Any idea how to solve this problem so that I have B-1 to B-5 written?

Note : If I decrease the height of the cell to 100, I see all button text as B-1 to B-5.
This question is related to my old question, but this is simpler version.
Sample Project

What I did is, not used tag and using accessibilityValue, I am fetching the button clicked id.

A: As you scroll down, the table view will reuse the cells that are no longer visible as it needs to display additional cells. The first time this happens is for cell "B-3". Because the table view is reusing a cell, the tag for the button in the cell was already previously set by your code to some number (probably 1). Thus, viewWithTag:999999999 will return nil. Your NSLog statements will make it look like things are working correctly, but actually you're trying to set a title on a nil button, thus the button in the reused cell does not get updated with the correct title.
For a solution: you could create a custom subclass of UITableViewCell with a property:
@property (nonatomic, weak) IBOutlet UIButton *button;

And in the storyboard or xib wire this up to your button. Or if necessary you could programmatically do this in the cell's awakeFromNib or init method. Now you can directly reference cell.button instead of using [cell viewWithTag:9999999].


text:
Q: Adjusting whole site size which is fixed on px? I made a site in which is fully sized with pixels and not percent, just like in the code preview below.
However It turned out that on screens with a small resolution you cannot see the site porperly. And the user has to zoom out in the browser to see the site properly.
Is there any easy way to fix that issue? such as a making a media query for browser zoom or something like that?

.fixed1, .fixed2, .fixed3{
  margin:0 auto;
}

.fixed1{
width:400px;
height:400px;
background-color:green;
}

.fixed2{
width:300px;
height:300px;
background-color:red;
}

.fixed3{
width:200px;
height:200px;
background-color:blue;
}

A: Add a viewport meta tag inside head tag

    <meta name="viewport" content="width=device-width, initial-scale=1">

I have tested it with mobile devices which have screen size smaller than 400.


text:
Q: Django 'time__contains' is not working in particular case I'm trying to compare time pasted to form with time saved in DB for deleting this record. I don't understand why it's not working when in DB is stored 8:15:00 and the user pasted 08:15. The field in DB is TimeField and for comparing I'm using .filter(time__contains=t) where t is string pasted from form. Only difference is in zero before 8. When in DB is it stored like 08:15:00, all is working.
class WateringSchedule(models.Model):
    time = models.TimeField()

t = '08:15'

print(WateringSchedule.objects.filter(time__contains=t).count())

Thanks.

A: I've only seen contains used with CharField. There is no reason to use it here. Just use the field name:
print(WateringSchedule.objects.filter(time=t).count())

Here I assume Django will parse the input string into a datetime.time object. You may need to use strptime() to do so manually.
Alternatively, you can use hour and minute.

A: You should try icontains instead of contains.


text:
Q: VS2012 SSRS Cannot See Data Fields I have a VS2012 SSRS report project with a shared data set. The data set is being created from a SQL Stored Proc. I used to use VS2008, and all of the available data fields would show below the data set, however, in VS2012 I cannot figure out how to get them to show. I've removed the data set, and added it back, I've completely removed the DataSource and added it back, nothing works.
The original report file was built in VS2008, and was converted to a VS2012 project. Not sure if this could be contributing to the problem.
Thank you.

A: Your screen shot shows the Solution Explorer pane. Data Fields never appeared in this pane, in any version of SSRS.
I suspect what you are looking for is the Report Data Pane, which you should find on the View menu
https://msdn.microsoft.com/en-us/library/cc627528(v=sql.120).aspx


text:
Q: PHP - Hold Session variable from Select Option box to every page I seem to be having a problem and after hours of searching and messing with different ideas I can't seem to come up with this seems to be simple PHP Session problem with my Select Options menu.
All I want to do is simple have the selected Hotel Name from the dropdown hold till it is changed, and this goes for every page. So I thought, of yea lets just use Sessions. Doesn't seem to work very well as it keeps refreshing the data. Here is my code, and maybe one of you guys can come up with a solution. I would really appreciate it!
We are using a json file to populate the menu that we get by using a CURL to call the data and then decode the json.
Here is the dropdown code:
<select id="hotelSelected" name="hotelSelected">
<?php
sort($hotelName);
foreach($hotelName as $value):
echo '<option value="'.$value.'"'.ucfirst($value).'</option>';
endforeach; ?>
</select>

And then I tried to create a session by doing this:
$_SESSION['hotelName'] = $hotelName;

And now I need this session to carry on every page. And possibly echo on certain pages by possibly using this:
echo $_SESSION['hotelName'];

Any help is appreciated or redirect me to a forum that can fix my problem. Thank you guys!

A: you should use session_start(); at the top of every PHP file which uses sessions.
Also if you have a form contains SELECT tag , after submitting the form you should use $_POST['hotelSelected'] for grabbing tha value of option selected by user.
EDIT 1:
    <select id="hotelSelected" name="hotelSelected">
    <?php
    sort($hotelName);
    foreach($hotelName as $key=>$value):
    echo '<option value=($_SESSION['hotelname'][$key]):"'.$_SESSION['hotelname'][$key].'"'.ucfirst($_SESSION['hotelname'][$key]).'?"'.$value.'"'.ucfirst($value).'</option>';
    endforeach; ?>
    </select>
<?php
    $_SESSION['hotelname']=$hotelname;

A: html
<select id="hotelSelected" name="hotelSelected" onchange="run(this)">
<?php
    sort($hotelName);
    foreach($hotelName as $value):
        echo '<option value="'.$value.'"'.ucfirst($value).'</option>';
    endforeach;
?>
</select>

javascript
function run(sel) {
    var i = sel.selectedIndex;
    if (i != -1) {
        $.post('updatesession.php', {id:i}, function(){
        alert('Session Updated!');
    });
    }
}

updatesession.php
if(isset($_POST['id'])){
    session_start();
    $_SESSION['hotelName']=id;
}


text:
Q: FACEBOOK:: Read images from a public fan page I need to extract images from a FB fan page.
I'm able to read the page post, I then check post by post to see if it is really a photo and then try to open the object_id related to photo.
The last point give me error: it told me I need an user token.
I'm developing an automated script that needs to work every 10 mins and downlad new data.
I'm not admin of the page.
Is there a solution?
thanks,
Andrea

A: I don't see the issue - have your user come back once every 60 days, get a long-lived access token for them, store it, and use that token to read the page's /feed connection
You can also use an App Access Token if the page has no demographic restrictions


text:
Q: Setting Div position up on another content I have a page content which have text in it.
underneath the content, there is a navigator bar, and I would like that whenever I Hover one of the element in the navigator, a div will open up just above the element I have just hovered on, and show some content.
I don't want the  DIV that will pop-up to push any object on the page, I would like it to be, like up on all of the objects on the page.
some code since I have to insert code tags if I want to post fiddle

here's a fiddle to demonstrate:
Click here for fiddle
In the fiddle, I want that whenever I hover First, the first-feedback will be shown just above him.
This is pretty much my code, I have just used jQuery to calculate my desired width, but I just can't get the div to be above the div he should be above. I can't just calculate by my eye and say how many pixels because the website is pretty much dynamic, so I need a formula to calculate that for me every time.
If you have any code suggestion, such as relocating the feedback div, please feel free to edit the fiddle!
Thanks in advance!

A: Update: Okay, I did it the way you specified: http://jsfiddle.net/2U7jB/3/. There are other ways to do it - it depends on your HTML.
Original Response: This is close to what you want: http://jsfiddle.net/2U7jB/2/
.popup {
    display: none;
    height: 35px;
    width: 100%;
    background-color: blue;
}

$('#first, #second, #third').on('mouseover', function() {
    $(this).children('.popup').show();
});
$('#first, #second, #third').on('mouseleave', function() {
    $(this).children('.popup').hide();
});

To get what you want, just create two divs inside #first, #second, and #third - the first div for the hidden (popup) content, and the second div for the nav menu / background color.


text:
Q: Storing data much bigger than RAM in SQLite I have around 100 GB of stock market data in the following format:
datetime             open    high   low     close   volume
2014-10-02 15:34:00  18.39  18.50   18.32   18.41   5100
2014-10-02 15:35:00  18.41  18.49   18.41   18.49   200
2014-10-02 15:36:00  18.45  18.50   18.45   18.46   600

Each ticker has its own CSV file of data in the format above, so I am thinking of storing each ticker's data in its own table. There would be around 10,000 tickers, so 10,000 tables.
My question is whether I should have a single database of all these tables, or have a separate database for each ticker. My priority is speed of accessing the data.
I will only be making simple queries (i.e. select * from TICKER where datetime > 2014-10-02 15:34:00) to pull the data into Pandas, and will only be using data from one ticker at a time (I am looping over a list of tickers and doing some analysis on them individually). All of this will be done locally on a computer with 8 GB of RAM.

A: You would store everything in one table.  There is more overhead than you might imagine in using a separate table for each ticker -- and queries and maintenance become a nightmare.  You can arrange your data using indexes, for faster access.
If performance on even slightly complex queries is an issue, you might want to consider a different database.


text:
Q: How many threads Parallel.For(Foreach) will create? Default MaxDegreeOfParallelism? I want to know, how many threads will be used when I run Parallel.For/ForEach loop.
I found, that it can be changed by MaxDegreeOfParallelism option.
MaxDegreeOfParallelism help on MSDN says (link):

By default, For and ForEach will utilize however many threads the
  underlying scheduler provides, so changing MaxDegreeOfParallelism from
  the default only limits how many concurrent tasks will be used.

But I don't know how many threads underlying scheduler provides.
How can I find out that?
I could test it with loop with 9999999 runs, however this test will show me number, but not the rule that determine that number.
Edit/added later:
I googled for "sheduler max concurrency", and I found (at MSDN - link), that TashSheduler class has MaximumConcurrencyLevel property, and:

Returns an integer that represents the maximum concurrency level. The
  default scheduler returns Int32.MaxValue.

That TaskSheduler class is used as "underlying scheduler" for these parallel loops?

A: According to MSDN:

The default scheduler for Task Parallel Library and PLINQ uses the .NET Framework ThreadPool to queue and execute work. In the .NET Framework 4, the ThreadPool uses the information that is provided by the System.Threading.Tasks.Task type to efficiently support the fine-grained parallelism (short-lived units of work) that parallel tasks and queries often represent.

Looking at the documentation of ThreadPool, it says:

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method.


text:
Q: What is the syntax of CurrentDateTime in Microsoft Access 2007? I'm not good at english.So please abide.
i want to know what is the syntax of CurrentDateTime in Microsoft Access 2007.
i mean,In MSSQL Server 2008 , we can use GetDate() function.
but it can't use in Access.
i want to insert current datetime into access database.
So please answer me...
Thanks stackoverflow...

A: You can use
Now()

to give you the current date time or
Time()
Date()

For the respective portions.


text:
Q: Top level opaque type with same underlying type and identical extensions methods I ran into an issue when defining opaque types with identical underlying types and extension methods, e.g.:
opaque type HandleA = Int

object HandleA:

  def apply(value: Int): HandleA = value

extension (handle: HandleA) @targetName("HandleA_value") def value: Int = handle

opaque type HandleB = Int

object HandleB:

  def apply(value: Int): HandleB = value

extension (handle: HandleB) @targetName("HandleB_value") def value: Int = handle

When the two definitions resided in the same file, the code compiled, but when defined in two separate files, the code did not compile with the following error:

value is already defined as method value in ...

Is there a way to create these definitions at the same level in separate files somehow?
I tried wrapping the definitions in objects in two separate files and making them available at the top-level of the package by exporting them
// HandleA.scala

object HandleAWrap:
  opaque type HandleA = Int

  object HandleA:

    def apply(value: Int): HandleA = value

    extension (handle: HandleA) @targetName("HandleA_value") def value: Int = handle

// HandleB.scala

object HandleBWrap:
  opaque type HandleB = Int

  object HandleB:

    def apply(value: Int): HandleB = value

    extension (handle: HandleB) @targetName("HandleB_value") def value: Int = handle

// Lib.scala

export HandleAWrap.*
export HandleBWrap.*

But doing this I got a different compilation error along the lines of:

cyclic reference via <import>

due to the usage of @targetName to avoid name clashes.


text:
Q: Dynamic class instance naming in Python I'm trying to write a program that determines whether two words are cognates. I've written two classes: featTup (basically a wrapper around a tuple containing the values of a letter), and featWord (basically a wrapper around of featTup objects.)
(Sorry this is all so long!)
Here's some (hopefully relevant) code:
class featTup(object):
    def __init__(self,char):
        self.char = char
        self.phone_vals = None
        self.dia_vals = None
        if self.char in phone_codes:
            self.phone_vals = phone_feats[phone_codes.index(char)]
        elif self.char in dia_codes:
            self.dia_vals = dia_feats[dia_codes.index(char)]
        ...

class featWord(list):
    def do_dia(self,char_feats,dia_feats):
        #This method handles the changes diacritics make to preceding phones
        for val in dia_feats:
            if dia_val:
                char_feats.change_val(tup,char_feats.index(dia_val),dia_val)

    def get_featWord(self):
        return self.word_as_feats

    def __init__(self,word):
        self.word = word
        self.word_as_feats = [featTup(char) for char in self.word]
        for char in self.word_as_feats:
            if char.is_dia():
                i = self.word_as_feats.char_index(char)
                self.word_as_feats.do_dia(self.word_as_feats[i-1],self.word_as_feats[i])

    def word_len(self):
        return len(self.get_featWord())

    def char_index(self,char):
        return self.word_as_feats.index(char)

The issue is that I want to take a list of words and make featWord objects for all of them. I don't know how long each list will be, nor do I know how many characters will be in each word.
More code:
def get_words(text1,text2):
    import codecs
    textin1 = codecs.open(text1,encoding='utf8')
    word_list1 = textin1.readlines()
    textin1.close()
    textin2 = codecs.open(text2,encoding='utf8')
    word_list2 = textin2.readlines()
    textin2.close()
    print word_list1,word_list2
    fixed_words1 = []
    fixed_words2 = []
    for word in word_list1:
        fixed_word = word.replace('\n','')
        fixed_words1.append(fixed_word)
    for word in word_list2:
        fixed_word = word.replace('\n','')
        fixed_words2.append(fixed_word)
    print fixed_words1,fixed_words2
    words1 = [(featWord(word)) for word in fixed_words1]
    words2 = [(featWord(word)) for word in fixed_words2]
    # for word1 in fixed_words1:
        # for x in xrange(len(fixed_words1)):
        words1.append(featWord(word))
    for word2 in fixed_words2:
        #for x in xrange(len(fixed_words2)):
        words2.append(featWord(word))
    print words1
    #words1 = [featWord(word) for word in fixed_words1]
    #words2 = [featWord(word) for word in fixed_words2]
    return words1,words2

def get_cog_dict(text1,text2,threshold=10,print_results=True):
    #This is the final method, running are_cog over all words in
    #both lists.
    word_list1,word_list2 = get_words(text1,text2)
    print word_list1, word_list2

As it stands, when I call either of these last two methods, I get lists of empty lists; when I instantiate new featWord objects from strings I just give it (e.g. x = featWord("ten"), or whatever) it works fine. A relevant thing is that featWord seems to return an empty list instead of  (when I instantiate featWord from IDLE, as above, it comes back as a list of featTup instances, which is good). I'm not sure why/if that's the problem.
It seems to me that (at least part of) my problem stems from improperly initializing the featWord. I'm constructing them, or whatever, but not assigning them names. I've tried just about everything I can think of (as the commented-out sections prove), and I'm stumped. There're answers on here about using dictionaries to name class instances and such, but since I can't pre-define a dictionary (each word and wordlist is potentially a different length), I'm not sure what to do.
Any help would be GREATLY appreciated. I'm kind of driving myself insane over here. Thanks.

A: your featWord class derives from list, but you never append anything to self, and you have overridden __init__, so lists __init__ never gets called, too.
So a featWord instance is just an empty list with some attributes and methods.
Their __repr__ is list's __repr__, that's why a list of featwords displays as a list of empty lists.
So: implement a meaningful __repr__, do not subclass from list, append something meaninful to self. Any of that will solve your problem.


text:
Q: Expresión regular para valores consecutivos en una contraseña necesito ayuda con un problema que tengo, necesito que valide que no haya valores consecutivos; a lo que me refiero es que no se pueda poner:
123 ó abc ó 345 ó cdf. etc
Actualmente tengo esta expresión regular:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[$#@&*_+-])(?!.*(.)\1{2})[a-zA-Z0-9$#@&*_+-]{8,15}$

La cual valida lo siguiente: si tiene mayúsculas, una minúsculas, si tiene un numero, si tiene los caracteres especiales y que un carácter idéntico no sea repetido más de 3 veces, con una longitud mínima de 8 y máxima de 15
Ejemplo:
HsEsp3$6_* --Valido
HsEsp3$666_* --invalido
Lo único que me hace falta es validar el que no haya valores consecutivos, ¿¿¿se puede hacer con una expresión regular o se tiene que hacer de otra manera???

A: No creo que con expresiones regulares sea posible hallar si posee caracteres consecutivos, pero con un poco de código y un bucle for si es posible, aquí te dejo mi solución:

let pass1 = "Hxj_6128B"; // válido
let pass2 = "Hxj_1234B"; // no válido

console.log( !hasConsecutive(pass1) );
console.log( !hasConsecutive(pass2) );

// si en alguna parte tiene 3 (o más) caracteres y números consecutivos retorna true, si no, false.
function hasConsecutive (input) {
  input = input.toLowerCase();

  let list = "abcdefghijklmnñopqrstuvwxyz0123456789";
  let coincidences = 0;

  for (let i = 1; i < input.length; i++) {
    let lastChar = input.charAt(i - 1);
    let char = input.charAt(i);
    let expectedChar = list.charAt(list.indexOf(lastChar) + 1);

    if (char == expectedChar) coincidences += coincidences ? 1 : 2;
    else coincidences = 0;

    // si son 3 caracteres consecutivos
    if (coincidences == 3) return true;
  }

  return false;
}

Espero que te sirva, Saludos!

A: Otra opción sin usar expresiones regulares. El funcionamiento es simple: compara el valor del caracter actual vs el anterior y verifica si tienen una diferencia de 1. Si es así es porque son consecutivos.
La función, además tiene de forma variable la cantidad de caracteres que quieres que no se repitan consec, y puse otro argumento reverse si quieres desactivar la evaluación de forma inversa (654...).

function validate(string, consec=3, reverse=true) {
    let cpos = cneg = cequ = 1;
    let last_code = cur_code = 0;
    for(let i=0; i<string.length; i++) {
        cur_code = string[i].charCodeAt(0);
        if(cur_code-last_code == 1) {
            cpos++; // consecutivos
        } else if (reverse && (cur_code-last_code == -1)) {
            cneg++; // consecutivos en reversa
        } else if (cur_code == last_code) {
            cequ++; // iguales
        } else {
            cpos = cneg = cequ = 1;
        }
        //
        if([cpos, cneg, cequ].includes(consec)) {
            return false;
        }
        last_code = cur_code;
    }
    return true;
}

// Pruebas
console.log(validate('HsEsp3$6_*')); // true
console.log(validate('HsEsp3$666_*')); // false
console.log(validate('HsEsp3$ABC_*')); // false
console.log(validate('HsEsp3$379_*')); // true
console.log(validate('HsEsp3$678_*', 4)); // true (tolera hasta 3 consecutivos)
console.log(validate('HsEsp3$678_*', 3)); // false
console.log(validate('HsEsp3$6543')); // false (reverse activado)
console.log(validate('HsEsp3$6543', 3, false)); // true (reverse desactivado)
console.log(validate('HsEsp3$?@A_*')); // false ** ¡¿qué?!

Si observas el último caso "falla", esto es porque ? @ y A son caracteres consecutivos. Tendrías que modificar el código para que si el caracter actual no es una letra o número no haga las comparaciones, pero si no te importa, lo dejas así.

A: No creo que sea buena idea una expresión regular entera, porque sería muy enredado.
¿Por qué no mejor verificas cada una de esas reglas en la cadena de forma consecutiva?
No sé como sería en javascript, pero algo como:
regex.match("[A-Z]", passw) # que tenga mayusculas
regex.match("[a-z]", passw) # que tenga minusculas
regex.match("\d", passw) # que tenga al menos un digito
regex.match("[$%&_-]", passw) # que tenga caracteres especiales
regex.match("^(.){8,15}$", passw) # que tenga una longitud de entre [8,15]
regex.match("(.)\1{2,}", passw) # busca los caracteres que se repitan más de 3 veces

En (.)\1{2,}, si la condición se cumple, entonces mandas una excepción con la validación de la contraseña.
De esta manera, cada condición la puedes poner dentro de una serie de validadores que regresan cada caso que NO se cumpla en la contraseña. Por ejemplo:
if not regex.match("(.)\1{2,}", passw):
    raise PasswdError("Los caracteres no se pueden repetir mas de 3 veces")

A: Podrías utilizar la siguiente expresión regular, en la cual verifica si existe caracteres repetidos continuos en el texto que ingresas.
^(?!.*(.)\1)

Veamos un ejemplo:

const regex = /^(?!.*(.)\1)/,
  t = document.getElementById('t'),
  r = document.getElementById('r');

t.addEventListener('input', () => {
  if (regex.test(t.value)) {
    r.innerText = 'Es válido';
  } else {
    r.innerText = 'Es inválido';
  }
});
<input id="t" type="text" />


text:
Q: scroll down page in center automatically and freeze I have a blogger page where I call another site page on my page:
Now I want this page automatically scroll down and freeze. So, no more scrolling, like this.

A: IF you were loading this in an iframe, you can turn off scrolling within your iframe, that will answer 1 part of your question.
To load the content of the iframe at a specific position you can use CSS to position the loaded page within your iframe. Something like this should do the job.


text:
Q: It sounds very strange but why? It seemed to get me stuck, so I couldn't move at all.
Why isn't this like this?
It seemed to have gotten
 me stuck, so I couldn't move at all.

A: We need a bit more context here to understand the situation at hand. However, I'll explain the difference in general.
Firstly, both sentences sound better with "stick" rather than "stuck".
Your first sentence seems to be a general commentary on a past event (possibly with recurrence if the action was repeated).

The graphics were terrible. Even a simple movement seemed to make me stick, so I couldn't move at all.

Emphasising recurrence:

Every time I pressed X it made me stick in the game.

Your second sentence sounds best as a deferred past perfect (commentating on an action more in the past than we currently are commenting on):

At first it seemed to have made me stick (to the spot), so I couldn't move at all. Then I realised I could move, but I was stuck inside the graphics of the game.

Generally speaking, I think both options seem quite interchangeable, unless you provide me with a more specific context.


text:
Q: SQLite Instr provides different value than expected I'm trying to pull a substring in a query using instr. The following command:
SELECT instr(ZSYNCPAYMENT, '{"t')
FROM ZPAYMENT;

provides a result of 64.
I copied and pasted the output of SELECT ZSYNCPAYMENT FROM ZPAYMENT into a hex editor and selected the number of bytes up to and including the { symbol, which is part of my instr function above. The selected number of bytes shows as decimal length of 71. Why is my instr output showing a value of 64? The screenshot below is the output of the SELECT ZSYNCPAYMENT above.

A: From INSTR():

The instr(X,Y) function finds the first occurrence of string Y within
string X and returns the number of prior characters plus 1, or 0 if Y
is nowhere found within X. Or, if X and Y are both BLOBs, then
instr(X,Y) returns one more than the number bytes prior to the first
occurrence of Y, or 0 if Y does not occur anywhere within X.

In the hex editor you use you see the difference in bytes of the position of the string '{"t' from the start of the value of ZSYNCPAYMENT.
This is not the same as the difference in characters when a string contains unicode characters, which I suspect is the case with the string you posted in the image.
If you want the difference in bytes cast both ZSYNCPAYMENT and '{"t' to BLOBs:
SELECT INSTR(
         CAST(ZSYNCPAYMENT AS BLOB),
         CAST('{"t' AS BLOB)
       )
FROM ZPAYMENT

See a simplified demo.


text:
Q: Mappings and usage of Kotlin data types and Swift data types Let's say I have a function foo which takes two arguments:
actual fun foo(list1: List<Long>, list2: List<Double>) {
...
}

According to the https://kotlinlang.org/docs/tutorials/native/apple-framework.html Kotlin's Long type is mapped to KotlinLong and Kotlin's Double is mapped to KotlinDouble. Now I would like to call this function from my iOS App. Let's say I have two arrays:
let list1Numbers = [1000.43, 564121.34, 5617172172.234, 100.7]
let list2Numbers = [2.1, 3.2, 1.7]

For the list2 I could do something like:
let list2NumbersKotlin = list2Numbers.map({KotlinDouble.init(double: $0)})

which is not very convenient but will work. The list1 is a bit more problematic. Since there is no Long in Swift, I do something like
let list1NumbersKotlin =  list1Numbers.map({KotlinLong.init(longLong: Int64($0))})

Questions:

*

*Is there a better way to do it ?

*What is a typical approach to deal with such types mapping when using Kotlin as an iOS Framework ? Unfortunately I couldn't find any examples on the Internet.

*Should certain types such as Long be completely avoided if I want to use Kotlin as iOS Framework ?

*Also, regarding mapping in general: since the Kotlin function
 fun testDouble(testVal: Double) {}

allows me to pass in Swift the Double directly:
HelloKt.testDouble(testVal: Double)

then why does the function
fun testList(testList: List<Double>) {}

not allow me to enter Double array but requires a KotlinDouble array ?
HelloKt.testList(testList: [KotlinDouble]){}

Passing a [Double] gives error:

Cannot convert value of type '[Double]' to expected argument type
'[KotlinDouble]'

A: *

*There are multiple ways.

You are talking about collections of data that are on the line between primitive types and objects, which tends to be a special case in Kotlin anyway.
Speaking to that, in Kotlin, you might want a LongArray and a DoubleArray rather than List<Long> and List<Double>. Coming from Swift, you'll be forced to explicitly box them. Kotlin will handle that for you when you're writing Kotlin code, but they're still getting boxed under the hood.
So, summary, either what you've done above, or take LongArray and DoubleArray as args rather than lists, and do a different translation. Either way, you will need to move the data into something Koltin compatible.
Obviously, if you put that in a helper function, ugly as it perhaps may be, you only need to do it once.

*Either your method or what I described.

*Long isn't problematic. There is a "long" in Swift, it's Int64. Having to wrap values like that isn't fun, but Kotlin and Swift are different languages, and there are compromises. If you use Int in Kotlin instead of Long, you'll need to wrap a Swift Int with Int32. A Kotlin Int is, in that sense, "problematic" in the same way. You need to specify which precision int you're using.

*In Kotlin, List<Long> is a list of Long objects, while just a Long is a primitive value. Kotlin hides the boxing of those values, but they are boxed. The Swift/Kotlin interface is forcing you to be more explicit. If you want primitive values, use the ___Array forms mentioned above.


text:
Q: Deciding whether a set is a smooth submanifold I ma given the following sets $X_a = \{(x,y,z) \in \mathbb{R}^3 | ax = y^2 + z^2\}$ and $X_b = \{(x,y,z) \in \mathbb{R}^3 | y^2 + bz= 1\}$. I am asked for which values of $a$ and $b$ are $X_a$ a smooth 2-manifold in $\mathbb{R}^{3}$, for which values is $Y_b$ a smooth 2-manifold in $\mathbb{R}^3$, for which values of $a$ and $b$ is the intersection $X_a \hat Y_b$ a smooth 1-manifold in $\mathbb{R}^3$?
My attempt at the first two questions is the following: For $X_a$, we can define the function $F(x,y,z) = ax -y^2-z^2$. Basically, we want to find the values of $a$ for which $0$ would be a regular value. THus, we compute the differential of the function $F$, which is gonna be given by the matrix $(\frac{\partial F}{\partial x},\frac{\partial F}{\partial y}, \frac{\partial F}{\partial z}) = (a, -2y, -2z)$. Now, we know $0$ is gonna be a regular value iff $\forall p \in F^{-1}(0)$, the matrix $(a, -2y, -2z)$ evaluated at this point is not all entries 0,  since then for any such value the differential will be surjective. But this will happen only for the point $(0,0,0) \in \mathbb{R}^3$. Thus, we conclude if $a \in \mathbb{R}\setminus \{0\}$ then $X_a$ will be  a smooth $2$-manifold in $\mathbb{R}^3$. (Of course this is using Regular value theorem).
For the second question, I did a similar process, but this time the differential of the function $F(x,y,z) = y^2+bz-1$ is given by $(0,2y,b)$. With the exact same reasoning, we conclude that $Y_b$ is gonna be a smooth $2$-manifold in $\mathbb{R}^3$ whenever $b\in \mathbb{R} \setminus \{0\}$.
For the third part, I am trying a similar approach, this time I am defining the map $F(x,y,z) = (ax-y^2- z^2, y^2+bz-1)$. Now, the differential of this map is the matrix
\begin{bmatrix}
    a & -2y & -2z \\
    0 & 2y & b
\end{bmatrix}
Now, again we want to find the values of $a$ and $b$ such that the differential is not surjective. So, we need to find the values of $a$ and $b$ that make the matrix above to have rank less than 2. So we need to find the values of $a$ and $b$ such that all the determinant of all $2 \times 2$ matrices vanish. By calculation, we end up having that these determinants are $2ya=0$, $ab=0$ and $-2yb + 4yz=0$. From this we conclude that the for $a=0, b=2yz$, the matrix will have rank less than 2 and so for $a \in \mathbb{R}\setminus \{0\}$ and $b \in \mathbb{R} \setminus \{b=2yz\}$, the intersection $X_a \cap Y_b$ would be a smooth 1-manifold in $\mathbb{R}^3$
Can anybody tell me if my process is correct or if not, where I could correct the mistakes? Thanks!


text:
Q: VERNEMQ auth using SQL Server I am trying to design something to authenticate my VERNEMQ mqtt broker clients using a SQL Server backend. I've read about webhooks and can use it but the deal breaker being that it does not support HTTPS. Was wondering if we can make vernemq directly authenticate from SQL Server, I've seen existing implementations on cockroach DB/Mongo/MySQL.

A: I think your 2 best options are a) to develop a native Plugin, possibly over ODBC driver, or b) contribute HTTPS WebHooks support to the VerneMQ project.
(as a maintainer of the project, I can say that PR's are always welcome ;)


text:
Q: What is best: Global Variable or Parameter in this python function? I have a question about the following code, but i guess applies to different functions.
This function computes the maximum path and its length for a DAG, given the Graph, source node, and end node.
To keep track of already computed distances across recursions I use "max_distances_and_paths" variable, and update it on each recursion.
Is it better to keep it as a function parameter (inputed and outputed across recursions) or
use a global variable and initialize it outside the function?
How can avoid to have this parameter returned when calling the function externally (i.e it
has to be outputed across recursions but I dont care about its value, externally)?
a better way than doing: LongestPath(G, source, end)[0:2]   ??
Thanks
# for a DAG computes maximum distance and maximum path nodes sequence (ordered in reverse).
# Recursively computes the paths and distances to edges which are adjacent to the end node
# and selects the maximum one
# It will return a single maximum path (and its distance) even if there are different paths
# with same max distance
# Input {Node 1: adj nodes directed to Node 1 ... Node N: adj nodes directed to Node N}
# Example: {'g': ['r'], 'k': ['g', 'r']})
def LongestPath(G, source, end, max_distances_and_paths=None):
    if max_distances_and_paths is None:
        max_distances_and_paths = {}
    max_path = [end]
    distances_list = []
    paths_list = []
    # return max_distance and max_path from source to current "end" if already computed (i.e.
    # present in the dictionary tracking maximum distances and correspondent distances)
    if end in max_distances_and_paths:
        return max_distances_and_paths[end][0], max_distances_and_paths[end][1], max_distances_and_paths
    # base case, when end node equals source node
    if source == end:
        max_distance = 0
        return max_distance, max_path, max_distances_and_paths
    # if there are no adjacent nodes directed to end node (and is not the source node, previous case)
    # means path is disconnected
    if len(G[end]) == 0:
        return 0, [0], {"": []}
    # for each adjacent node pointing to end node compute recursively its max distance to source node
    # and add one to get the distance to end node. Recursively add nodes included in the path
    for t in G[end]:
        sub_distance, sub_path, max_distances_and_paths = LongestPath(G, source, t, max_distances_and_paths)
        paths_list += [[end] + sub_path]
        distances_list += [1 + sub_distance]
    # compute max distance
    max_distance = max(distances_list)
    # access the same index where max_distance is, in the list of paths, to retrieve the path
    # correspondent to the max distance
    index = [i for i, x in enumerate(distances_list) if x == max_distance][0]
    max_path = paths_list[index]
    # update the dictionary tracking maximum distances and correspondent paths from source
    # node to current end node.
    max_distances_and_paths.update({end: [max_distance, max_path]})
    # return computed max distance, correspondent path, and tracker
    return max_distance, max_path, max_distances_and_paths

A: Global variables are generally avoided due to several reasons (see Why are global variables evil?). I would recommend sending the parameter in this case. However, you could define a larger function housing your recursive function. Here's a quick example I wrote for a factorial code:
def a(m):
    def b(m):
        if m<1:return 1
        return m*b(m-1)
    n = b(m)
    m=m+2
    return n,m
print(a(6))

This will give: (720, 8). This proves that even if you used the same variable name in your recursive function, the one you passed in to the larger function will not change. In your case, you want to just return n as per my example. I only returned an edited m value to show that even though both a and b functions have m as their input, Python separates them.

A: In general I would say avoid the usage of global variables. This is because is makes you code harder to read and often more difficult to debug if you codebase gets a bit more complex. So it is good practice.
I would use a helper function to initialise your recursion.
def longest_path_helper(G, source, end, max_distances_and_paths=None):
    max_distance, max_path, max_distances_and_paths = LongestPath(
        G, source, end, max_distances_and_paths
    )
    return max_distance, max_path, max_distances_and_paths

On a side note, in Python it is convention to write functions without capital letters and separated with underscores and Capicalized without underscores are used for classes. So it would be more Pythonic to use def longest_path():


text:
Q: How do I make a bitmap version of a WMF file that is loaded into a TImage.Picture and move that to a TSpeedButton.Glyph For the sake of a minimal complete question, I have a WMF file loaded into a TImage control on a form. This control contains the property Picture, which is a TPicture type.  I am trying to "rasterize" the WMF file that I loaded into the TImage, and store that into a TSpeedButton.Glyph.
What is interesting about this process is I am able to use this technique to create a resolution independent custom control (a button in my case) that will redraw its glyph for any resolution you like.
In real world usage, I would not have a TImage or a TSpeedButton, but this question is fundamentally about the process of moving content from TPicture to a TBitmap.
Here is the relevant semi-working code:
procedure CopyBitmap(  Source:TImage;  DestSpeedButton:TSpeedButton );
var
   bmp: TBitmap;
begin
   bmp:=TBitmap.Create;
   try
     // note: with WMF loaded, Source.Picture.Bitmap.Width and Height are 0.
     bmp.Width := Source.Width; // originally I had Source.Picture.Bitmap.Width, which didn't work.
     bmp.Height := Source.Height; //because Source.Picture.Bitmap.Height, doesn't work.
     bmp.Canvas.Draw(0,0, Source.Picture.Graphic );
     DestSpeedButton.Glyph:=bmp;
   finally
     bmp.Free;
   end;
end;

Is this the correct approach? Why does the image invert during copy?
A sample WMF file, the exact file I'm using, is found here.

A: Thanks David, for suggesting that I draw the background. This works.
Note that in production I would change the code below to use Vcl.GraphUtils helper called ScaleImage as the results are much prettier. See the second code sample.
// Quick and Dirty : No sub-pixel anti-aliasing.
// Also does not modifies Source, so set Source's size before you
// call this.
procedure CopyBitmap(  Source:TImage;  DestSpeedButton:TSpeedButton );
var
   bmp: TBitmap;
begin
   bmp:=TBitmap.Create;
   try
     bmp.SetSize( Source.Width, Source.Height);
     bmp.Canvas.Pen.Style := psClear;
     bmp.Canvas.Brush.Style := bsSolid;
     bmp.Canvas.Brush.Color := clFuchsia;
     bmp.Canvas.Rectangle(0,0, Source.Width+1,Source.Height+1 );
     bmp.Canvas.Draw(0,0, Source.Picture.Graphic );
     bmp.TransparentColor := clFuchsia;
     DestSpeedButton.Glyph:=bmp;
   finally
     bmp.Free;
   end;
end;

Alternative that uses more memory, and is using the TPicture type instead of TImage because in real use I don't even have a TImage just a TPicture, also this looks nicer. Note that it is written around some custom control of my own design (or yours) that has some property type TBitmap.  You have to substitute your own controls, or change TMyControlWithAGlyph to TSpeedButton if that's what you want to do:
// A Bit Better Looking. Uses Vcl.GraphUtils function ScaleImage
procedure CopyBitmap(  Source:TPicture;
                       Dest:TMyControlWithAGlyph;
                       DestType:TCopyDestTypeEnum;
                       AWidth,AHeight:Integer;
                       DoInvert:Boolean;
                       TransparentColor:TColor=clFuchsia );
var
   bmp,bmpFullSize: TBitmap;
   ARect:TRect;
   ScaleAmount:Double;
begin
   if not Assigned(Source) then
      exit;
   if not Assigned(Dest) then
      exit;

   if not Assigned(Source.Graphic) then
      exit;

   bmp:=TBitmap.Create;
   bmpFullSize := TBitmap.Create;
   try
     bmpFullSize.SetSize(  Source.Width, Source.Height );
     bmpFullSize.PixelFormat := pf24bit;
     bmpFullSize.Canvas.Pen.Style := psClear;
     bmpFullSize.Canvas.Brush.Style := bsSolid;
     bmpFullSize.Canvas.Brush.Color := TransparentColor;
     bmpFullSize.Canvas.Rectangle(0,0, Source.Width+1,Source.Height+1 );
     bmpFullSize.Canvas.Draw(0,0, Source.Graphic );

     bmp.SetSize( AWidth, AHeight);
     bmp.PixelFormat := pf24bit;

     // Vcl.GraphiUtil version needs a floating point scale.
     ScaleAmount := AWidth / Source.Width;
     ScaleImage(bmpFullSize,bmp,ScaleAmount );

     // This lets me have a white icon and turn it black if I want to
     // or vice versa
     if DoInvert then
       InvertBitmap(bmp);

     if DestType=DestLargeGlyph then
     begin
          Dest.LargeGlyph := bmp;
     end
     else
     begin
          Dest.Glyph:=bmp;
     end;
   finally
     bmp.Free;
     bmpFullSize.Free;
   end;
end;

The above code also calls this little helper:
function InvertBitmap(ABitmap: TBitmap): TBitmap;
var
   x, y: Integer;
   ByteArray: PByteArray;
begin
   ABitmap.PixelFormat := pf24Bit;
   for y := 0 to ABitmap.Height - 1 do
   begin
      ByteArray := ABitmap.ScanLine[y];
      for x := 0 to ABitmap.Width * 3 - 1 do
      begin
         ByteArray[x] := 255 - ByteArray[x];
      end;
   end;
   Result := ABitmap;
end;


text:
Q: Do an unlinked trefoil and figure-eight cobound an annulus in $B^4$? Let $K_1$ the trefoil (left or right hopefully does not matter?) and let $K_2$ be the figure-eight knot in $S^3 = \partial B^4$.  Are there any smooth properly embedded annulus $A$ in $B^4$ with $\partial A = K_1 \coprod K_2$?
I'm really interested in knowing some general obstructions for this sort of thing for more general knots $K_1,K_2$ so any ideas are welcome.  I figured that I would ask the question with two specific knots just for fun.

A: The relationship you're asking for is called concordance.  Determining if knots are concordant is quite difficult: there are many concordance invariants, but no kind of global picture of what it means.
One concordance invariant is the knot signature.  The trefoil has signature $-2$ and the figure-8 knot has signature $0$, so they are not concordant.  I got this data from the wonderful website Table of Knot Invariants.
As far as where to read about knot concordance, a good place to start is Livingston and Naik's book-in-progress here.

EDIT: Knots $K_0$ and $K_1$ are usually said to be (smoothly) concordant if there is a smoothly embedded annulus in $S^3 \times [0,1]$ connecting $K_0 \times \{0\}$ and $K_1 \times \{1\}$.  In the comments, I was asked to sketch why this is the same as having an annulus connecting $K_0$ and $K_1$ in $B^4$ (assuming that $K_0$ and $K_1$ are unlinked).
There are a lot of ways to prove this.  Here's a brief sketch of one of the easiest.  If $D$ is a small open round ball in $S^3$, then
$$\left(S^3 \times [0,1]\right) \setminus \left(D \times [0,1]\right) \cong B^4.$$
There is a tiny issue in that the right hand side is a manifold with corners, but as always corners can be smoothed.  Using this diffeomorphism, we immediately see that if there is a smoothly embedded annulus in $B^4$ connecting $K_0$ and $K_1$, then after possibly moving $K_0$ and $K_1$ around we can obtain a smoothly embedded annulus in $S^3 \times [0,1]$ connecting $K_0 \times \{0\}$ and $K_1 \times \{1\}$; this annulus avoids $D \times [0,1]$.  Conversely, if we can find an annulus in $S^3 \times [0,1]$ connecting $K_0 \times \{0\}$ and $K_1 \times \{1\}$, then homotoping everything we can assume that this annulus avoids some $D \times [0,1]$, and then transport it to an annulus in $B^4$ connecting $K_0$ and $K_1$.
The above sketch elides various identification we are making, but once you understand the geometry (draw a picture!) you'll see that they are all pretty clear.


text:
Q: Linux - importing "." or "::" within the root PATH I am looking into Miscellaneous Config and I am researching roots PATH. I am told that . and :: should be removed from the path as it is a security threat. I have the following example output of the PATH command:
/usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin:/usr/java7_64/jre/bin:/usr/java7_64/bin:/opt/IBM/xlC/13.1.3/bin

If this output was to contain :: or . how would it look like within in the above path so I can have an idea on how it will be structured as I am not sure.
Really appreciate the help on this one.

A: The PATH is just a colon-separated list of paths. If an entry is . or empty, it refers to the current directory. Also, leading and tailing empty entries count (they're created by leading or tailing colons).
So, if PATH is /bin:/usr/bin, it contains the two entries /bin and /usr/bin, so no reference to current directory.
On the other hand /bin::/usr/bin:.:/usr/local/bin: contains six entries: /bin, empty, /usr/bin, ., /usr/local/bin and empty. The . entries and the empty ones refer to the current path, these are the ones you don't want.
Parsing the PATH is likely to be easiest by splitting the string on the colons, and checking the resulting strings. How to do that exactly depends on your programming language.


text:
Q: What is the meaning of the eigenvectors of a mutual information matrix? When looking at the eigenvectors of the covariance matrix, we get the directions of maximum variance (the first eigenvector is the direction in which the data varies the most, etc.); this is called principal component analysis (PCA).
I was wondering what it would mean to look at the eigenvectors/values of the mutual information matrix, would they point in the direction of maximum entropy?

A: While it is not a direct answer (as it is about pointwise mutual information), look at paper relating word2vec to a singular value decomposition of PMI matrix:

*

*O. Levy, Y. Goldberg, Neural Word Embedding as Implicit Matrix Factorization

We analyze skip-gram with negative-sampling (SGNS), a word embedding
  method introduced by Mikolov et al., and show that it is implicitly factorizing
  a word-context matrix, whose cells are the pointwise mutual information (PMI) of
  the respective word and context pairs, shifted by a global constant. We find that
  another embedding method, NCE, is implicitly factorizing a similar matrix, where
  each cell is the (shifted) log conditional probability of a word given its context.
  We show that using a sparse Shifted Positive PMI word-context matrix to represent
  words improves results on two word similarity tasks and one of two analogy tasks.
  When dense low-dimensional vectors are preferred, exact factorization with SVD
  can achieve solutions that are at least as good as SGNS's solutions for word similarity
  tasks. On analogy questions SGNS remains superior to SVD. We conjecture
  that this stems from the weighted nature of SGNS's factorization.


text:
Q: How to fix this issue with multiple textures in Opengl I want to send multiple texture to fragment shader and than mix them there.
But due to some reason when i run this code only texture2 is showing.Here in my fragment shader even if i just write color=color1; than also i am seeing texure2.
My fragment shader:
    static const char* fragmentShaderSource = "\n\
    #version 150 core\n\
    in vec2 Texcoord;\n\
    uniform sampler2D tex0;\n\
    uniform sampler2D tex1;\n\
    out vec4 color;\n\
    void main(){\n\
        vec4 color1=texture(tex0,Texcoord);\n\
        vec4 color2=texture(tex1,Texcoord);\n\
        color=mix(color1,color2,0.5);\n\
        //color=color1;\n\
    }\n\
    ";

My Code for multiple texture:
    GLuint textures[2];
    glGenTextures(2, textures);
    int width, height;
    unsigned char* image;

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE0, textures[0]);
    image = SOIL_load_image("1.png", &width, &height, 0, SOIL_LOAD_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    glUniform1i(glGetUniformLocation(program, "tex0"), 0);
    SOIL_free_image_data(image);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE1, textures[1]);
    image = SOIL_load_image("2.png", &width, &height, 0, SOIL_LOAD_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    glUniform1i(glGetUniformLocation(program, "tex1"), 1);
    SOIL_free_image_data(image);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

And this is my window loop:
    while (!glfwWindowShouldClose(window)) {
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        if (glfwGetKey(window, GLFW_KEY_E)) {
            break;
        }
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

This is my whole Code If needed:
#define GLEW_STATIC
#include<gl\glew.h>
#include<GLFW\glfw3.h>
#include<iostream>
#include<SOIL.h>
//////////////////////////////////////
static const char* vertexShaderSource = "\n\
    #version 150 core\n\
    in vec2 position;\n\
    in vec3 inColor;\n\
    in vec2 texcoord;\n\
    out vec2 Texcoord;\n\
    out vec3 Color;

    void main(){\n\
        Color=inColor;\n\
        Texcoord=texcoord;\n\
        gl_Position=vec4(position,0,1);\n\
    }\n";

static const char* fragmentShaderSource = "\n\
    #version 150 core\n\
    //uniform vec4 fragmentColor;\n\
    in vec3 Color;\n\
    in vec2 Texcoord;\n\
    uniform sampler2D tex0;\n\
    uniform sampler2D tex1;\n\
    out vec4 color;\n\
    void main(){\n\
        vec4 color1=texture(tex0,Texcoord);\n\
        vec4 color2=texture(tex1,Texcoord);\n\
        color=mix(color1,color2,0.5);\n\
        //color=color1;\n\
    }\n\
    ";
//////////////////////////////////////

int main() {
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    GLFWwindow* window = glfwCreateWindow(1024, 620, "Window", nullptr, nullptr);

    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;

    if (glewInit() != GLEW_OK)
        return -1;

    GLfloat triangleVertices[] = {
        0.5f,0.5f,1,0,0,1,0,
        0.5f,-0.5f,0,1,0,1,1,
        -0.5f,-0.5f,0,0,1,0,1,
        -0.5f,0.5f,0,0,0,0,0
    };

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW);

    GLuint elements[] = { 0,1,2 ,3,0,2};
    GLuint ebo;
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

    ////////////////////////////////////////////////////////
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
    glCompileShader(vertexShader);
    GLint statusVertex;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &statusVertex);
    if (!statusVertex) {
        char buffer[1024];
        glGetShaderInfoLog(vertexShader, 1024, NULL, buffer);
        std::cout << "Error Compiling vertexShader:" << buffer << std::endl;
    }

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
    glCompileShader(fragmentShader);
    GLint statusFrag;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &statusFrag);
    if (!statusFrag) {
        char buffer[1024];
        glGetShaderInfoLog(fragmentShader, 1024, NULL, buffer);
        std::cout << "Error Compiling fragmentShader:" << buffer << std::endl;
    }

    GLuint program = glCreateProgram();
    glAttachShader(program, vertexShader);
    glAttachShader(program, fragmentShader);
    glBindFragDataLocation(program, 0, "color");
    glLinkProgram(program);//making connection
    glUseProgram(program);
    //////////////////////////////////////////////////////////

    GLint positionAttrib = glGetAttribLocation(program, "position");
    glVertexAttribPointer(positionAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), nullptr);
    glEnableVertexAttribArray(positionAttrib);

    GLint colorAttrib = glGetAttribLocation(program, "inColor");
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), (void*)(2 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(colorAttrib);

    GLint texAttrib = glGetAttribLocation(program, "texcoord");
    glVertexAttribPointer(texAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), (void*)(5 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(texAttrib);

    GLuint textures[2];
    glGenTextures(2, textures);
    int width, height;
    unsigned char* image;

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE0, textures[0]);
    image = SOIL_load_image("1.png", &width, &height, 0, SOIL_LOAD_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    glUniform1i(glGetUniformLocation(program, "tex0"), 0);
    SOIL_free_image_data(image);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE1, textures[1]);
    image = SOIL_load_image("2.png", &width, &height, 0, SOIL_LOAD_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    glUniform1i(glGetUniformLocation(program, "tex1"), 1);
    SOIL_free_image_data(image);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    /////////////////////////////////////////////////////////////
    while (!glfwWindowShouldClose(window)) {
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        //glDrawArrays(GL_TRIANGLES, 0, 3);

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        if (glfwGetKey(window, GLFW_KEY_E)) {
            break;
        }
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

A: glBindTexture takes the texture target not the unit.
Targets are: GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D_ARRAY (and extension specific targets).
The texture unit is passed to glActiveTexture and these are GL_TEXTURE0, GL_TEXTURE1 and so on, and is also what the sampler uniform is set to.

Change your code to
    glActiveTexture(GL_TEXTURE0);
--- glBindTexture(GL_TEXTURE_2D, textures[0]);
+++ glBindTexture(GL_TEXTURE_2D, textures[0]);

and
    glActiveTexture(GL_TEXTURE1);
--- glBindTexture(GL_TEXTURE_2D, textures[1]);
+++ glBindTexture(GL_TEXTURE_2D, textures[1]);


text:
Q: What will be the DD (Decision to Decision) path graph of the following code? I need to draw the DD path graph of the following code:
    #include <iostream.h>
    #include<conio.h>
    main()
    {
      char name[16]; #1
      int age; #2

      cout << "Enter your name: "; #3
      cin >> name; #4
      cout << "Enter your age: "; #5
      cin >> age; #6

      if (age < 21) #7
       cout << "You young whippersnapper, " << name << "!\n"; #8
      else if (age < 40) #9
       cout << name << ", you're still in your prime!\n"; #10
      else if (age < 60) #11
       cout << "You're over the hill, " << name << "!\n"; #12
      else if (age < 80) #13
       cout << "I bow to your wisdom, " << name << "!\n"; #14
      else #15
       cout << "Are you really " << age << ", " << name << "?\n"; #16

      return 0; #17
    } #18

The DD path graph I obtained is given below:

I'm not sure that it is the correct graph. Can anyone please verify?


text:
Q: Error "TestEngine with ID 'junit-jupiter' failed to discover tests". Getting this error while trying to run JUnit tests in a maven project I am trying to run tests in a project with Apache Maven 3.8.3, JDK 14, JUnit 5.8.1, jqwik 1.5.6
I'm using IntelliJ IDEA 2021.2.3 (Community Edition)
The libraries must be correctly imported but it still doesn't work.
When I try to run simple tests I 'm getting the following error message:
"Internal Error occurred.
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests"
Here is the pom.xml file. I'd appreciate any advice and thanks in advance!
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>tests</groupId>
    <artifactId>tests</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <build>
        <sourceDirectory>${project.basedir}/src</sourceDirectory>
        <testSourceDirectory>${project.basedir}/src/tests</testSourceDirectory>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                        <include>**/*Examples.java</include>
                        <include>**/*Properties.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>

    </build>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.8.1</version>
        </dependency>
        <dependency>
            <groupId>net.jqwik</groupId>
            <artifactId>jqwik</artifactId>
            <version>1.5.6</version>
        </dependency>

    </dependencies>
    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>
</project>


text:
Q: How to reset a counter to at 1 at each start of chapter? I want the numbering of definition, lemma and theorem has the form x.y,where x is the chapter and y represents the natural order 1,2,3...I use a counter for the value of y.Here is my code, but something undesired happened. The counter start from 0 at each chapter automatically, however I want it starts from 1. What should I do to deal with this problem? Thanks!
\documentclass{book}
\newcounter{moon}[chapter]
\newtheorem{mydef}{Definition}
\renewcommand{\themydef}{\thechapter.\arabic{moon}}
\def\endmydef{\stepcounter{moon}}
\newtheorem{mylem}{Lemma}
\renewcommand{\themylem}{\thechapter.\arabic{moon}}
\def\endmylem{\stepcounter{moon}}
\newtheorem{mythm}{Theorem}
\renewcommand{\themythm}{\thechapter.\arabic{moon}}
\def\endmythm{\stepcounter{moon}}

\begin{document}
\chapter{AlaAla...}
\begin{mydef}
   something
\end{mydef}
\begin{mylem}
   something
\end{mylem}
\begin{mythm}
   something
\end{mythm}

\chapter{BlaBla...}
\begin{mydef}
    something
\end{mydef}
\begin{mylem}
something
\end{mylem}
\begin{mythm}
something
\end{mythm}

\end{document}

A: Just spelling out my comment. All I did was to use this answer. When you compile it, you'll see that the lemma and theorem in the second chapter are numbered as they should even though there is no definition in.

\documentclass{book}
\usepackage{amsthm}
\newtheorem{mydef}{Definition}[chapter]
\newtheorem{mylem}[mydef]{Lemma}
\newtheorem{mythm}[mydef]{Theorem}

\begin{document}
\chapter{AlaAla...}
\begin{mydef}
   something
\end{mydef}
\begin{mylem}
   something
\end{mylem}
\begin{mythm}
   something
\end{mythm}

\begin{mydef}
    something
\end{mydef}

\chapter{BlaBla...}
\begin{mylem}
something
\end{mylem}
\begin{mythm}
something
\end{mythm}

\end{document}

A: General answer
This is not (easily) possible. The better way would be to move the stepping of the counter before the use of it. This is how it is done in cases like this in TeX. Because if you use \refstepcounter instead of \stepcounter to make these counters work with \ref this is the only way, to let TeX know from where on the counter is "active" as label.
Howerver in your case the way to go would be to make the three counters "aliases" for each other and use the optional argument of \newtheorem to make the base counter within the chapter counter.
Change your definitions to:
\newtheorem{mydef}{Definition}[chapter] % < counter within chapter counter
\newtheorem{mylem}{Lemma}
\newtheorem{mythm}{Theorem}
\makeatletter
   \let\c@mylem\c@mydef % make lem counter an alias for def counter
   \let\themylem\themydef % copy format of def counter in lem counter
   \let\c@mythm\c@mydef % make thm counter an alias for def counter
   \let\themythm\themydef % copy format of def counter in lem counter
\makeatother

by the way: it's not a good idea to use \def\endmydef{\stepcounter{moon}} since this will overwrite everything else that is don in the \end part usually …


text:
Q: iterating over vector iterates infinitely I am using visual studio 2008:
I am trying to iterate over a vector through iterator itrv but it goes into infinite loop for some reason:
Error :
ERROR : Expression: map/set iterator not incrementable
Code:
int main(
{
    set<int> s1;
    set<int>::iterator itr;
            s1.insert(43);
            s1.insert(42);
            s1.insert(41);
            s1.insert(3);
            s1.insert(2);
            s1.insert(1);

    vector<int> vec;
    vector<int>::iterator itrv=vec.begin();

    for(itr=s1.begin();itr!=s1.end();++itr)
    {
        cout<<*itr;
        vec.push_back(*itr);
        cout<<endl;
    }

        cout<<"so the size of vector is SIZE : "<<vec.size()<<endl; //i get 6 here

//PROBLEM IN THIS LOOP. GOES TO INFINITE LOOP AND PRINTS JUST '1' INFINITELY
        for(itrv=vec.begin();itrv!=vec.end();++itr)
        {
            cout<<*itrv<<endl;
        }

I even tried printing the elements of vector using subscript, it prints fine.
But with iterator it fails:
cout<<vec[0]<<endl;
cout<<vec[1]<<endl;
cout<<vec[2]<<endl;
cout<<vec[3]<<endl;
cout<<vec[4]<<endl;
cout<<vec[5]<<endl;
cout<<"with itrv \n";
itrv=vec.begin();
cout<<*itrv;itr++;
cout<<*itrv;itr++;
cout<<*itrv;itr++;
cout<<*itrv;itr++;
cout<<*itrv;itr++;
cout<<*itrv;itr++;

A: for(itrv=vec.begin();itrv!=vec.end();++itr)

It should be
for(itrv=vec.begin();itrv!=vec.end();++itrv)

Otherwise, itrv was not moved and itrv != vec.end() was always true whenever vec is not empty.


text:
Q: using font-size on divs without text to propagate height/other property's value to child elements I have this simple CSS:
div {
  height: 50px;
  border-bottom: 1px solid black;
  position: relative;
}

div:before {
  content: '';
  display: inline-block;
  width: 30px;
  height: 30px;
  background: green;
  position: absolute;
  top: 50px;
}

The idea is that green box is positioned right below the bottom border. For that I need to explicitly specify top property on it. I was thinking about the ways to avoid specifying explicit measure in pixels and somehow receive it from a parent. The only solution I could come up with is to specify font-size on parent equal to parent's height and then reference it in the child with em. So the following solution is possible:
div {
  font-size: 50px; //equal to height
}

div:before {
  top: 1em;
}

What are the glaring drawbacks of such approach? The advantage is that greenbox div can be added to a parent with any height without needing to change top property of geenbox div.

A: The simplest fix is to use top: 100% as shown below.
The 100% value computes based on the height of the parent element, so the net result is that the
top of the pseudo-element is aligned with the bottom edge of the parent block.
The advantage of this approach is that it will work for any height value of the parent div and any height value of the pseudo-element.

div {
  height: 80px;
  border-bottom: 1px solid black;
  position: relative;
}

div:before {
  content: '';
  display: inline-block;
  width: 30px;
  height: 30px;
  background: green;
  position: absolute;
  top: 100%;
}

A: This should work. It will keep it under the parent, regardless of the parent's height.
div:before {
  content: '';
  display: inline-block;
  width: 30px;
  height: 30px;
  background: green;
  position: absolute;
  bottom:-30px;
}


text:
Q: how to parse html I have downloaded the Java HtmlParser but I dont know how to use the API  for extracting the HTML data. Can you give some example so that I can work on it?

A: You're talking about HtmlParser? Rather pick a parser with less verbose API like Jsoup. All you need to learn are then CSS selectors which are already obvious enough to the average frontend developer.
Here's a kickoff example which displays your current question and the names of all answerers:
package com.stackoverflow.q3416036;

import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Test {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://stackoverflow.com/questions/3416036");
        Document document = Jsoup.parse(url, 3000);

        String question = document.select("#question .post-text").text();
        System.out.println("Question: " + question);

        Elements answerers = document.select("#answers .user-details a");
        for (Element answerer : answerers) {
            System.out.println("Answerer: " + answerer.text());
        }
    }

}

See also:

*

*Pros and cons of HTML parsers in Java


text:
Q: Help with boost::regex trim This regex will trim the string at line breaks.  I want it to trim both end only and preserve any line breaks in the middle.
string s("     Stack \n Overflow    ");
boost::regex expr("^[ \t]+|[ \t]+$");
std::string fmt("");
cout << boost::regex_replace(s, expr, fmt) << endl;

A: If you want to make the regular expression match at the beginning and the
end of the input string(want to preserve spaces around the in-between \n),
\A and \z instead of ^ and $ might meet the purpose.
For example:
boost::regex expr("\\A[ \t]+|[ \t]+\\z");