text:
Q: Why Django is not rendering some HTML files from Django app directory? I am new to djando and building my first project app 'accounts' in django framework. The 'accounts' app has a templates\accounts folder where all the .html files are residing. The problem is, django is rendering all the .html files except reso.html located in my templates directory.
While rendering reso.html, its throwing following error when http://127.0.0.1:8000/masterdata/ is typed in URL bar:
OSError at /masterdata/
[Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html'
Request Method: GET
Request URL:    http://127.0.0.1:8000/masterdata/
Django Version: 3.1.4
Exception Type: OSError
Exception Value:
[Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html'
Exception Location: C:\Users\Parijat\Desktop\Theis project\env\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents
Python Executable:  C:\Users\Parijat\Desktop\Theis project\env\Scripts\python.exe
Python Version: 3.9.0
Python Path:
['C:\\Users\\Parijat\\Desktop\\Theis project\\CRM',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\python39.zip',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\DLLs',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\lib',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39',
 'C:\\Users\\Parijat\\Desktop\\Theis project\\env',
 'C:\\Users\\Parijat\\Desktop\\Theis project\\env\\lib\\site-packages']

I tried setting up the TEMPLATE variable in setting.py so that django can search templates from my directory but everytime its throwing the same error. For example I changed
'DIRS': [], to 'DIRS': [BASE_DIR / 'accounts'],

Below is an image showing the location of my .html files:-

Setting.py

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

SECRET_KEY = 'ss3@*&2)-+e!3bxok+afpflc&j!e(6tz^z_+80a*yh)oos8@m!'

DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [

    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

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

ROOT_URLCONF = 'CRM.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {

            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

            ],
        },
    },
]

WSGI_APPLICATION = 'CRM.wsgi.application'

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

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

MEDIA_URL='/images/'

STATICFILES_DIRS=[

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

]

urls.py @ project directory where the same setting.py is located

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse

urlpatterns = [

    path('admin/', admin.site.urls),
    path('', include('accounts.urls'))

]

urls.py @ where apps.py and admin.py is located

from django.urls import path
from . import views
urlpatterns = [

    path('', views.home, name = 'home'),
    path('customers/<str:pk_test>/', views.customer, name = 'customers'),
    path('product/', views.product, name= 'product' ),
    path('create/', views.create_order, name = 'create'),
    path('create/<str:pk>/', views.UpdateOrder, name = 'updateorder'),
    path('delete/<str:pk>/', views.deleteorder, name = 'delete'),
    path('plan_production/', views.planproduction),
    path('masterdata/', views.masterdata1),
]

Views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from . models import *
from . forms import OrderForm
from django.template import Context, Template
from django.template.loader import *

# Create your views here.
def home(request):
    order_model = orders.objects.all()
    customers_model = customers.objects.all()
    total_customers = customers_model.count()
    total_orders = order_model.count()
    delivered = order_model.filter(status='delivered').count()
    pending = order_model.filter(status='pending').count()
    context = {'order':order_model, 'customers': customers_model, 'total_customers': total_customers, 'total_orders': total_orders, 'delivered': delivered, 'pending': pending}

    return render(request, 'accounts\index.html', context)

def customer(request, pk_test):

    customer_model = customers.objects.get(id=pk_test)
    order_model = customer_model.orders_set.all()
    order_count = order_model.count()
    context = {'customer':customer_model, 'order':order_model, 'total_order':order_count}
    return render(request, 'accounts\customers.html', context)

def product(request):

    product_model = products.objects.all()
    return render(request, 'accounts\products.html', {'products':product_model})

def create_order(request):

    form = OrderForm()
    if request.method == 'POST':
         form = OrderForm(request.POST)
    if  form.is_valid():
        form.save()
        return redirect('/')

    context = {'form': form}
    return render(request, 'accounts\order_form.html', context)

def UpdateOrder(request, pk):
    order = orders.objects.get(id=pk)
    form = OrderForm(instance=order)
    if request.method == 'POST':
         form = OrderForm(request.POST, instance= order)
    if  form.is_valid():
        form.save()
        return redirect('/')
    context = {'form':form}
    return render(request,'accounts\order_form.html', context)

def deleteorder(request,pk):
    order = orders.objects.get(id=pk)
    if request.method == 'POST':
         order.delete()
         return redirect('/')
    context = {'item': order}
    return render(request,'accounts\delete.html', context)

def planproduction(request):
        return render(request,'accounts\plan_production.html')

def masterdata1(request):
    return render(request,'accounts\reso.html')

reso.html

{% extends 'accounts/main.html' %}
{%load static%}
{% block content %}

Master Data

Resource Mater Data

Add new resources or Update the existing resources

Master Data

Skills Mater Data

Add new skills

{% endblock %}

Project name-CRM
Django app-accounts
Below is an image of the project structure

A: You need to add your app to INSTALLED_APPS setting in settings.py
INSTALLED_APPS = [
    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts' # <- here
]

A: I had this issue, return render() function not accepting my html file as an argument and I solved it by doing two things:

*

*in the settings.py template DIRS I changed to ['templates'] (before I had ['anotherdirinsidemydjangofiles\templates']

*I moved the templates folder to the main project directory (it was a sub dir inside Django's project folder and that wasn't rendering at all).


text:
Q: Client Potential XSS without being properly sanitized or validated I am getting the below message on checkmarx scan on my code.
Gets user input for the text
element. This element's value then flows through the code without being properly sanitized or validated and is
eventually displayed to the user in method
Below is my code. Could some help me how to sanitize the below scenario.
Script as follows:
function setSummary(select,summary,lim, summaryHidden, limHidden) {
    if(select[select.selectedIndex].value == '-1') {
        summary.innerHTML = '';
        lim.innerHTML = '';
        summaryHidden.value = '';
        limHidden.value = '';
    } else {
        summary.innerHTML = 'Test1 - '+select[select.selectedIndex].text;
        summaryHidden.value = 'Test2 - '+select[select.selectedIndex].text;
        lim.innerHTML = 'Virtual - '+select[select.selectedIndex].text;
        limHidden.value = 'Virtual - '+select[select.selectedIndex].text;
    }
}

I am getting checkmarx vulnerability at below line for without being properly sanitized or validated
summary.innerHTML = 'Test1 - '+select[select.selectedIndex].text;

Could some please help me, How to properly sanitize the above line.

A: Whether or not this is exploitable, really depends on the context of how this function is being called, where the object select is coming from (and how it is populated - is this ever externally controllable?)
Regardless, the simplest solution here would be to set the value to the innerText property, instead of innerHTML, like so:
summary.innerText = 'Test1 - ' + select[select.selectedIndex].text;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как обновить TextView при изменении в RecyclerView? Есть активность CartActivity, в котором расположен RecyclerView. Так же есть класс RecyclerViewAdapter. Для ViewHolder прописан ClickListener, где пользователю отображается AlertDialog с предложением удалить выбранный элемент из списка.
CarActivity.java
...
 while (cursor.moveToNext()) {
                currentItem = new Item();
                currentItem.setId( cursor.getInt(idColumnIndex));
                currentItem.setName(cursor.getString(nameColumnIndex));
                currentItem.setPrice(Double.parseDouble(cursor.getString(priceColumnIndex)));
                currentItem.setAmount(Integer.parseInt(cursor.getString(amountColumnIndex)));
                currentItem.setImage(cursor.getString(imageColumnIndex));
                sumOrder += currentItem.getPrice()*currentItem.getAmount();
                items.add(currentItem);
            }

            mAdapter = new RecyclerViewAdapter(items, R.layout.row, this);
            mRecyclerView.setAdapter(mAdapter);
            progressBar.setVisibility(View.GONE);
            mSwipeRefreshLayout.setRefreshing(false);
            txtSumOrderView.setText(getString(R.string.txt_sum_order, sumOrder));
...

RecyclerViewAdapter.java
...
viewHolder.itemView.setOnClickListener(view -> {
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                          (dialog, which) -> {
                                  items.remove(currentItem);
                                  notifyDataSetChanged();
                              }
                          });
                  alertDialog.show();
}
...

Как сказать активности, что списочный массив items с RecyclerView изменился, чтобы снова пересчитать общую сумму уже оставшихся позиций и обновить текст в элементе TextView у активности?

A: Ваша архитектура использует непродуктивное решение с копированием данных из базы в динамический список и помимо удаления из списка вам так же надо отдельно делать удаление из базы данных (первая часть ответа, решение для SimpleCursorAdapter виджета ListView, но сама проблема думаю понятна), что еще добавляет сумбура в реализацию.
Предлагаю вам обратить внимание на последние решения в организации архитектуры взаимодействия виджетов с данными, предложенную Google - Architecture Components  (вторая часть ответа по ссылке выше). С появлением в библиотеке поддержки 27.1.0 класса адаптера для RecyclerView ListAdapter архитектура получила полный цикл взаимодействия и теперь любые операции с данными в БД автоматически отображаются на виджете, то есть теперь вам достаточно просто сделать записи, удаления, изменения в БД и они тут же будут отображены на экране.Естественно вам не понадобится никакое дублирование данных в списки, двойные операции по изменению данных и прочие ненужные проблемы.
Подробнее ознакомится с новой архитектурой можно по этой серии уроков
Так же стоит обратить внимание на то, что вычисления с данными в БД лучше доверить самой БД, а адаптеру только заниматься непосредственно выводом на экран, а не расчетами. В данном случае вы вычисляете значение sumOrder в адаптере, можно доверить это БД, используя вычисляемые столбцы. Например:
SELECT price, count, price*count AS sum  FROM  items

Здесь в выборке мы получим 3 столбца: значения из столбцов price, count и вычисляемый столбец sum (он будет добавлен в выборку, хотя в таблице и нет такого столбца), с произведением первых двух столбцов. Теперь можно просто брать оттуда данные с нужным результатом, а не считать их в адаптере.


text:
Q: Segfault when creating an array larger than 100000 How can I fix this code?  I can't input a value for n more than 100000 but I have declared it as long long int.
I tried to solve it but couldn't. Please tell me what is wrong.
#include<stdio.h>

void main() {
    long int n;
    scanf("%ld",&n);
    unsigned long long int a[n];
    unsigned long long int max[n];
    for(unsigned long long int i=0;i<n;i++) {
        scanf("%lld",&a[i]);
    }
    for(unsigned long long int i=0;i<n;i++) {
        unsigned long long int count=0;
        for(unsigned long long int j=0;j<n;j++) {
            if(a[i]==a[j]) {
                count++;
            }
        }
        max[i]=count;
    }

    for(unsigned long long int i=1;i<n;i++) {
        if(max[0]<max[i]) {
            max[0]=max[i];
            a[0]=a[i];
        }
        else if(max[0]==max[i]) {
            if(a[0]>a[i]) {
                a[0]=a[i];
            }
        }
    }
    printf("%lld",a[0]);
}

A: You're declaring variables on the stack that are too big:
unsigned long long int a[n];
unsigned long long int max[n];

These variables are declared local to the function main, meaning that on most implementations they live on the stack.  The stack is typically not that big, so when you specify a large value for n it creates arrays on the stack that are too big, overflowing the stack and causing a segfault.
Rather than creating the arrays on the stack, use malloc to create them on the heap:
unsigned long long int *a = malloc(n * sizeof(*a));
unsigned long long int *max = malloc(n * sizeof(*a));

Also, make sure you check the return value of malloc and call free when you're done.


text:
Q: ASP.NET MVC ajax jquery preloader so I know you could use show() and hide() of jquery during onbegin and oncomplete events of ajax calls to approach the ajax preloader effect.
What I want to know is is there a way to do it across the board? instead of manually going to each ajax form and adding onbegin and oncomplete functions etc.

A: Check out the jQuery.ajaxSend() and jQuery.ajaxComplete() events: they allow you to specify the common handler for all AJAX requests.


text:
Q: Spring read multipart attachment as input stream I'm developing a spring web service.Is there a way to read Multipart attachments in a soap message as a input stream with spring?

A: What version of Spring framework do you use?
if you are using 4.0 please refer this document.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html

A: refer this url it will may be help you
http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically.

A: Instead of using multipart/form-data, you can use httpservletRequest inputstream to upload a file directly using curl command.
@RestController
public class MyController {
@RequestMapping(path="/load", method=RequestMethod.POST )
public ResponseEntity<?> streamData(HttpServletRequest request) {

  InputStream dataStream = request.getInputStream();

...
}
From Git bash, you can invoke using
$ curl -T initialFeed.txt -X POST http://localhost:8080/load
https://curl.haxx.se/docs/manpage.html#-T


text:
Q: jOOQ: Get Referenced Table from Foreign Key I need to get the referenced table from a ForeignKey but there is no such property.
I can get the table but this is useless because it's the table I got the ForeignKey from.
Here's an example. What I want is TOSCA.KAMPAGNE.

Is there a way to get it?

A: Use ForeignKey.getKey().getTable()


text:
Q: read file content from DB I have stored a flatfile (.txt format) in DB as BLOB and retrieving it using JPA like below.
@Lob
@Column( name="TXT_FILE")
private byte[] txtFile;

Could you please suggest, how can I get the content of this text file from this byte[]?

A: Well, I'm supposing that you didn't persist the whole file, but only it's content.
If so, you could just read it by doing a new String(yourObject.getTxtFile(), "UTF-8")
Note that used UTF-8 as the encoding pattern. So you'll need to store data with it too.


text:
Q: Query for unfulfilled IAP when using Windows.Services.Store We've migrated our app from using Windows.ApplicationModel.Store to Windows.Services.Store as suggested int he documentation. However, we can't seem to find any way to query for and fulfill unfulfilled purchases. With the old API, we could call GetUnfulfilledConsumablesAsync to get the unfulfilled products, loop through those and fulfill them when the app started. There doesn't seem to be anything equivalent to this with the new API. We also get an empty array of items when querying the REST API (https://collections.mp.microsoft.com/v6.0/collections/query), so I assume that is only returning fulfilled items.

A: *

*As far as I can tell, the new getUserCollectionAsync method only returns consumables that haven't yet been "fulfilled," so it effectively does the same thing.

*The REST API wasn't returning anything because the Azure Active Directory client ID hadn't been added to the app in the Partner Dashboard. Around 24 hours after this it started returning the results correctly.


text:
Q: How to populate list data from server side to display tag using ajax in jsp I am working on a leave approval table, where managers can approve or reject leave for this I am using display tag to populate the pending leave request.
<disp:column title="Reject">
  <input type="button" class="btn" value="Reject"
          onclick="rejectLeave(this,${rows.id})" />
</disp:column>

onclick I am sending ajax request to approve the leave or reject leave. After updating the DB table, I am fetching the pendingleaverequest details again in the arrylist,  how do I pass this info to jsp to be displayed using displaytag.
<disp:table name="pendingLeaveRequest" id="rows">
          <disp:column></disp:column>
</disp:table>

Will json accept array list or only Map?


text:
Q: declare 'this' value for helper function I have a class:
const helper = function(val){
   console.log(this.a);
   console.log(this.b);
   this.bar();
};

export class Foo {

 public b = '45'
 private a = 15;

 bar(){

 }

 myMethod(){
    return helper.apply(this,arguments);
 }

}

the problem is, in the helper function, it doesn't know what the context is (what the value of 'this' is).
Is there a way for me to tell typescript that the value for this in the helper function is an instance of Foo?
(the reason I use the helper function is to create true private methods).

A: Try adding this on top of your helper function:
let self: Foo = this as Foo;
// use self instead of this below

Alternatively, you could replace all instances of this in it with (this as Foo).

A: You can declare the type of this for any function by adding an extra parameter named this. The this parameter will not be emitted to Javascript, it will be just for the benefit of the compiler to be able to type check your code:
const helper = function(this: Foo, val: number){
    console.log(this.a); /// error a is private
    console.log(this.b);
    this.bar();
 };

This will not however break encapsulation, you will still not be able to access private properties from outside the class, so unless you create the function inside the class it will still give an error as above. For functions defined inside the class it will not give errors:
export class Foo {

    public b = '45'
    private a = 15;
    bar() { }
    createHelper() {
        return function (this: Foo, val: number) {
            console.log(this.a);
            console.log(this.b);
            this.bar();
        };
    }

    myMethod() {
        return this.createHelper().apply(this, arguments);
    }

}


text:
Q: Kill a C program being executed by python script I am presently using a python script to run a c executable like
os.system("./a.out \"%s\" " %p)

There are many binary instruction available to me (i1,i2,i3.... i10 to be exact). I am generating the permutations of these instructions (of length 1,2,3...10) using itertools in python. The string payload p (in snippet above) is one such permutation. I am measuring the time taken for each permutation as follows:
start = time.clock()
os.system("./a.out \"%s\" " %p)
print time.clock() - start

(This may not be best way to measure time. But that is a subject of another question.)

Now for some permutations I get segmentation fault and the python script proceeds to another permutation. But for some permutations, I get no response (like stuck in a infinite loop)like:
58 60 452 547 583 649 756 777 932 965
key  Not found
(Nothing happens after this. This is due to bad combination
 of instructions or bad payload.
I have to press ctrl C to proceed to next permutation)
^C---------------[9 8 ]------------
The gadget seq is [mov,ret xor eax,eax,ret ] and time taken is
0.000254 (this is the bad permutation of instructions)

(Next permutation.. )

After I  press Ctrl + C, python script goes to next permutation. To put it more clearly
perm = itertools.permutations(gadget_list,2) #perm is list of all permutations of 2 instructions
for string in list(perm):
#generate the payload p from string which is one of the permutation
#feed it to c program and measure time
    start = time.clock()
    os.system("./a.out \"%s\" " %p)
    print time.clock() - start

Now for longer length of permutation it becomes tedious to press Ctrl C for every bad payload. Is there any way by which I can automate killing/stopping the C program (which I was doing by pressing Ctrl C) which gets stuck due to bad payload and proceed to next permutation?

A: to gain more control of the child process, you need to use subprocess module.
import time
from subprocess import Popen
from shlex import split

proc = Popen(split("./a.out '%s'" % p))

rtime, timeout = 0, 10
while rtime < timeout:
    rc = proc.poll()
    if rc is not None:
       break # process finished.
    time.sleep(1)
    rtime += 1
else:
    proc.kill()

A: Try rather something like:
os.system("timeout 5 ./a.out \"%s\" " %p)

for killing the process after 5 seconds for instance.
Just open a shell and try:
timeout 2 yes

to see.


text:
Q: Blob binding in httpTrigger not working in VS2017 Azure function template I want to pass the filename of blob to the httptrigger, through get request as below.
http://localhost:7071/api/CSVDataMigrationHttpTrigger/testdata.csv

Code for the azure function
public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "CSVDataMigrationHttpTrigger/{name}")]
        HttpRequest req, string name,
        [Blob("csvdata-upload/{name}", FileAccess.Read, Connection = "AzureWebJobsStorage")]
        Stream inputBlob, ILogger log)
    {}

inputBlob parameter is not resolved and it returns null.
But if i give filename as "testData.csv" as below in the Blob parameter, then inputBlob get resolved properly.
  public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "CSVDataMigrationHttpTrigger/{name}")]
            HttpRequest req, string name,
            [Blob("csvdata-upload/testData.csv", FileAccess.Read, Connection = "AzureWebJobsStorage")]
            Stream inputBlob, ILogger log){}

A: I found out finally, the filename was case sensitive, when passed to blob. Hope it helps anyone who has the same issue.

A: Check whether your blob is actually uploaded in the Storage Container. The stream will be null only if the blob is Not Exist/Unable to find in the container


text:
Q: NuGet v4 contentFiles not getting copied to output I'm having trouble with NuGet copying files to output, using NuGet v4 CLI.
My directory structure looks like this:
repo
repo\CodeAnalyzer.nuspec
repo\CodeAnalyzer.props
repo\contentFiles\any\any\StyleCop.ruleset

Here's my CodeAnalyzer.props file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PackageName>CodeAnalyzer</PackageName>
    <PackageVersion>0.1.0</PackageVersion>
  </PropertyGroup>
  <PropertyGroup>
      <CodeAnalysisRuleSet>StyleCop.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
</Project>

And CodeAnalyzer.nuspec file:
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>CodeAnalyzer</id>
    <description>Provides standard code analyzer tooling and customisation.</description>
    <authors>Me</authors>
    <version>0.1.0</version>
    <dependencies>
      <dependency id="StyleCop.Analyzers" version="1.1.118" />
    </dependencies>
    <contentFiles>
      <files include="any/any/*" buildAction="Content" copyToOutput="true" flatten="false" />
    </contentFiles>
  </metadata>
  <files>
    <file src="contentFiles\any\any\StyleCop.ruleset" target="contentFiles" />
    <file src="CodeAnalyzer.props" target="build" />
  </files>
</package>

On CLI I am packing using:
.\nuget.exe pack .\CodeAnalyzer.nuspec
In the resulting .nupkg, there is a contentFiles directory with the StyleCop.ruleset file in, so that works.
If I then install the package in a project, it picks up on the StyleCop.Analyzers dependency fine, and it looks for the StyleCop.ruleset file, so the .props file is fine.
But the StyleCop.ruleset file isn't placed anywhere.
Feel like I've tried a lot of changing buildActions to None/Content, copyToOutput to true/false, different paths for the contentFiles.file element and the file.file element.
Edit: the consuming project is using PackageReferences for NuGet packages, not packages.config.

A: I was have this issue, when i had turned lot of changes and nothing worked. And finally solved by using PackageReferences
packages.config projects use content/
PackageReference projects use contentFiles/
You can find more about immutable content here:
ContentFilesExample
nuget-contentFiles-demystified

*

*Existing project with nuget references via packages.config

*Installed NuGet package with content files

*Build project

*
No content files in output directory

*Conversion of packages.config to PackageReferences

*Build project

*
Content files have been copied to output directory

IDE is Visual Studio 2017. The project is an application project which means it is in the old csproj format.
Updated Answer
The GeneratePathProperty attribute was added to PackageReference
<PackageReference Include="EO.Pdf" GeneratePathProperty="true">
    <Version>19.0.83</Version>
</PackageReference>

Check your \obj\.csproj.nuget.g.props to verify the variables are generated
Variables are prefixed with Pkg. It sounds like they are automatically generated for all nuget packages with a tools folder.

A: contentFiles with PackageReference works fundamentally differently to content with packages.config. With packages.config, you must use tooling (Visual Studio) to install packages, and at install-time, NuGet will copy content to the project directory and whatever other changes it needs to (like telling the Project System to modify the csproj). With packages.config restore is conceptually different to install, and all restore does is unzip the package in the expected location so that the lib/<tfm>/*.dll assemblies are available at compile-time.
With PackageReference it's possible to hand edit the csproj without tooling having any knowledge this happened. This means when NuGet does a restore, it has no idea if this is the first time a particular package was restored for the project, or just the first time on this computer (in fact, NuGet doesn't even check the existing state of the project on the machine, so currently it has no idea if the package has been previously restored in the project on the current computer). Although you can still use tooling (Visual Studio, or dotnet add package), this is nothing more than a convenient way to edit the csproj. This is a long way to say that the concept of install vs restore no longer exists with PackageReference. There is now only restore.
Since the concept of install no longer exists with PackageReference, there's a big question about how to do content files, if NuGet were to copy files to the consuming project's directory. If NuGet copies the file every restore, it means if the developers of the project modify the file, they lose their changes on the next NuGet restore. If NuGet doesn't overwrite files, then when the project changes the package version, the new content from the new package will not be updated.
So, the way that contentFiles works is that NuGet tells the build system about the files, and they're used as links from the global packages folder. At build time for .NET Framework TFMs, or at publish time for .NET Core TFMs, the files are copied to the output directory. But at no time are they ever copied to the project directory. If using Visual Studio, they should appear in Solution Explorer, but if you click a file to open it, it opens in read-only mode, since it would be bad to make project-specific changes to the global packages folder, which is used by all projects on the computer. So, conceptually it's similar to copying the file on every build, and in order to discourage developers of the consuming project from making changes, it doesn't bother copying the files to the directory. It also means there's less to check into source control.
Since the content file you're using is a build-time asset, not a runtime asset, I suggest that contentFiles is not the right place to put your ruleset file. I'd just put it in the build/ directory next to your props file. Since your props file doesn't specify a path to your ruleset file, I believe it tells MSBuild to look in the props file's directory, so it'll just work. Worst case you change it to $(MSBuildThisFileDirectory)StyleCop.ruleset. This is under the assumption you're fine with the consuming projects not being able to modify the ruleset file. If you do wish them to be able to modify the file, then NuGet is not an appropriate delivery mechanism, and I suggest you look at dotnet new item templates instead.

A: Here's another answer that addresses this:
https://stackoverflow.com/a/68243917/56621
TL;DR - when packing files into the package make sure you follow the "any/any" naming convention for target frameworks/languages, otherwise it won't work


text:
Q: Store a table row index as an array index There a simple function:
selected_row = []; // global scope

function toggleRowNumber(rowIndex) {
  if(selected_row[rowIndex]) selected_row.splice(rowIndex, 1);
  else selected_row[rowIndex] = 1;
}

usage
toggleRowNumber(50000); // click the row - write the index
toggleRowNumber(50000); // click the row again - remove the inxed

alert(selected_row.length);

50001
OK
Delightful feature!
So is there a way to direct write|read an index without any searchin/looping? And without this huge feat as decribed above.
Thanks.

A: If I understoold correctly, you want to store and index where you can check/set whether an item is selected or not. If that is the case, you are looking for a "key - value" data structure. Then, why not use a map?
var selected_row = {};

function toggleRowNumber(rowIndex) {
if(selected_row[rowIndex]) selected_row[rowIndex] = 0; //or = undefined;
else selected_row[rowIndex] = 1;
}

That is better because hash map will save you time and space.

*

*Space becuase you are not storing hundreds of 'undefined' values in a vector.

*Time because, hash function used to access elements is pretended to hit the right position in many cases.


text:
Q: C++ Program Gets Crash on recalling Function from Main? I have a class Movie with data members genre Actors and size.
class Movie
{
private:
    string* Actors;
    string* genre;
    int size = 0;

I have used setters and getters method to initialize the data members. First I have set the size to 2 from main by calling the
setsize()

member function for genre and then called the member function
set_genre().

from main. Here comes the problem, whenever i re-call the
setsize()

for Actors and set the size for actors and Debug my program it takes input for both genre and actors but when it comes to display it crashes, displaying Exception thrown. I have tried so many things but i don't know how to resolve this problem. Please anyone help me with this, it's a task from my lab instructor.
CLASS...
class Movie
{
private:
    string* Actors;
    string* genre;
    int size = 0;
public:
    Movie()
    {
        Actors = new string[size];
        genre = new string[size];
    }
    void setsize(int x)
    {
        size = x;
    }
    void set_actors()
    {
        Actors = new string[size];
        for (int i = 0; i < size; i++)
        {
            cout << "ACTOR " << i + 1 << endl;
            getline(cin, Actors[i]);
        }
    }
    void set_genre()
    {
        genre = new string[size];
        for (int i = 0; i < size; i++)
        {
            cout << "GENRE " << i + 1 << endl;
            getline(cin, genre[i]);
        }
    }
    void display_actors()
    {
        for (int i = 0; i < size; i++)
        {
            cout << Actors[i] << endl;
        }
    }
    void display_genre()
    {
        for (int i = 0; i < size; i++)
        {
            cout << genre[i] << endl;
        }
    }
    ~Movie()
    {
        delete[]genre;
        delete[]Actors;
    }
};

MAIN...
Movie M1;
    M1.setsize(2);//GENRE SIZE SET TO 2
    M1.set_genre();
    M1.setsize(4);//ACTOR SIZE SET TO 4
    M1.set_actors();
    cout << "DISPLAYING DATA" << endl;
    M1.display_actors();
    M1.display_genre();

A: Least fix will be preparing separate variables for

*

*size of current Actors

*size of current genre

*size for next reading

It will be like this:
class Movie
{
private:
    string* Actors;
    string* genre;
    int Actors_size = 0, genre_size = 0;
    int size = 0;
public:
    Movie()
    {
        Actors = new string[size];
        genre = new string[size];
    }
    void setsize(int x)
    {
        size = x;
    }
    void set_actors()
    {
        Actors = new string[size];
        for (int i = 0; i < size; i++)
        {
            cout << "ACTOR " << i + 1 << endl;
            getline(cin, Actors[i]);
        }
        Actors_size = size;
    }
    void set_genre()
    {
        genre = new string[size];
        for (int i = 0; i < size; i++)
        {
            cout << "GENRE " << i + 1 << endl;
            getline(cin, genre[i]);
        }
        genre_size = size;
    }
    void display_actors()
    {
        for (int i = 0; i < Actors_size; i++)
        {
            cout << Actors[i] << endl;
        }
    }
    void display_genre()
    {
        for (int i = 0; i < genre_size; i++)
        {
            cout << genre[i] << endl;
        }
    }
    ~Movie()
    {
        delete[]genre;
        delete[]Actors;
    }
};

This code will at least work without crashing if instances of this class aren't copied, but have problems of memory leak (pointers to old arrays are thrown away without being freed) and have risk of using dangling pointers and double-free because it doesn't follow The Rule of Three.
To avoid many troubles of memory management, you shouldn't use manual allocation of dynamic arrays and you should use std::vector instead.
It will be like this:
#include <vector>

class Movie
{
private:
    std::vector<string> Actors;
    std::vector<string> genre;
    // sizes are stored in the vectors, so no external size management is required
    int size = 0;
public:
    Movie()
    {
        // vectors will be implicitly initialized, so no explicit initialization is required
    }
    void setsize(int x)
    {
        size = x;
    }
    void set_actors()
    {
        Actors.resize(size);
        for (int i = 0; i < size; i++)
        {
            cout << "ACTOR " << i + 1 << endl;
            getline(cin, Actors[i]);
        }
    }
    void set_genre()
    {
        genre.resize(size);
        for (int i = 0; i < size; i++)
        {
            cout << "GENRE " << i + 1 << endl;
            getline(cin, genre[i]);
        }
        genre_size = size;
    }
    void display_actors()
    {
        for (size_t i = 0; i < Actors.size(); i++)
        {
            cout << Actors[i] << endl;
        }
    }
    void display_genre()
    {
        for (size_t i = 0; i < genre.size(); i++)
        {
            cout << genre[i] << endl;
        }
    }
    ~Movie()
    {
        // explicit deallocation isn't also required
    }
};


text:
Q: How to inhibit selection of TK Text widget? I am trying to find the best way to inhibit text selection in a Tk text widget.
Here an example of code using Iwidget's ScrolledText:
package require Iwidgets
iwidgets::scrolledtext .t
pack .t

I already tried to bind to <<Selection>> virtual event without success yet to unbind <Double-1> event.
Any ideas?

A: It's moderately awkward to prevent the selection from being created (there are a great many bindings that do things with it) but you can easily prevent it from affecting the rest of the application (by configuring the text widget to have -exportselection false). Then all you need to do is ensure that it can't be seen by configuring it to be invisible (through the text widget's -selectbackground and -selectborderwidth options).


text:
Q: hibernate: attempt to lock a deleted instance I'm trying to lock an entity while working on it, and I'm doing the following:
1: retrieveing the entity from the database using this method:
@Override
public Optional<T> findById(final Serializable id) {
    Session session = getSession();
    T e = session.get(persistentClass, id);
    return Optional.ofNullable(e);
}

2: locking the entity:
public T myMethod(final Serialzable id){
   //...
   T entity = getById(id);
   LockRequest lr = session.buildLockRequest(LockOptions.UPGRADE);
   lr.setTimeOut(LOCK_REQUEST_TIME_OUT);
   lr.lock(entity); // <-- problem is in this line
   //...
}

but I get this exception:
org.hibernate.ObjectDeletedException: attempted to lock a deleted instance: [com.x.y.Entity#1]

As you can see I'm just retrieving the entity and locking it, not sure why the entity is in the deleted state!!


text:
Q: Probability in a small interval is $P. dx$ Reif says

... variable $u$ which can assume any value in the continuous range $a_{1}<u<a_{2}$. To give a probability description of such a situation, one can focus attention on any infinitesimal range of the variable between $u$ and $u+d u$ and ask for the probability that the variable assumes a value in this range. One expects that this probability is proportional to the magnitude of $d u$ if this interval is sufficiently small;

*

*Indeed, the probability must be expressible as a Taylor's series in powers of du and must vanish as $d u \rightarrow 0$. Hence the leading term must be of the form $P d u$, while terms involving higher powers of $d u$ are negligible if $d u$ is sufficiently small.

So expanding probability function as Taylor series I've
$P(x+d x)=P(x)+\frac{P^{\prime}(x)}{1 !} d x+\frac{P^{\prime \prime}(x)}{2 !} d x^{2}+\cdots$
in limit $dx$ is small we've
$P(x+d x)=P(x)+{P'(x)} d x$
Now how do I make the connection that "probability is proportional to the magnitude of $d x$ if this interval is sufficiently small"?

A: Your probability function $P(x)$ is apparently the cumulative distribution that is $P(x)=\mathbf{Pr[x}\le x\mathbf{]}$ so $P(x+dx)=\mathbf{Pr[x}\le x+dx\mathbf{]}\approx P(x)+P'(x)dx$, that is $P(x+dx)-P(x) = \mathbf{Pr[}x < \mathbf{x}\le x+dx\mathbf{]}\approx P'(x)dx$ where now $P'(x)$ is the probability density.

A: Continuous probability distributions are defined by the probability density, which is a function $\rho(x)$ of the random variable $x$ defined such that the area under it's curve between $x_1,x_2$ is the probability $P(x_1<x<x_2)\equiv\int_{x_1}^{x_2}\rho(x)dx$. Note that for continuous distributions, the probability at a point is zero, as the (Reimann) integral vanishes (the area under the curve if $x_1=x=x_2$ is zero, there's no 'rectangle' you can draw). This is no more than saying that I cannot tell you the mass of a single point in a glass of water, but if you give me the density of water and fill a certain volume I can integrate the density over that volume and give you the mass. In other words, continuous probability distributions are useful only to calculate the probability for a given range of possible outcomes.
Now, assume that you ask 'what's the probability of finding $x$ in an infinitesimal neighbourhood of $x_0$, say $(x_0-\epsilon/2, x_0+\epsilon/2)$. Then, you'd have $$P(x\in(x_0-\epsilon/2, x_0+\epsilon/2))=\int_{x_0-\epsilon/2}^{x_0+\epsilon/2}\rho(x)dx\approx\rho(x_0)\epsilon$$
Since the density is approximately constant in infinitesimal interval, the same as a curved line is straight if you go close enough. You can recast this as
$$P\bigg(x\in\big((x_0-\epsilon/2),(x_0-\epsilon/2)+\epsilon\big)\bigg)\approx \rho(x_0)\epsilon $$
You can also write $\rho(x-\epsilon/2)$ if you like, but for small $\epsilon$ they're the same thing(do a Taylor expansion and see what happens as $\epsilon\to 0$).


text:
Q: Best datastructure for iterating over and moving elements to front As part of a solution to a bigger problem that is finding the solution to a maximum flow problem. In my implementation of the relabel-to-front algorithm I'm having a performance bottleneck that I didn't expect.
The general structure for storing the graph data is as follows:
struct edge{
    int destination;
    int capacity;
};

struct vertex{
    int e_flow;
    int h;
    vector<edge> edges;
};

The specifics of the algorithm are not that important to the question. In the main loop of the solution I'm looping over all vertices except the source and the sink. If at some point a change is made to a vertex then that vertex is put at the front of the list and the iteration starts again from the start. Until the end of the list is reached and we terminate. This part looks as follows now
//nodes are 0..nodeCount-1 with source=0 and sink=nodeCount-1
vector<int> toDischarge(nodeCount-2,0);
for(int i=1;i<sink;i++){
    toDischarge[i-1]=i;
}//skip over source and sink
//custom pointer to the entry of toDischarge we are currently accessing
int point = 0;
while(point != nodeCount-2){
    int val = toDischarge[point];
    int oldHeight = graph[val].h;
    discharge(val, graph, graph[val].e_flow);
    if(graph[val].h != oldHeight){
        rotate(toDischarge.begin(), toDischarge.begin()+point, toDischarge.begin()+point+1);
        //if the value of the vertex has changed move it to the front and reset pointer
        point = 0;
    }
    point++;
}

I tried using an std::list data structure before the vector solution but that was even slower even though conceptually that didn't make sense to me since (re)moving elements in a list should be easy. After some research I found out that it was probably horribly performant due to caching issues with list.
Even with the vector solution though I did some basic benchmarking using valgrind and have the following results.

If I understand this correctly then over 30% of my execution time is just spent doing vector element accesses.
Another solution I've tried is making a copy of the vertex needed for that iteration into a variable since it is accessed multiple times, but that was even worse performance because I think it is also making a copy of the whole edge list.
What data structure would improve the general performance of these operations? I'm also interested in other data structures for storing the graph data if that would help.

A: It seems to me that this is what std::deque<> is for. Imagine it as a 'non-continuous vector', or some vector-like batches tied together. You can use the same interface as vector, except that you cannot assume that adding an index to the first element's pointer results in the given element (or anything sensible other than UB); you need to use [] for indexing. Also, you have dq.insert(it, elem); that's quick if it is std::begin(it) or std::end(it).


text:
Q: Adding a custom key in Symfony 2 in-memory user provider? How to add a custom key in Symfony 2 in-memory user provider?
providers:
    administrators:
        memory:
            users:
                admin: { password: admin, roles: [ 'ROLE_USER' ] }

If I modify the above adding an image property the user isn't able to login anymore. Really a strange issue.
providers:
    administrators:
        memory:
            users:
                admin: { password: admin, roles: [ 'ROLE_USER' ], image: "img/plh.png" }

A: Reason is on Error log:
PHP Fatal error:  Uncaught exception 'Symfony\Component\Config\Definition\Exception\InvalidConfigurationException' with message 'Unrecognized options "image" under "security.providers.in_memory.memory.users.manage"' in ~/vendor/symfony/symfony/src/Symfony/Component/Config/Definition/ArrayNode.php:306

Check:
https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php#L562
To fix it, you could extend Configuration of the SecurityBundle:
http://symfony.com/doc/current/cookbook/bundles/prepend_extension.html


text:
Q: why is CSS stylesheet partly not working in my Django app? Is it something to do with retrieving database data? I believe I have all the Django settings correct as I have followed a few tutorials including a Linkedin one. I think I have identified where the problem occurs. The CSS stylesheet does work on my app everywhere except at the part of the code where I am retrieving postgres data.In addition when I modify the code and remove the postgres code the CSS will work and style that area. Therefore I don't understand why it stops working when I add the postgres! I have also included {% load static %} at the top of my HTML.
I include my HTML the code below..
Code Snippet when it works:

Stories!!!!

Repunzel!!

Lets see hdewdow Repunzel manages to escape the tower, have an adbenture and finds out the truth!!.

Alladin!!

Let's see if Kitty, Jasmine and Alladin manage with Genies' help to outsmart the baddies!!.

/When it doesn't work/

Stories!!!!

    {% for drawing in drawings.all %}

Repunzel!!

{{ drawing.summary }}

    {% endfor %}

drawing is my drawing object that I included in my model definition and it is stored in postgres. I do connect to the database as i retrieve the data. The whole issue is that the CSS styling for that specific part doesn't work when included in the django for loop.
I also include the views and models code below...
#views.py
from django.shortcuts import render,get_object_or_404
from .models import Drawing

def drawingshome(request):
drawings = Drawing.objects
return render(request, 'drawings/drawingshome.html',{'drawings':drawings})

#models.py
from django.db import models

class Drawing(models.Model):
 image = models.ImageField(upload_to='images/')
 summary = models.CharField(max_length=200)
 classname = models.CharField(max_length=200, default='0000000')
 source = models.CharField(max_length=200, default='0000000')
 altname = models.CharField(max_length=200, default='0000000')

def __str__(self):
    return self.summary

Many thanks for your help and your time.

A: Declare a variable.
drawings = 'postgres_db_data'

Try:
{% for drawing in drawings %}

Note: I have removed .all and 'postgres_db_data' is your DB query instance.
I have done the same in many of development and succeeded.


text:
Q: how to separate Day and Night Record using Mysql Statement In my SQL database I store date with time stamp for example like this(2015-09-21 18:02:14) I have requirement to get last time(18:02:14) is Day or Night using SQL statement
If you have another idea please share with me. I would like to use it if it fits my requirements.
In my table if have 20 record same date then get only day record how to  create query like that

A: If the day defines from 6am to 6pm, Then
SELECT column
FROM  `tablename`
WHERE HOUR( column )
BETWEEN 6
AND 18;

A: First you should define what is a day and night. Then you can use DATE_FORMAT function to convert datetime field to HH:MI string.
For example you can select records from 18:00 to 8:00 (Night)
select * from t
WHERE DATE_FORMAT(dt, '%H:%i')>='18:00'
      or  DATE_FORMAT(dt, '%H:%i')<'09:00'

SQLFiddle demo

A: You should have another table (or other data source) that supplies the sunset and sunrise times, then compare you own datetime, to that source. You can compare either before adding to your table (and make another column named isDay) or when SELECTing from the table.
Note:

*

*Sunset/Sunrise times depend on your geo-location.

*There are API's that can provide that info

*There are algorithms that can assist in calculating that info

Examples:

*

*http://sunrise-sunset.org/api

*http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2015-12-13

*I need a sunrise/sunset webservice api

A: -- from sql server 2008 until now
SELECT
    CASE WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 'DAY'
        ELSE 'NIGHT'
    END

-- from sql server 2012 until now, if you don't like CASE
SELECT IIF(DATEPART(HOUR, GETDATE()) < 18, 'DAY', 'NIGHT')

18 = 6PM
you can replace GETDATE() with your DATETIME column
SELECT
    CASE WHEN DATEPART(HOUR, 'yourDateTimeColumn') < 18 THEN 'DAY'
        ELSE 'NIGHT'
    END AS PeriodOfDay
FROM 'yourTable'


text:
Q: SVG code: Can I use point decimals and percentages on all browsers? In SVG code I used point decimals: .001 instead of 0.001
And percentage number like 50%
I have been told that using these numbers used to be a cross browser incompatibility issue in the past, but I haven't been able to replicate the problem in 5 browsers.
Should I revisit all my SVGs and replace the point decimals and percentages?
Is this not an issue anymore, at least across latest versions of most popular browsers?

A: Credit to @Robert Longson, and @herrstrietzel
Based on their comments I have deduced that leading point decimal (like .0694) and % values (where appropriate), have no compatibility issues.
Simply make sure that your data type supports the values you used by testing in few browsers you have on hand, and if all looks as intended then you are doing it right and its safe to assume that these values will work in all updated popular browsers.


text:
Q: ArrayList Contains with Object always returns false Here is my code:
package bikeproject;

import java.util.ArrayList;
import java.util.Random;

public class BikerList {
    public static void main(String[] args) {
        ArrayList<Bike> bikes = new ArrayList<Bike>();

        int mountainBikeSales = 0;
        int roadBikeSales = 0;

        fillArray(bikes);

        displayStock(bikes);

//      calculateStock(bikes);
        System.out.println(displayBkeNumbers(bikes));
    }

    static void fillArray(ArrayList<Bike> bikes) {
        Random rand = new Random();
//      int number = 2;
//      int a = rand.nextInt(2);

        for (int i = 0; i < 10; i++) {
            if (rand.nextInt(2) < 1) {
//              System.out.println(rand.nextInt(2));
                bikes.add(new MountainBike());
            } else {
//              System.out.println(rand.nextInt(2));
                bikes.add(new RoadBike());
            }
        }
    }

    static void displayStock(ArrayList<Bike> bikes) {
        for (Bike bike : bikes) {
            System.out.println(bike);
        }
    }

    static int calculateStock(ArrayList<Bike> bikes) {
        int bikesSold = 0;
        for (Bike bike : bikes) {
            if (bikes.contains(new MountainBike())) {
                bikesSold++;
            }
        }
        return bikesSold;
    }

    static String displayBkeNumbers(ArrayList<Bike> bikes) {
        int mb = 0;
        int rb = 0;

        mb = calculateStock(bikes);
        rb = bikes.size() - mb;

        return "\nStock Levels" + "\nWe have " + mb + " mountain Bike in Stock" + "\nWe have " + rb
                + " Road bikes in Stock";
    }
}

I really believe there is an error in the calculateStock() method because it always returns false, In the calculateStock() method I want to add the value to the bikesSold variable if each bike in the array is an instance of a mountain bike.
The output generated by the code above:
Stock Levels
We have 0 mountain Bike in Stock
We have 10 Road bikes in Stock

Mountain Bike is always 0 although it is already in the ArrayList.
The expected output, something like this:
Stock Levels
We have 4 Mountain Bikes in stock
We have 6 Road Bikes in stock

A: static int calculateStock(ArrayList<Bike> bikes) {
    int bikesSold = 0;
    for (Bike bike : bikes) {
        if (bikes.contains(new MountainBike())) { //problematic line
            bikesSold++;
        }
    }
    return bikesSold;
}

does not work, because, .contains(Object o):

returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

So, bikes.contains(new MountainBike()) will always return true as long as there is, at least, one instance of the MountainBike contained (according to the .equals(Object o) method) in the bikes list.
Rather, you should want to check if the current object is an instance of a particular type you would want to check it against (MountainBike, in this case), like this:
static int calculateStock(ArrayList<Bike> bikes) {
    int bikesSold = 0;
    for (Bike bike : bikes) {
        if (bike instanceof MountainBike) {
            bikesSold++;
        }
    }
    return bikesSold;
}

A: This if (bikes.contains(new MountainBike()))  creates a new object and checks if it's already in the list. It's not.
You need to do something like if (bike instanceof Mountainbike) .
There are better ways, but that will solve your problem.


text:
Q: MATE remove window list from panel using dconf write or I see that I just have to find 'the right spot' to right click, but I fail and fail. Every where I click the click goes to the nearest window in the list.
I've tried editing the dconf dump file to remove the windowlist but I discover that is not the way to do it.

A: Consider to use gsettings instead of dconf.
Simple hacky way:
gsettings set org.mate.panel object-id-list \
"$(gsettings get org.mate.panel object-id-list | sed "s/'window-list', //")"

Explanation. On my clean installation of Ubuntu MATE 18.04 LTS the output of
gsettings get org.mate.panel object-id-list

is
['briskmenu', 'firefox', 'notification-area', 'indicatorappletcomplete', 'clock', 'show-desktop', 'window-list', 'workspace-switcher', 'trashapplet']

With | sed "s/'window-list', //" piping we can remove 'window-list', from parameter value and change it to the following:
['briskmenu', 'firefox', 'notification-area', 'indicatorappletcomplete', 'clock', 'show-desktop', 'workspace-switcher', 'trashapplet']

then we pass this value to gsettings set org.mate.panel object-id-list.

Note: this method is also suitable for Ubuntu MATE 16.04 LTS.


text:
Q: fullpage is not a constructor issue I always run into the same issue and currently i dont know a way out.
Following problem:
I try to use fullpage for my website. Here is a simplified version of what i am doing:
<!DOCTYPE html>

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

Home

Project

Contact

Content of my "jsApplication.js":
new fullpage('#fullpage', {
              licenseKey: 'OPEN-SOURCE-GPLV3-LICENSE',
              autoScrolling: true,
});

I always get the following error: "TypeError: fullpage is not a constructor".
So what i am doing wrong?
best regards

A: I found solution.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

is required.


text:
Q: HTML CSS Modal: Position fixed not working I am trying to create a Modal
I have given the Background component position:fixed still its starting from the toggle button
when position:fixed is active:

when position:fixed is not active:

const Background = styled.div`
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  position: fixed;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
`;

      {' '}
      {showModal ? (
        <Background>
          <ModalWrapper showModal={showModal}>
            <ModalImg src={require('./modal.jpg')} alt='camera' />
            <ModalContent>

Are you ready?

Get exclusive access to our next launch.

              <button>Join Now</button>
            </ModalContent>
            <CloseModalButton
              aria-label='Close modal'
              onClick={() => setShowModal((prev) => !prev)}
            />
          </ModalWrapper>
        </Background>
      ) : null}

A: the  tag used in the last segment of code as a wrapper/parent is not style neutral, it has some default styling which is causing such problem.
Replace is with <> </>
 <>
      {' '}
      {showModal ? (
        <Background>
          <ModalWrapper showModal={showModal}>
            <ModalImg src={require('./modal.jpg')} alt='camera' />
            <ModalContent>

Are you ready?

Get exclusive access to our next launch.

              <button>Join Now</button>
            </ModalContent>
            <CloseModalButton
              aria-label='Close modal'
              onClick={() => setShowModal((prev) => !prev)}
            />
          </ModalWrapper>
        </Background>
      ) : null}
    </>

And now everything works fine!


text:
Q: AssertionError: You cannot render this Element if it is not in a Figure I wrote the following code:
import folium
map = folium.Marker(location=[80, -100], zoom_start=6, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="My map")
fg.add_child(folium.Marker(location=[80, -100], popup="Marker Here", icon=folium.Icon(color="green")))

map.save("Map.html")

and i keep getting this error message:
Traceback (most recent call last):
  File "c:/Users/king/Desktop/applications/mapping/maps.py", line 6, in <module>
    map.save("Map.html" )
  File "C:\Users\king\AppData\Local\Programs\Python\Python38-32\lib\site-packages\branca\element.py", line 169, in save
    html = root.render(**kwargs)
  File "C:\Users\king\AppData\Local\Programs\Python\Python38-32\lib\site-packages\branca\element.py", line 614, in render
    assert isinstance(figure, Figure), ('You cannot render this Element '
AssertionError: You cannot render this Element if it is not in a Figure.

i am trying to save the progress of the map i'm building and it keeps bringing up the error message

A: According to the docs the Marker should be added to a Map
map = folium.Map(
        location=[80, -100],
        zoom_start=6,
        tiles="Mapbox Bright"
      )

fg = folium.FeatureGroup(name="My map")

folium.Marker(
    location=[80, -100],
    popup="Marker Here",
    icon=folium.Icon(icon='green')
).add_to(map)


text:
Q: Toolbar above keyboard doesn't hide when keyboard hides I've added a toolbar above keyboard to show Done button to dismiss keyboard. I've added it on my login screen. When keyboard is showing and I tap on saved Password icon to select saved password, keyboard hides but toolbar doesn't hide. Toolbar sits at the bottom of screen and then moves up with keyboard when keyboard shows again. It looks bad.
How do I fix it so that Toolbar doesn't show on it's own and shows/hide only with keyboard?
override func viewDidLoad() {
    super.viewDidLoad()
    self.emailTextField.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
    self.passwordTextField.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
}

@objc func tapDone(sender: Any) {
    self.view.endEditing(true)
}

extension UITextField {

    // Add done button above keyboard
    func addDoneButton(title: String, target: Any, selector: Selector) {
        let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 44.0)))

        let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let barButton = UIBarButtonItem(title: title, style: .plain, target: target, action: selector)
        barButton.setTitleTextAttributes([NSAttributedString.Key.font : UIFont.main, NSAttributedString.Key.foregroundColor : UIColor.red], for: [])
        toolBar.setItems([flexible, barButton], animated: false)
        self.inputAccessoryView = toolBar
    }
}

A: I personally handle this in a different way as I'm not using any toolbar but custom views above the keyboard. As I want those views to animate and appear/disappear depending on the keyboard position, I first listen to keyboard changes:
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardChanged(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)

And then handle the keyboard current size and position manually here like so:
func keyboardChanged(_ userInfo: Dictionary<AnyHashable, Any>?) {
    if let userInfo = userInfo {
        let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
        if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
            // keyboard is masked, you can mask/move your toolbar here
        } else {
            // update your toolbar visibility and/or position/constraints here using 'endFrame?.size.height'
        }

        // animate your toolbar or any other view here:
        UIView.animate(withDuration: duration,
                delay: TimeInterval(0),
                options: animationCurve,
                animations: {
                     // animate what you need here
                     self.view.layoutIfNeeded()
                },
                completion: nil)
    }
}

So in your case I would create the toolbar first and constraint it to the bottom of the screen. Then I would use the code above to handle its position and visibility.
Then, whenever the keyboard position is updated, you can handle the toolbar (position and visibility) in the keyboard notification handler shown above.

A: Might not be a direct answer to this question but I highly suggest you to take a look at the IQKeyboardManager library. By default, it is a one liner keyboard handler but you can add your accessory views easily and it manages them well
https://github.com/hackiftekhar/IQKeyboardManager


text:
Q: What did Einstein mean by-matter curves and warps spacetime? In general relativity one keeps hearing that.
Please tell what is really means and its connection to reality we see around us?

A: The curvature of spacetime describes tidal gravity, that is gravitational effects that change from one event to another in spacetime. Let's get a little background.
Let's exclude gravity for a minute and consider the idea of spacetime without gravity. Spacetime means that we have a 4D space where three dimensions are space and one is time. In this framework a point particle traces out a "worldline" where each "event" on the line represents the location of the particle at a given time. Two intersecting worldlines represent two particles that collide, and two parallel worldlines represent particles that are at rest with respect to each other.
One nice thing about this view is that Newton's first and second laws can be expressed geometrically. Newton's first law says that free particles have straight worldlines, and the second law says that the force is proportional to how tightly the worldline bends. So an accelerometer directly measures the amount that a worldline bends.
So to recap: a particle's spacetime worldline represents the position at each moment in time, if an attached accelerometer reads 0 then the worldline is straight and parallel worldlines represent particles at rest with respect to each other and intersecting worldlines represent particles colliding.
Now, let's consider gravity. Suppose that we have two objects far outside of a planet but at the same altitude, and let's say that the planet and the objects only interact gravitationally, so like neutrinos they can just pass through each other. Now, if those two objects start out at rest then that means their worldlines are parallel to each other. Gravity does not activate an accelerometer, so according to our earlier discussion that means that the worldlines are straight (also called geodesics). However, if we wait long enough then they will collide at the center, meaning their worldlines will intersect.
Geometrically, that means that we have two initially parallel straight lines that intersect. This is not possible in flat geometry, but it is possible in curved geometry. For example, consider two nearby longitude lines, longitude lines are great circles, so they are geodesics, or the spherical equivalent of straight lines. At the equator they are parallel, but they intersect at the poles. This is because the geometry on a sphere is curved rather than flat.
This means that curved spacetime geometry represents the effects of gravity. With curvature in spacetime you can have initially parallel straight lines intersect, representing particles initially at rest that collide despite never having accelerometers detect any forces bending their worldlines.
This is what it means for matter to curve spacetime. Tidal gravity, that is gravity that changes from one place to another, has effects that cannot be explained using flat spacetime geometry but can be explained using curved spacetime geometry. The amount of curvature is related to the strength of tidal gravitational effects, and this is what is described by the Einstein field equations.
Taken seriously this idea also predicts gravitational effects on time, which have been measured to very high precision. So it appears to be more than just an odd metaphor. To date this approach has passed all experimental tests while ruling out many alternatives.

A: I would like to complement Dale's answer with a bit of the mathematics of General Relativity.
It isn't only matter that warps spacetime; radiation and other forms of energy do also. Spacetime curvature is actually caused by the density and flow of energy and momentum, represented by the energy-momentum tensor $T_{\mu\nu}$ on the right side of the Einstein field equation,
$$G_{\mu\nu}=\frac{8\pi G}{c^4}T_{\mu\nu}.$$
On the left side of the equation is another tensor, $G_{\mu\nu}$, measuring the curvature of spacetime. Einstein realized that the two are simply proportional!
Everyone can intuitively understand that a two-dimensional surface, such as a sphere, can have curvature. But how can three-dimensional space, or four-dimensional spacetime, have curvature?
Dale described a curved space as one in which initially parallel lines don't stay parallel. Another way to think about it is that a curved space is one in which the Pythagorean Theorem doesn't hold. On the curved surface of a sphere, there is no coordinate system in which
$$ds^2=dx^2+dy^2$$
as on a plane. Similarly, although you are used to thinking that
$$ds^2=dx^2+dy^2+dz^2$$
in 3D space and
$$ds^2=dx^2+dy^2+dz^2-c^2dt^2$$
in 4D Minkowski spacetime, these equations actually apply only when the space or spacetime is "flat" because of the absence of energy and momentum. When you generalize the notion of infinitesimal separation between spatial points or spacetime events so that $ds^2$ can be an arbitrary quadratic form like
$$\begin{align}ds^2&=g_{xx}(x,y,z)dx^2+g_{yy}(x,y,z)dy^2+g_{zz}(x,y,z)dz^2\\&+2g_{xy}(x,y,z)dx dy+g_{xz}(x,y,z)dx dz+g_{yz}(x,y,z)dy dz\end{align}$$
for a 3D space, you have what is called Riemannian geometry instead of Euclidean geometry. The six functions $g_{ij}(x,y,z)$ are components of what is called the "metric tensor" because this tensor tells you how to measure distances in the space.
You can imagine a similar expression with more terms for spacetime.
The curvature tensor $G_{\mu\nu}$ that measures how "non-Euclidean" space is, or how non-Minkowskian spacetime is, is an expression that depends on the metric tensor $g_{\mu\nu}$ and its first and second derivatives. When there is no energy and momentum present, the metric is "flat", all the components of the metric tensor are just 1 or 0 (in Cartesian coordinates), and all components of the curvature tensor are zero.
This is boring. What is interesting is when the presence of energy and momentum cause the metric to be non-Pythagorean. Gravity -- from apples falling, to black holes, to the expanding universe -— is just the consequences of the metric being allowed to be non-Pythagorean!


text:
Q: How to get the AppWidgetId of a Compose Glance widget? I have a table with all the widgets a user has created. I want to customize individual widgets using the according table entry and update the according table entry upon interaction with a widget.

uid
AppWidgetId
Title

0
23
First widget

1
165
Second widget

(1) When the user clicks on the widget, I want to update only the entry for the widget that was clicked. In the non-Glance world, I do this by adding an onClickListener to every widget which looks somewhat like this:
val widgetView = RemoteViews(context.packageName, R.layout.widget_layout)
val widgetPendingIntent = ...
widgetView.setOnClickPendingIntent(R.id.appwidget_text, widgetPendingIntent)
val appWidgetManager = AppWidgetManager.getInstance(context)
appWidgetManager.updateAppWidget(appWidgetId, widgetView)

In the glance widget, I assume that I need to make the composable clickable like this:
    @Composable
    override fun Content() {
        Column(
            modifier = GlanceModifier
                .fillMaxSize()
                .clickable(onClick = actionRunCallback<ClickOnWidget>())
        ) {
            Text(
                text = "Title",
                modifier = GlanceModifier.fillMaxSize(),
            )
        }
    }

The ActionCallback looks like this:
class ClickOnWidget : ActionCallback {
    override suspend fun onRun(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
       // Update my table with the click
    }
}

I would expect an appWidgetId here, but only see a glanceId: GlanceId. Can I use this to get the appWidgetId or directly use glanceId as an identifier in my table?
(2) I want to style my widget according to the data in the table. What is the best way to style the widget according to the table entry with the according appWidgetId? E.g. somehow like this:
    @Composable
    override fun Content() {
        Column(
            modifier = GlanceModifier
                .fillMaxSize()
                .clickable(onClick = actionRunCallback<ToastAction>())
        ) {
            Text(
                // *** Add a text depending on the appWidgetId ***
                text = titleOf(appWidgetId),
                modifier = GlanceModifier.fillMaxSize(),
            )
        }
    }

A: You cannot get the AppWidgetId, and this is by design.
For your use case, we recommended creating your own stable ID each time a new App Widget is created. You will store that ID in the state attached to the App Widget and use it to link it to some of your data (where you would have previously stored the AppWidgetId). The reason for this indirection is that we intend on handling Backup & Restore, but the AppWidget IDs change during that process, so relying on them in your own data structures is not a very good approach.
To implement this, you might want to look at GlanceAppWidget.stateDefinition, PreferencesGlanceStateDefinition, LocalState and GlanceAppWidget.updateAppWidgetState.

A: Well, I struggled with this as well, finally I log the glanceId, it prints like this: AppWidgetId(appWidgetId=304)
This is my hack way:
val appWidgetId = LocalGlanceId.current.toString().filter { it.isDigit() }.toInt()

It should be fine if you don't upgrade your glance version or Google keeps print glance id with appWidgetId.


text:
Q: Ipython : Installation error, unable to find _sqlite.so On trying to install ipython for Python3.4 I get a message that it is already installed.
pip3 install ipython
Requirement already satisfied (use --upgrade to upgrade): ipython in /usr/local/lib/python3.4/site-packages

But when I try to run it with ipython3 notebook I get all this:
Traceback (most recent call last):
  File "/usr/local/bin/ipython3", line 11, in <module>
sys.exit(start_ipython())
  File "/usr/local/lib/python3.4/site-packages/IPython/__init__.py", line 120, in start_ipython
return launch_new_instance(argv=argv, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 573, in launch_instance
app.initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error
return method(app, *args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/IPython/terminal/ipapp.py", line 321, in initialize
super(TerminalIPythonApp, self).initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error
return method(app, *args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/IPython/core/application.py", line 369, in initialize
self.parse_command_line(argv)
  File "/usr/local/lib/python3.4/site-packages/IPython/terminal/ipapp.py", line 316, in parse_command_line
return super(TerminalIPythonApp, self).parse_command_line(argv)
  File "<string>", line 2, in parse_command_line
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error
return method(app, *args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 471, in parse_command_line
return self.initialize_subcommand(subc, subargv)
  File "<string>", line 2, in initialize_subcommand
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error
return method(app, *args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/IPython/config/application.py", line 402, in initialize_subcommand
subapp = import_item(subapp)
  File "/usr/local/lib/python3.4/site-packages/IPython/utils/importstring.py", line 42, in import_item
module = __import__(package, fromlist=[obj])
  File "/usr/local/lib/python3.4/site-packages/IPython/html/notebookapp.py", line 67, in <module>
from .services.sessions.sessionmanager import SessionManager
  File "/usr/local/lib/python3.4/site-packages/IPython/html/services/sessions/sessionmanager.py", line 7, in <module>
import sqlite3
  File "/usr/local/lib/python3.4/sqlite3/__init__.py", line 23, in <module>
from sqlite3.dbapi2 import *
  File "/usr/local/lib/python3.4/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ImportError: No module named '_sqlite3'

Assuming that the last line is the most important
ImportError: No module named '_sqlite3'
I tried to install all sorts of dependencies for it:
apt-get install sqlite3 libsqlite3-dev
When I tried installing Pysqlite via pip3 install pysqlite :
Collecting pysqlite
  Using cached pysqlite-2.6.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-ggtq7_wu/pysqlite/setup.py", line 85
        print "Is sphinx installed? If not, try 'sudo easy_install sphinx'."
                                                                       ^
    SyntaxError: Missing parentheses in call to 'print'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ggtq7_wu/pysqlite

However Sphinx is already installed. I even reinstalled it.
pip3 install sphinx
Requirement already satisfied (use --upgrade to upgrade): sphinx in /usr/local/lib/python3.4/site-packages
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.3 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): snowballstemmer>=1.1 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): docutils>=0.11 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): babel>=1.3 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): sphinx-rtd-theme<0.2,>=0.1 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): alabaster<0.8,>=0.7 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): Pygments>=2.0 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): six>=1.4 in /usr/local/lib/python3.4/site-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in /usr/local/lib/python3.4/site-packages (from Jinja2>=2.3->sphinx)
Requirement already satisfied (use --upgrade to upgrade): pytz>=0a in /usr/local/lib/python3.4/site-packages (from babel>=1.3->sphinx)

Hence I have not been able to resolve it because evidently that file _sqlite3.so which should be in /usr/local/lib/python3.4/lib-dynload does not exist and I cannot find a way to install it.

A: I managed to resolve it thanks to the help I got in the comments.
Just putting it here to make it easy for anyone else who may have the same issue to figure out whats going on.

The issue is in using a self compiled version of Python, before the sql dev files were installed. Hence the bindings did not take.

First I had to use sudo apt-get install sqlite3 libsqlite3-dev to get the relevant sqlite files.

Then I had to recompile the Python by using a Source Tarball and executing the following commands to recompile it.

make clean
./configure
make
make install

A: I got the same issue on CentOS 6.8 and I installed sqlite-devel and then I re-compiled the python and got the issue fixed:
yum install sqlite-devel


text:
Q: How to create a video playlist in reactjs, using html5 video tag? import React, { Component } from 'react';

import "./Video.css";

export class Video extends Component {
    constructor(props) {
        super(props)

        this.state = {
            index: 1,
            videos: []
        }
        this.numbers = 5;
        for (var i = 1; i < this.numbers + 1; i++) {
            this.setState({
                videos: this.state.videos.push('Video/v' + i + '.mp4')
            })
        }
    }

    render() {
        return (

                <video className='video px-2 py-2' autoPlay width='950px' height='auto' src='Video/v1.mp4' ></video>

        )
    }
}

export default Video

Above is the code for my reactjs video player component I want to create playlist for the urls in the this.state.videos.
Any one can help me thank you.

A: import React, { Component } from 'react';

import "./Video.css";

export class Video extends Component {
    constructor(props) {
        super(props)

        this.state = {
            index: 1,
            videos: []
        }
        this.numbers = 5;
    }

    looping(event) {
        if( this.state.index === this.numbers){
            this.setState({
                index : 1
            })
        }else{
            this.setState({
                index : this.state.index + 1
            })
        }
        event.target.src = `Video/v${this.state.index}.mp4`
        event.target.play();
    }
    render() {
        return (

                <video className='video px-2 py-2' autoPlay width='950px' height='auto' src='Video/v1.mp4' onEnded = {(event) => this.looping(event)} ></video>

        )
    }
}

export default Video

I just removed this.state.video url and track array elements using this.numbers.
I just added a looping function, in which it will loop over array to give a sense of playlist.
Reactjs supports onEnded event for video tag


text:
Q: Link between two products Could someone help me to solve this problem :
Let's denote by $A_i$ the following product,
$$ A_i = \prod_{\substack{k=1 \\ k\neq i}}^n (a_k - a_i) $$
Is there any link or simple formula between $A_i$ and $A_j$ ?
Thank you for your answers.

A: Put $P(x)=\prod_{\substack{k=1}}^n (a_k - x) $. Then $A_i=-P'(a_i)$.


text:
Q: On the module over cyclotomic fields. Let $\zeta$ be the $p^l$-th root of unity in the complex plane, where $p$ is a prime number.
Suppose $M$ be a finitely generated $\mathbb{Q}(\zeta)$-module.
Is it true that $\dim_\mathbb{Q} M\geq \frac{1}{p^l} \dim_{\mathbb{Q}(\zeta)} M$?

A: The field extension is of degree $[\mathbb Q(\zeta):\mathbb Q]=\phi(p^l)=p^{l-1}(p-1)$, therefore we obtain
$$ \dim_{\mathbb Q(\zeta)} M = p^{l-1}(p-1) \dim_{\mathbb Q} M $$
for the vector space dimensions.


text:
Q: Trying to detect all the circles with HoughCircles in openCV (python) I am following this tutorial: https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/
I was playing around with the parameters ( even those you don't see in the code ex: param2) of HoughCircles and it seems very innacurate, in my project, the disks you see on the picture will be placed on random spots and i need to be able to detect them and their color.
Currently i am only able to detect few circles, and sometimes some random circles are drawn where there is no circles so i am a bit confused.
Is this the best way to do circle detection with openCV or is there a more accurate way of doing it ?
Also why is my code not detecting every circles ?
Initial board : https://imgur.com/BrPB5Ox
Circle drawn : https://imgur.com/dT7k29E
My code :
import cv2
import numpy as np

img = cv2.imread('Photos/board.jpg')
output = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100)
# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")
    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    # show the output image
    cv2.imshow("output", np.hstack([img, output]))
    cv2.waitKey(0)

Thanks a lot.

A: First of all you can not expect HoughCircles to detect all circles in different type of situations. It is not an AI. It has different parameters according to get desired results. You can check here to learn more about those parameters.
HoughCircles is a contour based function so you should be sure the contours are being detected properly. In your example I am sure bad contour results will come up because of the lighting problem. Metal materials cause light explosion in image processing and this affects finding contours badly.
What you should do:

*

*Solve the lighting problem

*Be sure about the HoughCircle parameters to get desired output

*Instead of using HoughCircle you can detect each contour and their mass center ( moments help you to find their mass center). Then you can measure each length of contour points to that mass center if all equal then its a circle.

A: Hough transform works best on monochromatic/binary image, so you may want to preprocess it with some sort of threshold function. Parameter values for the function are very important for proper recognition.

Is this the best way to do circle detection with openCV or is there a more accurate way of doing it ? Also why is my code not detecting every circles ?

there's also findContours function
https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0
which, to my liking, is more robust and general; you may want to give it a try


text:
Q: importance of correlation between data for a PROC CLUSTER i'm working on a clustering analysis on SAS.
I need to improve an actual code :
PROC CLUSTER METHOD=WARD DATA= Distance_matrix
NOEIGEN
CCC
PSEUDO
PRINT = 50
OUTTREE= Tree;
id item1;

This is doing a Hierarchical clustering using the ward distance. The data are a distance matrix on product x product.
And i was wondering about the NOEIGEN argument of this method. SAS say :

NOEIGEN: suppresses computation of the eigenvalues of the covariance matrix and
  substitutes the variances of the variables for the eigenvalues when
  computing the cubic clustering criterion. The NOEIGEN option saves
  time if the number of variables is large, but it should be used only
  if the variables are nearly uncorrelated. If you specify the NOEIGEN
  option and the variables are highly correlated, the cubic clustering
  criterion might be very liberal. The NOEIGEN option applies only to
  coordinate data.

But, automatically there is some correlation in the data no? Otherwise we wouldn't be able to cluster them in categories...

A: When there are a large number of variables, a whole lot of small correlations can lead to useful clusters. Of course, defining what exactly "large" and "small" and "useful" mean would need a lot of Monte Carlo work.
Note, however, the last sentence of the highlighted text: NOEIGEN only works on coordinate data and you have a distance matrix.


text:
Q: Loop through collection in laravel and get specific data from the collection I'm trying to go through a collection and I need to get a list of products according to certain keys. but I get the following error when I print the list with dd:

"array_key_exists(): The first argument should be either a string or an integer"

this is my function
public function reemplazaCostoZona($zona, $destino, $especie, $costo, $transporCollect){

 $productos = $transporCollect->where([['zona',$zona],['destino', $destino],['especie',$especie]])
                                     ->pluck('producto');
 dd($productos );

}

Collection:

I need to obtain the list of products for destination zone and species, That is to say that for my example of collection, for zone 1 destination 5 specie 1 I would have in my list product 1 and there may be more.
function where Im obtain collection:
public function storeTranspor3($request){
      DB::table('transpor')->truncate();
      $var = DB::select("select flu.zona, flu.destino, flu.producto, pro.especie, sup.codigo, dtr.cod_fundo, sup.sup_ha, dtr.dist_pavimento, dtr.dist_no_pavimento, dtr.peaje
      from flujos flu
      left join super sup on (sup.zona = flu.zona)
      left join d_transporte dtr on (dtr.cod_fundo = (sup.codigo / 1000000) and dtr.destino = flu.destino)
      left join productos pro on (pro.producto = flu.producto)
      left join especies esp on (esp.especie = pro.especie)
      order by flu.zona, dtr.cod_fundo, flu.producto, flu.destino, sup.codigo");
      $tansporCollect = collect();
      $tansporCollectsinCosto = collect();
      foreach ($var as $f) {
        if($f->codigo != null){
          if($f->especie == 1){
            $a = 0.177548*$f->dist_no_pavimento;
            $b = 0.0746*$f->dist_pavimento;
            $c = 0.0333*$f->peaje;
            $costoFundo = ($a + $b + 1.1191 + 0.399 + $c)*$f->sup_ha;
          }
          else{
            $a = 0.1652*$f->dist_no_pavimento;
            $b = 0.0694*$f->dist_pavimento;
            $c = 0.0357*$f->peaje;
            $costoFundo = ($a + $b + 1.0421 + 0.599 + $c)*$f->sup_ha;
          }
            $tansporC =[
              'zona' => $f->zona,
              'destino' => $f->destino,
              'producto' => $f->producto,
              'especie' => $f->especie,
              'costo' => $costoFundo
            ];
            $tansporCollect->push($tansporC);

            $tansporsinCosto = [
              'zona' => $f->zona,
              'destino' => $f->destino,
              'producto' => $f->producto,
              'especie' => $f->especie,
            ];
            $tansporCollectsinCosto->push($tansporsinCosto);
        }
      }

      $zonas = $tansporCollect->pluck('zona')->unique();
      $destinos = $tansporCollect->pluck('destino')->unique();
      $especies = $tansporCollect->pluck('especie')->unique();
      $transporCollectUnique = $tansporCollectsinCosto->unique();

      foreach($zonas as $zon){
        $costoZona = $tansporCollect->where('zona',$zon);
        foreach($destinos as $destin){
          $costoDestino = $costoZona->where('destino',$destin);
          foreach($especies as $espec){
            $costoEspecie = $costoDestino->where('especie',$espec)->avg('costo');
            /*HERE IM CALL OTHER FUNCTION */
            $this->reemplazaCostoZona($zon, $destin, $espec, $costoEspecie, $transporCollectUnique);

          }
        }
      }
  }

I'm with  laravel 5.8

A: You are not using the where function of collections correctly. For collections you need the following:
$productos = $transporCollect->where('zona', $zona)
                             ->where('destino', $destino)
                             ->where('especie',$especie)
                             ->pluck('producto');

Hope that helps!


text:
Q: is it posible to use partialview with modal inside of another partialview and display the modal on the main page? I am using a Partialview for displaying a table with data inside a normal razor page. I want to edit and first off all display a specific row of data with another partial view (Modal) When i am debuging my code, the Pagehandler is never called.

Table partialview inside my razorpage:

            @{
                await Html.RenderPartialAsync("_ArticlePositonsPartial", Model.TempPositionsView, ViewData);
             }

Table looks like this:

Call of partialview inside the table partialview:

                            <button class="btn btn-outline-primary btn-sm" data-toggle="ajax-modal" data-url="@Url.Page("NewInvoice", "EditPositionPartial", @Model.TempPositions[i])"> </button>
                            @Html.AntiForgeryToken()
                            <button class="btn btn-outline-danger btn-sm" onclick="GetPartialView(2,@Model.TempPositions[i].Id)"> </button>

Pagehandler
      public async Task<PartialViewResult> OnPostEditPositionPartial(FaktTempPositionen f)
        {
            FaktTempPositionen faktTempPosition = await _TempArticlePositionRepository.GetPositionBySessionKeyAndId(f.SessionKey, f.Id);

            return new PartialViewResult
            {
                ViewName = "_EditPositionPartial",
                ViewData = new ViewDataDictionary<FaktTempPositionen>(ViewData, faktTempPosition),
            };
        }

Partialview i want to display
   @model Rechnungen.Models.Views.TempPositonsView

test

**

                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Schließen</button>
                <button type="button" class="btn btn-primary" data-save="modal">Speichern</button>

JS vor modal:

A: Since you are using $.get,you should call a get handler:
 public async Task<PartialViewResult> OnGetEditPositionPartial(FaktTempPositionen f)
        {
            FaktTempPositionen faktTempPosition = await _TempArticlePositionRepository.GetPositionBySessionKeyAndId(f.SessionKey, f.Id);

            return new PartialViewResult
            {
                ViewName = "_EditPositionPartial",
                ViewData = new ViewDataDictionary<FaktTempPositionen>(ViewData, faktTempPosition),
            };
        }


text:
Q: razor get not working The following code doesn't work.
The Controller SupportController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Token.Creator.Site.Models;

namespace Token.Creator.Site.Controllers {
    public class SupportController : Controller {
        CustomerModel customerModel = new CustomerModel();

        public ActionResult Index() {
            return View();
        }
        [HttpGet]
        public ActionResult Search(string serialnumber) {
            var items = S0PinListModel.GetFromList(customerModel.GetS0Pins(serialnumber));
            items.Message = "Es konnten " + items.Count + " gefunden werden :)";
            items.Type = MessageType.SuccessMessage;
            return PartialView("_S0PinListView", items);
        }
    }
}

The PartialView _S0PinListView.cshtml
@using Token.Creator.Site.Models;
@model S0PinListModel

@if (!string.IsNullOrWhiteSpace(Model.Message)) {
    var type = "";
    switch (Model.Type) {
        case MessageType.ErrorMessage: type = "alert alert-danger";
            break;
        case MessageType.InfoMessage: type = "alert alert-info";
            break;
        case MessageType.SuccessMessage: type = "alert alert-success";
            break;
        case MessageType.WarningMessage: type = "alert";
            break;
    }

        @Model.Message×

}

            #
            Seriennummer
            S0Pin
            Ersteller

        @if (Model != null && Model.Count > 0) {
            foreach (var item in Model) {

                @item.ID
                @item.Serialnumber
                @item.Pin
                @item.Creator.Username

            }
        } else {

                Leider sind konnten keine S0Pins gefunden werden :(

        }

The MainView Support/Index.cshtml
@using Token.Creator.Site.Models;
@{
    ViewBag.Title = "Support";
}

Support

Suchen Sie nach S0Pins und setzten Sie Token zurück.

Nach S0Pins suchen

        @using (Ajax.BeginForm("Search", "Support", new AjaxOptions() {
            UpdateTargetId = "szeropindata",
            HttpMethod = "GET" <----- THIS IS IMPORTANT
        }, new {
            @class = "modal-dialog form-horizontal",
            id = "search_szeropin"
        })) {

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

S0Pin suchen

                        Seriennummer

                            @Html.TextBox("serialnumber", "", new { @class = "form-control", id = "serialnumber" })

                    <button type="button" class="btn btn-default" data-dismiss="modal">Abbrechen</button>
                    <input type="submit" class="btn btn-primary" value="Suchen" />

        }

The Model S0PinListModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Token.Creator.Site.Models {
    public class S0PinListModel : List<S0Pin> {
        public static S0PinListModel GetFromList(List<S0Pin> s0pinList) {
            var list = new S0PinListModel();
            list.AddRange(s0pinList);
            return list;
        }
        private S0PinListModel() {
        }
        public MessageType Type { get; set; }
        public string Message { get; set; }
    }
}

What do I need to change?

A: Note to myself and everybody else, ever, really ever set the HttpMethod Property in AjaxOptions


text:
Q: uwsgi + django via Nginx - uwsgi settings/spawn? I am leaning towards uwsgi+nginx for my Django app, can anyone share the best method for starting up my uwsgi processes? Does anyone have experience tuning uwsgi?

A: Launchd on OSX
Upstart/init on the unices.
uwsgi also has its own process manager, so you can just run that as well.
Tuning:
Check the mailing list, for advice on your particular requirements.  Uwsgi is amazing, it is a complete deploy solution.
Nginx above 0.8.40 will build the uwsgi bindings by default, Build nginx, build uwsgi and you are golden.

A: these are the functions i use in my fabfile.py file (check out python fabric if you haven't already):
def start_uwsgi():
    with cd(env.server.uwsgi):
        if(exists('server.pid')):
            stop_uwsgi()
            run('sleep 1')
        run('source venv/bin/activate;uwsgi --ini uwsgi.ini;'))

def stop_uwsgi():
    with cd(env.server.uwsgi):
        if(exists('server.pid')):
            run('source venv/bin/activate;uwsgi --stop server.pid;'))

In my uwsgi.ini file i specify:
[uwsgi]
socket = :{{your_port}}
master = true
vhost = true
no-site = true
processes = 1
enable-threads = true
pidfile = server.pid
daemonize = server.log
auto-procname = true
procname-prefix = servername_

for me the main gotyas were:

*

*use the daemonise option if you want to keep the uwsgi server going after you close your terminal/ssh session

*use vhost to run multiple sites under the same uwsgi instance, which is great if your bottleneck is memory, like mine is with the otherwise fantastic webfaction host

*pidfile tracks the current instance, enabling you to call uwsgi --stop pidfile, uwsgi --start pidfile

*procname and procname-prefix/append give a nice name to your process so you can easily single it out using ps -u username | grep some_string

A: I will go with supervisord for managing the starting, stoping process.