text:
Q: Determine promise state using Promise.race and setImmediate TL;DR: Will already resolved promises always beat setImmediate in a race?
Background:
Sometimes you want to know if a promise is resolved without awaiting its completion. There are some old legacy tricks like using util.inspect to get the internal state and checking if it contains the string "<pending>". However, a more stable solution is to use Promise.race() to essentially wait for your unknown promise with a (very small) timeout.
const p = doSomething();

const result = await Promise.race([
    p,
    new Promise(resolve => setTimeout(resolve, 1))
]);

if (result) {
   // p was resolved within 1 ms!
   ...
}

This will at most wait 1 ms to get result, which will then either contain the resolved value of p or undefined.
If required, the "timeout promise" may of course return something different than undefined to distinguish actual undefined values returned from doSomething():
const PENDING = Symbol.for('PENDING');
const result = await Promise.race([
    p,
    new Promise(resolve => setTimeout(() => resolve(PENDING), 1))
]);

if (result !== PENDING) {
  ...
}

Now we'll either get the resolved value from doSomething() or the unique symbol PENDING.
Now to my question. In addition to setTimeout, there's a setImmediate function that basically behaves like a timer that expires immediately; it just gives the event loop a go before resolving. When using this in my Promise.race expression above, empirically it seems to work, i.e., if p is already resolved it will beat setImmediate in a race, but I'm wondering if there is any such guarantee - or if I should be using a timer of 1 ms to guarantee that a resolved promise beats the timer?
I've tried putting p before and after the setImmediate promise in the array passed to Promise.race and it worked both ways, but still I'm worried it might behave randomly or be OS dependent? Or is the fact that setImmediate waits for one round of I/O enough to guarantee that any resolved promises will win?
From the documentation:

Schedules the "immediate" execution of the callback after I/O events' callbacks

Edit:
I found that even this "seems" to work:
const result = await Promise.race([p, new Promise(resolve => resolve(PENDING))]);

or actually even this:
const result = await Promise.race([p, Promise.resolve(PENDING)]);

However, here the order is important. If p is resolved and is before the timeout promise, it will win, but if it's after the timeout promise in the array it will lose.
The question is the same though: is this approach guaranteed to let p win if it's already resolved?

A: Considering the codes below in Nodejs
Ref. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
setImmediate(() => console.log("setImmediate"));
setTimeout(() => console.log("setTimeout"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("Promise"));
console.log("sync");

Output:
You can notice the sequence and that's how it is executed in order.
sync
nextTick
Promise
setTimeout
setImmediate

To answer your question, we can wrap the codes in Promises like below:
(async function main() {
  const result = await Promise.race([
    new Promise(resolve => resolve("sync")),
    new Promise(resolve => setImmediate(() => resolve("setImmediate"))),
    new Promise(resolve => setTimeout(() => resolve("setTimeout"))),
    new Promise(resolve => Promise.resolve().then(() => resolve("Promise"))),
    new Promise(resolve => process.nextTick(() => resolve("nextTick"))),
  ]);
  console.log({ result });
})();

As sync function is to be executed first, so it would be returned.
Output:
{ result: 'sync' }

You can comment one of the Promise above to see which one resolve first.


text:
Q: Angular Issue in production build, but not in local development. ERROR TypeError: Cannot read property 'call' of undefined I've been having an issue where one of my Angular 8 apps works without issues and as expected when ran locally (ng serve), however, when built and ran on production (ng build) it will give me the below error when a component is clicked in my app and code is ran.
Error received in console:
ERROR TypeError: Cannot read property 'call' of undefined
    at d.l (main-es2015.5d76d03ab70e1112760a.js:1)
    at new d (main-es2015.5d76d03ab70e1112760a.js:1)
    at Giow.e.exports (main-es2015.5d76d03ab70e1112760a.js:1)
    at e.df (main-es2015.5d76d03ab70e1112760a.js:1)
    at e.stretch (main-es2015.5d76d03ab70e1112760a.js:1)
    at e.getHashPassword (main-es2015.5d76d03ab70e1112760a.js:1)
    at p.newAccount (main-es2015.5d76d03ab70e1112760a.js:1)
    at Object.handleEvent (main-es2015.5d76d03ab70e1112760a.js:1)
    at Object.handleEvent (main-es2015.5d76d03ab70e1112760a.js:1)
    at Object.handleEvent (main-es2015.5d76d03ab70e1112760a.js:1)
br @ main-es2015.5d76d03ab70e1112760a.js:1
handleError @ main-es2015.5d76d03ab70e1112760a.js:1
Xp @ main-es2015.5d76d03ab70e1112760a.js:1
(anonymous) @ main-es2015.5d76d03ab70e1112760a.js:1
(anonymous) @ main-es2015.5d76d03ab70e1112760a.js:1
invokeTask @ polyfills-es2015.a8cec314c5933902d1c0.js:1
onInvokeTask @ main-es2015.5d76d03ab70e1112760a.js:1
invokeTask @ polyfills-es2015.a8cec314c5933902d1c0.js:1
runTask @ polyfills-es2015.a8cec314c5933902d1c0.js:1
invokeTask @ polyfills-es2015.a8cec314c5933902d1c0.js:1
y @ polyfills-es2015.a8cec314c5933902d1c0.js:1
b @ polyfills-es2015.a8cec314c5933902d1c0.js:1

Error after disabling minification using below stackblitz example:
ERROR TypeError: Cannot read property 'call' of undefined
    at Hmac.CipherBase (main-es2015.02649c002b843ca5ea1e.js:63726)
    at new Hmac (main-es2015.02649c002b843ca5ea1e.js:63860)
    at createHmac (main-es2015.02649c002b843ca5ea1e.js:63907)
    at PasswordService.uno_hkdf (main-es2015.02649c002b843ca5ea1e.js:77684)
    at PasswordService.stretch (main-es2015.02649c002b843ca5ea1e.js:77671)
    at AppComponent.ngOnInit (main-es2015.02649c002b843ca5ea1e.js:77535)
    at checkAndUpdateDirectiveInline (main-es2015.02649c002b843ca5ea1e.js:36518)
    at checkAndUpdateNodeInline (main-es2015.02649c002b843ca5ea1e.js:47852)
    at checkAndUpdateNode (main-es2015.02649c002b843ca5ea1e.js:47791)
    at prodCheckAndUpdateNode (main-es2015.02649c002b843ca5ea1e.js:48645)

Code:
import { Injectable } from '@angular/core';
import { pbkdf2Sync } from 'pbkdf2';
import * as createHmac from 'create-hmac';

@Injectable()
export class PasswordService {
  public stretch(emailInput, passwordInput) {
    const salt = new Buffer('identity.mozilla.com/picl/v1/' + 'quickStretch' + ':' + emailInput, 'utf8');
    const password = new Buffer(passwordInput, 'utf8');
    const key: Buffer = pbkdf2Sync(password, salt, 1000, 128, 'sha256');
    const info = new Buffer('identity.mozilla.com/picl/v1/' + 'authPW', 'utf8');
    const outcome = this.df(key, info, '', 128);
    return outcome;
  }

  df(key, info, salt, length) {
    const k = createHmac('sha256', salt).update(key).digest(); /* <----------- FAILS HERE */
    const k2 = createHmac('sha256', k);
    const counter = new Buffer([1]);
    k2.update(info);
    k2.update(counter);
    return k2.digest().toString('base64');
  }
}

After debugging and stepping through the service via developer console, I found that it will fail on the first line of my df function, specifically at createHmac('sha256', salt); It seems like the create-hmac package is undefined, but I'm not sure why it would compile without errors in this case. I have been unable to find any similar issues related to the 'create-hmac' package online which leads me to believe it has something to do with how my app is setup but I'm not sure where to start looking.
Things I have tried from various searches online but always resulted in the same error:
1. rm -rf /node_modules/ -> npm update -> npm install
2. require() instead of import()
3. es5 to es2015 in tsconfig.json
4. Updating create-hmac and pbkdf2 packages
5. Downgrading @angular/cli and @angular-devkit/build-angular
6. Build with other flags such as ```ng build --build-optimizer --aot```
7. Node v10.15, v10.16, and v12.16
8. Using a constructor for createHmac
9. Using import createHmac from 'create-hmac'

ng --version
Angular CLI: 8.3.20
Node: 10.16.0
OS: linux x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.20
@angular-devkit/build-angular     0.803.20
@angular-devkit/build-optimizer   0.803.20
@angular-devkit/build-webpack     0.803.20
@angular-devkit/core              8.3.20
@angular-devkit/schematics        8.3.20
@angular/cdk                      8.2.3
@angular/cli                      8.3.20
@angular/http                     7.2.16
@angular/material                 8.2.3
@ngtools/webpack                  8.3.20
@schematics/angular               8.3.20
@schematics/update                0.803.20
rxjs                              6.5.4
typescript                        3.5.3
webpack                           4.39.2

Any insight is appreciated. Thanks!
SOLUTION FOUND
https://forum.aeternity.com/t/important-fix-for-angular-typeerror-cannot-read-property-call-of-undefined-at-hash-cipherbase-index-js-7/4153

A: Look at this stackblitz I created (with angular 8 as per your setup):
https://stackblitz.com/edit/so-60536842-create-hmac
The one change I had to do to make it work as regards your code is:
import createHmac from 'create-hmac';

Otherwise (import * as createHmac from 'create-hmac';) was throwing me an error: createHmac is not a function

redpajama_set_name: RedPajamaStackExchange


text:
Q: my handmade ELF file, 'mov eax,1' 'ret' came out an error of segmentation fault I am inspired by link.And I want to implement an C compiler step by step.This is my first step to implement an main function in C.
Here is my code.I use the function 'elf_write' to write an elf file by hand,but when I run the generated ELF file,came out an error of segmentation fault(the Linux version of my computer is Ubuntu 12.04.5 LTS (GUN/Linux 3.2.0-80-generic x86_64)):
    void elf_write(FILE *elf)
    {
        unsigned char code[] = {
            //0x55,//push ebp
            0xb8,0x01,0x00,0x00,0x00,//mov eax,1
            //0x89,0xe5,//mov ebp,esp
            //0x5d,//pop ebp
            0xc3//ret
        };

        uint64_t entry = 0x400000;
        Elf64_Ehdr ehdr = {
            .e_ident = {
                ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
                ELFCLASS64,
                ELFDATA2LSB,
                EV_CURRENT,
                ELFOSABI_SYSV,
            },
            .e_type = ET_EXEC,
            .e_machine = EM_X86_64,
            .e_version = EV_CURRENT,
            .e_entry = entry + sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr),
            .e_phoff = sizeof(Elf64_Ehdr),
            .e_ehsize = sizeof(Elf64_Ehdr),
            .e_phentsize = sizeof(Elf64_Phdr),
            .e_phnum = 1
        };
        Elf64_Phdr phdr_text = {
            .p_type = PT_LOAD,
            //.p_offset = sizeof(Elf64_Ehdr) + 2*sizeof(Elf64_Phdr),
            .p_flags = PF_X | PF_R,
            .p_vaddr = entry,
            .p_filesz = sizeof(code),
            .p_memsz = sizeof(code),
            .p_align = 0x200000
        };
        fwrite(&ehdr, sizeof(ehdr), 1, elf);
        fwrite(&phdr_text, sizeof(phdr_text), 1, elf);
        fwrite(code, sizeof(code), 1, elf);
    }

when I change the code to this,it executed perfectly and print "ABCDE" in the terminal.
    unsigned char code[] = {
        0xb8,0x01,0x00,0x00,0x00,//mov rax,1
        0xba,0x06,0x00,0x00,0x00,//mov rdx,12
        0xbe,0x9a,0x00,0x40,0x00,//mov rsi,0x4000b0
        0xbf,0x01,0x00,0x00,0x00,//mov rdi ,1
        0x0f,0x05,               //syscall
        0xb8,0x3c,0x00,0x00,0x00,//mov rax,60
        0xbf,0x00,0x00,0x00,0x00,//mov rdi ,0
        0x0f,0x05,               //syscall
        0x41,0x42,0x43,0x44,0x45,0x0A//ABCDE
    };


text:
Q: increasing disk space for mysql data volume I have a master mysql server which has approached 80% of the available disk space. Total disk space size is 200GB. Though, it's not an immediate concern but I have to deal with at some point soon. the data directory is mounted on to logical volume.
--- Logical volume ---
LV Path                /dev/mysql/data
LV Name                data
VG Name                mysql
LV UUID                UNse6Y-QgCX-Ap6D-UXvr-VXs5-r8dc-g91Vhn
LV Write Access        read/write
LV Creation host, time localhost, 2012-09-19 15:22:49 +0100
LV Status              available
# open                 2
LV Size                200.00 GiB
Current LE             51200
Segments               1
Allocation             inherit
Read ahead sectors     auto
- currently set to     256
Block device           253:3

And this is mounted under /data directory.
/dev/mapper/mysql-data  /data                   reiserfs        defaults,noatime,nodiratime,notail,data=writeback 0 1

Unfortunately, the binary logs are located inside the the /data directory.
# grep -i log-bin /etc/my.cnf
log-bin                 = /data/binlog/mysql-bin.log

I am looking for the best option to increase the disk space and or moving the binary logs to
a separate disk location without having to restart mysql or with minimal downtime?
The database version is:
mysql> SHOW VARIABLES LIKE "%version%";
+-------------------------+---------------------+
| Variable_name           | Value               |
+-------------------------+---------------------+
| protocol_version        | 10                  |
| version                 | 5.1.61-log          |
| version_comment         | Source distribution |
| version_compile_machine | x86_64              |
| version_compile_os      | redhat-linux-gnu    |
+-------------------------+---------------------+
5 rows in set (0.00 sec)

Is there any good solution? Please help.

A: You say you have bin logging enabled.  This leads me to believe you have replication running.
To minimize down time you could promote your slave to master.  The finer details on how to do this really depends on your setup.  Maybe it will involve updating application configurations, maybe it will involve changing the DNS to your "master server".
Prior to the promotion ensure you slave is configured they way you would like, e.g. not writing binlogs to the data directory.  Make sure all the grants present on the master are on the slave.  Make sure the slave is not running in read only mode when you are ready to bounce.
Prior to promotion you'll want to ensure both the master and slave are in read only mode.   Run show master status; on the slave to see what log file and position you'll use for change master to after you reconfigure and restart the old master to run as a slave.
Once the old slave is promoted to the new master you can take your time to move the old binlogs to a new file system and reconfigure to keep new logs out of the data dir.


text:
Q: How to write a loop that calculates power? I'm trying to write a loop that calculates power without using the pow() function. I'm stuck on how to do that. Doing base *= base works for even powers upto 4, so there is something totally weird that I can't seem to figure out.
int Fast_Power(int base, int exp){
    int i = 2;
    int result;

    if(exp == 0){
        result = 1;
        }
    if(exp == 1){
        result = base;
        }
    else{
        for(i = 2; i < exp; i++){
            base *= base;
            result = base;
        }
    }
    return result;
}

A: base *= base;

Your problem lies with that statement, you should not be changing base at all. Rather, you should be adjusting result based on the constant value of base.
To do powers, you need repeated multiplication, but the base *= base gives you a repeated squaring of the value and you'll therefore get a much bigger value than desired. This actually works for powers of four since you iterate 4 - 2 times, squaring each iteration, and x4 == (x2)2.
It will not work for higher powers like six since you iterate 6 - 2 times, and x6 != (((x2)2)2)2. That latter value is actually equivalent to x16.

As an aside (despite your contention), it's actually not guaranteed to work for powers of two. If you follow the code in that case, you'll see that result is never assigned a value so the return value will be arbitrary. If it's working for you, that's accidental and likely to bite you at some point.

The algorithm you can use should be something like:
float power(float base, int exponent):
    # 0^0 is undefined.

    if base == 0 and exponent == 0:
        throw bad_input

    # Handle negative exponents.

    if exponent < 0:
        return 1 / power(base, -exponent)

    # Repeated multiplication to get power.

    float result = 1
    while exponent > 0:
        # Use checks to detect overflow.

        float oldResult = result
        result *= base
        if result / base is not close to oldResult:
            throw overflow
        exponent -= 1

    return result

This algorithm handles:

*

*negative integral exponents (since x-y = 1/xy);

*the undefined case of 00; and

*overflow if you do not have arbitrary-precision values (basically, if (x * y) / y != x, you can be reasonably certain an overflow has occurred). Note the use of "not close to", it's unwise to check floats for exact equality due to potential for errors due to precision limits - far better to implement a "is close enough to" check of some description.

One thing to keep in mind when translating to C or C++, a 2's complement implementation will cause issues when using the most negative integer, since its negation is often the same value again again due to the imbalance between the positive and negative values. This is likely to lead to infinite recursion.
You can fix that simply by detecting the case early on (before anything else), with something like:
if INT_MIN == -INT_MAX - 1 and exp == INT_MIN:
    throw bad_input

The first part of that detects a 2's complement implementation, while the second detects the (problematic) use of INT_MIN as an exponent.

A: What you were doing wrong is base *= base each time through the loop, which changes the base itself, each iteration.
Instead you want the base to remain the same, and multiply the final result by that original base "exp" times.
int Fast_Power(int base, int exp){
    int result=1;

    if(exp == 0){
        result = 1;
    }
    if(exp == 1){
        result = base;
    }
    else{
        for(int i = 0; i < exp; i++){
            result *= base;
        }
    }
    return result;
}

A: The basic but naive algorithm you are looking for that is horribly subject to integer overflow is:
int Fast_Power (int base, int exp)
{
    int result = base;

    if (exp == 0)
        return result ? 1 : 0;

    for (int i = 1; i < exp; i++) {
        result *= base;
    }

    return result;
}

Note: result can very easily overflow. You need to employ some basic check to prevent integer-overflow and Undefined Behavior.
A minimal check (see: Catch and compute overflow during multiplication of two large integers), can be incorporated as follows. You must use a wider-type for the temporary calculation here and then compare the results against INT_MIN and INT_MAX (provided in the limits.h header) to determine if overflow occurred:
#include <limits.h>
...
int Fast_Power (int base, int exp)
{
    int result = base;

    if (exp == 0)
        return result ? 1 : 0;

    for (int i = 1; i < exp; i++) {
        long long int tmp = (long long) result * base;  /* tmp of wider type */
        if (tmp < INT_MIN || INT_MAX < tmp) {           /* check for overflow */
            fputs ("error: overflow occurred.\n", stderr);
            return 0;
        }
        result = tmp;
    }

    return result;
}

Now if you attempt, e.g.  Fast_Power (2, 31); an error is generated and zero returned.
Additionally as @paxdiablo notes in the comment Zero to the power of zero may be undefined as there is no agreed upon value. You can add a test and issue a warning/error in that case if you desire.

A: First off, I agree it was probably a mistake to use base *= base. That said, it's not necessarily the mistake. My first impression was that OP was trying to compute powers the way that a human might do by hand. For example if you wanted to compute 3^13 a reasonable way is to start is by computing exponents which are powers of 2.

*

*3^1 = 3

*3^2 = 3*3 = 9

*3^4 = 3^2 * 3^2 = 81

*3^8 = 3^4 * 3^4 = 6,561

Then you can use these results to compute 3^13 as

*

*3^13 = 3^1 * 3^4 * 3^8 = 1,594,323

Once you understand the steps you could code this. The hardest part is probably determining when to stop squaring the base, and which squares should be included in the final calculation. Perhaps surprisingly the (unsigned) binary representation of the exponent tells us this! This is because the digits in binary represent the powers of two which sum together to form the number. With that in mind we can write the following.
int Fast_Power(int base, int exp) {
    int result = 1;
    unsigned int expu = exp;
    unsigned int power_of_two = 1;
    while (expu > 0) {
        if (power_of_two & expu) {
            result *= base;
            expu ^= power_of_two;
        }
        power_of_two <<= 1;
        base *= base;
    }
    return result;
}

This code doesn't have overflow protection, though that would be a good idea. Sticking with the original prototype it still accepts negative exponents and returns integers, which is a contradiction. Since OP didn't specify what should occur upon overflow or negative exponents this code doesn't attempt to handle either of those cases. Reasonable methods of addressing these issues are provided by other answers.


text:
Q: Python : How to pass the value of a foreign key in my Django template? I have created a Bid model so that type-2 users can bid on some 'Post' created by type-1 users. For achieving this, I made a foreign key for post field in the model 'Bid'.
Actually i wanted to relate the bids to a particular post with auto generated 'id' in the 'post' model. So i placed the get_absolute_url beside Post 'id' in my template. I am new to django and I am not sure whether it works for what i want or not.
How can i relate the bid with post_id to a particular post in the template so that i can get a bid amount placed by various type-2 users for a particular post? I would appreciate helping me solve this.
Here's my code:
Models.py:
class Post(models.Model):

    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = PostManager()

    def __str__(self):
        return self.post_id

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"id": self.post_id})

    class Meta:
        ordering = ["-timestamp", "-Time"]

class Bid(models.Model):

    bid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    post = models.ForeignKey(Post, default=uuid.uuid4, related_name='bids' )
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, unique=False)
    amount = models.IntegerField()

    def get_absolute_url(self):
        return reverse("accept_bid", kwargs={"bid_id": self.bid_id})

    def __unicode__(self):
        return self.amount

    def __str__(self):
        return self.amount

forms.py:
class BidForm(forms.ModelForm):
    // Defined a post field as ModelChoiceField
    post = forms.ModelChoiceField(queryset= Post.objects.all(), label="Post", widget=forms.RadioSelect(), initial=0)
    amount = forms.IntegerField(help_text='Place the bid for a Post')

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(BidForm, self).__init__(*args, **kwargs)
        self.fields['post'].queryset = Post.objects.all

    class Meta:
        model = Bid
        fields = ["amount"]

views.py:
def live_bid_truck(request, **kwargs):
    if request.method=='post':
        form = BidForm(request.POST or None)

        if  form.is_valid():
         bid = form.save(post)
         bid = form.save(commit=False)
         print(form.cleaned_data.get('amount'))
         bid.user = request.user
         bid.post = form.cleaned_data['post'] // Set my post here

         bid.save()
    else:
        form=BidForm()
        post_queryset = Post.objects.all()
        context = {
        "post_queryset": post_queryset,
        "title": "List",
        'form': form,

    }
        return render(request, 'loggedin_truck/live_bid_truck.html', context)

live_bid_truck.html
{% for post in post_queryset %}

            Load No.
            From

 // Returns the post_queryset with radio buttons
            {{form.post}}
            {{ post.from1 }}

             Amount

            <form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
            {% render_field  form.amount  class="form-control" %}

<input type='submit' value='Post Bid'/></form>

{% endfor %}

Update - 1:
Views.py:
def live_bids(request):
    post_queryset = Post.objects.all().prefetch_related('bids')
    bid_queryset = Bid.objects.all().order_by('amount')

    context = {
        "post_queryset": post_queryset,
        "bid_queryset": bid_queryset,
        "title": "List",
    }
    return render(request, 'loggedin_load/live_bids.html', context)

live_bids.html:
{% for post in post_queryset %}
{{post.id}}
{% for bid in post.bids.all %}
{{bid.amount}}
{% endfor %}
{% endfor %}

A: If I understood correctly, the goal is to be able to list the related bidders/bids on the post? If so, then you can use select_related (if you're selecting parents from child) of prefetch_related (if you're doing a reverse lookup)
1) First of all in your Bid model better related_name would be "bids", like so;
post = models.ForeignKey(Post, default=1, related_name='bids' )

2) Secondly inside def live_bid_truck(request): make the post query like this so that you would get all the related objects in one database hit.;
Post.objects.all().prefetch_related('bids')

3) Then in your template you can use can access the related bids for the post
{% for bid in post.bids.all %} // In your case post is obj
    {{ bid }}  // Access whatever you need from the bid like {{ bid.user }}
{% endfor %}

You should be able to call post.bids.all and receive values even without prefetch by just following the backward relation. If you're not getting any values, then you probably are not setting them properly. prefetch_related helps with the performance as the number of posts increase.

FROM YOUR CODE
In your BidForm there is no reference to the post and I don't know if you have it in your custom save() method or not. When you save this form as it is, post_id will be the default value 1
# NO REFENCE TO post
class BidForm(forms.ModelForm):

 class Meta:
    model = Bid
    fields = ["amount"]

Also in your view you don't set the post either.
def live_bid_truck(request):

    form = BidForm(request.POST or None)

    if  form.is_valid():
        bid = form.save(commit=False)

        print(form.cleaned_data.get("amount"))
        bid.user = request.user # YOU SET THE USER
        bid.post = ?? # YOU DON'T SET THE POST HERE EITHER,
                      # SO ALL YOUR BIDS HAVE THE DEFAULT POST id = 1
                      # DO YOU ACTUALLY HAVE POST with id = 1?

        bid.save()

        # WHAT HAPPENS IF YOU PRINT BID POST ID HERE ??
        # CHECK HERE IF YOU REALLY HAVE THE RELATED POST ID.
        print(bid.post.id)


text:
Q: PHP changing string with "<" char I'm getting crazy with this... I just put something simple like this:
$pass = "axX/dss(z\<zbE";
die($pass);

and PHP return this:
axX/dss(z\

And every string that I put the "<" char occurs the same, the string is "shorted" by the "<" character.
Help please...
Thanks.
Oh, I'm using CodeIgniter.

OK
This is getting freak...
Now my code is like this:
$pass = "dsJ<32.\wwe^";
echo $pass;
echo '<br>';
$pass = "cz\vU(rV<zbE";
echo $pass;

And my return is:
dsJ<32.\wwe^
czU(rV

The first string uses de "<" char, and it's OK... but the second...

A: The string isn't being changed at all. See here: http://3v4l.org/b3RaQ
What's happening is your browser is hiding the < character, it looks like HTML.
If you want to display the string in the browser properly, wrap it with htmlentites() or <pre> tags when troubleshooting.
UPDATE: I also copy/pasted your new code, which you can see here: http://3v4l.org/Uq9HY. It's still working. Maybe you can setup a test case at http://3v4l.org/ that reproduces the problem?

A: Escape it with <. < is a common symbol in html (and in php, by extension)


text:
Q: Uncaught TypeError: Super expression must either be null or a function - It won't go away I get error saying:

Uncaught TypeError: Super expression must either be null or a function
    at index.js:974:1
    at index.js:973:1
    at Module.<anonymous> (index.js:972:1)
    at n (index.js:14:1)
    at e.exports (index.js:50:6)
    at Object.<anonymous> (index.js:4:1)
    at f ((index):1:1398)
    at Module.79 (change-password.js:26:15)
    at f ((index):1:1398)
    at Object.46 (main.96136933.chunk.js:1:87)

Here is my index.js

import React from "react";
import ReactDOM from "react-dom";
import { HashRouter, Route, Routes } from "react-router-dom";
import AccountDetails from "./components/admin/account-details";
import AddDeveloper from "./components/admin/add-developer";
import AddProperty from "./components/admin/add-property";
import Address from "./components/admin/adress";
import ChangePassword from "./components/admin/change-password";
// import Dashboard from "./components/admin/dashboard";
// import EditDeveloper from "./components/admin/edit-developer";
// import FavouriteProperties from "./components/admin/favourite-properties";
import ListDeveloper from "./components/admin/list-developer";
import ListProperty from "./components/admin/list-property";
import Payment from "./components/admin/payment";
import Profile from "./components/admin/profile";
import FreeholdGridPage from "./components/freehold";
import HomeV1 from "./components/home-v1";
import LoginV1 from "./components/login";
import MyAccount from "./components/my-account";
import PersistLogin from "./components/persistLogin";
import RegisterV1 from "./components/register";
import RequireAuth from "./components/require-Auth";
import Service from "./components/service";
import { AuthProvider } from "./context/AuthProvider";

class Root extends React.Component {
  render() {
    return (
      <HashRouter>

          <AuthProvider>
            <Routes>
              <Route path="/" element={<HomeV1 />} />
              <Route path="/login" element={<LoginV1 />} />
              <Route path="/register" element={<RegisterV1 />} />
              <Route path="/freehold" element={<FreeholdGridPage />} />
              <Route element={<PersistLogin />}>
                <Route element={<RequireAuth />}>
                  <Route path="/service" element={<Service />} />
                  <Route path="/my-account" element={<MyAccount />}>
                    {/* <Route path="dashboard" element={<Dashboard />} /> */}
                    <Route path="profiles" element={<Profile />} />
                    <Route path="address" element={<Address />} />
                    <Route
                      path="account-details"
                      element={<AccountDetails />}
                    />
                    <Route path="dev/list" element={<ListDeveloper />} />
                    <Route path="prop/list" element={<ListProperty />} />
                    {/* <Route path="fav-prop" element={<FavouriteProperties />} /> */}
                    <Route path="dev/add" element={<AddDeveloper />} />
                    <Route path="prop/add" element={<AddProperty />} />
                    <Route path="payments" element={<Payment />} />
                    <Route
                      path="change-password"
                      element={<ChangePassword />}
                    />
                    {/* <Route path="dev/edit/:id" element={<EditDeveloper />} />
                    <Route path="prop/edit/:id" element={<EditDeveloper />} /> */}
                  </Route>
                  {/* <Route path="/service-details" element={<ServiceDetails />} />
                  <Route path="/team" element={<Team />} />
                  <Route path="/add-listing" element={<AddListing />} /> */}
                </Route>
              </Route>
            </Routes>
          </AuthProvider>

      </HashRouter>
    );
  }
}

export default Root;

ReactDOM.render(<Root />, document.getElementById("quarter"));

Here is my changepassword.js

import React from "react";

function ChangePassword() {
  return (

          <form action="#" className="ltn__form-box contact-form-box">

Change Password

            <input
              type="password"
              name="password"
              placeholder="Current Password*"
            />
            <input
              type="password"
              name="password"
              placeholder="New Password*"
            />
            <input
              type="password"
              name="password"
              placeholder="Confirm New Password*"
            />

              <button className="theme-btn-1 btn btn-block" type="submit">
                Save Changes
              </button>

          </form>

  );
}

export default ChangePassword;

I am struggling on it for a whole day. Can you please help me? I have tried all of the possible solutions but still could not come to fix this issue. The other posts say this about importing the wrong component but I feel everything is good here.

A: You can put this line in your first file:
import { Component } from 'react';

for more information read this post.


text:
Q: Why I am getting compitable type error in django while updating a blog post? I am trying to make a social networking site like Twitter. When I try to update a post it shows the error in the following screenshot. I can't find out the actual cause of the error.

views.py

    @login_required
def editpost(request,id):
    mainpost = get_object_or_404(NewPost,id = id)
    postform = NewPostForm(instance = mainpost)
    if request.method == "POST":
        postform = NewPostForm(request.POST, instance= mainpost)
        user = request.user.id
        timestamp = datetime.now()
        if postform.is_valid:
            post = postform.save(commit=False)
            postdata = NewPost(id = id,post = post,timestamp = timestamp)
            postdata.save()
            return HttpResponseRedirect(reverse("index"))

    return render(request,"network/editform.html",{
        "postform" : postform,
        "mainpost" : mainpost,
        "id" : id,
    })

models.py

class NewPost(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    post = models.TextField()
    timestamp = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return f"{self.post}"

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("profile/<int:id>",views.profilepage,name="profile"),
    path("profile/<int:id>/following/addfollower",views.followersPeople,name="addfollower"),
    path("profile/<int:id>/following/removefollower",views.followersRemove,name="removefollower"),
    path("postform", views.createpost, name="postform"),
    path("editform/<int:id>",views.editpost,name="editpost"),
    path("following",views.followerspost,name="following"),
]+ static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

editform.html

{% extends 'network/layout.html' %}

{% block body %}

                New post
                <form id="NewPostForm" action="" method="POST">
                    {% csrf_token %}

                        {{ postform }}

                    <input class="btn btn-success" type="Submit" value="Submit">
                </form>

{% endblock %}

I am having this error:

A: When editing the instance, you save the form, so:
from django.shortcuts import redirect

@login_required
def editpost(request,id):
    mainpost = get_object_or_404(NewPost, id=id)
    postform = NewPostForm(instance=mainpost)
    if request.method == 'POST':
        postform = NewPostForm(request.POST, instance=mainpost)
        timestamp = datetime.now()
        if postform.is_valid():  # 🖘 call is_valid()
            postform.instance.timestamp = datetime.now()
            postform.save()  # 🖘 save the form
            return redirect('index')

    return render(request, 'network/editform.html', {
        'postform' : postform,
        'mainpost' : mainpost,
        'id' : id,
    })
If you want to update the timestamp each time you edit the NewPost object, you can use auto_now=True [Django-doc], instead of auto_now_add=True:
class NewPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.TextField()
    timestamp = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.post}'


text:
Q: How to add javascript to static block? I have a javascript that I need to add to a static block. Could anyone explain it step by step?

A: Login to the admin and navigate to content > blocks, find the block you want to edit and click on select > edit.
Click on the hide/show editor button to hide the editor (make sure there are no icons above the text box).
Paste in your Javascript and save the static block. If you see a message about cache then click on it and clear the cache.
Internal JS:

External JS:

Call a template that contains your JS:
{{block type="core/template" block_id="example.id" template="your/template/path.phtml"}}

A: Login to admin panel Click on CMS > Static Blocks.
Create New Block suppose Identifier = block_test
Add Content :
Click here to check Javascript

For testing Create CMS page and call CMS block from CMS page
suppose URL Key = test
Add Content :
{{block type="cms/block" block_id="block_test"}}

Go to front end /test and click on "here" link, alert message will popup.

A: 1) Create a phtml file in : app/design/frontend/{yourPackage}/{yourTheme}/template/cms/customcms.phtml then put your code in this file.(the code that you want to display in a static block, not the external Js URL)
2) Go to admin cms>static block>your static block>content>hide editor>past this code:
{{block type="core/template name="custom.cms" template="cms/customcms.phtml"}}
3) add this code in app/design/frontend/{yourPackage}/{yourTheme}/layout/local.xml
<layout version="0.1.0">
   <default translate="label" module="page">
       ...
       <reference name="head">
          <action method="addLinkRel"><rel>text/javascript</rel><href> https://YOUR URL TO THE EXTERNAL JS ... .js</href></action>
       </reference>
   </default>
</layout>


text:
Q: Applying same style to multiple child divs Here is my html

1

2

3

4

1

2

3

4

In the CSS, I have following.
#id1 > div {
    border: 1px solid white;
    width: 100px;
    height: 50px;
    margin: 5px;
}

#id2 > div {
    border: 1px solid white;
    width: 100px;
    height: 50px;
    margin: 5px;
}

I wanted to combine it in following values.
#id1 > div #id2 > div  {
    border: 1px solid white;
    width: 100px;
    height: 50px;
    margin: 5px;
}

But this does not work. I can add a class and apply to all 8 divs but I am wondering if there is any better way of getting this done.

A: Try this:
#id1 > div, #id2 > div  {
    border: 1px solid white;
    width: 100px;
    height: 50px;
    margin: 5px;
}

Multiple CSS selectors should be separated by a coma.

A: first, your selector is lacking a comma:
#id1 > div, #id2 > div  {

afaik, assigning a css class to the id divs would be best practice. an alternative might be the following selector:
#id1 > div, #id1 ~ div[id] > div  {

you chose all div children of div siblings of #id1 sporting an id attribute.
it smells like some dirty hack though...

A: Separate with Comma
#id1 > div, #id2 > div  {
border: 1px solid white;
width: 100px;
height: 50px;
margin: 5px;
}


text:
Q: Using Semaphors to create a thread safe stack in C? I'm trying to make a stack that I implemented thread safe using semaphors. It works when I push a single object onto the stack, but terminal freezes up as soon as I try to push a second item onto the stack or pop an item off of the stack. This is what I have so far and am not sure where I'm messing up. Everything complies right, but the terminal just freezes as previously stated
Heres where I create the stack
sem_t selements, sspace;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

BlockingStack *new_BlockingStack(int max_size)
{
    sem_init(&selements, 0, 0);
    sem_init(&sspace, 0, max_size);

    BlockingStack *newBlockingStack = malloc(sizeof(BlockingStack));
    newBlockingStack->maxSize = max_size;
    newBlockingStack->stackTop = -1;
    newBlockingStack->element = malloc(max_size * sizeof(void *));

    if (newBlockingStack == NULL)
    {
        return NULL;
    }

    if (newBlockingStack->element == NULL)
    {
        free(newBlockingStack);
        return NULL;
    }

    return newBlockingStack;
}

And here are the Push and Pop:
bool BlockingStack_push(BlockingStack *this, void *element)
{
    sem_wait(&sspace);
    pthread_mutex_lock(&m);

    if (this->stackTop == this->maxSize - 1)
    {
        return false;
    }
    if (element == NULL)
    {
        return false;
    }
    this->element[++this->stackTop] = element;
    return true;

    pthread_mutex_unlock(&m);
    sem_post(&selements);

}

void *BlockingStack_pop(BlockingStack *this)
{
    sem_wait(&selements);
    pthread_mutex_lock(&m);

    if (this->stackTop == -1)
    {
        return NULL;
    }
    else
    {
        return this->element[this->stackTop--];
    }

    pthread_mutex_unlock(&m);
    sem_post(&sspace);
}

A: SUGGESTED CHANGES:
sem_t sem;
...
BlockingStack *new_BlockingStack(int max_size)
{
    sem_init(&sem, 0, 1);
    ...

bool BlockingStack_push(BlockingStack *this, void *element)
{
    sem_wait(&sem);
    ...
    sem_post(&sem);
    ...

Specifically:

*

*I would only initialize one semaphore object unless I was SURE I needed others

*I would use the same semaphore for push() and pop()

*pshared: 0 should be sufficent for synchronizing different pthreads inside your single process.

*Initialize the semaphore to 1, because the first thing you'll do for either "push" or "pop" is sem_wait().

A: For thread safety you already have mutex used (pthread_mutex_lock(&m) and pthread_mutex_unlock(&m)). Using such mutual exclusion is enough for that purpose. Once one thread obtains the mutex, other thread blocks on pthread_mutex_lock(&m) call.
And only the thread currently obtaining the mutex can call pthread_mutex_unlock(&m).

A: OK, i was working on this and finally cracked the answer after doing a little bit of internet research and debugging my code. The error was the the mutex_unlock and the sem_post had to come before the return.
Take my pop for example:
void *BlockingStack_pop(BlockingStack *this)
{
    sem_wait(&selements);
    pthread_mutex_lock(&m);

    if (this->stackTop == -1)
    {
        return NULL;
    }
    else
    {
        return this->element[this->stackTop--];
    }

    pthread_mutex_unlock(&m);
    sem_post(&sspace);
}

notice how the pthread_mutex_unlock(&m);  and the   sem_post(&sspace); come after the return, they actually must be placed before every return like so:
void *BlockingStack_pop(BlockingStack *this)
{
...
    pthread_mutex_unlock(&m);
    sem_post(&sspace);
        return NULL;
...
        pthread_mutex_unlock(&m);
    sem_post(&sspace);
        return this->element[this->stackTop--];
...

}


text:
Q: RegEx - Exclude random String between specific tags I have to change a lot of tags in an XML-Document and think RegEx might be the best solution for this, but I can't figure out the correct snytax:
<tag1 attribute="value1">random content1<tag1>
<tag1 attribute="value2">random content2<tag1>
<tag1 attribute="value1">random content3<tag1>

This is the current state. "tag1" can have different values for "attribute" at the moment. The new structure gets rid of those combinations, but instead uses specific elements for that.
<tag1 attribute="value1">random content1<tag1>
<!-- tag1 + value1 requires <tag2>random content1</tag2> : -->
<tag2>random content1<tag2>

<tag1 attribute="value2">random content2<tag1>
<!-- tag1 + value2 requires <tag3>random content2</tag3> : -->
<tag3>random content1<tag3>

I need to change all of those tag->attribute-combinations without touching the content inbetween. Is it possible to select those specific tags while excluding their contents?
Help is very appreciated!


text:
Q: opencv or javacv or other I am developing face detection photo capture application in android. Some one said that use of opencv native camera is the best to capture face. I heard javacv also to capture face. Can anyone tell what is the best method opencv (or) javacv (or) other than these two.
Thanks.

A: OpenCV has an official version for android in which you program in Java. It is usually named OpenCV4Android.
JavaCV is a non-official Java version of OpenCV.
Writing native code using Android NDK will usually be much faster than using the SDK. Face detection must be faster in opencv than javacv.
My advice is for you to use OpenCV4Android, it will be easier for you, and also has more documentation: https://opencv.org/platforms/android/

A: OpenCV now has bindings for desktop Java, make a look at this
From the link:

This has two major advantages:

*

*The Java wrapper is automatically kept up-to-date.

*The bindings closely match the original C++ interface.
       More information is available in the new tutorial...

A: OpenCV is a very good Computer visio library. It has C, C++ and Python API. JavaCV is Wrapper of OpenCV using java.
based on your purpose you can use native C API using Android NDK. If you are focus on Java then you can use JavaCV.


text:
Q: resolving the error due to xen building\installation can't resolve the error when I am trying to build xen package using manjaro linux and 5.11.6-1 kernel.
Really appreciate fro thoughts. Thanks.
  ...

  GEN     target/sparc/trace.c
  GEN     util/trace.c
  GEN     config-all-devices.mak
make[1]: Entering directory '/home/username/xen/src/xen-4.14.1/tools/qemu-xen/slirp'
make[1]: Nothing to be done for 'all'.
make[1]: Leaving directory '/home/username/xen/src/xen-4.14.1/tools/qemu-xen/slirp'
  BUILD   pc-bios/optionrom/multiboot.img
  BUILD   pc-bios/optionrom/linuxboot.img
  BUILD   pc-bios/optionrom/linuxboot_dma.img
  BUILD   pc-bios/optionrom/kvmvapic.img
ld: Error: unable to disambiguate: -no-pie (did you mean --no-pie ?)
ldmake[1]: *** [Makefile:53: multiboot.img] Error 1
: Error: unable to disambiguate: -no-pie (did you mean --no-piemake[1]: *** Waiting for unfinished jobs....
 ?)
make[1]: *** [Makefile:53: linuxboot.img] Error 1
ld: Error: unable to disambiguate: -no-pie (did you mean --no-pie ?)
ld: Error: unable to disambiguate: -no-pie (did you mean --no-pie ?)
make[1]: *** [Makefile:53: kvmvapic.img] Error 1
make[1]: *** [Makefile:53: linuxboot_dma.img] Error 1
  BUILD   pc-bios/optionrom/pvh.img
ld: Error: unable to disambiguate: -no-pie (did you mean --no-pie ?)
make[1]: *** [Makefile:50: pvh.img] Error 1
make: *** [Makefile:581: pc-bios/optionrom/all] Error 2
make: Leaving directory '/home/username/xen/src/xen-4.14.1/tools/qemu-xen-build'
make[3]: *** [Makefile:218: subdir-all-qemu-xen-dir] Error 2
make[3]: Leaving directory '/home/username/xen/src/xen-4.14.1/tools'
make[2]: *** [/home/username/xen/src/xen-4.14.1/tools/../tools/Rules.mk:235: subdirs-install] Error 2
make[2]: Leaving directory '/home/username/xen/src/xen-4.14.1/tools'
make[1]: *** [Makefile:72: install] Error 2
make[1]: Leaving directory '/home/username/xen/src/xen-4.14.1/tools'
make: *** [Makefile:134: install-tools] Error 2
==> ERROR: A failure occurred in build().
    Aborting...


text:
Q: Looking for a batch file that will give me file dimensions in a folder of jpgs I'm trying to find a batch file that I can run in a folder of jpgs that will give me either pixel dimensions or height and width in inches along with the file names... anything like that already out there? thx.

A: This is a hybrid batch/jscript file that can be used as a base for your code. Save as batch file. When executed, it will return the dimensions of the files that expose a dimension property in the indicated folder.
@if (@This==@IsBatch) @then
@echo off

    Cscript //nologo //e:jscript "%~f0" /folder:"%~dp0" /delim:";"

    exit /b

@end
var DETAILS_FILENAME=0;
var DETAILS_DIMENSIONS=31;

    var folder=WScript.CreateObject('Shell.Application').NameSpace(WScript.Arguments.Named.Item('folder'));
    var delim=WScript.Arguments.Named.Exists('delim') ? WScript.Arguments.Named.Item('delim') : '|';
    for (var e=new Enumerator(folder.Items()); !e.atEnd(); e.moveNext()){
        var i=e.item();
        var d=folder.GetDetailsOf(e.item(),DETAILS_DIMENSIONS);
        if (d) WScript.StdOut.WriteLine(folder.GetDetailsOf(i,DETAILS_FILENAME) + delim + d.replace(/[^0-9x]*/g,''));
    };


text:
Q: How to modify angularjs data outside of a controller? I have a main page that consists of only two parts: a navigation headline, and the dynamic content.
index.html:

        {{nav.name}}

The navigation is achieved as follows:
app.config(function($routeProvider, $locationProvider) {
    $routeProvider.when("/test", {
        templateUrl : "templates/test.html",
        controller : "testController"
    });
});

The headline links should be provided by the backend on each webservice request.
Question: how can I trigger the following initfunction from within another controller (the one receiving the get response)? I lateron want to trigger this method from within different controllers.
app.controller('MainCtrl', ['$scope', function($scope) {
    this.init = function(data) {
        $scope.navs = data;
    }
}]);

I tried the following, which did not work:
test.html:

some stuff provided by testController.js

testController.js:
angular.module('test').controller('testController', ['$scope', '$http', '$controller', function($scope, $http, $controller) {
    $http.get(url)
        .success(function(data) {
            $controller('MainCtrl').init(data.mynavigation); //assume navigations exists

            //process content in data
        });
}]);

Result:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20MainCtrl

A: Instead of setting the data with the init, I recomend to inject a service in your $scope of controller, so you don't need to call the function in controller but just change the data of your service.
Something like this:
app.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
    this.navs = myService;
}]);

html:

        {{nav.name}}

Then, your service:
app.factory('myService',function() {
   var myService = {
       data: [],
       setData(data): function(data) {
           this.data = data;
       }
   }
   return myService;
});

This is just to ilustrate: the myService is the same object in all your application, if you change the myService.data, every controller that injects this service will use the same data.
So you put your trigger in another controller to update this service. This technique is used to share data between directives too.

A: If you want to run init function whitin your controller initialization, just call this.init() in your controller.
To wok with inheritance, consider doing scope inheritance. There are examples in docs : https://docs.angularjs.org/guide/controller
If you want to reuse call/response code, you may consider creating a service and injecting it as a dependence in your controller as you need. Create a service that returns a promise and handle this promise inside controllers.
Refer to https://docs.angularjs.org/api/ng/service/$q in order to understand how to work with angular promises.
Refer to AngularJS: Service vs provider vs factory for more information about services usage.


text:
Q: Overwriting HTTP response headers Is there a way to overwrite the http response headers returned in Jmeter? I'm testing a web service that returns JSON and when an invalid request is sent, the JSON response returned doesn't contain application/json (or any for that matter) in the response header. If I save the response to a file, I see the actual JSON returned, but looking at the response in a Results tree doesn't show a response. Unless there is a way to load the response from file and parse the error message from the file, I'm hoping to somehow overwrite the HTTP response header and force jmeter to treat the response as JSON.
Any suggestions are welcome!

A: Using a beanshell post processor, you can write some script that would force the value for the header, or write out to a file.
You can also add a listener that would write the results to file for you. Granted - this is less convenient for debugging then Tree View.

A: As it turns out JMeter does not support response header overloading. While the response isn't displayed in the Results tree, it is actually available to other assertions. I was able to still provide assertions to validate responses even though the response was missing from the GUI.


text:
Q: Unable to locate the successfully deployed custom timer job I have successfully deployed my timer job and it appears in the Central Admin but I cannot find it in Job Definitions or Running Jobs either in the Monitoring option of Central Admin. What could be the cause of this problem??

A: I think you have only deployed the solution (wsp) file of the timer job. You will also need to activate the feature for your timer job.
Go to the Site collection features of your Web-application and Activate your timer job feature from there.
This should start showing your timer job in the list of Job Definitions in the Central Administration.
I hope this helps.

A: After deploying solution, go to your solution scope level (Web application/Site Collection) and activate feature. Then on SharePoint Server restart the SharePoint Timer Service.


text:
Q: How to create a new rows from column values of pandas data frame I have dataframe like below
Input
Date         Country    Type         Zip_Incl     Zip_Excl
10/4/2020      FR   Regional        57_67_68
2/1/2020       GB   Regional                      AB_DD
17/3/2021      GB   Regional        BT_TY         TS_TN
18/3/2021      GB   Regional
19/1/2021     IN    Regional                      68

I need to transform the input based on below conditions:
1)If Zip_incl is  not empty then value to Zip_incl should be passed into Zip_Final
2)IF Zip_incl and Zip_Excl values are present then value of Zip_incl should be passed into Zip_Final
3)If Zip incl is empty and value is present for Zip_Excl is present then Zip_Excl should be passed to Zip_Final
Output
Date      Country   Type    Zip_Incl     Zip_Excl   Zip_Final
10/4/2020   FR  Regional     57                     57
10/4/2020   FR  Regional     67                     67
10/4/2020   FR  Regional     68                     68
2/1/2020    GB  Regional                 AB         AB
2/1/2020    GB  Regional                 DD         DD
17/3/2021   GB  Regional     BT          TS         BT
17/3/2021   GB  Regional     TY          TN         TY
18/3/2021   GB  Regional
19/1/2021   IN  Regional                 68         68

How can this be done?

A: In your case we can do bfill with axis=1 then split the string and explode it
df['Zip_F']=df.filter(like='Zip').bfill(1).iloc[:,0].str.split('_')
df=df.explode('Zip_F')
df
        Date Country      Type  Zip_Incl Zip_Excl Zip_F
0  10/4/2020      FR  Regional  57_67_68      NaN    57
0  10/4/2020      FR  Regional  57_67_68      NaN    67
0  10/4/2020      FR  Regional  57_67_68      NaN    68
1   2/1/2020      GB  Regional       NaN    AB_DD    AB
1   2/1/2020      GB  Regional       NaN    AB_DD    DD
2  17/3/2021      GB  Regional     BT_TY    TS_TN    BT
2  17/3/2021      GB  Regional     BT_TY    TS_TN    TY
3  18/3/2021      GB  Regional       NaN      NaN   NaN
4  19/1/2021      IN  Regional       NaN       68    68

Update
df[['Zip_Incl','Zip_Excl']]=df[['Zip_Incl','Zip_Excl']].mask(df[['Zip_Incl','Zip_Excl']].notnull(),df.Zip_F,axis=0)
df
Out[178]:
        Date Country      Type Zip_Incl Zip_Excl Zip_F
0  10/4/2020      FR  Regional       57      NaN    57
0  10/4/2020      FR  Regional       67      NaN    67
0  10/4/2020      FR  Regional       68      NaN    68
1   2/1/2020      GB  Regional      NaN       AB    AB
1   2/1/2020      GB  Regional      NaN       DD    DD
2  17/3/2021      GB  Regional       BT       BT    BT
2  17/3/2021      GB  Regional       TY       TY    TY
3  18/3/2021      GB  Regional      NaN      NaN   NaN
4  19/1/2021      IN  Regional      NaN       68    68

A: Assuming the dtypes are all string I'd consider the following
import pandas as pd
import numpy as np
df = pd.DataFrame({"Type":["Regional"]*5,
                   "Zip_Incl":["57_67_68", "", "BT_TY", "", ""],
                   "Zip_Excl":["","AB_DD", "TS_TN", "", "68"]})

# this tell us the element that are not ""
(~df[["Zip_Incl", "Zip_Excl"]].eq(""))

   Zip_Incl  Zip_Excl
0      True     False
1     False      True
2      True      True
3     False     False
4     False      True

While the following returns the first not empty string in every row
sel = (~df.eq("")).values.argmax(1)

Now with some numpy tricks we can get your output
mat = df[["Zip_Incl", "Zip_Excl"]].values
df["Zip_Final"] = mat[np.arange(mat.shape[0]), sel]

Update In case your df is not that big and you are looking for a not numpy solution you could do
def fun(row):
    if row["Zip_Incl"] != "":
        return row["Zip_Incl"]
    elif row["Zip_Excl"] != "":
        return row["Zip_Excl"]
    else:
        return ""

df["Zip_Final"] = df.apply(fun, axis=1)

In both cases the output is
       Type  Zip_Incl Zip_Excl Zip_Final
0  Regional  57_67_68           57_67_68
1  Regional              AB_DD     AB_DD
2  Regional     BT_TY    TS_TN     BT_TY
3  Regional
4  Regional                 68        68

Update2: I just realized you want then to split Zip_Final in different row. Using one of the previous methods you could add these lines
df["Zip_Final"] = df["Zip_Final"].str.split("_")

# you need pandas > 0 .25
df = df.explode("Zip_Final")

print(df)

       Type  Zip_Incl Zip_Excl Zip_Final
0  Regional  57_67_68                 57
0  Regional  57_67_68                 67
0  Regional  57_67_68                 68
1  Regional              AB_DD        AB
1  Regional              AB_DD        DD
2  Regional     BT_TY    TS_TN        BT
2  Regional     BT_TY    TS_TN        TY
3  Regional
4  Regional                 68        68


text:
Q: Minimum and Maximum float value in MiniZinc From the MiniZinc specification :

Floats represent real numbers. Float representations are implementation-defined. This means that the representable range and precision of floats is implementation-defined. However, an implementation should abort at run-time on exceptional float operations (e.g., those that produce NaN, if using IEEE754 floats).

What does it means that Float representations are implementation-defined? Does it depends on the solver which will be used?
And how the Float representation is handled by the mzn2fzn tool? Which are its bound?

A: MiniZinc tries to adhere to the IEEE standard. The compiler itself (the minizinc driver or its older brother mzn2fzn) adheres to this standard, as far as my knowledge goes. Internally the compiler uses a 64 bit precision for its floating point values. If there are any problems where the compiler does not adhere to these standards, I would encourage you to report them.
The standards for the solvers are a different matter. MiniZinc only enforces minimal control over the solvers. If you want to ensure they employ the correct standards you will have to verify with the manufacturer of the solver. This is why the specification says it is implementation-defined, as the solver might use 32-bits, like Gecode, 64-bit, as most solvers do, or a fully different technique like an interval library.


text:
Q: How to get Screens DPI by Qt application in Linux framebuffer mode(without X11) Currently I am running Qt and QML application in Embedded Linux Built using buildroot. GUI comes up good in the screen.
Application runs in framebuffer mode, X11 is not present in Linux.
I want to know the DPI of the screen in my application.
I used below Qt API to get DPI
qreal screenDPI = QApplication::primaryScreen()->physicalDotsPerInch();
qDebug() << "***************screenDPI***************" << screenDPI;

Output of the above is
***************screenDPI***************inf

It is not fetching the required DPI value.
Screen size 800*480.
Same API works good in Ubuntu Linux 18.04 and Windows.
physicalDotsPerInch is not working as expected.
Is there any alternative API that I can use to get DPI of the screen in embedded Linux running in frame buffer mode.

A: Is it possible to get QApplication::primaryScreen()->physicalSize?
If so you could calculate the DPI yourself by using the geometry of your window.
What device are you using? what is the output of :
manufacturer
model
name


text:
Q: Why will my form not work when extending a template Hello all my form does not work when I am extending a template with jinja2. How can I get the form to function with the template?
The goal is to be able to have one parent file that I can then add in all my child files into instead of having to add in the header and footer every time. This time now that I am trying to add in a form will not let the form be interactive. The form is acting like an image where you cannot select anything or interact with anything.
My parent file is:

    <link rel="shortcut icon" href="/static/img/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/static/img/favicon.ico" type="image/x-icon">
<title>On Deck Shooting Apps</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="/static/CSS/layout.css" type="text/css" />

OnDeckShooting

Advanced event management

        {% block head %}

Home

Sign in/up

Admin console

Console

Staff Management

ALERTS

Sign up Shooters

Contact Us

logout

        {% with messages = get_flashed_messages() %}
          {% if messages %}

            {% for message in messages %}

{{ message }}

            {% endfor %}

          {% endif %}
        {% endwith %}

    {% endblock %}

        {% block content %}{% endblock %}

{% block footer %}

Copyright © 2015 - All Rights Reserved - ondeckshootingapps.com

      <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="PAYPALSTUFF
">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

    {% endblock %}

My child file is:
{% extends "Header.html" %}
{% block content %}

CREATE SHOOT

<form action="" method="post" name="form">
      {{ form.hidden_tag() }}

Name of shoot:

          {{ form.nameofshoot(size=40) }}

Number of days in shoot:

            {{ form.day}}

<input type="submit" value="Create Shoot">

  </form>

{% endblock %}

My css is:
@charset "utf-8";
/*
Template Name: BusinessToday
Author: OS Templates
Author URI: http://www.os-templates.com/
Licence: Free to use under our free template licence terms
Licence URI: http://www.os-templates.com/template-terms
File: Layout CSS
*/

@import url("navi.css");
@import url("forms.css");
@import url("tables.css");

html{overflow-y:scroll;}
body{margin:0; padding:0; font-size:12px; font-family:verdana, Arial, Helvetica, sans-serif; color:#FFFFFF; background-color:#29313C;}

.justify{text-align:justify;}
.bold{font-weight:bold;}
.center{text-align:center;}
.right{text-align:right;}
.nostart{margin:0; padding:0; list-style-type:none;}

.clear{clear:both;}
br.clear{clear:both; margin-top:-15px;}

a{outline:none; text-decoration:none;}

.fl_left, .imgl{float:left;}
.fl_right, .imgr{float:right;}

img{display:block; margin:0; padding:0; border:0;}
.imgl, .imgr{border:1px solid #DFDFDF; padding:5px; color:#666666; background-color:#FFFFFF;}
.imgl{margin:0 8px 8px 0; clear:left;}
.imgr{margin:0 0 8px 8px; clear:right;}

/* ----------------------------------------------Wrapper------------------------------------- */

div.wrapper{display:block; width:100%; margin:0; text-align:left;}
div.wrapper h1, div.wrapper h2, div.wrapper h3, div.wrapper h4, div.wrapper h5, div.wrapper h6{margin:0 0 20px 0; padding:0 0 8px 0; font-size:20px; font-weight:normal; font-family:Georgia, "Times New Roman", Times, serif; border-bottom:1px dotted #DDDDDD;}
.col1{color:#666666; background-color:#E3F1F9;}
.col2{color:#FFFFFF; background-color:#000000;}
.col3, .col4, .col5{color:#666666; background-color:#FFFFFF;}
.col6{color:#999999; background-color:#F3F3F3;}
.col6 a{color:#2684B7; background-color:#F3F3F3;}
.col7, .col7 a{color:#FFFFFF; background-color:#29313C;}

/* ----------------------------------------------Generalise------------------------------------- */

#header, #topbar, #intro, #services, #breadcrumb, #container, #footer, #copyright{display:block; position:relative; width:960px; margin:0 auto;}

/* ----------------------------------------------Header------------------------------------- */

#header{padding:30px 0; font-family:Georgia, "Times New Roman", Times, serif;}
#header #logo{display:block; float:left; width:300px; margin-top:7px;}
#header #logo h1, #header #logo p{margin:0; padding:0; line-height:normal;}
#header #logo h1{margin:0 0 10px 0; padding:0; font-size:36px; border:none;}
#header h1 a{color:#3A6C86; background-color:#E3F1F9;}
#header #newsletter{float:right; padding:10px 10px 12px 10px; color:#000000; background-color:#ADD6ED;}
#header #newsletter p{margin:0 0 8px 0; font-family:Verdana, Arial, Helvetica, sans-serif;}

/* ----------------------------------------------Topbar------------------------------------- */

#topbar{z-index:1000;}
#topbar #search{display:block; float:right; width:242px; height:36px; margin:0; padding:10px 0 0 17px; color:#FFFFFF; background-color:#000000; border-left:1px dotted #666666; overflow:hidden;}

/* ----------------------------------------------Homepage Intro------------------------------------- */

#intro{padding:30px 0 5px 0; font-size:16px; font-family:Georgia, "Times New Roman", Times, serif;}
#intro .fl_left{display:block; float:left; width:515px; height:240px; margin:0; padding:30px; color:#FFFFFF; background-color:#2684B7;}
#intro .fl_left h2{font-size:46px; margin:0 0 15px 0; padding:0; border:none; color:#FFFFFF; background-color:#2684B7;}
#intro .fl_left p{margin:0; padding:0; line-height:1.6em;}
#intro .fl_left p.readmore{display:block; width:100%; margin:20px 0 0 0; padding:0; text-align:right; line-height:normal;}
#intro .fl_left p.readmore a{padding:8px 15px; font-size:18px; color:#FFFFFF; background-color:#1C5E82;}
#intro .fl_right{float:right;}

/* ----------------------------------------------Services------------------------------------- */

#services ul, #services p, #services h2, #services img{margin:0; padding:0; list-style:none;}
#services li{display:block; float:left; width:294px; height:180px; margin:0 9px 0 0; padding:10px; color:#666666; background-color:#EFEFEF;}
#services li:hover, #services li:hover h2{color:#666666; background-color:#E5E5E5;}
#services li.last{margin-right:0;}
#services .fl_right{display:block; float:right; width:185px; padding:10px 0 0 0;}
#services h2{margin:0 0 5px 0; padding:0 0 3px 0; font-size:14px; font-weight:bold; color:#666666; background-color:#EFEFEF; border-bottom-color:#666666;}
#services p{margin:0; padding:0; line-height:1.6em;}
#services p.readmore{display:block; width:100%; margin:15px 0 0 0; padding:0; text-align:right; line-height:normal;}
#services p.readmore a{padding:8px 15px; font-weight:bold; color:#FFFFFF; background-color:#666666;}

/* ----------------------------------------------BreadCrumb------------------------------------- */

#breadcrumb{padding:30px 0; border-bottom:1px solid #CCCCCC;}
#breadcrumb a{color:#2684B7; background-color:#FFFFFF;}
#breadcrumb ul{margin:0; padding:0; list-style:none;}
#breadcrumb ul li{display:inline;}
#breadcrumb ul li.current a{text-decoration:underline;}

/* ----------------------------------------------Content------------------------------------- */

#container{padding:30px 0; line-height:1.4em;}
#container a{color:#2684B7; background-color:#FFFFFF;}
#container h1, #container h2, #container h3, #container h4, #container h5, #container h6{padding-bottom:8px; border-bottom:1px dotted #CCCCCC;}
#content{display:block; float:left; width:600px;}

/* Comments */

#comments{margin-bottom:40px;}
#comments .commentlist{margin:0; padding:0;}
#comments .commentlist ul{margin:0; padding:0; list-style:none;}
#comments .commentlist li.comment_odd, #comments .commentlist li.comment_even{margin:0 0 10px 0; padding:15px; list-style:none;}
#comments .commentlist li.comment_odd{color:#666666; background-color:#FFFFFF;}
#comments .commentlist li.comment_odd a{color:#3E7060; background-color:#FFFFFF;}
#comments .commentlist li.comment_even{color:#666666; background-color:#E8E8E8;}
#comments .commentlist li.comment_even a{color:#3E7060; background-color:#E8E8E8;}
#comments .commentlist .author .name{font-weight:bold;}
#comments .commentlist .submitdate{font-size:smaller;}
#comments .commentlist p{margin:10px 5px 10px 0; padding:0; font-weight:normal; text-transform:none;}
#comments .commentlist li .avatar{float:right; border:1px solid #EEEEEE; margin:0 0 0 10px;}

/* ----------------------------------------------Column------------------------------------- */

#column{display:block; float:right; width:300px;}
.flickrbox ul{margin:0; padding:0; list-style:none;}
.flickrbox li{display:block; float:left; width:80px; height:80px; margin:0 15px 15px 0; padding:4px; color:#666666; background-color:#FFFFFF; border:1px solid #CCCCCC;}
.flickrbox li.last{margin-right:0;}
#column .holder, #column #featured{display:block; width:300px; margin-bottom:20px;}
#column .holder h2.title{display:block; width:100%; height:65px; margin:0; padding:15px 0 0 0; font-size:20px; line-height:normal; border-bottom:1px dashed #666666;}
#column .holder h2.title img{float:left; margin:-15px 8px 0 0; padding:5px; border:1px solid #666666;}
#column div.imgholder{display:block; width:290px; margin:0 0 10px 0; padding:4px; color:#666666; background-color:#FFFFFF; border:1px solid #CCCCCC;}
#column .holder p.readmore{display:block; width:100%; font-weight:bold; text-align:right; line-height:normal;}

/* Featured Block */

#column #featured a{color:#666666; background-color:#F9F9F9;}
#column #featured ul, #column #featured h2, #column #featured p{margin:0; padding:0; list-style:none;}
#column #featured a{color:#2684B7; background-color:#F9F9F9;}
#column #featured li{display:block; width:250px; margin:0; padding:20px 25px; color:#666666; background-color:#F9F9F9;}
#column #featured li p.imgholder{display:block; width:240px; height:90px; margin:20px 0 15px 0; padding:4px; border:1px solid #CCCCCC;}
#column #featured li h2{margin:0; padding:0 0 14px 0; font-weight:normal; font-family:Georgia, "Times New Roman", Times, serif; line-height:normal; border-bottom:1px dashed #666666;}
#column #featured p.readmore{display:block; width:100%; margin-top:15px; font-weight:bold; text-align:right; line-height:normal;}
#column #latestnews{display:block; width:100%; margin:0; padding:0; list-style:none;}
#column #latestnews li{display:block; margin:0 0 20px 0; padding:0 0 15px 0; border-bottom:1px dotted #DDDDDD;}
#column #latestnews li.last{margin-bottom:0;}
#column #latestnews p{margin:0; padding:0; line-height:normal;}
#column #latestnews .imgl{margin:0 10px 10px 0; padding:4px;}

/* ----------------------------------------------Footer------------------------------------- */

#footer{padding:30px 0;}
#footer h2{margin-bottom:10px; border-bottom:1px dotted #999999;}
#footer p, #footer ul, #footer a{margin:0; padding:0; font-weight:normal; list-style:none; line-height:normal;}
#footer .footbox{display:block; float:right; width:190px; margin:0 0 0 30px; padding:0;}
#footer li{margin-bottom:3px; line-height:1.6em;}
#footer .last{margin:0;}
#login{display:block; float:left; width:300px;}

/* ----------------------------------------------Copyright------------------------------------- */

#copyright{padding:20px 0;}
#copyright p{margin:0; padding:0;}

A: Your CSS is the problem. A style is being applied to an element defined in Header.html that is causing your form to be hidden underneath another element. If you inspect the page you will see that div.col6 is sitting on top of div#content. This is caused by the following two lines in layout.css:
#content{display:block; float:left; width:600px;}

#header, #topbar, #intro, #services, #breadcrumb, #container, #footer, #copyright{display:block; position:relative; width:960px; margin:0 auto;}

The float:left; in the first line coupled with the position:relative; in the second is causing this.
Without knowing the ultimate goal of your design, it's hard to say what the correct solution is, but you have three choices:

*

*Remove the float:left;.

*Remove the position:relative;, or at least rearrange your CSS so it isn't applied to #footer.

*Clear the float. You can do this with something like:

      {% block content %}{% endblock %}

A: The problem is where my {{block contents}} is located. It is in the footer css class move your {{block contents}} to the container class


text:
Q: Twitter status update api not working I am trying to tweet using this sample program and getting an error
I am following this tutorial
Here is the code
var Twitter = require('twitter');

var client = new Twitter({
    consumer_key: 'CONSUMER_KEY',
    consumer_secret: 'CONSUMER_SECRET',
    access_token: 'ACCESS_TOKEN',
    access_token_secret: 'ACCESS_TOKEN_SECRET'
});

//var stat = ["First Tweet","Second Tweet","Third Tweet","Forth Tweet","Fifth Tweet"];

client.post('statuses/update', {status: 'I Love Twitter'},  function(error, tweet, response){
  if(error) throw error;
  console.log(tweet);  // Tweet body.
  console.log(response);  // Raw response object.
});

whenever i run this code i receive following error
E:\Local server\nodejs\status_update\test.js:12
  if(error) throw error;
                  ^
[object Object]

A: try it this way. Fixed mine.
client.post('statuses/update', {status: "words"}, function(error, tweet, response){
  if (!error) {
    console.log(tweet);
  }
});


text:
Q: CSS for table gets affected with Table in Date Picker I am trying to create a CSS to display a table to show all contents in iPad
in order to avoid displaying horizontally. The Problem I am facing here is
in Date    Picker table, which gets affected with this CSS .
    @media
      only screen and (max-width: 760px),
      (min-device-width: 768px) and (max-device-width: 1024px)  {

         /* Force table to not be like tables anymore */

        table, thead, tbody, th, td, tr {
            display: block;
        }

         /* Hide table headers (but not display: none;, for accessibility) */

        thead tr {
            position: absolute;
            top: -9999px;
            left: -9999px;
        }

        tr { border: 1px solid #ccc; }

        td {
            /* Behave  like a "row" */
            border: none;
            border-bottom: 1px solid #eee;
            position: relative;
            padding-left: 50%;
        }

        td:before {

            /* Now like a table header */

            position: absolute;
            /* Top/left values mimic padding */
            top: 6px;
            left: 6px;
            width: 45%;
            padding-right: 10px;
            white-space: nowrap;
        }
     }

How can I avoid the Date Picker table to get affected with this CSS


text:
Q: How to make a php script that reads filenames and details from any directory and stores it on database? I am given a lot of video files on my server folder, so adding all of them is impossible, I need to develop a php script that will read the contents of a folder and populate my database table with details such as filename, size, path, etc.
Furthermore I need to use that data for displaying the video list to users so everything must be accurate.
Please tell me how to?

A: See here to see how to loop through a directory and get the filenames and file sizes. (Copied and edited here for simplicity)
$folder = '/my/path/to/dir';
foreach(glob($folder) as $file){
    $size = filesize($file);
    echo "Name=$file, size=$size<br />";
}

Instead of using echo to display the results you will simply use mysqli or PDO functions to run an INSERT query to insert into your table.  Since this is not input coming from a user it is not so imperative to use prepare and bind but it is good practice to do so (and more efficient as well).
Then when you display the video list you will once again use mysqli or PDO functions to run a SELECT query and then echo these values onto your page in appropriate HTML syntax.
I'm guessing, based on your question, that some of these concepts might be new to you. If you do not know how to program in PHP or use SQL or create HTML pages then you are going to need to spend some serious time going through tutorials and watching youtube videos and reading books.

A: I suggest you to use Iterators from SPL (Standart PHP Library) for an OOP aproach, for recursive iterations you should use DirectoryRecursiveIterator;
$directoryIterator = new RecursiveDirectoryIterator("/path/");
$recursiveIterator = new RecursiveIteratorIterator($directoryIterator);

foreach ($recursiveIterator as $filename => $fileInfo) {
    $filesize = $fileInfo->getSize();
    $path = $fileInfo->getPath();

    //insertDataIntoMysql($filename, $filesize, $filepath);
}


text:
Q: Eclipse Content Assist function arguments auto-insert I use Eclipse StatET for R programming.
I am looking for a way to autocomplete function definition and insert parameters names.
Say I have following function (in R):
GetFC = function(key_, portf_name_, type_, db_name_){}

Then when I invoke content assist I see following picture:

Is there anyway, that content assist will insert not only the function name, but also all parameters?
Like that:

A: Use content assist twice: first time to choose your function, second time to see the arguments and select one:


text:
Q: Динамическое масштабирование текста в TextView android Задача:  в списке элемента сделать фиксироваными отступы сверху, снизу и между строками. Я задал отступы в корневом элементе, если задать эти отступы в LinearLayout котором находятся TextView, то текст тоже не масштабируется, а нижние и верхние края залазят  на текст и перекрывают его. Как сделать так что бы размер шрифта менялся? При этом высота элемента списка должна быть фиксированной.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="97.5dp"
android:orientation="horizontal"
android:background="@color/colorWhite"
android:layout_paddingTop="20dp"
android:layout_marginBottom="20dp"
>

<!-- Progress Bar -->

<com.github.lzyzsd.circleprogress.DonutProgress
    android:id="@+id/progress_bar"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
    custom:donut_progress="70"
    custom:donut_text_size="10sp"
    custom:donut_text_color="@color/colorBlack"
    custom:donut_finished_color="@color/colorGreen"
    custom:donut_unfinished_color="@color/colorBackgroundDarckGrey"
    custom:donut_finished_stroke_width="4.5dp"
    custom:donut_unfinished_stroke_width="4.5dp"
    />

<!-- Title of package-->
<LinearLayout
    android:id="@+id/titleDescriptionCase"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerVertical="true"
    android:gravity="center_vertical"
    android:layout_toRightOf="@+id/progress_bar"
    android:layout_toEndOf="@+id/progress_bar"
    android:layout_toLeftOf="@+id/buyCase"

    >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Rihanna Love the way"
        android:textColor="@color/colorFontBlue"
        android:textSize="16sp"
        android:singleLine="false"
        />

    <TextView
        android:id="@+id/description"
        android:layout_width="196dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="6dp"
        android:singleLine="false"
        android:text="Just gona stand there and ..."
        android:textColor="#535353"
        android:textSize="13sp"

        />

</LinearLayout>

<!--Buy and about-->

<LinearLayout
    android:id="@+id/buyCase"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingRight="16dp"
    android:paddingLeft="16dp"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignTop="@+id/titleDescriptionCase">

    <!-- Buy button -->
    <Button
        android:id="@+id/btnBuy"
        android:layout_width="62.5dp"
        android:layout_height="26dp"
        android:background="@drawable/button_board_baground"
        android:text="4.99 $"
        android:textColor="@color/colorFontBlue"
        android:textSize="14sp"
        />

    <!-- Short description about package -->

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerVertical="true"
        android:layout_marginTop="9dp"
        android:text="230 words"
        android:textSize="14sp"
        />

</LinearLayout>

<!--  SHADOWS -->

<LinearLayout
    android:id="@+id/shadowLayoutBottom"
    android:layout_width="match_parent"
    android:layout_height="2.5dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/shadow_bottom"
    android:orientation="horizontal" />

<LinearLayout
    android:id="@+id/linearLayoutTop"
    android:layout_width="match_parent"
    android:layout_height="1.7dp"
    android:layout_alignParentTop="true"
    android:background="@drawable/shadow_top"
    android:orientation="vertical" />

 </RelativeLayout>

A: https://github.com/grantland/android-autofittextview подходящая для этой задачи либа, наглядный пример по ссылке


text:
Q: group cohomology for SO(3) and SO(3,1) I am studying relativistic quantum mechanics and I have encountered the concept of projective representation for a group.
I have read in http://groupprops.subwiki.org/wiki/Projective_representation that the fact that a projective representation of G cannot be changed into a normal representation (without "up to phase" composition) is related to the second group cohomology of G. (Here I do not mean the second cohomology group, the "topological" one, but this http://groupprops.subwiki.org/wiki/Second_cohomology_group_for_trivial_group_action).
Now, it should be true that both SO(3) and O(3,1) (the homogeneous Lorentz group) admit intrisically projective representations (e.g the usual isomorphism $\ SO(3) = SU(2)/\{Id,-Id\}$, should be the projective representation for SO(3)).
I therefore would like to know how to compute the cohomology groups of SO(3) and O(3,1) to check that they are not trivial.
If you have any suggestions for books explaining projective representations they are welcome as well.


text:
Q: Joomla jQuery is not defined on my website http: //******.com/, when I upgrade to php 7 it gives me the error of Uncaught ReferenceError: jQuery is not defined when it is defined at the beginning of my index.php
The strange thing is that with version 5 of php everything is correct. What can be the failure?
$jquery = '';
jimport('joomla.version');
$version = new JVersion();
if(version_compare($version->getShortVersion(), '3.0', '>=')){
    JHtml::_('jquery.framework');
} else {
    JHTML::_('behavior.mootools');
    JFactory::getDocument()->addScript($this->baseurl.'/templates/'.$this->template.'/js/jq.min.js');
}

Then inside of html of the index.php any jQuery code tells me that it is not defined. Why can it be?
Thank you!!

A: You can update your core joomla jQuery, install this plugin jQuery easy
in plugin configurations you can change core joomla jQuery


text:
Q: An error is raised when I use stat_compare_means I tried with R to add the "p" values on a boxplot, but an error is raised when I use  stat_compare_means. I looked quickly on google but I still do not understand ...
Here is the boxplot I try to display :
boxplot <- ggplot(data, aes(x = Produit, y = P.cell.ouv)) +
  geom_boxplot() +
  scale_y_continuous(name ="Proportion de cellules vidées", limits=c(0,0.5)) +
  scale_x_discrete(name ="") +
  geom_text(data = myletters_df, aes(label = letter, y = 0.35 ), colour="black", size=5) +
  stat_compare_means( label.x = 0.7, method = "kruskal.test")

And here the error raised
> boxplot
Don't know how to automatically pick scale for object of type quosure/formula. Defaulting to continuous.
Don't know how to automatically pick scale for object of type quosure/formula. Defaulting to continuous.
Error in validDetails.text(x) :
  'pairlist' object cannot be coerced to type 'double'

How can I fix this?


text:
Q: Are quantum mechanics and quantum physics the same field? What is the difference between quantum mechanics and quantum physics?

A: There is one more term one should discuss in this thread, quantum theory.
They're largely equivalent and in most cases, each of them may be replaced by any other. S_H overstates the difference by suggesting that "quantum mechanics" is a quantum version of "mechanics" while "mechanics" is just a subset of physics. However, "quantum mechanics" isn't used just for mechanics. Quantum mechanics is used for the new set of principles that underlie all quantum theories whether or not they could be interpreted as "mechanics" or e.g. "field theory". After all, quantum mechanics shows that particle-like "mechanical" properties of elementary particles or light are always complemented by their field-like "wave" properties. In this sense, quantum mechanics does imply that "mechanics" includes the rest of physics including fundamental fields when it's done properly.
The term "quantum theory" was born around 1900 when Max Planck explained the black body radiation by the light quanta. Quantum mechanics is what was born in the mid 1920s except that later, all these advances would be considered parts of the same "revolution" that may be called either "quantum theory" or "quantum mechanics".
So one could say that all the three terms are synonyma. Physicists would almost always pick "quantum mechanics" as the preferred label for any theory that follows the postulates of quantum mechanics or for the postulates themselves. On the other hand, "quantum physics" and "quantum theory" is more likely to be used by the outsiders or in the non-expert context.

A: They are used as synonyms as far as I am aware.

A: Mechanics is a subset of Physics. However, quantum mechanics or quantum physics do not necessarily mean the same thing because Physics is a very broad term where as mechanics is a specialized area of physics dealing with motion of bodies in a frame of reference.
P.S.: If you meet with any researcher in any area other than business, you would see how often they use the term physics in their research to explain a phenomenon/behavior.

A: I believe the difference between QM, QP and QT is the context for which they are used, QM meaning the dynamics for which the particles behave, QP describes the nature of all physical phenomenon and QT is the field of the science attempting to explain the problems and paradoxes involved.


text:
Q: Builder Design Pattern - How to make field only accessible to one of its subtype I have created a builder for client types A and B.
Client TypeA has two fields fieldA and fieldB (see below), while client TypeB has two additional fields. How can I make sure field C and D are only accessible to client TypeB, i.e. client TypeA should not take field fieldC and fieldD when creating it.
Construction client A:
client.builder()
    .withClientType(ClientType.TypeA)
    .withFieldA(fieldA)
    .withFieldB(fieldB)
    .build();

Construction client B:
client.builder()
    .withClientType(ClientType.TypeB)
    .withFieldA(fieldA)
    .withFieldB(fieldB)
    .withFieldC(fieldC)
    .withFieldD(fieldD)
    .build();

What's the correct usage builder pattern in this case?

A: It's not possible to construct instances of different classes using the same Builder. As @RDK has pointed out in the comments you have to implement the Builder pattern for each of your classes.
Builder might have the same hierarchy as the classes they are meant to instantiate. That would allow to reuse the functionality of the parent-builder.
Below, I've provided a hierarchy of Builders inspired by the classic implementation from the "Effective Java" by Joshua Bloch (a former Sun Microsystems employee, who led the design and implementation of many Java platform features, including the Java Collections Framework).
Firstly, it's worth noticing that using Builder with inheritance adds a bit of complexity because methods all methods of the Builder should be self-returning, i.e. in order to chain methods each method except build() returns this instance of Builder. But it should a concrete Builder, not it's parent type (because parent might be unaware of all the methods that child has declared).
The answer to this problem would be a self-referencing generic type, in the "Effective Java"  a generic type with a recursive type parameter. Don't get intimidated, pause for a second and try to recall how java.lang.Enum looks like. Enum<E extends Enum<E>> - that's an example of the self-reference, recursively pointing at a particular subclass of java.lang.Enum.
Similarly, we need a generic builder referencing to itself ClientBuilder<T extends ClientBuilder<T>> and declaring a self-returning abstract method self() (which return an instance of T) that would be implemented by every concrete class.
Note: there's no need in enum ClientType to differentiate between ClientA and ClientB, since they are already different classes.
That how implementation of an AbstractClient and two concrete client, each having static nested Builder might look like.
Abstract classes AbstractClient + ClientBuilder
public abstract class AbstractClient {

    protected ClientType type;
    protected A a;
    protected B b;

    protected AbstractClient(ClientBuilder<?> builder) {
        this.a = builder.a;
        this.b = builder.b;
    }

    public static abstract class ClientBuilder<T extends ClientBuilder<T>> {
        protected A a;
        protected B b;

        public T withFieldA(A a) {
            this.a = a;
            return self();
        }

        public T withFieldB(B b) {
            this.b = b;
            return self();
        }
        // abstract methods
        public abstract AbstractClient build(); // returns a concrete Client
        public abstract T self();               // returns a concrete implementation of ClientBuilder
    }
}

Concrete classes ClientA + ABuilder
public class ClientA extends AbstractClient {

    private ClientA(ABuilder builder) {
        super(builder);
    }

    // other constructors, getters, etc

    public static ABuilder builder() {
        return new ABuilder();
    }

    public static class ABuilder extends AbstractClient.ClientBuilder<ABuilder> {

        @Override
        public ClientA build() {
            return new ClientA(this);
        }

        @Override
        public ABuilder self() {
            return this; // simply returning This instance of Builder
        }
    }
}

Concrete classes ClientB + BBuilder
public static class ClientB extends AbstractClient {

    protected C c;
    protected D d;

    private ClientB(BBuilder builder) {
        super(builder);
        this.c = builder.c;
        this.d = builder.d;
    }

    // other constructors, getters, etc

    public static BBuilder builder() {
        return new BBuilder();
    }

    public static class BBuilder extends AbstractClient.ClientBuilder<BBuilder> {
        protected C c;
        protected D d;

        public BBuilder withFieldC(C c) {
            this.c = c;
            return self();
        }

        public BBuilder withFieldD(D d) {
            this.d = d;
            return self();
        }

        @Override
        public ClientB build() {
            return new ClientB(this);
        }

        @Override
        public BBuilder self() {
            return this; // simply returning This instance of Builder
        }
    }
}

Usage example (dummy classes A, B, C, D are not exposed, use the link below to see the code in action):
public static void main(String[] args) {
    ClientA clientA = ClientA.builder()
        .withFieldA(new A("1"))
        .withFieldB(new B("Alice"))
        .build();

    ClientB clientB = ClientB.builder()
        .withFieldA(new A("2"))
        .withFieldB(new B("Bob"))
        .withFieldC(new C("admin"))
        .withFieldD(new D("fooBar"))
        .build();

    System.out.println(clientA);
    System.out.println(clientB);
}

Output:
ClientA{ a=A[a=1], b=B[b=Alice] }
ClientB{ a=A[a=2], b=B[b=Bob], c=C[c=admin], d=D[d=fooBar] }

A link to Online Demo.

A: Another example that I like. The idea here is, there are several kind of "Root" [A,B,C], each with their own attributes.  At any point you can switch to a different Builder which gives you a different kind of "Root" with common behaviours stored in AbstractBuilder.
It is also possible that they inherit each other and similarly their builders can also inherit each other.
abstract class AbstractBuilder {
    protected String common;

    public AbstractBuilder withCommon(String common){
        this.common = common;
        return this;
    }

    public abstract Root build();
    public A.BuilderA asBuilderA(){
        return new A.BuilderA(common);
    }

    public B.BuilderB asBuilderB(){
        return new B.BuilderB(common);
    }

    public C.BuilderC asBuilderC(){
        return new C.BuilderC(common);
    }
}
abstract class Root{
    private final String common;

    @Override
    public String toString() {
        return "Root{" +
                "common='" + common + '\'' +
                '}';
    }

    Root(String common) {
        this.common = common;
    }
}
class A extends Root {
    private final String a;

    @Override
    public String toString() {
        return "A{" +
                "a='" + a + '\'' +
                "} " + super.toString();
    }

    public A(String common, String a) {
        super(common);
        this.a = a;
    }
    public static class BuilderA extends AbstractBuilder {
        protected String a;

        public BuilderA(String common) {
            super();
            withCommon(common);
        }

        public BuilderA withA(String a){
            this.a = a;
            return this;
        }

        public A build(){
            return new A(common, a);
        }
    }
}

class B  extends Root {
    private final String b;

    @Override
    public String toString() {
        return "B{" +
                "b='" + b + '\'' +
                "} " + super.toString();
    }

    public B(String common, String b) {
        super(common);
        this.b = b;
    }
    public static class BuilderB extends AbstractBuilder {
        protected String b;

        public BuilderB(String common) {
            super();
            withCommon(common);
        }
        public BuilderB withB(String b){
            this.b = b;
            return this;
        }

        public B build(){
            return new B(common, b);
        }
    }
}

class C extends Root {
    private final String c;

    @Override
    public String toString() {
        return "C{" +
                "c='" + c + '\'' +
                "} " + super.toString();
    }

    public C(String common, String c) {
        super(common);
        this.c = c;
    }
    public static class BuilderC extends AbstractBuilder {
        protected String c;

        public BuilderC(String common) {
            super();
            withCommon(common);
        }
        public BuilderC withC(String c){
            this.c = c;
            return this;
        }

        public C build(){
            return new C(common, c);
        }
    }
}

public class BuilderExample {

    public static void main(String[] args) {
        A.BuilderA builderA = new A.BuilderA("common").withA("a")
                .asBuilderB().withB("b")
                .asBuilderC().withC("c")
                .asBuilderA();
        System.out.println(builderA.build()); //A{a='null'} Root{common='common'}
        System.out.println(builderA.withA("aa").build()); //A{a='aa'} Root{common='common'}
        System.out.println(builderA.asBuilderB().withB("bb").build()); //B{b='bb'} Root{common='common'}
    }
}


text:
Q: Create NSMutableArray by a NSString value How I can create a NSMutableArray (name) dynamically by a NSString value?
e.g. NSString *stringName = @"helloArray1";

Then create the NSMutableArray with the "helloArray1" dynamically.
e.g. NSMutableArray * (--here the stringName / helloArray1---) = [NSMutableArray new];

And then the NSLog:
NSLog(@"%@", (--here the stringName / helloArray1---) );

Thanks for your help

A: I think that's not possible.
Better is set dynamically all into object. For example:
NSMutableDictionary *variables = [NSMutableDictionary new];
for (int i = 0; i < 10; i++) {
    NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:@"1", @"2", nil];
    [variables setObject:temp forKey:[NSString stringWithFormat:@"value_%d", i]];
}

NSLog(@"%@", [variables objectForKey:@"value_1"]);