text:
Q: MailChimp OAuth2: Invalid Mailchimp API Key - wrong datacenter - library may not support datacenter mapping scheme I have successfully implemented a one time pass through MailChimp's (MC) six step OAuth2 process, documented at http://apidocs.mailchimp.com/oauth2/, using Python and Django. The problem is I want my users to be able to authorize MC once and then I will use that authorization to make calls to MC in the future (with their permission, of course).
Here's how I am doing it:
Step 1: Redirect use to the MC authorize URI.
(works fine)
Step 2: User enters their MC credentials.
(works fine)
Step 3: User gets redirected back to a URI on my server, and
Step 4: I make a request to the MC access token URI, and
Step 5: MC returns an access token.
headers = {
    'User-Agent': 'oauth2-draft-v10',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'login.mailchimp.com',
    'Accept': 'application/json'
}
payload = {
    'grant_type': 'authorization_code',
    'client_id': settings.MAILCHIMP_CLIENT_ID,
    'client_secret': settings.MAILCHIMP_CLIENT_SECRET,
    'code': code,
    'redirect_uri': settings.MAILCHIMP_REDIRECT_URI
}

response = requests.post(settings.MAILCHIMP_ACCESS_TOKEN_URI, headers=headers, data=payload)
response_dict = response.json()
access_token = response_dict['access_token']

At this point I save the access_token, the datacenter-less API key, in my database.
Step 6: I make a request to the MC metadata URI to get a datacenter.
Note that this step occurs multiple times as I need to make MC calls on the user's behalf, whereas Steps 1-5 only occur once.
headers = {'Authorization': 'OAuth ' + access_token}
response = requests.get(settings.MAILCHIMP_METADATA_URI, headers=headers)
response_dict = response.json()
dc = response_dict['dc']

Step 7: I construct an API key and make MC calls using the Python library.
mkey = access_token + '-' + dc
mcapi = mailchimp.Mailchimp(apikey=mkey)

mcapi.do_something_fun_with_mailchimp()...

The problem is that the final step intermittently returns the error,

Invalid Mailchimp API Key: <key>-dc . You are accessing the wrong datacenter - your client library may not properly support our datacenter mapping scheme.

What am I doing wrong?

A: My workflow is correct, except that I only need to do it once. I can store the access_token and the datacenter (key-dc) in my database and use it for future calls.
Although I still don't know exactly what was causing my problem, I now know that it was not related to this workflow. It's correct.

A: I think the Endpoint in the client library is "http://.api.mailchimp.com" so you need to send the token as only access token as per this part from documentation:

api_endpoint - this is http://.api.mailchimp.com. If you don't
  have a datacenter aware wrapper, use this api endpoint and the
  access_token as your API Key.


text:
Q: Cannot Resolve Symbol Google API Client in Android Studio I'm getting an error in Android Studio for the following:
mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();

I have put this in my manifest,
<meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
and compile 'com.google.android.gms:play-services:6.5.87' in my gradle dependencies.
I've downloaded the required sdk files as well.
Why do I still get this error?

A: I had to do the following to get my app to compile successfully:

*

*Update my build.grade with 'com.google.android.gms:play-services:<version>'

*Add imports as needed:
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

*In Android Studio: File --> Invalidate/Restart...

*Clean build

A: For the benefit of searchers:
If you are following the android tutorial that relates to this, you can add the dependency via the UI.

*

*In Android Studio, go to File > Project Structure.

*Go to the dependencies tab.

*On the right hand side add a 'Library Dependency'.

*Type "com.google.android.gms:play-services" into the searchbox and pick the appropriate dependency.

*Then follow @Dmac's answer

A: Even though not officially listed in the tutorial, you must use the following imports:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

A: I had this problem, only with import com.google.android.gms.common.api.GoogleApiClient;I unfortunately had moved <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> after its relative activity <activity android:name=".MapsActivity" android:label="@string/title_activity_maps" ></activity>. I returned to previous state and the problem was solved.

A: Add following lines to your dependencies to use Google Places Api interfaces
dependecies{compile 'com.google.android.gms:play-services:11.2.0'
testCompile 'junit:junit:4.12'

}

A: Just to log the problem.
This happens when there is version conflict. Check the build message, and it will suggest the version you should be importing.
The classpath version in main gradle (classpath 'com.google.gms:google-services:3.1.0') should be complaint with the version of jar included in the app gradle (compile 'com.google.android.gms:play-services-auth:11.0.0')

A: the question is old ,but now that GoogleApiClient is deprecated I found out that I can't use it anymore and that one should use its substitute,
subclasses of GoogleApi .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Unable to generate unique count for 10 counts for my practical work. This question requires me to generate 10 separate unique counts from a range (1, 1000). Each count supposes to generate a total of 10 numbers of odd and even numbers. I can only use a while loop to execute 10 unique counts. Any help would be appreciated thanks!
SAMPLE OUTPUT QUOTED

*

*Out of 100 random numbers, 56 were odd, and 44 were even.

*Out of 100 random numbers, 60 were odd, and 40 were even.

*Out of 100 random numbers, 47 were odd, and 53 were even.

*Out of 100 random numbers, 54 were odd, and 46 were even.

*Out of 100 random numbers, 48 were odd, and 52 were even.

*Out of 100 random numbers, 53 were odd, and 47 were even.

*Out of 100 random numbers, 46 were odd, and 54 were even.

*Out of 100 random numbers, 52 were odd, and 48 were even.

*Out of 100 random numbers, 53 were odd, and 47 were even.

*Out of 100 random numbers, 48 were odd, and 52 were even.

MY OUTPUT

*

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

*Out of 100 random numbers, 51 were odd, 49 were even.

MY CODE
import random

# loop counter for 100 random numbers
loop = 0
# part of end result
msg = 'Out of 100 random numbers,'
# count for even numbers
even_count = 0
# count for odd numbers
odd_count = 0
# gen  number counter
gen_num01 = False
#loop count event
loop_count = 0

#Counter for 10 loop_count event
    loop_count_event = False
while loop_count < 10:
loop_count += 1

#while count for 100 random numbers
while loop < 100:

    num_gen = random.randint(1,1000)
    loop += 1

    if num_gen % 2 == 0:

        even_count += 1
        msg02 = 'were even.'

    elif num_gen % 2 > 0:

        odd_count += 1
        msg01 = 'were odd,'

if gen_num01 == False:

    print(msg, odd_count, msg01, even_count, msg02)

A: Looks like you are not initializing the loop counter each time, so the inner loop isn't executing, and you are not initializing the counters either.
You also don't need to set msg01 & msg02 on each number since you always initialize them to the same thing.
Try this:
import random

# loop counter for 100 random numbers
loop = 0
# part of end result
msg = 'Out of 100 random numbers,'
# count for even numbers
even_count = 0
# count for odd numbers
odd_count = 0
# gen  number counter
gen_num01 = False
#loop count event
loop_count = 0
#Counter for 10 loop_count event loop_count_event = False
msg02 = 'were even.'
msg01 = 'were odd,'

while loop_count < 10:

    loop_count += 1
    even_count = 0
    odd_count = 0
    loop = 0

    #while count for 100 random numbers
    while loop < 100:

        num_gen = random.randint(1,1000)
        loop += 1

        if num_gen % 2 == 0:
            even_count += 1
        else:
            odd_count += 1

if gen_num01 == False:
    print(msg, odd_count, msg01, even_count, msg02)

A: Your results are not uncommon, this is simply the way pseudo-random generators work. If you are using > python 3.2, then go for random.randrange(0, 100). Here's a quote from the documentation of the function:

Changed in version 3.2: randran
  ge() is more sophisticated about
  producing equally distributed values. Formerly it used a style like
  int(random()*n) which could produce slightly uneven distributions.

Otherwise, another solution may be int(random.uniform(0, 1) * 100).

A: You need to reinitialise loop to zero each time through the outer loop.
What's happening is that for the first outer loop, the loop variable is going from zero to a hundred (or thereabouts). Then, on subsequent outer loops, the inner loop isn't running because its control variable is already too high.
That's why you're getting exactly the same counts for odd and even, despite the fact they're not zeroed either, which would normally result in the values accumulating.
The following code shows what I mean:
import random

msg = 'Out of 100 random numbers,'

for loop_count in xrange(10):
    even_count = 0
    odd_count = 0

    for loop in xrange(100):
        num_gen = random.randint(1,1000)

        if num_gen % 2 == 0:

            even_count += 1
            msg02 = 'were even.'

        elif num_gen % 2 > 0:

            odd_count += 1
            msg01 = 'were odd,'

    print(msg, odd_count, msg01, even_count, msg02)

and it gives the output:
('Out of 100 random numbers,', 48, 'were odd,', 52, 'were even.')
('Out of 100 random numbers,', 52, 'were odd,', 48, 'were even.')
('Out of 100 random numbers,', 46, 'were odd,', 54, 'were even.')
('Out of 100 random numbers,', 43, 'were odd,', 57, 'were even.')
('Out of 100 random numbers,', 44, 'were odd,', 56, 'were even.')
('Out of 100 random numbers,', 42, 'were odd,', 58, 'were even.')
('Out of 100 random numbers,', 49, 'were odd,', 51, 'were even.')
('Out of 100 random numbers,', 54, 'were odd,', 46, 'were even.')
('Out of 100 random numbers,', 57, 'were odd,', 43, 'were even.')
('Out of 100 random numbers,', 55, 'were odd,', 45, 'were even.')


text:
Q: Accessing Javascript Object Keys I'm having the hardest figuring out how to this (seems so simple).
I have a Javascript Object as shown here
Output of console.log(data):
{"prevExists":false,"pubKey":"b5","ID":"5f1"}

I'm trying to access the different key value pairs.
When I try the expected methods, I get back undefined.
I have tried:
var pubKey = "pubKey";
data.pubKey
data[pubkey];
data["pubKey"];

I know I'm missing something really obvious here.

A: You have several ways of accessing keys, depending on which keys you're talking about.
In your example, any of those would work:
var data = {
    "prevExists":false,
    "pubKey":"b5",
    "ID":"5f1"
};

// Access all keys of enumerable string-keyed properties
Object.keys(data).forEach((key) => console.log(key,data[key]));
// Access all keys of enumerable and non-enumerable string-keyed properties
Object.getOwnPropertyNames(data).forEach((key) => console.log(key,data[key]));
// Access all keys of enumerable string-keyed properties of your object, its prototype, and all the prototype chain...
for (let key in data)
    console.log(key,data[key]);

If you want to have a better understanding of what is an object's property, you can have a look at this recent answer I wrote on the topic.

A: You can use Object.keys and a foreach loop to access the properties on the object.

var data = {"prevExists":false,"key":"b5","ID":"5f1"};

Object.keys(data).forEach(function(key) {
    console.log('key - ' + key + ' :: value - ' + data[key]);
});

A: First you need to create a reference to your object. Like this:
var myObj = { "prevExists": false, "key": "b5", "ID": "5f1" };

Then, you can access the elements using their keys:
console.log(myObj["prevExists"]);

Console exit:
false

Good luck!

A: Use the Object.keys method

var data = {"prevExists":false,"pubKey":"b5","ID":"5f1"}
console.log(Object.keys(data));

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

A: You are confusing yourself with the line var pubKey="pubKey".
There are 2 ways to access object parameters:
const data = {"prevExists":false,"pubKey":"b5","ID":"5f1"};
// var pubKey = "pubKey"; This line is not needed

1) data.pubKey
If you use the dot operator (.), then you reference it with the key name.
2) data["pubKey"];
If you use brackets ([]), then you use the string that matches the key.
If you add the line:
const pubKey = "pubKey";

, then data[pubKey] will also work, because it evaluates to data["pubKey"]


text:
Q: react-data-table-component with nested tables I am using react-data-table-component in a node/react page. I have 2 data sets, List and ListNested.
list is a collections of document data (xlsm to be specific) that has the most recent version of the document on each row.
listNested is a similar data set, but contains all previous versions of each record in list (if they exist).
I have my parent table defined as:
return(
  <DataTable
    title="Documents"
    columns={columns}
    data={list}
    pagination={true}
    fixedHeader={true}
    keyField="document_id"
    striped={true}
    highlightOnHover={true}
    noDataComponent=

      <Loader
        type="Oval"
        color="#005ea2"
        height={100}
        width={100} />

    persistTableHead={true}
    defaultSortField="updated_at"
    defaultSortAsc={false}
    overflowY={true}

    expandableRows
    expandableRowDisabled={row => row.disabled}
    expandableRowsComponent={<ExpanableComponent />}

  />
);

and my ExpandableComponent defined as:
const ExpanableComponent = ({listNested}) =>
  <DataTable
    columns={columnsNested}
    data={listNested}
    pagination={true}
    fixedHeader={true}
    keyField="doc_name"
    striped={true}
    highlightOnHover={true}
    noDataComponent=
No previous versions of this document were found.

    persistTableHead={true}
    defaultSortField="updated_at"
    defaultSortAsc={false}
    overflowY={true}
  />;

the documentation [Here] does not clearly define this type of nesting. I tried using the doc_name attribute as the keyField, but it doesn't work properly. The nested data shows up in the parent table instead of nested table, but the nested table headings DO show up in the nested row.
In the picture below, rows 2 and 3 are coming from the listNested data set in the ExpandableComponent and should be nested under row 1. however, row 1 shows an empty data set (circled).

I verified the lists both have the data I want them to, I am just stuck on how to stick the second list into the nested section.

A: To make this work you have to call your prop exactly data, not listNested, like this:
const ExpanableComponent = ({data, ...props}) =>
  <DataTable data={data} {...props}/>

By the way, it even works with calling itself as an expandableRowsComponent.
export default function MyDataTable({data, ...props}) {
    return <Datatable
        expandableRows
        expandableRowsComponent={<MyDataTable className="ml-3"/>}
        noTableHead={!!data}
        noHeader={!!data}
        {...props}
    />
}

To use this component you don't have to use prop data. Two latter props indicate that if  data is undefined (since [] is still truthy), then the table doesn't show anything.

A: I added {data} argument as the first argument in the props of expandable component and it worked for me.


text:
Q: Angular 2 Typescript Object is undefined after attempting to map json data to it I have this json data that is being returned from the server that won't map to my typescript object. I am sure it's a small issue but I can't find it, nor can my teammate.
JSON:
{"labels: ["foo","bar"],  "sums":null, "sid":0, "cid":0}
My typescript object:

import {Claim} from './Claim';
import {ResponseInfo} from './ResponseInfo';
import {Rule} from './Rule';
import {ServiceLine} from './ServiceLine';

export interface ClaimResponse {
    labels: string[];
}

This is my service:

import {Injectable} from '@angular/core';
import {Observable}    from 'rxjs/Observable';
import {RequestOptions, Http, Response, Headers, URLSearchParams} from '@angular/http';
import {ClaimResponse} from './ClaimResponse';

@Injectable()
export class EvaluationDetailService {
    constructor(private http: Http) { }

    getEvaluationDetail(): Observable<ClaimResponse> {
        return this.http.get('./EvaluationDetail/GetEvaluationDetail')
            .map((res: Response) => <ClaimResponse>res.json())
            .do(data => console.log(JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Here is my component:

@Component({
    selector: 'claim-evaluationdetail',
    templateUrl: './Scripts/EvaluationDetail/evaluationdetail.component.html',
    providers: [EvaluationDetailService, HTTP_PROVIDERS],
    directives: [ResponseInfoComponent, ServiceLineComponent, OverlayPanel]
})

export class EvaluationDetailComponent implements OnInit {
    constructor(private _evaluationDetailService: EvaluationDetailService) { }

    claimResponse: ClaimResponse    ;
    visible: boolean = false;
    showRules: boolean = false;

    ngOnInit() {
        this.getClaimResponse();
    }

    getClaimResponse() {
        this._evaluationDetailService.getEvaluationDetail().subscribe(claimResponse => this.claimResponse = claimResponse);
    }
}

The data gets returned perfectly fine from the server (see the JSON data above), but if I try to access anything involving "this.claimResponse", it is undefined.
What am I doing wrong?

A: I think you have the same problem I had minutes ago.
In your componentes.html put
*ngIf="claimResponse"

before trying to access any of its properties.
I hope it helps

A: Either as @AndrésGuibarra wrote wrap your template with
<div *ngIf="claimResponse">

so it doesn't get rendered until data is available or use the safe-navigation (Elvis) operator to avoid errors when claimResponse is null and Angular tries to access properties:
claimResponse?.someProp


text:
Q: When click expand button, scroll fit current expand contents in react First, I apologize for not explaining well.
When I create multiple Accordion using mui(each AccordionDetails height are 80vh). How can I see the entire content of that selected Accordion?
Thank you.
I attached a screenshot for better understanding and code.
SOLUTION
I solved this one using useref and scrollIntoView.

import React, {useState} from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export default function Example() {
    const [data, setData] = useState([
        {name:"hello",desc:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget."},
        {name:"hello",desc:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget."},
        {name:"hello",desc:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget."},
        {name:"hello",desc:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget."},
    ])

    return (
    <div>
      {data.map((data) => {
        return(
         <Accordion>
         <AccordionSummary
           expandIcon={<ExpandMoreIcon />}
           aria-controls="panel1a-content"
           id="panel1a-header"
         >
           <Typography>{data.name}</Typography>
         </AccordionSummary>
         <AccordionDetails style={{height:"100vh"}}>
           <Typography>
             {data.desc}
           </Typography>
         </AccordionDetails>
       </Accordion>
        )
      })}
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


text:
Q: Oracle Standby Database - Archivelog GAP Good Afternoon!
I've done some research around fixing archivelog gap between Primary and Standby databases, and a few links provide tips on the querying V$archived_log, v$archive_gap and v$log_history. They are really great source of information, however, I have a scenario in which both servers need to have archivelog retention due storage limits, so standby database let's say, has archivelog sequences from D to P, and from P to R, being R today's.
What would be the implications, apart from having missing data, in a case of need to put standby temporarily as production db in case of failure? Would it work, or the best practice is to recreate stdb database and apply only continuous archives from now on?
Thanks.

A: Assuming you mean that the database is "missing" logs from P->R, and that your primary database no longer has those logs either, then the answer is that you'll have a functional database (upon standby activation as a primary) but you will be missing data from P-> the Activation point.
The thing to remember here is that your standby is only as good as your last archive log that was fully applied. Without intervention on your part, your standby database is essentially frozen in time, and will never advance.
If you're missing archive logs, and they are truly unrecoverable (did you check storage backups? Backups to tape?), then your standby, IMO, is worthless as a production level standby. You, and your business, may have a different opinion based on your usage of the database in question.
But if this was truly a production level standby database that is meant to take over for production in a disaster scenario, personally, I would rebuild the standby immediately.

A: If you found gap in your standby and the archived logs are deleted. You may try resolving gaps with incremental backups. Takes less time and trouble (especially if the DB size is big), than creating a standy from ground up.
 Resolving Gaps in Data Guard Apply Using Incremental RMAN BAckup


text:
Q: Django model data not appearing My model data for my website wont appear on new page when using slug and I am unsure as to why this is happening as I managed to get it to work with the previous page of the website but when I try to call it on my html page nothing will load now and I use the slug in the view to access the page.
Models.py
class Parasite(models.Model):
    name = models.CharField(max_length=128, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(max_length=100000)
    image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Parasite, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

views.py
def view_parasite(request,parasite_name_slug):
    context_dict = {}
    try:
        parasite = Parasite.objects.get(slug=parasite_name_slug)
        context_dict['parasites'] = parasite
    except Parasite.DoesNotExist:
       context_dict['parasites'] = None
    return render(request, 'parasites_app/viewpara.html', context = context_dict)

viewpara.html
{% extends 'parasites_app/base.html' %}
{% load static %}
{% block content_block %}

{% for p in parasite %}
    <h3>{{p.name}}</h3>

{% endfor %}

{% endblock %}

urls.py
 urlpatterns = [

             path('login/', views.user_login, name='login'),
                path('logout/', views.user_logout, name='logout'),
                path('admin/', admin.site.urls),
                path('', views.public, name='public'),
                path('public/', views.public, name='public'),
                path('private/', views.logged_in_content, name='private'),
                path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'),
                path('<slug:post_name_slug>/', views.show_post, name='show_post'),

        ]

        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

A: First mistake - you are getting one Parasite object (cause you use method get) and you call it with plural name 'parasites':
parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasites'] = parasite

Second mistake - when you want to show it in template, you call for single parasite, but you decided to name the key parasites.
{% for p in parasite %}

Third mistake - don't use for loop for one object, just call it.
Answer:
views.py
parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasite'] = parasite

viewpara.html
{% block content_block %}

    {{ parasite.name }}

{% endblock %}


text:
Q: How to get Display Name Attribute using PropertyDescriptor C# ASP.NET MVC 4 I am using property descriptor to generically iterate over the properties and print their attribute names as table header. It works fine printing the property name, but not for the [Display(Name = "Test")]
Class:
public class Transaction
{
    [Display(Name = "Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number

Markup:
    @foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(Model[0]))
    {
       @descriptor.DisplayName;
    }

Just prints the "DELETE" name rather than "Test".  The descriptor has a Name, and DisplayName option and both are set to "DELETE"
What am I doing wrong?

A: You have to use [DisplayName("Test")] instead of [Display(Name = "Test")], please check this:
public class Transaction
{
    //[Display(Name = "Test")]
    [DisplayName("Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number
}

You can check this in DotNetFiddle.

A: Use [DisplayName("Test")] in place of [Display(Name = "Test")]


text:
Q: Printf between two different for loops not working I am trying to debug using printf. I have inserted it between for loops, but I do not receive the output of it. I am certain that the algorithm is continuing after it and arriving to the end, it's like the reader is ignoring it.
Here's the code :
for (i = 0; i < lower; ++i) {
    buf3[i] = (buf[i] + buf2[i] )/2;
    printf("\n %d",buf3[i]);
}
printf("hiiiiiiiiiiiiiiiiiiii %d",i);

for (i; i < upper; ++i) {
    if (upper == num2) {
        buf3[i] += buf2[i]/2;
        printf("\n %d",buf3[i]);

    }
    else {
        buf3[i] += buf[i]/2;
        printf("\n %d",buf3[i]);

    }
}

printf("\n %d",upper);

The "hiiiii..." message is the one not being seen on the screen. (I tried replacing it by many other messages such as int or anything else, but in vain. I also tried to put another printf right above the first for loop, again it returned nothing).
Please note that upper and lower aren't huge numbers.
Thanks in advance.

A: The printf in question does not print a newline, so the output is buffered until a later printf prints a newline.
Add the newline, and you should see the output:
printf("hiiiiiiiiiiiiiiiiiiii %d\n",i);

A: Try adding \n after %d.
Also i is not initialised in the second loop


text:
Q: Trying to make a chrome extension with socket.io I am trying to make my chrome extension using socket.io, but I am facing a lot of difficulties importing the socket.io client into my application.
I am using Manifest V3 which means I only have one service_worker, so I tried using importScripts but that does not work for some reason. I cannot call the io() function after using importScripts. Then I tried changing the Content Security Policy to get it from the CDN but I get an error saying that it's invalid.
Any idea on how I can do this?

A: About the importScripts, you can try to bundle the background script by using webpack, rollup or esbuild. This will make it more complicated, or you can search a boilerplate on github.
Service worker may be inactive at any time. so that you won't be able to stay connected to the server all the time when you use socketio on service worker. Otherwise you need some hack to keep service worker alive. For example, content scripts sendMessage to it orderly and continuously. (I just imagined it this way but haven't try it yet.)


text:
Q: Magento 1.9: Google Payment Gateway module I'm looking for a module for Magento Google Pay Gateway method, please help me, I'm stuck. How to get module or from where I can get, or otherwise is it required to used third party payment gateway module ?

A: For Magento 2, This module contains Google Pay:
https://marketplace.magento.com/paypal-module-braintree.html

But For Magento 1 We Don't have Ready Made module:
You have to Create module by your own : Reference are Click Here, Click Here


text:
Q: UPDATE apenas nas últimas linhas inseridas Estou importando algumas planilhas Excel via ETL para um banco relacional. O problema é que para que eu consiga realizar o relacionamento das tabelas, estou usando consultas para a inserção das chaves estrangeiras. Porém, conforme o banco cresce, essas consultas estão levando um tempo absurdamente grande.
Existe alguma forma de realizar um UPDATE apenas nos últimos registros que foram incluídos? Por exemplo:
UPDATE estrutura q
SET q.id_horizonte = (SELECT h.id_horizonte FROM horizonte h
WHERE q.observacao = h.observacao AND q.nome_horizonte = h.nome_horizonte AND q.amostra_codigo = h.amostra_codigo)
LIMIT 50

Não está funcionando dessa forma, mas a minha pergunta é justamente essa: existe alguma maneira para que esse UPDATE não seja aplicado em todos os registros da tabela e só nos últimos 50 incluídos? Isso ajudaria muito com o desempenho das consultas.

A: Experimente
UPDATE estrutura q
SET q.id_horizonte =
(SELECT h.id_horizonte
FROM horizonte h
WHERE q.observacao = h.observacao
AND q.nome_horizonte = h.nome_horizonte
AND q.amostra_codigo = h.amostra_codigo)
WHERE q.id_horizonte
IN
(SELECT id_horizonte
FROM estrutura
ORDER BY id_horizonte DESC Limit 50)

A: Consegui resolver colocando uma condição simples no meu UPDATE. No meu caso funcionou porque os campos que eu quero atualizar estão sempre nulos.
UPDATE estrutura q
SET q.id_horizonte = (SELECT h.id_horizonte FROM horizonte h
WHERE q.observacao = h.observacao AND q.nome_horizonte = h.nome_horizonte AND q.amostra_codigo = h.amostra_codigo)
WHERE id_horizonte IS NULL


text:
Q: Equivalent of dplyr rowwsie combn in data.table I have this code which performs combn on all the values of a particular dataframe. It is done by using dplyr rowwise
library(dplyr,warn.conflicts = FALSE)
library(tidyr)
Column1<-c("red","blue")#creating column1
Column2<-c("green","white")#creating column2
Column3<-c("aqua","magenta")#creating column2
df_1<-data.frame(Column1, Column2, Column3)#creating data frame
df_2 <- df_1 %>% rowwise() %>%
  mutate(COMB=list(combn(c_across(Column1:Column3),2,simplify = FALSE))) %>%
  unnest(cols = COMB) %>%
  unnest(cols=COMB)

Created on 2020-11-07 by the reprex package (v0.3.0)
It results in following
| \# A tibble: 12 x 4                |
|------------------------------------|
|    Column1 Column2 Column3 COMB    |
|    <chr>   <chr>   <chr>   <chr>   |
|  1 red     green   aqua    red     |
|  2 red     green   aqua    green   |
|  3 red     green   aqua    red     |
|  4 red     green   aqua    aqua    |
|  5 red     green   aqua    green   |
|  6 red     green   aqua    aqua    |
|  7 blue    white   magenta blue    |
|  8 blue    white   magenta white   |
|  9 blue    white   magenta blue    |
| 10 blue    white   magenta magenta |
| 11 blue    white   magenta white   |
| 12 blue    white   magenta magenta |

Is it possible to perform a rowwise combn function in data.table. For e.g. on the following
library(data.table)
Column1<-c("red","blue")#creating column1
Column2<-c("green","white")#creating column2
Column3<-c("aqua","magenta")#creating column2
df_1<-data.table(Column1, Column2, Column3)#creating DT

Created on 2020-11-07 by the reprex package (v0.3.0)

A: With data.table, we can create the 'COMB' using Map
library(data.table)
setDT(df_1)[, COMB := list(do.call(Map, c(f1, .SD)))]

where
f1 <- function(...) combn(c(...), m = 2, simplify = FALSE)

Or if we want to expand the rows
out <- df_1[, grp := seq_len(.N)][df_1[,
      combn(unlist(.SD), 2), .(grp)], on = .(grp)][, grp := NULL]
setnames(out, 'V1', 'COMB')

-output
out
#    Column1 Column2 Column3    COMB
# 1:     red   green    aqua     red
# 2:     red   green    aqua   green
# 3:     red   green    aqua     red
# 4:     red   green    aqua    aqua
# 5:     red   green    aqua   green
# 6:     red   green    aqua    aqua
# 7:    blue   white magenta    blue
# 8:    blue   white magenta   white
# 9:    blue   white magenta    blue
#10:    blue   white magenta magenta
#11:    blue   white magenta   white
#12:    blue   white magenta magenta

A: You can get the data in long format and create combinations for each row.
library(data.table)

df_1[, row := seq_len(.N)]
df_2 <- melt(df_1, id.vars = 'row')
df_1[df_2[, combn(value, 2), row], on = 'row'][, row := NULL][]

#    Column1 Column2 Column3      V1
# 1:     red   green    aqua     red
# 2:     red   green    aqua   green
# 3:     red   green    aqua     red
# 4:     red   green    aqua    aqua
# 5:     red   green    aqua   green
# 6:     red   green    aqua    aqua
# 7:    blue   white magenta    blue
# 8:    blue   white magenta   white
# 9:    blue   white magenta    blue
#10:    blue   white magenta magenta
#11:    blue   white magenta   white
#12:    blue   white magenta magenta


text:
Q: How to use if="some condition" in ZK template tag I have a <template> tag in my ZUL file, and I want to use this template when some condition accured (for example, when some LABEL's value change to some text).
Please look at below code... As you can see, "templateStatus" is my label's name, but it did not work.
How can I fix this issue?
    <template name="allTaskTemplate" var="allTask" if="templateStatus.value == 'allTask'">
        <row>
            <label value="" />
            <label value="@load(allTask.documentDTO.docTypeDTO.title)"/>
            <label value="@load(allTask.documentDTO.docNumber)"/>
            <label value="@load(allTask.documentDTO.docDateTime)"/>
            <label value="@load(allTask.assignerID)"/>
            <label value="@load(allTask.assigneeID)"/>
            <label value="@load(allTask.assignDateTime)"/>
            <label value="@load(allTask.assignDateTime)"/>
            <label value="@load(allTask.assignDateTime)"/>
            <label value="@load(allTask.assignDateTime)"/>
            <label value="@load(allTask.documentDTO.docTypeStateDTO.stateActionDTO.actionDTO.title)"/>
            <label value="@load(allTask.catalogDTO.catalogTypeDTO.title)"/>
        </row>
    </template>
</grid>

A: Using an if statement:
<zk if="${vm.type=='foo'}">
    <!-- Child components -->
</zk>

<zk if="${vm.type=='check'}">
    <!-- Child components -->
</zk>

<zk if="${vm.type=='something'}">
    <!-- Child components -->
</zk>

<zk if="${vm.type=='value'}">
    <!-- Child components -->
</zk>

A: See the below example of ZK. You can use conditional templates...
<grid model="@bind(vm.itemList) @template(vm.type eq 'foo'?'template1':'template2')">
    <template name="template1">
    <!-- child components -->
    </template>

    <template name="template2">
    <!-- child components -->
    </template>
</grid>

For more information, you can see the official page of ZK, Collection and Selection.
Se the below code for...
   <menubar id="mbar" children="@bind(vm.menuList) @template(empty each.children?'menuitem':'menu')">
    <template name="menu" var="menu">
        <menu label="@bind(menu.name)">
            <menupopup children="@bind(menu.children) @template(empty each.children?'menuitem':'menu')"/>
        </menu>
    </template>
    <template name="menuitem" var="item">
        <menuitem label="@bind(item.name)" onClick="@command('menuClicked',node=item)" />
    </template>
</menubar>

See the above. Using more than two templates you can do something like this. I don't know your requirement, but you can use the above logic and implement it in your code.
Or you can see the ZK Forum for the same, Zk forum.


text:
Q: How to retrieve text value from input-tag element? I need to retreive phone number from the UI element which looks like this:

And here is the HTML-code of this element:
<label class="card__phone input">
    <input class="input__text ng-pristine ng-untouched ng-valid ng-valid-mask ng-not-empty" ng-model="person.msisdn" ui-mask="+9 (999) 999-9999" disabled="" placeholder="+_ (___) ___-____" type="text">
</label>

As you can see, we do not have a phone number data in this element, just format. I've tried to find the number using .//*[contains(text(), '+7 (921) 222-3344')] XPATH search - no results.
Forntend engeneers use Angular JS to build current web-app.

A: Well, the answer is to getAttribute("value"), from the WebElement.


text:
Q: What does the orthogonalisation step for U and V in SVD do exactly? I'm reading about Singular Value Decomposition and I'm confused about one aspect. I hope someone can clarify this for me.
So the SVD looks like this: $C = U \Sigma V^T$. One always notes something like "the columns of $U$ are orthonormal eigenvectors of $A A^T$, the columns of $V$ are orthonormal eigenvectors of $A^T A$.
What I'm confused about is: what if the U and V matrices are not orthogonal? I've come along an example which calculates the eigenvectors and values of $AA^T$ and $A^T A$, which are then orthogonalized. But then U and V do not actually contain the eigenvectors as columns anymore, right? Does this have implications for SVD to be exact? Is this an approximation then?

A: The spectral theorem tells us that for any symmetric matrix (such as $AA^T$ or $A^TA$) we can choose orthonormal eigenvectors.  When we "orthogonalize" $U$, we start with any eigenvectors of $AA^T$, then mess around with them (that is, apply the Gram Schmidt process) to get new columns for $U$ that are both eigenvectors of $AA^T$ and orthonormal. It is possible to do this precisely because $AA^T$ is a symmetric matrix.
If the matrices $U$ and $V$ were not orthogonal, then SVD would be a lot less convenient (and useful). In particular, instead of writing $A = U\Sigma V^T$, we'd have to write $A = U \Sigma V^{-1}$.  Things go further downhill if you try to apply SVD.


text:
Q: How can I test a custom android ROM on sdk emulator? Hey I want to test a ROM on android emulator?
Can I convert somehow the zip file to an system.img file? Or can I reboot the emulator in recovery mode?


text:
Q: MYSQL SELECT DISTINCT songid, time ORDER BY TIME i have a currently listening box on the homepage of my music website, and i have a table like this:
id,userid,songid,time

now every time a user plays a song, the id of the song is inserted into the songid field and also the time. so sometimes i have duplicate songid (inserted by different users).
Now here is my sql statement:
SELECT DISTINCT songid,time FROM songs ORDER BY time DESC LIMIT 10

that gives me the last ten songs that were listened, however sometimes it returns duplicate data too! how can i fix this problem? Thanks in advance

A: If the time is the datetime the song was last played, you can group the gons with the last time each was played:
SELECT songid,MAX(time)
FROM songs
GROUP BY songid
ORDER BY time DESC
LIMIT 10

A: You'll want to aggregate over songid:
SELECT songid, MAX(time) AS most_recent_time
FROM songs
GROUP BY songid
ORDER BY most_recent_time DESC
LIMIT 10

A: SELECT  *
FROM    songs s
WHERE   id =
        (
        SELECT  id
        FROM    songs si
        WHERE   si.songid = s.songid
        ORDER BY
                si.songid DESC, si.time DESC, si.id DESC
        LIMIT 1
        )
ORDER BY
        time DESC, id DESC
LIMIT 10

Create the following indexes:
songs (songid, time, id)
songs (time, id)

for this to work fast.
Unlike the GROUP BY songid solutions, this does not require a full table scan or a full index loose scan on songs.


text:
Q: Command "Let\newpage\relax" cuts my bibliography! I' have used Latex to write my M2 Master, and I must say it is a fantastic tool, but as a complete noob I had a lot of hard time finding and understanding which commands I needed for what purpose. Anyway I ended up with something that I liked in the end. Yet just yesterday, checking my bibliography to get a reference for the thesis I am now preparing... I noticed that some references missed at the end of my bibliography, more precisely that my bibliography was interrupted before my Webography began.

So I searched for a little moment, and then I analyzed the code section where the bibliography is supposed to be printed:
\defbibfilter{web}{
    type=misc or
    type=online
}

{\let\newpage\relax
\printbibliography[heading=bibintoc, title={Bibliographie},nottype=misc, nottype=online]}
{\let\newpage\relax
\printbibliography[heading=bibintoc, title={Webographie},filter=web]}

\newpage
\listoffigures

\newpage

At the end of my bibliography print, and just before the print of the webography, I have this \let\newpage\relax command. As I have written this months ago, I didn't remember why I had written that XD, so I replaced by
\newpage

Complied and...pouf! my bibliography wasn't cut anymore.

So yes, basically I have solved my problem alone, but I didn't understand why the command \let\newpage\relax created that bug. Moreover, replacing all occurrences of that command by "\newpage" doesn't change a thing.
So my question: can someone explain me what exactly does \let\newpage\relax do, and why in my case it did cut my bibliography before the end?
Thank you!!


text:
Q: Removing a prefix from a string Trying to strip the "0b1" from the left end of a binary number.
The following code results in stripping all of binary object. (not good)
>>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11)
>>> aan=bbn.lstrip("0b1")  #Try stripping all left-end junk at once.
>>> print aan    #oops all gone.
''

So I did the .lstrip() in two steps:
>>> bbn = '0b1000101110100010111010001' #    Same fraction expqansion
>>> aan=bbn.lstrip("0b")# Had done this before.
>>> print aan    #Extra "1" still there.
'1000101110100010111010001'
>>> aan=aan.lstrip("1")#  If at first you don't succeed...
>>> print aan    #YES!
'000101110100010111010001'

What's the deal?
Thanks again for solving this in one simple step. (see my previous question)

A: In Python 3.9 you can use bbn.removeprefix('0b1').
(Actually this question has been mentioned as part of the rationale in PEP 616.)

A: The strip family treat the arg as a set of characters to be removed. The default set is "all whitespace characters".
You want:
if strg.startswith("0b1"):
   strg = strg[3:]

A: No. Stripping removes all characters in the sequence passed, not just the literal sequence. Slice the string if you want to remove a fixed length.

A: This is the way lstrip works. It removes any of the characters in the parameter, not necessarily the string as a whole. In the first example, since the input consisted of only those characters, nothing was left.

A: Lstrip is removing any of the characters in the string. So, as well as the initial 0b1, it is removing all zeros and all ones. Hence it is all gone!

A: @Harryooo: lstrip only takes the characters off the left hand end. So, because there's only one 1 before the first 0, it removes that. If the number started 0b11100101..., calling a.strip('0b').strip('1') would remove the first three ones, so you'd be left with 00101.

A: >>> i = 0b1000101110100010111010001
>>> print(bin(i))
'0b1000101110100010111010001'

>>> print(format(i, '#b'))
'0b1000101110100010111010001'
>>> print(format(i, 'b'))
'1000101110100010111010001'

See Example in python tutor:
From the standard doucmentation (See standard documentation for function bin()):
bin(x)
Convert an integer number to a binary string prefixed with "0b". The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. Some examples:
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix "0b" is desired or not, you can use either of the following ways.
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.


text:
Q: Numpy: Why can'I assign a matrix to another matrix's indexed part? Why can't I assign value of an indexed part of matrix from another matrix? Let's see the code example below:
n, m = 5, 10
X = np.random.randint(0, 10, (n, n))
indices = np.random.randint(0, m, (n,))

res1 = np.zeros((m, m))
res2 = np.zeros((m, m))
res3 = np.zeros((m, m))

for i in range(n):
    for j in range(n):
        res1[indices[i], indices[j]] = X[i, j]

res2[:n, :n] = X # ========================================================
(res2[:n, :n] == X).all() # ===============================================
# True (assign to continuous blocks is ok)

res2[indices, ...][:, indices] = X  # directly index from array and assign value
(res2 == res1).all()
# False, res2 stays all-zero

row_mat, col_mat = np.meshgrid(indices, indices)[::-1]
points_arr = np.stack([np.ravel(row_mat), np.ravel(col_mat)]).T
rows, cols = zip(*points_arr)
res3[rows, cols] = X.flatten()
(res3==res1).all()
# True

The toy sample shown in above codes is to copy an array X's value to another array res by coordinate-to-coordinate mapping. res1 shows the for loop implementing this. We're all familiar with the expression commented with ====, where continuous blocks' value can be jointly assigned (is it really "continuous" in memory?). However this is not applicable to enumerated index, as is shown in res2. copy.deepcopy doesn't work either.
Yes I've figured out a way to achieve this (as res3). First create meshgrid of indexed coordinates, and then use tuple indexing like assigning a long list of points.
But why? What's the numpy logic behind this? Are there any similar fallible points? Anyone who could explain this is appreciated!

A: When you do:
res2[indices, ...][:, indices] = X

The part res2[indices, ...] creates a new array independent of res2, because you are using advanced indexing. The later bit [:, indices] = X will assign values to that new array, not to res2. To achieve what you want, you can use np.ix_:
res2[np.ix_(indices, indices)] = X


text:
Q: Cocoa Bindings: NSObjectController not KVC-compliant for the representedObject property I've been through a bunch of Core Data examples and the Apple documentation.  I'm at a wall after working on this all day.
All I want to happen is I type some text into a text field, save the file, open it again and see the text there.
I made a very very simple Core Data document-based app to experiment. Here are the particulars:
1) The data model has one Entity ("Note") with one attribute ("title") which is an NSString.
2) I created a view controller "ManagingViewController" that loads in a view called "NoteView" into a box in MyDocument.xib without a problem.  NoteView.nib has just one NSTextField in it.
ManagingViewController.h
#import <Cocoa/Cocoa.h>
#import "Note.h"

@interface ManagingViewController : NSViewController {
NSManagedObjectContext *managedObjectContext;
IBOutlet NSTextField *title;

}
@property (retain) NSManagedObjectContext *managedObjectContext;
@property (retain, readwrite) NSTextField *title;
@end

and ManagingViewController.m
#import "ManagingViewController.h"
#import "Note.h"

@implementation ManagingViewController
@synthesize managedObjectContext;
@synthesize title;

- (id)init
{

    if (![super initWithNibName:@"NoteView" bundle:nil]) {
        return nil;
    }

    return self;

}
@end

I have a NSManagedObject called "Note.h"
#import <CoreData/CoreData.h>
#import "ManagingViewController.h"
@interface Note :  NSManagedObject
{
}
@property (nonatomic, retain) NSString * title;
@end

and the .m file:
#import "Note.h"
#import "ManagingViewController.h"
@implementation Note
@dynamic title;
@end

In NoteView.nib my:
1) File's Owner is ManagingViewController and the IBOutlets to the Text Field and the view are connected.
2) I dragged over an NSObjectController object into the Interface Builder document window called "Note Object Controller".  I set mode to "Entity" and the Entity Name to "Note".  "Prepares content" and "Editable" are checked on.  (All the examples I've done and been able to find use an NSArrayController here.  I don't need an array controller right?  I do want to be able to open multiple windows for the same app but I still don't think I need an arraycontroller? All the examples have a NSTableView and a add button.  There's no need for an add button here since I don't have an NSTableView).
3) The NSTextView bindings for value I have it bound to "Note Object Controller" with a controller key of representedObject and a Model Key Path of title.
When I run my app I get
[<NSObjectController 0x20004c200> addObserver:<NSTextValueBinder 0x20009eee0>
forKeyPath:@"representedObject.title" options:0x0 context:0x20009f380] was
sent to an object that is not KVC-compliant for the "representedObject" property.

What am I doing wrong?  I want to type in the text field, save the file, open it again and see the text there.

A:
[<NSObjectController 0x20004c200> addObserver:<NSTextValueBinder 0x20009eee0> forKeyPath:@"representedObject.title" options:0x0 context:0x20009f380] was sent to an object that is not KVC-compliant for the "representedObject" property.

What am I doing wrong?

The error message tells you what you're doing wrong: You're trying to bind to the representedObject property of your object controller, but it doesn't have one. Binding to properties that don't exist cannot work.
The Note is the content object of the NSObjectController, so that's the controller key you need to bind to: content.


text:
Q: Need help in Firebase query for this scenario I have DB structure as

and my code query is
quesRef = myRef.child("questions").orderByChild("timestamp").endAt("120");

Ideally as per my understanding all the values whose timestamp is less than 120 should get return, but in my case, almost all the questions are getting returned.
Am I doing something wrong ?

A: You are querying to an ending value of the string "120" instead of the number 120.
Instead, it should read:
quesRef = myRef.child("questions").orderByChild("timestamp").endAt(120);

I'm not sure why the timestamp would be as low as 120 anyway, but perhaps that's just for testing purposes?


text:
Q: Given $a \in (0,1)$, given an example of a Borel set $E \subset \mathbb{R}^2$ with Lebesgue Density $a$? So I've seen this question asked in the context of $\mathbb{R}$, but I'm unsure as to how I'm supposed to approach this problem in $\mathbb{R}^2$.
Furthermore, I was informed that there exists pretty easy examples of such sets in $\mathbb{R}^2$, but I'm unaware of any.  The main issue I'm having in $\mathbb{R}^2$ is computing the measure of the intersection $E \cap B_r(x)$ (as this gets rather complicated quickly outside of pretty simple sets $E$).  Ideally I want a set $E$ such that $m(E \cap B_r(x)) = a \pi r^2$ for small $r > 0$.
Does anyone have some suggestions on where to start?  Thank you.

A: I seem to have overcomplicated this.  Since I want $m(E \cap B_r(x)) = \alpha \pi r^2$, it's clear to me now that if you sweep out a section of the plane with angle $\theta = 2 \pi \alpha$, then you get exactly: $$\frac{m(E \cap B_r(x))}{m(B_r(x))} = \frac{\frac{2 \pi \alpha}{2 \pi}\pi r^2}{\pi r^2} = \alpha$$ using the formula for the area of the section of a circle (ofcourse this is at $x = (0,0)$).


text:
Q: How to optimize MySQL query with JOIN and WHERE? I have two MySQL tables:

*

*shows (banner shows)

*clicks (banner clicks).

CREATE TABLE `shows` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`data` text NOT NULL,
`created_at` date NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `clicks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`show_id` int(11) unsigned NOT NULL,
`data` text NOT NULL,
`created_at` date NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`),
KEY `show_constaraint_idx` (`show_id`),
CONSTRAINT `show_constaraint` FOREIGN KEY (`show_id`) REFERENCES `shows` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Each table has 40 000 000 records.
I added 40 000 000 records to shows table:
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE (i <= 40000000) DO
INSERT INTO `shows` (data, created_at) values (
    CONCAT(MD5(RAND()), MD5(RAND())),
    FROM_UNIXTIME(unix_timestamp('2021-01-01') + floor(rand() * (unix_timestamp('2021-12-31') - unix_timestamp('2021-01-01') + 1)))
);
SET i = i + 1;
END WHILE;
END;
//
CALL doWhile();

I added 40 000 000 records to clicks table:
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE (i <= 40000000) DO
INSERT INTO `clicks` (show_id, data, created_at) values (
    (FLOOR(1 + RAND() * 40000000)),
    CONCAT(MD5(RAND()), MD5(RAND())),
    FROM_UNIXTIME(unix_timestamp('2021-01-01') + floor(rand() * (unix_timestamp('2021-12-31') - unix_timestamp('2021-01-01') + 1)))
);
SET i = i + 1;
END WHILE;
END;
//
CALL doWhile();

SQL query execution time is 10 sec:
SELECT shows.id,
    shows.data,
    clicks.id,
    clicks.data
FROM clicks
INNER JOIN shows ON shows.id = clicks.show_id
WHERE shows.created_at = '2021-03-03'
AND clicks.created_at >= '2021-03-03'
AND clicks.created_at <= '2021-03-06'

I tried to optimize SQL query, but SQL query execution time is 10 sec:
SELECT sub_shows.id,
    sub_shows.data,
    sub_clicks.id,
    sub_clicks.data
FROM (
    SELECT clicks.id,
        clicks.show_id,
        clicks.data
    FROM clicks
    WHERE clicks.created_at >= '2021-03-03' AND clicks.created_at <= '2021-03-06'
) as sub_clicks
INNER JOIN (
    SELECT shows.id,
        shows.data
    FROM shows
    WHERE shows.created_at = '2021-03-03'
) as sub_shows ON sub_shows.id = sub_clicks.show_id

EXPLAIN same for both queries:

How can I optimize the query?
Answer:
Change innodb_buffer_pool_size to 12G
(Rick James)

A: You would be better to have a compound index covering BOTH parts of the join criteria vs individual.
Suggest Indexes as listed
Shows    ( created_at, id )
Clicks   ( show_id, created_at )

The reason for both keys to help is that an index utilize both parts without having to go to the raw data pages to qualify the records.  Only after qualifying does it need to retrieve the additional columns in result set.
I would also adjust and reverse the query to the smallest granular item... The SHOWS table on the single date in the primary FROM position of the query.
SELECT
      shows.id,
      shows.data,
      c.id,
      c.data
   FROM
      shows s
         JOIN clicks c
            ON s.id = c.show_id
          AND c.created_at >= '2021-03-03'
          AND c.created_at <= '2021-03-06'
   WHERE
      s.created_at = '2021-03-03'


text:
Q: Is -7/3 equivalent to 2/12? If so how? here's a link to the video of a guy solving an algebraic equation on YouTube and he says that that is the answer. Go to 4:11 on the video video with equation on it

A: At 5:03 in the video, the maker of the video writes the fraction $\frac{-28}{12}$, which he explains can be reduced to $\frac{-7}{3}$.
It is unclear how your question about $\frac 2{12}$ is connected to this video.

A: Yeah he simplified it, I understood that part but I miscalculated, I didn't take into account the x+3 ÷4, so (-7/3)+3÷4 should equal 2/12 like he said,  I didn't take into account that part I just saw -7/3 and thought he meant it equaled 2/12, thanks anyways

A: The problem he is solving is
$\frac {x+3}4 = \frac 2{12}$.
and he is asking what is $x$.
Now $x$ will not be $\frac 2{12}$.  $\frac {x+3}4 = \frac 2{12}$.
He does the proble to solve for $x$ and  gets that
$x =\frac {-28}{12}$.  That is what !!!$x$!!! is.  And it not what $\frac 2{12}$ is.  The original $\frac 2{12}$, where refered to $\frac {x+3}4$ is gone and we are not talking about it anymore.  FOr that matter we are no longer talking about $\frac {x+3}4$.  That also is gone, and we are only interested in $x$.
Remember !!!$x$!!!! is a number and we are just trying to figure out what it is:
$\frac {x+3}4 = \frac 2{12} \implies$
$12(x+3) = 4*2 \implies$ (note: we are no longer talking about $\frac 2{12}$ nor about $\frac {x+3}4$... let go of the past, man...)
$12x + 36 = 8 \implies$
$12x = 8-36 = -28\implies$ (note: we are no longer talking about $12(x+3)$ or $12x + 36$ or $8$.... let it go, let it go....)
$x = \frac {-28}{12}$.  And now we are no longer talking about $12x$ or $-28$ what's done is done; it's how we got here, and we owe it our thanks but in the here and now, we are talking about $x$.
And we found $x = \frac {-28}{12}$..... which is the same thing as $\frac {-3}2$.  But none of them have anything to do with $\frac 2{12}$ which was what $\frac {x+3}4$ was.  And $\frac {x+3}4$ was something entirely different.
=====
Perhaps an anology:
We start with $x + 2 = 7$
So that means $x = 5$.  But we started with $7$ and ended with $5$?  Does that mean $7 = 5$?
Of course not.  The first part we were talking about  $x+2$ being $7$.  In the second part we are talking about $x$ which is ENTIRELY different that $x+2$.  So one thing is $7$ and the other thing is $5$.  That doesn't mean $7$ and $5$ are the same thing.


text:
Q: HTML Multiple spaces Alignment I want there rows alignment by col, I write the code:
result.seq_content = 'GCAUCCGGGUUGAGGUAGUAG'
result.vel_bar =     '|| ||||||  ||| ||| ||'
result.seq_match =   'CG.AGGUUC..UUC.AUC.UC'

    {{ result.seq_content}}

    {{ result.vel_bar}}

    {{ result.seq_match}}

But the result is

Multiple spaces become a space.
I used tag pre, but the size of A, C, G, U is not equal to the size of | or space, so it failed.
I changed the code:
result.seq_content = 'GCAUCCGGGUUGAGGUAGUAG'
result.vel_bar =     '|| ||||||  ||| ||| ||'
result.seq_match =   'CG.AGGUUC..UUC.AUC.UC'

    {{ result.seq_content}}

    {% for e in result.vel_bar %}
        {% if e == ' '%}
            &nbsp
        {% else%}
            {{ e}}
        {% endif%}
    {% endfor%}

    {{ result.seq_match}}

But the size of {{ e}} is bigger than A, C, G, U.
So how could I align multiple spaces, like this:
GCAUCCGGGUUGAGGUAGUAG
|| ||||||  ||| ||| ||
CG.AGGUUC..UUC.AUC.UC

Thanks! :D
The problem has been solved.
I replaced all ' ' with nbsp;, and cancel the automatic escape, this is my code:
result.vel_bar = result.vel_bal.repalce(' ', ' ')

{{ result.seq_content }}
{% autoescape false%}
{{ result.vel_bar}}
{% endautoescape %}
{{ result.seq_match }}

Thank you for help. :D

A: You can break those sequence elements using some php/js/python arrays and then build it up using php/js/python using the css classes that make it happen:
http://jsfiddle.net/ewR54/5/
So basically you parse your data:
GACU
||||
CUGA ..

^--Parser -->

and for each sequence you take the 3 elements out (ex: G, |, C) and build it using php, js or python using the div construction in that fiddle I posted.
Have fun.

A: Try using
 tag in

    'GCAUCCGGGUUGAGGUAGUAG'
    '|| ||||||  ||| ||| ||'
    'CG.AGGUUC..UUC.AUC.UC'

Demo

A: First of all it was good to use a monospace font. HTML replaces multiple spaces to a single one: but you can replace each space with
result.vel_bar.replaceAll(/\s/, ' ')
This way your alignment should be perfect.


text:
Q: How can I determine whether the current process has a UI open? I am writing some library code which will rerun the current process as an administrator/root. The problem is (for linux at least) that if the calling code is a command line application the best way would be to call sudo whereas if it is a gui application, gksudo is appropriate. For completeness sake though, solutions (or pointers to solutions) for other os's are also welcome.
Also, this is useful so that for GUI apps, I can turn off printf statements.

A: I'd run gksu(do) if the environment variable DISPLAY is set. It doesn't really matter if the application has a GUI or not, if there's an X-server running, and we can use it, why shouldn't we?
Doesn't allow you to determine if you should disable stdout output. However, stderr output is generally captured in .xsession-errors, even if no terminal is connected, so you might not want to disable that output afterall.


text:
Q: Memcached php sessions keep increasing I run a lamp stack of a couple of application servers which used a single dedicated memcache server for hosting sessions. The problem is that the items in the cache increase in a steady almost linear pace. This worries me. I figured that when the cache fills out the oldest entries will be overwritten and there shouldn't be a problem. But it seems impossible to gain any insight in the actual usage.
The versions I use are as following:
server-side:

*

*Ubuntu 10.04

*memcached 1.4.2

application-side:

*

*ubuntu 10.04

*php 5.3.2

*libmemcached-0.44

*pecl memcached 1.0.2

I've also tried this setup with pecl memcached 2.0.0b1, pecl memcache 2.2.6 and build against libmemcached-0.49 of which only the last had a minor impact at all. Is this behavior normal and as intended or would this be a failure of session_destroy?

A: Regrettably it was my own misunderstanding of memcached which gave me a wrong impression about the behavior. After some additional research I came across two (1, 2) articles which clarified the internal workings for me.
Garbage will not be collected. This still doesn't give me insight in the actual usage but at least takes away some worries. As long as I don't get evictions it should be just fine.


text:
Q: Gray-out the background when popup opens I call below javascript on click of link/textbox or button.
function OpenPopupLinkRisk(Number)
{
    window.open("../PopUp.aspx?id=" + Number, "List", "scrollbars=no,resizable=yes,width=700,height=450");
    return false;
}

I donot want user to do anything else until he closes the popup window. So how can I grey background and force user to first close the popup and then do any other activity on application.
Can anyone suggest me how to achieve this ?
Thanks !

A: First of all, i would really disrecommend using window.open for this unless you really need a new browser popup window. If you want to stick with it persee, then will have to use a timer or something to manually check when the window is closed like:
var popup = window.open('http://www.example.com', 'example', '');
var timer = setInterval(function() {
    if(window.closed) {
        clearInterval(timer);
        alert('Closed alright');
    }
}, 100);

Else, check some tutorials on the subject, Modal Popup

A: First a direct solution to you problem that I wouldn't advice using it an then an approach you should be taking and is better from usability as well as security point of view.
Check whether popup window has closed
// mask your page
mask();

// open popup
var popup = window.open("../PopUp.aspx?id=" + Number);

// check whether it's been closed
function check()
{
    if (popup && !popup.closed)
    {
        setTimeout(check, 1000);
    }

    // unmask your page
    unmask();
}
check();

Modern (and better) alternative
Using window.open is a bad solution because it's a security risk and popup blockers prevent sites to open new windows. It's also considered bad practice.
A much better modern alternative is to display the new page as modal window inside your page directly. This will not open new windows and users stay as they are.
There are tons of javascript plugins for modal windows. Make a Google search.


text:
Q: How to sort out elements by their value in data- attribute using JS I need to sort out the elements that are already displayed in ascending order so that they just rearrange. I need to sort them out by the values in their data-val attributes.

Item a

Item b

Item c

Item d

<button onclick="sortOut()">Sort Out</button>

I made an example here: http://jsfiddle.net/quatzael/uKnpa/
I dont know how to do that. I kind of started but it is probably wrong.
I need the function to firstly find out what elements have class called "item" and then those with this class sort out by the value of their data-val attribute.
It has to work in all browsers so the solution should probably involve .appendChild()
Tnx for any help..

A: You need to append them to the DOM in the newly sorted order.
Here's what I added to your code to do this:
divs.sort(function(a, b) {
    return a.dataset.val.localeCompare(b.dataset.val);
});

var br = document.getElementsByTagName("br")[0];

divs.forEach(function(el) {
    document.body.insertBefore(el, br);
});

http://jsfiddle.net/RZ2K4/
The appendChild() method could be used instead of .insertBefore() if your sorted items were in a container with nothing else.
To support older browsers, you would use .getAttribute("data-val") instead of .dataset.val.
And if you want a numeric sorting, you shouldn't use .localeCompare in the .sort() function.

A: you can add flex property for the wrapper and use order to order them.
or you can reappend elements to their parent
Demo

const items = Array.from(document.querySelectorAll("li"));
const btn = document.querySelector("button");
const orderBy = Array(5).fill().map((x, i) => i + 1); // [1..5]

btn.addEventListener("click", clickHander);
function clickHander() {
  orderBy.forEach(i => {
    const item = items.find(x => x.getAttribute("data-order") === `${i}`);
    item.style.order = i;
    // OR: item.parentElement.appendChild(item);
  });
}
ul {
  display: flex;
  flex-direction: column;
}

order 4

order 3

order 1

order 5

order 2

<button>sort</button>


text:
Q: 'Sign in as Different User' Not "Taking" In some instances of WSS or MOSS when you use the "Sign in as Different User" option, the new login doesn't "take".  Is there any known issue here?  Usually logging out and then logging back in with the second user does work.  This seems like a pretty big problem and I've seen it on and off over the years, mostly while testing with different identities.
UPDATE 1: I'm seeing it in several hosted WSS situations, so I don't actually know what authentication they are using.  Interestingly, I don't see it in some hosted WSS situations, too.  And consistently within the instance. This might tell us that the authentication method might matter.
UPDATE 2: Another piece of info I should have included in the first place: The reason that I'm asking this is that the $().SPServices.SPGetCurrentUser in SPServices sometimes returns the previous user.  All I'm doing in that function is loading the _layouts/userdisp.aspx?Force=True page and pulling the Name from the page. It's the column with the label 'Account', but the InternalName is 'Name':
<!--  FieldName="Account"
             FieldInternalName="Name"
             FieldType="SPFieldText"
           -->

Here's the SPServices function:
// Function which returns the account name for the current user in DOMAIN\username format
$.fn.SPServices.SPGetCurrentUser = function() {
    var username = "";
    $.ajax({
        async: false, // Need this to be synchronous so we're assured of a valid value
        url: $().SPServices.SPGetCurrentSite() + "/_layouts/userdisp.aspx?Force=True", // Force parameter forces redirection to a page that displays the information as stored in the UserInfo table rather than My Site.
        complete: function (xData, Status) {
            $(xData.responseText).find("table.ms-formtable td#SPFieldText").each(function() {
                if(/FieldInternalName=\"Name\"/.test($(this).html())) username = $(this).text();
            });
        }
    });
    return username.replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '');
};

One would like to think that this page would always represent the currently logged in user, but sometimes it represents the prior user. Not good.
UPDATE 3:
I may have come up with a fix for this in my SPServices library, at least. It doesn't solve the larger problem that SharePoint seems to have, though.
I added a unique Query String parameter (just the current time) to the call to userdisp.aspx in SPGetCurrentUser per arunduttgp's suggestion. This seems to force the browser to do a hard refresh on the page in the AJAX call, getting the correct values for the logged in user even when the current SharePoint page is showing the prior user incorrectly.
 url: $().SPServices.SPGetCurrentSite() + "/_layouts/userdisp.aspx?Force=True&" + new Date().getTime(),

A: I get this a lot, just not consistently. A page refresh will sometimes sort it out. I've taken to just using the "runas" command to avoid using "Sign in as Different User" and the associated issues.
runas /user:{Domain}\{UserID} [/savecred] "C:\Program Files\Internet Explorer\iexplore.exe [Optional URL]"

You can create shortcuts on your desktop to make this easier.

A: Just refreshing the page is not enough, the majority of times this is simply due to browser caching but a page refresh will not refresh the browser cache.
In IE you would click Cntrl + F5 to clear the cache and do a full refresh, not sure what the same command would be in FireFox or other browsers but the concept will be the same.

A: I see Paul's comment above about seeing the issue more with NTLM. I run Kerberos in the vast majority of my environments, and I very rarely see it at all, so it could be the case where it's related to NTLM.
It's got to be some sort of cache either within the browser or the session. I wouldn't think that there's a way to force a refresh through the script, unless you can refresh the destination URL before reading from it.

A: I don't necessarily have a solution for you (other than the "refresh the page a couple times" others have mentioned, but as a data point I only started seeing this behavior when I first upgraded to IE8.  In fact on machines where I still have IE7, I never see it at all.  I'd be curious if others share this experience.

A: A more dependable way to determine the logged on user may be to just ask the server instead of going through SharePoint ( which at this point is acting as a middle man). Getting the variable directly may help with the whole refresh question as there may be some lag as the credentials are updated, guessing here.
This page should help. Specifically, the LOGON_USER variable will have the value you need.

A: I'm dealing with same issue of login as Different user not refreshing the page to show the new user and that users permissions. Usually though (Firefox) after a page refresh the correct user and permissions are showing.
But I think a related problem is that if a user lands on the AccessDenied.aspx page and attempts to logon as a different person (using the provided link) it seems to have a similar failure of not updating with the new users permissions and such. Only workaround is to have users close all browser windows and start over by logging in with the correct credentials.
I don't know if this is a new shortcoming of using Windows Integrated Auth and updated browsers holding onto previous credentials or what.

A: I like Clayton Firth's solution, using the "runas" command.  Any way to make it prompt for the user?  Also, can I run this command from a link within SharePoint?  Essentially I would like to replace the "Sign in as Different User" menu option witht the "runas" command.


text:
Q: Online Shop cart not adding correctly I created an online shop but when the user adds an item to the cart it seems that the first item has 0 in its quantity which does not seem right.
As mentioned above when an item is first on the list the quantity is 0 where it should be 1. That needs to be corrected.
also for some reason when you click the side arrow to increase the quantity amount and the price increases, I am not sure how to go about that.
I have attached the screenshot of what it currently looks like.
let carts = document.querySelectorAll('.shop-item-button');

let products = [
    {
    name: 'Corin Bed',
    tag: 'Corin Bed-Vienna Dark Blue.jpg',
    price: 3500,
    inCart:0
},
{
    name: 'Miranda Bed',
    tag: 'Miranda Bed - Elephant & Anthracite.jpg',
    price: 2500,
    inCart:0
},
{
    name: 'Miuzza Bed',
    tag: 'Miuzza Bed - Vienna Cream.jpg',
    price: 2000,
    inCart:0
},
{
    name: 'Norma Bed',
    tag: 'Norma Bed - Vienna Beige.jpg',
    price: 3000,
    inCart:0
},
{
    name: 'Alpha Bedside',
    tag: 'ALPHA 1 DRAWER PEDESTAL-light oak.jpg',
    price: 1200,
    inCart:0
},
{
    name: 'Cyrus Bedside',
    tag: 'CYRUS 1 DOOR PEDESTAL - wedge.jpg',
    price: 1567,
    inCart:0
},
{
    name: 'Gamma Bedside',
    tag: 'GAMMA 2 DRAWER PEDESTAL-light oak.jpg',
    price: 900,
    inCart:0
},
{
    name: 'Gamma 3 Bedside',
    tag: 'GAMMA 3 DRAWER PEDESTAL-walnut.jpg',
    price: 1100,
    inCart:0
},
{
    name: 'Takka Bedside',
    tag: 'TIKKA 1 DRAWER PEDESTAL-mahogany.jpg',
    price: 800,
    inCart:0
},
{
    name: 'Alexia Chair',
    tag: 'ALEXA CHAIR - GRIJS.jpg',
    price: 1500,
    inCart:0
},
{
    name: 'Jean Chair',
    tag: 'JEAN STOOL - ANTRACIET.jpg',
    price: 1050,
    inCart:0
},
{
    name: 'Maxime Chair',
    tag: 'MAXIME CHAIR - ECRU.jpg',
    price: 1300,
    inCart:0
},
{
    name: 'Oscar Chair',
    tag: 'OSCAR CHAIR - ANTRACIET.jpg',
    price: 700,
    inCart:0
},
{
    name: 'Caden Coffee Table',
    tag: 'CADEN 120x60cm COFFEE TABLE-Light Oak.jpg',
    price: 1500,
    inCart:0
},
{
    name: 'Judy Coffee Table',
    tag: 'JUDY 100x55cm COFFEE TABLE-light oak.jpg',
    price: 1300,
    inCart:0
},
]

for(let i = 0; i < carts.length; i++){
    carts[i].addEventListener('click', () =>{
        cartNumbers(products[i]);
        totalCost(products[i])
    })
}

function onloadCartNumbers(){
    let productNumbers = localStorage.getItem('cartNumbers');

    if(productNumbers){
        document.querySelector('.cart span').textContent = productNumbers;
    }
}

function cartNumbers(products){
    let productNumbers = localStorage.getItem('cartNumbers');

    productNumbers = parseInt(productNumbers);

    if( productNumbers ){
        localStorage.setItem('cartNumbers', productNumbers + 1);
        document.querySelector('.cart span').textContent = productNumbers + 1;
    }
    else{
        localStorage.setItem('cartNumbers', 1);
        document.querySelector('.cart span').textContent = 1;
    }

    setItem(products)
}

function setItem(products){
   let cartItems = localStorage.getItem('productsIncart')
   cartItems = JSON.parse(cartItems);

    if(cartItems != null) {

        if(cartItems[products.tag] == undefined){
            cartItems = {
                ...cartItems,
                [products.tag]:products
            }
        }
        cartItems[products.tag].inCart += 1;
       }
       else{
           products.incart = 1;
           cartItems = {
               [products.tag]: products
           }
       }

    localStorage.setItem("productsIncart",JSON.stringify (cartItems));
}

function totalCost(products){
//console.log("the product price is", products.price);
let cartCost = localStorage.getItem("totalCost");

console.log("the product price is", cartCost);

if(cartCost != null){
    cartCost = parseInt(cartCost);
    localStorage.setItem("totalCost", cartCost + products.price);
}
else{
    localStorage.setItem("totalCost", products.price);
}
}

function displayCart(){
    let cartItems = localStorage.getItem("productsIncart");
    cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products")
let cartCost = localStorage.getItem("totalCost");
    if(cartItems && productContainer){
        productContainer.innerHTML = '';
        Object.values(cartItems).map(item => {
            productContainer.innerHTML += `

            <svg class="remove" clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m12.002 2.005c5.518 0 9.998 4.48 9.998 9.997 0 5.518-4.48 9.998-9.998 9.998-5.517 0-9.997-4.48-9.997-9.998 0-5.517 4.48-9.997 9.997-9.997zm0 8.933-2.721-2.722c-.146-.146-.339-.219-.531-.219-.404 0-.75.324-.75.749 0 .193.073.384.219.531l2.722 2.722-2.728 2.728c-.147.147-.22.34-.22.531 0 .427.35.75.751.75.192 0 .384-.073.53-.219l2.728-2.728 2.729 2.728c.146.146.338.219.53.219.401 0 .75-.323.75-.75 0-.191-.073-.384-.22-.531l-2.727-2.728 2.717-2.717c.146-.147.219-.338.219-.531 0-.425-.346-.75-.75-.75-.192 0-.385.073-.531.22z" fill-rule="nonzero"/></svg>

                ${item.name}

${item.price}

            <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m22 12.002c0-5.517-4.48-9.997-9.998-9.997-5.517 0-9.997 4.48-9.997 9.997 0 5.518 4.48 9.998 9.997 9.998 5.518 0 9.998-4.48 9.998-9.998zm-8.211-4.843c.141-.108.3-.157.456-.157.389 0 .755.306.755.749v8.501c0 .445-.367.75-.755.75-.157 0-.316-.05-.457-.159-1.554-1.203-4.199-3.252-5.498-4.258-.184-.142-.29-.36-.29-.592 0-.23.107-.449.291-.591z" fill-rule="nonzero"/></svg>
            <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m2.009 12.002c0-5.517 4.48-9.997 9.998-9.997s9.998 4.48 9.998 9.997c0 5.518-4.48 9.998-9.998 9.998s-9.998-4.48-9.998-9.998zm8.211-4.843c-.141-.108-.3-.157-.456-.157-.389 0-.755.306-.755.749v8.501c0 .445.367.75.755.75.157 0 .316-.05.457-.159 1.554-1.203 4.199-3.252 5.498-4.258.184-.142.29-.36.29-.592 0-.23-.107-.449-.291-.591z" fill-rule="nonzero"/></svg>

${item.inCart}

            R${item.inCart * item.price}

            `
        });

        productContainer.innerHTML += `

          Cart Total

            R${cartCost}

        `
    }

    let remove = document.querySelector(".remove")

    remove.addEventListener("click",()=>{
        localStorage.removeItem("productsIncart");
        localStorage.removeItem("totalCost");
        localStorage.removeItem("cartNumbers");

        alert("button was clicked")
    })
}

onloadCartNumbers()
displayCart()


text:
Q: iTunes Connect, internal test, vendor ID change When we do internal test release in iTunes Connect, user install app with Testflight. So my question is:
Does the vendorID( NSUUID *identifierForVendor) will change?
Base on apple's doc, normal update from Appstore should not change vendorID, but also mention that Ad-Hoc distribute may cause something else.
For more explanation, my use case is: device install the current live version app, then use internal test in iTunes Connect to install the test version which has same bundle ID. In that case, the live app has been override and I notice the vendor ID may changed.

A: Like what list in https://stackoverflow.com/a/16680879/2450847 (thanks aramusss provided), normal App update(at least from Appstore), do NOT change VendorID.
Test result(thanks a lot for @invertedfjord's add on):
For the app with same bundle ID.
Test builds, including Xcode direct build, testFilght internal test build, testFlight external build, all have the same vendor ID and will not be changed during any version update or overwrite install.
Appstore builds have same vendor ID and will not be changed for any version update.
Test builds and Appstore builds have different vendor IDs. In that case, any update or overwrite install between test build and Appstore build will change the Vendor ID.
Explanation:
VendorID should be provided by Appstore and if not, generated from bundleID. Test build of the App(even testFlight version) for sure does not directly purchased from Appstore. As result VendorID will be different compare with Appstore version.

A: If you are testing it with TestFlight internally in iTunes Connect and not using testflightapp.com, it should not change.
Must mention, however, that Apple is hiding this Vendor ID (you need to search a bit for it), which can mean Apple does not want you to use it.


text:
Q: How can move a LUKS container from the middle of a partition to the beginning? For the tl;dr, skip to the bottom.
I have a dual-boot setup with Mac OS X at the beginning of my drive and three GNU/Linux partitions at the end of the drive. I don't have the relevant machine on hand to give an fdisk dump, but here's a rough overview of the original disk layout:
/dev/sda1: EFI System Partition
/dev/sda2: Macintosh HD (main OS X partition)
/dev/sda3: Recovery HD (part of OS X's recovery system)
/dev/sda4: /
/dev/sda5: /home inside a LUKS container
/dev/sda6: swapspace inside a LUKS container

I'm reinstalling GNU/Linux on this system and as a part of that, I want to make / encrypted. However, that requires a separate /boot. In order to create that partition, I resized Macintosh HD and moved Recovery HD back to the end of Macintosh HD. I also took the opportunity to make my / larger. So the end result is a disk that looks like this:
/dev/sda1: EFI System Partition
/dev/sda2: Macintosh HD (main OS X partition) (smaller than before)
/dev/sda3: Recovery HD (part of OS X's recovery system)
/dev/sda4: /boot
/dev/sda5: / (larger than before, and now inside a LUKS container)
/dev/sda6: /home inside a LUKS container
/dev/sda7: swapspace inside a LUKS container

tl;dr: Here's the problem: due to the order in which I configured things, I now have a cryptsetup-created LUKS container in the middle of /dev/sda5. Because it's in the middle, nothing can find it to unlock/mount/recover it. How can I move my cryptcontainer to the beginning of the partition? Probably this involves two distinct steps (actually finding the thing on disk, then using that information to move it), but I'm not sure. Googling's turned up nothing.

A: LUKS has a distinct header, you could find possible offsets with grep:
# grep -a -b --only-matching 'LUKS' /dev/sda5
1832480940:LUKS
1959072314:LUKS
2019974297:LUKS

For each possible offset you find, you could create a loop device and see if it's a valid LUKS device or not:
# losetup --find --show --offset 1832480940 --read-only /dev/sda5
/dev/loop3
# cryptsetup luksOpen /dev/loop3 luksloop3
...mount -o ro, ls, backup, umount...
# cryptsetup luksClose luksloop3
# losetup -d /dev/loop3

Once you have found the correct offset, you can move it to the beginning of the partition using dd. This is dangerous, if you get the offset wrong or cancel the operation, the data is lost. So you should make a backup first in any case.
# dd if=/dev/sda5 of=/dev/sda5 bs=1M iflag=skip_bytes skip=1832480940

See if it worked:
# cryptsetup luksOpen /dev/sda5 luks

Restore from backup otherwise.


text:
Q: JavaFX Scene builder controller I am trying to manipulate the text in a TextField generated by Scene Builder. My controller looks like this:
@FXML
private TextField textDescr;

public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    textDescr = new TextField();
    assert textDescr != null : "fx:id=\"textDescr\" was not injected: check your FXML   file 'provingGroundsUI.fxml'.";
    Game.mainFSM.enter();
}
public void setText(String s) {
    // TODO Auto-generated method stub
    textDescr.setText(s);
}

I am getting a NullPointerException. I have tried bot with and without the textDescr = new TextField(); part. I don't quite understand....I thought that JavaFX initialized all the UI variables at the start of the program.

A: Your controller class should implement Initializable
The @FXML annotation shows that the field will be initialized by the JavaFX. So make sure, you remove the new TextField thing.
Are you sure you assigned this controller in the FXML?

A: *

*How looks your FXML?

*To manipulate the textDescr in the setText Function has a lot of risks. It is better to use a binded StringProperty:

    @FXML
    private Text textDescr;

    private StringProperty textProperty = new SimpleStringProperty();

    @FXML
    void initialize() {
            assert textDescr != null : "fx:id=\"textDescr\" was not injected: check your FXML file 'TestView.fxml'.";
           textDescr.textProperty().bind(textProperty);
    }

    public ReadOnlyStringProperty textProperty(){
          return textProperty;
    }


text:
Q: React Redux Persist is rehydrating, but no stored data is retrieved, instead, default I've been struggling with this problem for two days, so I need help!
I have a React web in which I've added Redux Persist (also Redux Saga for handling requests) as the documentation said.
I'm testing with a store that doesn't have any saga in the middle, when I trigger an action, the data is updated, I can see it in the Debugger, but when I refresh, despite the Redux Hydrate process runs, that value goes back to the default one.
store.js
import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga'
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

import rootReducer from './reducers';
// import rootSaga from './sagas';

const persistConfig = {
    key: 'root',
    storage: storage,
    // whitelist: ['login', 'account', 'layout'],
    stateReconciler: autoMergeLevel2, // see "Merge Process" section for details.
};

const persistedReducer = persistReducer(persistConfig, rootReducer);
const sagaMiddleware = createSagaMiddleware();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(persistedReducer, composeEnhancers(applyMiddleware(sagaMiddleware)));
const persistor = persistStore(store);

export { store, persistor, sagaMiddleware };

reducers.js
import { combineReducers  } from 'redux';

// Front
import layout from './layout/reducer';

// Authentication Module
import account from './auth/register/reducer';
import login from './auth/login/reducer';
import forget from './auth/forgetpwd/reducer';

const rootReducer = combineReducers({
    layout,
    account,
    login,
    forget
});

export default rootReducer;

reducer.js (the one I'm testing, Layout)
import { ACTIVATE_AUTH_LAYOUT, ACTIVATE_NON_AUTH_LAYOUT, TOGGLE, TOGGLE_LD } from './actionTypes';

const initialState={
    topbar:true,
    sidebar:true,
    footer:true,
    is_toggle : true,
    is_light : true
}

const layout = (state=initialState,action) => {
    switch(action.type){
        case ACTIVATE_AUTH_LAYOUT:
            state = {
                ...state,
                ...action.payload
            }
            break;
        case ACTIVATE_NON_AUTH_LAYOUT:
            state = {
                ...state,
                ...action.payload
            }
            break;

        case TOGGLE:
            state = {
                ...state,
                is_toggle : action.payload
            }
            break;

        case TOGGLE_LD:
            state = {
                ...state,
                is_light : action.payload
            }
            break;

        default:
            // state = state;
            break;
    }
    return state;
}

export default layout;

actions.js
import { ACTIVATE_AUTH_LAYOUT, ACTIVATE_NON_AUTH_LAYOUT, TOGGLE, TOGGLE_LD } from './actionTypes';

export const activateAuthLayout = () => {
    return {
        type: ACTIVATE_AUTH_LAYOUT,
        payload: {
            topbar: true,
            sidebar: true,
            footer: true,
            rodri: 'butta',
            layoutType: 'Auth'
        }
    }
}

export const activateNonAuthLayout = () => {
    return {
        type: ACTIVATE_NON_AUTH_LAYOUT,
        payload: {
            topbar: false,
            sidebar: false,
            footer: false,
            layoutType: 'NonAuth'
        }
    }
}

export const toggleSidebar = (is_toggle) => {
    return {
        type: TOGGLE,
            payload: is_toggle

    }
}

export const toggleLightDark = (is_light) => {
    return {
        type: TOGGLE_LD,
            payload: is_light

    }
}

index.js (APP)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';

import rootSaga from './store/sagas';

import {persistor, store, sagaMiddleware} from './store';

sagaMiddleware.run(rootSaga);

const app = (
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <BrowserRouter>
                <App />
            </BrowserRouter>
        </PersistGate>
    </Provider>
);

ReactDOM.render(app, document.getElementById('root'));
serviceWorker.unregister();

And fragments of the class
...
this.props.toggleSidebar(!this.props.is_toggle);
...

const mapStatetoProps = state => {
    const { is_toggle,is_light } = state.layout;
    return {  is_toggle,is_light };
}

export default withRouter(connect(mapStatetoProps, { toggleSidebar })(Topbar));

The debugger
First time run, when I toggle the menu bar so the action gets triggered)

After refreshing the browser, the rehydrate should bring the layout -> is_toggle to false.. but it remains true (as default)

Fragments in color:

A: I think your issue is how you are setting up your store:
const store = createStore(persistedReducer, composeEnhancers(applyMiddleware(sagaMiddleware)));

The structure of this function is createStore(reducer, [preloadedState], [enhancer])
So you are trying to pass your enhancers as preloadedState.
Try changing it to this:
const store = createStore(persistedReducer, {}, composeEnhancers(applyMiddleware(sagaMiddleware)));

Also, when you setup your persistConfig I see that you have the whitelist commented out.  Any reducer state you want to keep needs to be in this list so it should not be commented out:
// whitelist: ['login', 'account', 'layout'],  // uncomment this

And finally as a side note, you don't need break in all of your switch cases

A: I faced the same bug, the thing worked for me was in the comments of the Author's question saying:

And this solution didn't worked for me :( https://github.com/rt2zz/redux-persist/issues/1114#issuecomment-549107922

So if anyone stuck on this issue then could try this solution out at: https://github.com/rt2zz/redux-persist/issues/1114#issuecomment-549107922
Issue: My Persist was being called first before rehydrate, making my states to the default state again. Hence everytime i refresh my states were gone from the local storage.


text:
Q: Change the column label? e.g.: change column "A" to column "Name" Can anyone tell me how to change the column label?
For example, I want to change Column "A" to Column "Name" in Excel.

A: I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:
First, insert a new row at the beginning of the sheet. Within that row, define the names you need:

Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now:

Now whenever you scroll down in the document, the first row will be "pinned" to the top:

A: What version of Excel?
In general, you cannot change the column letters. They are part of the Excel system.
You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.
In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.
If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

A: If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...:
Button Office(top left)
Excel Options(bottom)
Advanced(left)
Right looking: Display options fot this worksheet:
Select the worksheet(eg. Sheet3)
Uncheck: Show column and row headers
Ok


text:
Q: Moment Timezone has no data for EDT in react React native project has
import moment from 'moment-timezone/builds/moment-timezone-with-data-2012-2022'
...
    var jun = moment("2014-06-01T12:00:00Z");
    jun.tz('EDT')

Results in error about absence of EDT

Moment Timezone has no data for EDT. See http://momentjs.com/timezone/docs/#/data-loading/

tz object has packed zones and America/New_York|EST EDT|50 40|01010101010101010101010|1GI70 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0|21e6 in particular
jun.tz('America/Los_Angeles')

or
jun.tz('UTC')

works as expected.
Adding time zone as suggested on the momentjs.com website doesn't change the outcome.
npm 5.0.0, node 8.0.0, moment-timezone: 0.5.14, react-moment: 0.7.0, moment: 2.22.0


text: Q: How can I disable screen iOS capture How to disable the screen in iOS or how can we show a blur screen when the screen capture event is trigger? I need to prevent screen capture by users of my app, for security reasons. The contents I display are confidential and should not be copied onto the device.


text:
Q: overriding virtual function return type differs and is not covariant I have ported my application from 32 bit to 64 bit platform and came across various build issues. I solved almost everything but I have come to an error I cannot figure out.
Could anyone advise on solving this error?

"Error    61 error C2555: 'CICEVisionDlg::DoModal': overriding virtual
  function return type differs and is not covariant from
  'CDialog::DoModal'

Code for the DoModal override:
int CICEVisionDlg::DoModal()
{
  int nRet;
  m_bPopup = TRUE;
  CEXTDLLState EXTDLLState(m_hResDllModule);
  nRet = CDialog::DoModal();
  m_bPopup = FALSE;
  return nRet;
}

A: When you override a virtual function, you must return a correct type, where "correct" depends on the return type from the base class.
"Correct" means either the exact same type, or else with pointer and reference return types only, a "more specific" type. If the function in the base class Base returns X*, then the derived class can return a different type Y* provided that Y is a derived class of X.
Your problem is that the override of the DoModal function in the derived class CICEVisionDlg doesn't match the return type of the function in CDialog that it is overriding. Whether it's supposed to be covariant or not depends on the return type -- if it's not supposed to be covariant anyway then you can ignore that, and the error means "your function returns the wrong type!"

A: Return value of DoModal is INT_PTR, which is simply int on 32 bit but __int64 on 64 bit platform. Change the return value of the overriding function to INT_PTR and it will compile on both.


text:
Q: Marionette - not able to append to regions I am trying to append a view in to a region, but i am getting an error saying:
undefined is not a function

here is my template:

here is my script:
var MenuView = Backbone.View.extend({
    template:_.template($('#menuTemp').html()),
    initialize:function(){
        this.render();
    },
    render:function(){
       this.$el.html(this.template);
       return this;
    }
});

container = new Backbone.Marionette.Region({
  el: "#container"
});

MyLayout = Backbone.Marionette.LayoutView.extend({
  template: "#my-layout",

  regions: {
    menu: "#menu",
    content: "#content"
  }
});

// Show the "layout" in the "container" region
layout = new MyLayout();
container.show(layout);

layout.menu.show(new MenuView().render().el); //not working

Here is Live Demo
Any one help me to fix the issue please?
Thanks in advance.

A: The problem is your last line:
layout.menu.show(new MenuView().render().el)

Marionette automagically takes care of rendering the view. So you just need to call:
layout.menu.show(new MenuView())

And it'll work just great.