text:
Q: How is it possible that someone has two accounts with the same name? How is it possible that someone has two accounts with the same name?
CHECK LINKS:
1- eran
2- eran

A: Names are not unique.  I had account with my openid and I accidentally created another account with google and started over with the same name.

A: This problem is actually quite common (scroll down). This is because SO lets people have the same name.

A: In this particular case, they could be merged as they matched on a number of fields.
But in general, it's possible to have a lot of users named "James", we don't enforce uniqueness of display names by choice.

A: They are unregistered users so they don't technically have an account, if this is an issue it should be on meta. So I believe you're posting in the wrong section.

A: I'm sure there is probably more than one person in the world named "eran", but the pictures indicate that the accounts have the same email address and are probably therefore the same person.
As per ChrisF's suggestion, I have flagged the question asked by this user to inform the mods of this.


text:
Q: Get date , month and year from particular date I want to get the date , month and year from the particular date.
I have used below code :
 String dob = "01/08/1990";

        int month = 0, dd = 0, yer = 0;

        try {

            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            Date d = sdf.parse(dob);
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            month = cal.get(Calendar.MONTH);
            dd = cal.get(Calendar.DATE);
            yer = cal.get(Calendar.YEAR);

        } catch (Exception e) {
            e.printStackTrace();
        }

So from the above code i am getting month -0 , yer - 1990 and date - 8
But i want month - 01 , date - 08 and yer - 1990.
I have defined the date format also but i am not getting perfect value from date, month and year.

A: Month in calendar will be from 0-11. You have to add +1 in month.
String dob = "01/08/1990";
String month = 0, dd = 0, yer = 0;
try {
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
     Date d = sdf.parse(dob);
     Calendar cal = Calendar.getInstance();
     cal.setTime(d);
     month = checkDigit(cal.get(Calendar.MONTH)+1);
     dd = checkDigit(cal.get(Calendar.DATE));
     yer = checkDigit(cal.get(Calendar.YEAR));

} catch (Exception e) {
     e.printStackTrace();
}

checkDigit method for adding preceeding zero. checkDigit() method returns String value. if You want to convert in integer then you can do like Integer.parseInt(YOUR_STRING);
// ADDS 0  e.g - 02 instead of 2
    public String checkDigit (int number) {
        return number <= 9 ? "0" + number : String.valueOf(number);
    }

A: public static void main (String[] args) throws java.lang.Exception
{
     String dob = "01/08/1990";

    int month = 0, dd = 0, yer = 0;

    try {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date d = sdf.parse(dob);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        month = cal.get(Calendar.MONTH);
        dd = cal.get(Calendar.DATE);
        yer = cal.get(Calendar.YEAR);

        System.out.println("Month - " + String.format("%02d", (month+1)));
        System.out.println("Day - " + String.format("%02d", dd));
        System.out.println("Year - " + yer);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Since months in the Calendar are considered from 0-11 so we need to add
  1 to it.

I have executed a sample you can check here

A: In java.util.Calendar month is zero based, so it gives you correct values.
Check the constants in the Calendar class:
public final static int JANUARY = 0;
public final static int FEBRUARY = 1;
...
public final static int DECEMBER = 11;

redpajama_set_name: RedPajamaStackExchange


text:
Q: TYPO3 Fluid resource.record.fal With the vhs viewhelper "resource.record.fal" i select the image from the page ressources. This works very fine but i also want to inheritance the image as long as there is no other image uploaded.
Is there a way to do that? The slide attribute is not available for this viewhelper.
I know i can do all of this just with Typoscript but i want to find a solution based on Fluid.
Here is my code:
<v:resource.record.fal table="pages" field="media" uid="{data.uid}" as="resources" >
<f:for each="{resources}" as="resource">
    <v:resource.image identifier="{resource.id}" />
</f:for>

A: Okay, here goes some Fluid free-styling inline syntax:
{v:page.rootLine()
    -> v:iterator.column(columnKey: 'media', indexKey: 'uid')
    -> v:iterator.filter(preserveKeys: 1)
    -> v:iterator.keys()
    -> v:iterator.last()
    -> f:variable(name: 'firstPageUidWithMedia')}

In steps:

*

*Extract the page root line

*Extract a sub-array of all media column values, use column uid as keys

*Filter this to remove any empty values but preserve the keys

*Extract a sub-array of only the keys

*Pick the last key, which is the real page UID we want

*Assign that to a variable

Then use the {firstPageUidWithMedia} instead of {data.uid}.

A: I am working to upgrade Typo3 from 6.2 to 9.5 LTS, i founded that fluidcontent will be used anymore, now below code used for previewing image in Flux content.
I have replaced my old code:
<f:for each="{v:content.resources.fal(field: 'teaserImage')}" as="image">
    <img src="{f:uri.image(src:'{image.id}',maxWidth:'64',treatIdAsReference:'1')}" alt="{image.alternative}"/>
</f:for>

To Below New code:

 <v:content.resources.fal field="teaserImage" as="images" record="{record}">
        <f:for each="{images}" as="image">
            <f:if condition="{image}">
                <f:image src="{image.id}" treatIdAsReference="1" maxWidth="100"/>
            </f:if>
        </f:for>
 </v:content.resources.fal>

A: I developed this VH which do what you need :
namespace Your\Vendor\ViewHelpers;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Frontend\Page\PageRepository;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;

/**
 * View helper to get the first image of rootline.
 */
class RootlineFirstImageViewHelper extends AbstractViewHelper
{
    use CompileWithRenderStatic;

    /**
     * {@inheritdoc}
     */
    public function initializeArguments()
    {
        $this->registerArgument('pid', 'int', '', true);
    }

    /**
     * {@inheritdoc}
     */
    public static function renderStatic(
        array $arguments,
        \Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ): ?File {
        $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
        $pages = GeneralUtility::makeInstance(PageRepository::class)->getRootLine($arguments['pid']);
        $files = [];
        foreach ($pages as $page) {
            /** @var FileReference[] $files */
            $files = $fileRepository->findByRelation('pages', 'media', $page['uid']);
            if (!empty($files)) {
                break;
            }
        }

        // It would be nice to have an extra argument to get a random image of the array.
        return !empty($files) ? $files[0]->getOriginalFile() : null;
    }
}

Then you can call it like this in your Fluid template :
<f:variable name="rootlineFirstImage"><whatever:rootlineFirstImage pid="{data.uid}"/></f:variable>
<f:if condition="{rootlineFirstImage}">
    <f:image image="{rootlineFirstImage}" width="1280"/>
</f:if>


text:
Q: Is there any distinction between using function or pointer to function notation? Consider the following program:
#include <stdio.h>

void f() {}
void g1(void fun(void)) { printf("%p\n", &fun); }
void g2(void (*fun)(void)) { printf("%p\n", fun); }

int main(void) {
    g1(f);
    g2(&f);
    printf("%p\n", &f);
    return 0;
}

As C11 does not have lambda expressions, there is no way a literal function could be passed as parameter to g1 or g2, so in a way, these two functions do the same thing(you must define the parameters first); I'm reading a book right now that says that

The fact that technically this function (f) is passed on as a function
  pointer (to g1) is usually of minor interest, [...]

So, what I understand is that the writer is saying that both semantically are equivalent.
But the addresses that get printed when calling g1 and g2 are different, where g2 outputs the real address of f. This means that g1 makes a copy of f, meaning that f is passed by value. Is the book wrong or am I? I don't think the book is wrong, but the addresses are different and certainly it matters which one you choose. And if there are any distinctions, which one should be prefered in what scenario?

A: You are very wrong.
Whenever you think you pass a function to a function, you are actually passing a pointer to it.
Whenever a function Looks like it has a function-parameter, it actually has a function-pointer-parameter.
Now, in one of your functions you print the value of a pointer to the argument, in the other the argument. Aside from the fact that %p is for void* not for other data-pointers and especially not for function-pointers, which means you have Undefined Behavior, there is every reason to expect them to be different, especially on an architecture with a shared address space for data and instructions.

A:
But the addresses that get printed when calling g1 and g2 are different, where g2 outputs the real address of f. This means that g1 makes a copy of f, meaning that f is passed by value.

You are incorrect. In both g1 and g2, the variable fun is a function pointer, not a function. Using &fun in g1 gives the address (on the stack) where the function pointer is stored -- not the actual address of the function.
Functions are not values in C or C++. They cannot be copied, and they cannot be passed by value.


text:
Q: Split A string using "," but not ", " in java I have a String like this:
123,TV,August 14, 2020,"This is a fantasy series, and top rated"

I'm using String.split() on this but my delimiter should only separate the string based on comma with no trailing space.
Expected Output
["123","TV","August 14, 2020","This is a fantasy series, and top rated"]

Actual Output
["123","TV","August 14"," 2020","This is a fantasy series", " and top rated"]

It is splitting the strings considering all the commas. I just want to consider the commas with no trailing space or double quotes(").
Can someone please advice me on this?

A: You may combine with a Negative Lookahead (?!\s) to assert there is no space afte the comma
String s = "123,TV,August 14, 2020 ,\"This is a fantasy series, and top rated\"";
List<String> parts = Arrays.stream(s.split(",(?!\\s)"))
        .map(x -> x.replaceAll("^[\"\\s]|[\"\\s]$", ""))
        .collect(Collectors.toList());
for (String p : parts) {
    System.out.println(">>" + p + "<<");
}

>>123<<
>>TV<<
>>August 14, 2020<<
>>This is a fantasy series, and top rated<<


text:
Q: Python - [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091) I have an Amazon linux 2 VM and I am making a python requests from this VM. For making the request I am using self signed certificate.
I have appended the self signed certificate file content to the file "/etc/pki/tls/certs/ca-bundle.crt".
The CURL command works fine, however when making requests using python's requests method it throws below error.
ERROR :  (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)'))
I tried using "verify" parameter for Python requests method by providing path of both "MyAppcert.crt" as well as "ca_bundle.crt" files, however both approach fails.
import requests
requests.get("https://<my-endpoint>:8888/", verify="/home/ec2-user/ssl_cert/MyAppcert.crt")

This same use case works fine on Windows server.
Any help will be appreciated.
Regards,
Rahul Kumbhar

A: @SteffenUllrich Thank you for the response. I verified my certificate using "openssl x509 -in file.pem -text" and found that "keyUsage = Certificate Sign" was missing. After creating new certificate with "keyUsage = Certificate Sign" the issue was resolved.

A: you need to fake the SSL when you send the socket.
Try this in your code:
    import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

or

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

Both working very well for me, for example - https://twitter.com/bro_dev_/status/1447598426120720384?s=20 I have run this code today and it worked.
from:
https://github.com/webprice/python-twitter-examples/blob/f8ad6f69f423afdcbd83d89cc7e17e2f61d92ed4/bs4_SSL


text:
Q: Firebase search for users with same username/ database structure The structure of my database has users with a username that is created when a user creates an account. The username is under the meta data.  I already have over 2000 users and never thought to restrict usernames/ make sure not duplicates or append numbers when people login with facebook or google (I am currently just using their names in those cases).  I want to be able to search for usernames:
  "Users" : {
    "eOhY4Wp6QNUtEjVTdmBff8UDY5p2" : {
      "meta" : {
        "username" : "testName"
      }
    }
  }

I figured the only way would be to create another section that lists usernames in reverse:
"UserList" : {
        "testName" : "eOhY4Wp6QNUtEjVTdmBff8UDY5p2",
      }

But the issue with this is that I can't have multiple users with the same username/ I don't think it's possible to have multiple nodes that have the same key.
Is this the best method to approach this situation?  Or is there an alternative to have the same username (I don't want to pull down the whole users using snapshot since this would be super data intensive).  If this is the best method I was figuring I would go in and manually change the duplicates that are already in the database.
Edited Additional Content:
Here is the only approach I know of to get usernames from first structure would be to get the whole snapshot and then filter for users with the username- this would download the entire snapshot which is super data intensive since I only need the users that have the username that I am searching for:
const snapshot = await firebase.child("Users").on("value")

I know there is the OrderBy method, but isn't that a top level approach/ wouldn't I need "testName" directly under users rather than 2 layers deeper.
    const snapshot = await firebase.child("Users").orderByChild("username")
   .equalTo('testName')

A: Since your user name is in a property that is nested under a known path, you can query it like this:
firebase.child("Users")
   .orderByChild("meta/username")
   .equalTo('testName')


text:
Q: Django why model foreign key cascade will not trigger delete? there two basic ways to do something when an instance gets deleted:

*

*Overwrite Model.delete

*Signal

I used to reckon both of them serve the same purpose, just provides different ways of writing, but works exactly.
However, in this occasion, I realise I was wrong:

class Human(models.Model):
    name = models.CharField(max_length=20)

class Pet(models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(Human, related_name="pet", on_delete=models.CASCADE)

    def delete(self, *args, **kwargs):
        print('------- Pet.delete is called')
        return super().delete(*args, **kwargs)

h = Human(name='jason')
h.save()
p = Pet(name="dog", owner=h)
p.save()

h.delete()
# nothing is shown

Why Pet.delete Is not firing at Human.delete By the foreign cascade? Does I have to apply a signal on this? If so, would it cost more performance?
I am building something very heavy, comment system, filter decent records and delete when the commented target get deleted, the comment model has many null-able foreign key fields, with models.CASCADE Set, only one of them is assigned with value. But in product delete view, I call product.delete Then triggers cascade, but comment.delete Is not firing.
Currently, the project has delete Defined on many models, with assumption that it is always triggered when the instance get removed from database, and it is tremendous work to rewrite it in signal. Is there a way to call delete When at cascading? (I know it is likely impossible since it is a database field specification)

I implement a mix-in for Commendable models with extra methods defined, therefore, I decided to modify delete method to signal to something like this:
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import pre_delete

# Create your models here.
class Base:
    def __init_subclass__(cls):
        @receiver(pre_delete, sender=cls)
        def pet_pre_delete1(sender, instance, **kwargs):
            print('pet pre delete 1 is called')

        @receiver(pre_delete, sender=cls)
        def pet_pre_delete2(sender, instance, **kwargs):
            print('pet pre delete 2 is called')

class Human(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return f'<human>{self.name}'

class Pet(Base, models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(Human, related_name="pet", on_delete=models.CASCADE)

    def __str__(self):
        return f'<pet>{self.name}'

# ------- Pet.delete is called
# pet pre delete 1 is called
# pet pre delete 2 is called

it works fine in testing, I wonder if there is any risk using this, would it be garbage collected?


text:
Q: Is there any difference between f:ajax and a4j:ajax? Is there any significant difference between f:ajax and a4j:ajax tags?
I know about a4j:ajax from Richfaces 4 is based on native f:ajax JSF2 tag adding some attributes not found in f:ajax like onbegin, onbeforedoupdate, bypassUpdates, limitRender, status and focus but which one to use when I only need to send a simple ajax request or partial rendering ? Is there performance issues between f:ajax and a4j:ajax?

A: Here is more information on the differences between f:ajax and a4j:ajax: http://mkblog.exadel.com/2010/08/what-richfaces-a4jajax-adds-on-top-jsf-2-fajax-tag/

A: The <a4j:ajax> tag is just the more convenient form of the basic <f:ajax> tag. You can find a nice overview of all differences in this page.
The execute attribute supports an extra @region value pointing to the <a4j:region>. Any EL in execute and render attributes is resolved in current request instead of in initial request.
The JS function of the onevent attribute of both tags will be invoked 3 times (the passed-in data.status has then the values begin, complete, success). This forces you to use a switch or if when you're only interested in one of them or want to treat them differently. The <a4j:ajax> makes this more convenient with onbegin, onbeforedomupdate and oncomplete attributes respectively. See also this related question: JSF 2: How show different ajax status in same input?
If you're not interested in any of those enhancements, then using <f:ajax> should be perfectly fine as well. The performance difference is (and must be) totally negligible and not be the reason to choose one over the other.


text:
Q: org.springframework.security.oauth2 not working properly I have a problem with initialising org.springframework.security.oauth2. VS code says about troubles resolving it. I think I may have a problem with dependencies and pom.xml, but i don't know how to fix them. It the code below VS doesn't recognize the .oauth2 part at all.
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;

I tried to find solutions online, but I couldn't understand them or how to implement it in my own situation.


text:
Q: Convert Windows Application to Windows Service I am having a Windows Application and I want to run it with WINDOWS SERVICE. I have created a WINDOWS SERVICE Application, now How would I integrate my WIN APP within this windows service application?

A: This is quite a common requirement and I suggest you to consider the following:
My code will be be using the following package  : TopShelf
After :
nuget Install-Package Topshelf

In your start have something like the following :
    public static int Main()
    {
        var exitCode = HostFactory.Run
        (
            c =>
            {
                c.Service<Service>
                (
                    sc =>
                    {
                        sc.ConstructUsing(name => new Service());

                        sc.WhenStarted((service, hostControl) => service.Start(hostControl));

                        sc.WhenStopped((service, hostControl) => Service.Stop(hostControl));
                    }
                );

                c.SetServiceName("ServiceName");

                c.SetDisplayName("DisplayName");

                c.SetDescription("Description");

                c.EnablePauseAndContinue();

                c.EnableShutdown();

                c.StartAutomaticallyDelayed();

                c.RunAsLocalSystem();
            }
        );

        return (int)exitCode;
    }

And follow the configuration available in
TopShelf configuration
We are using TopShelf in lots of our projects and it completely fulfills our needs.


text:
Q: How to inject content page with form data after submission? When you build a form on Squarespace, you can redirect the user to another content page on form submission. Is there a way to inject values from that form to the new content page?

A: Yes, there is a way to do it with the following approach, assuming that the page you are redirecting to is on the same domain:

*

*Add a submit event listener to the form. This should not interfere with Squarespace's own submission functionality.

*Within the function called by the listener, serialize the form's data/fields.

*Store the serialized data within sessionStorage.

*Access the sessionStorage data on the new page.

*Parse the serialized data if necessary and utilize it within a function on the new page.

If the new page is instead on a separate domain, then things would be done similarly except that instead of using Squarespace's own feature for setting the new landing page, you'd use JavaScript to set the window.location, passing the sessionStorage data as query parameters to the new page.


text:
Q: How to locate corresponding arrayList entries from textfile in Java14 I've run into a problem with my code. I'm reading employer information out of a text file. There are fifteen total employees with corresponding names, age, and department. Each department has 5 employees. Example of txt file:
|Kyle; 35; Floral |
|John; 40; Meat   |
|Alex; 25; Dairy  |
|Matt; 30; Floral |
|Jill; 45; Floral |
| ...             |

These 3 pieces of information(name,age,dept) are stored into an array list that has 15 elements.
The program firsts asks for the department:
Ex:
Where is the employee located?
1. Floral
2. Meat
3. Dairy

inputs 1
Choosing a number only lists the employees of the department.
Which employee in Floral would you like to view information?
1. Kyle
2. Matt
3. Jill
4. ...
5. ...

This is the issue. I need a way to track the employee's element in array list and display contents. For example, picking Matt would correspond to ArrayList element of [0]. Is there a way to connect ArrayList elements in such a way that you can split them up in categories and subcategories?

A: You said:

These 3 pieces of information(name,age,dept) are stored into an array list that has 15 elements.

No, mixing various pieces of data across elements of a single list is a poor choice of data structure.
Being object-oriented, Java lets you define a class as your own custom data type.
In Java 16, this has become much easier when the main purpose of your class is to communicate data transparently and immutably. The new records feature enables a very brief class definition. The compiler implicitly creates the constructor, accessor methods, equals & hashCode, and toString.
public record Employee ( String name , int age , String department ) {}

Make your list of employees.
List< Employee > employees = new ArrayList<>() ;
employees.add( new Record ( "Kyle" , 35 , "Floral" ) ) ;
employees.add( new Record ( "John" , 40 , "Meat" ) ) ;
…

Loop those to generate your menu.
int nth = 0 ;
for( Employee employee : employees )
{
    nth ++ ;
    Sytem.out.println( nth + employee.name() ) ;
}

Subtract one from the user's choice of one-based ordinal number to get a zero-based index number.
int userChoice = … ;
int index = ( userChoice - 1 ) ;
Employee employee = employees.get( index ) ;
System.out.println( employee ) ;

If you want to narrow the list to employees of a certain department, make another list.
String targetDepartment = … ;
List< Employee > employeesForOneDept = new ArrayList<>() ;
for( Employee employee : employees )
{
    if( employee.department().equals( targetDepartment ) )
    {
        employeesForOneDept.add( employee ) ;
    }
}

There are more sophisticated ways to go about this. But as a beginner, this is a good way to start.


text:
Q: Operation subclass "main" method not getting called when OperationQueue executes? I have created a subclass "MyOperation" inheriting from base class "Operation". I have added a function in "MyOperation" which gets called when the class in instantiated. However the "main" method is not getting called when the operation class is created and added to an Operation Queue.
class MyOperation: Operation {

let iterations:Int
let tag:String

init(iterations:Int, tag:String) {
    self.iterations = iterations
    self.tag = tag
}

/**
 When Operation queue begins execution it calls the main method without parameters, so any parameters needed should be passed through initializer.
 **/

override func main() {
    performCalculation()
}

func performCalculation(){
    let start = CFAbsoluteTimeGetCurrent()
    for _ in 0..<iterations {

        self.doCalculations()
    }
    let end = CFAbsoluteTimeGetCurrent()
    print("time for \(tag):\(end-start)")
}

func doCalculations() {

    let x = 100
    let y = x*x
    let _ = y/x
}

}

I am calling MyOperation class from ViewDidLoad of a viewcontroller.
override func viewDidLoad() {
    super.viewDidLoad()
   createOperationQueuewithMyOperationClass()
}

func createOperationQueuewithMyOperationClass(){

    let operationQueue = OperationQueue()
    operationQueue.addOperation {
        MyOperation(iterations: 10000000, tag: "Operation-1")
    }

    operationQueue.addOperation {
      MyOperation(iterations: 1000, tag: "Operation-2")
    }

    operationQueue.addOperation {
      MyOperation(iterations: 100000, tag: "Operation-3")
    }
}

A: You are using the wrong addOperation. The one you have simply adds a block operation onto the queue and the block is creating the operation and doing nothing with it. You want this:
operationQueue.addOperation(MyOperation(iterations: 100000, tag: "Operation-3"))

Note the lack of braces { ... } and the parentheses instead.
You were calling addOperation(() -> Void) instead of addOperation(Operation)


text:
Q: attack of the b team server isn't working well please help My Attack of the B Team server suddenly shut down. When it is starting it crashes.
This is the crash report:
Encountered an unexpected exception IllegalArgumentException
java.lang.IllegalArgumentException: Too big view radius!
    at net.minecraft.server.management.PlayerManager.<init>   (SourceFile:166)
    at net.minecraft.world.WorldServer.<init>(WorldServer.java:113)
    at  net.minecraft.server.MinecraftServer.func_71247_a(MinecraftServer.java:24 6)
    at net.minecraft.server.dedicated.DedicatedServer.func_71197_b(DedicatedSe rver.java:187)
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:445)
    at net.minecraft.server.ThreadMinecraftServer.run(SourceFile:583)
2014-06-03 15:43:57 [SEVERE] [Minecraft-Server] This crash report has   been saved to:   /Users/rodrigobracamonte/Desktop/BTeam_Server_v1.0.10b/./crash- reports/crash-2014-06-03_15.43.57-server.txt
2014-06-03 15:44:03 [INFO] [ForgeModLoader] [BiomesOPlenty] Version check failed

What can I do to fix this? 3 days ago it worked perfectly well.

A: As DatEpicCoderGuyWhoPrograms points out, the error here is
java.lang.IllegalArgumentException: Too big view radius!

You will need to locate your server.properties file. On Unix, this file is generated in the working directory, according to the wiki. Just search for it if you can't find it in the usual suspect folders (like the server folder, or your user folder).
Open the file with a text editor, and change the entry for view-distance to a value between 3 and 15. 10 is recommended, high view distances are quite demanding on your system.


text:
Q: landsat NDVI time series plot in R, based on point or pixel I am using R language and I would like to create a NDVI time series plot, NDVI vs time, based on irregular intervaled landsat images. I have found a method to create a raster stack and plot the average NDVI of the total area over time. Average NDVI is okay, but i would like to plot for a selected point (pixel based or xy coordinate) within the area.
Any suggestion? I am very new to R so a step by step explanation would be really helpful

A: Do you want an interactive map, or are you fine with plotting the NDVI timeseries for one (or few) specific points? In the latter you raster::extract() the NDVI-Stack values under your points, and use the returned dataframe as input for your plot.

Edit:
I was thinking... You actually can do some interactive point-selection using raster::click(). So as a little example I just wrote this for you:
library(raster)
# Sample Dataset
year2000 <- raster(nrows=10, ncols=10, vals=runif(100, -1,1))
year2005 <- raster(nrows=10, ncols=10, vals=runif(100, -1,1))
year2010 <- raster(nrows=10, ncols=10, vals=runif(100, -1,1))
year2015 <- raster(nrows=10, ncols=10, vals=runif(100, -1,1))

NDVI.stack <- stack(year2000, year2005, year2010, year2015)  # Representing your layerstack

# Plot Stack, select point and automaticly extract values
plot(NDVI.stack[[1]])  # One exemplary layer for orientation
values <- click(NDVI.stack, n=1)

# Compose and plot dataframe
timeseries <- data.frame(year = c(2000, 2005, 2010, 2015),
                         values = values[1, ])
plot(timeseries, type="l")


text:
Q: Relation between angular velocity and linear velocity in a pendulum For a pendulum in simple harmonic motion, I understand that the period is independent of amplitude, and I know that the angular velocity is inversely proportional to the period. However, doesn't the angular velocity change as linear speed changes?

A: Yes there is a very simple relationship between the angular velocity and the tangential velocity, given by $v_t = \omega r$, where $v_t$ is the tangential velocity, $\omega$ is the angular velocity and $r$ is the radius of the pendulum.

A: There are two different concepts of angular velocity associated with a pendulum, and you have mixed up the two.
The displacement of the pendulum is given by something like:
$$ x = A \sin(\omega t) \tag{1} $$
where $\omega$ is a constant called the angular velocity and related to the frequency and period by:
$$ \omega = 2\pi f = \frac{2\pi}{\tau} $$
However there also the angluar velocity of the pendulum bob around the pivot point which is given by:
$$ \Omega = \frac{v}{r} $$
and if we differentiate equation (1) to get the velocity we get:
$$ \Omega = \frac{A\omega}{r} \cos(\omega t) \tag{2} $$
so this second type of angular velocity is not a constant. Your confusion arises because you have mixed up the constant $\omega$ and the variable $\Omega$.


text:
Q: math with ctime and time_t Does anyone know how todo math with ctime? I need to be able to get the time in sec in "time_t" (like it normally does) and then subtract a set number of seconds from it before inputting time_t into ctime to get the time and date.
so basically it would calculating the date of so many sec ago.

A: time_t
The most basic representation of a date and time is the type time_t. The value of a time_t variable is the number of seconds since January 1, 1970, sometimes call the Unix epoch. This is the best way to internally represent the start and end times for an event because it is easy to compare these values.
struct tm
While time_t represents a date and time as a single number, struct tm represents it as a struct with a lot of numbers:
struct tm
{
  int tm_sec;            /* Seconds.    [0-60] (1 leap second) */
  int tm_min;            /* Minutes.    [0-59] */
  int tm_hour;            /* Hours.    [0-23] */
  int tm_mday;            /* Day.        [1-31] */
  int tm_mon;            /* Month.    [0-11] */
  int tm_year;            /* Year    - 1900.  */
  int tm_wday;            /* Day of week.    [0-6] */
  int tm_yday;            /* Days in year.[0-365]    */
  int tm_isdst;            /* DST.        [-1/0/1]*/
};

Conversion
You can convert a time_t value to a struct tm value using the localtime function:
struct tm startTM;
    time_t start;

    /* ... */

    startTM = *localtime(&start);

So,you can subtract subtract a set number of seconds like this
startTm.tm_sec -= somesecond;

add convert to time_t like this
struct tm startTM;
    time_t start;

    /* ... */

    start = mktime(&startTM);

and use ctime fun to convert date
ctime(&start)

hope it can helpful!

A: You can try:
time_t now = time( NULL);
struct tm now_tm = *localtime( &now);
now_tm.tm_sec -= 50;   // subtract 50 seconds to the time
now_tm.tm_sec +=1000;  // add 1000 sec to the time
printf( "%s\n", asctime( &now_tm));

A: time_t is an integral type.  It always represents a number of seconds, so you can freely add/subtract integers from it.
Example:
time_t now = time(nullptr);
time_t one_minute_ago = now - 60;
std::cout << ctime(&one_minute_ago) << std::endl;


text:
Q: passing object with collection from domain to modelDTO with nhibernate above is code which I use to manipulate with data from my domain to dto model, which I use for wcf serialization. My question is how to pass object mother with collection of childrens into MotherDTO. With current code situation I pass only data without collection children. Do I need to use session in line and to add session  MotherDTO dto = new MotherDTO(data, session); and to use that session to retreive collection of childrens in dto. If so, how ? Please help.
Regards,
public MotherDTO GetMotherData()
    {
        using (ISession session = instance.OpenSession())
        {
            using (ITransaction tx = session.BeginTransaction())
            {
                Mother data = session.Query<Mother>()
                    .Fetch(x => x.Childrens)
                    .FirstOrDefault();
                tx.Commit();

                MotherDTO dto = new MotherDTO(data);
                return dto;
            }
        }
    }

MotherDTO.cs
        public MotherDTO(Mother x)
        {
            Name = x.Name;
            List<Children>Childrens= new List<Children>();
            foreach (Children obj in x.Childrens)
            {
                States.Add(obj);
            }
        }

Mother.cs
 public virtual string Name
        {
            get { return _Name; }
            set
            {
                _Name = value;
            }
        }

        public virtual Iesi.Collections.Generic.ISet<Children> Childrens
        {
            get
            {
                return _Childrens;
            }
            set
            {
                if (_Childrens == value)
                    return;
                _Childrens = value;
            }
        }

A: Since you're already (eager) loading your Children collection you can use Automapper to populate your DTOs.
If you want to know how to configure Automapper to work with nested collection you can read here:
Mapper.CreateMap<Order, OrderDto>()
    .ForMember(dest => dest.OrderLineDtos, opt => opt.MapFrom(src => src.OrderLines));
Mapper.CreateMap<OrderLine, OrderLineDto>()
    .ForMember(dest => dest.ParentOrderDto, opt => opt.MapFrom(src => src.ParentOrder));
Mapper.AssertConfigurationIsValid();


text:
Q: VoiceXML without Telephone I want to run my Vxml application locally without using Telephone.
IS it possible or not? If so please tell me software which is needed and also direct me how  to run?

A: Use Voxeo's Prophecy.  You can download a 2 port version of their software for free and it runs VoiceXML and CCXML.  It is highly compliant with the standards since they have employees on the standards committee.  It comes with a free Text-To-Speech (TTS) and speech recognition system.  Their extreme tech support is also free. It also comes with SIP softphone that you can use to place calls into it using your PC's mic and speakers.  You can go to this blog for more information on how to install and test VoiceXML applications on Prophecy.


text:
Q: Build Node doesn't appear in Team Explorer for a C# DLL project in Visual Studio 2013 linked to TFS-Git I've created a TFS + Git project on tfs.visualstudio.com. I've commited my changes and pushed them on Master to the Git repo hosted on TFS.
In Team Explorer, I see the usual "Changes", "Branches", "Commits" and "Settings" Nodes/Menu. However the "Build" node is not there at all.
When creating a MVC 4 application however, the "Build" Node is always there.
It looks like the Build Definition is hosted on TFS for my MVC application but there's no way to create a new one for my DLL Project, inside the IDE or on the TFS web side (in the Build section).
Do you have any idea what I'm doing wrong?
Should I quit the idea to build a custom DLL using TFS?

A: Ok it looks like it was a glitch in Visual studio 2013 preview / TFS.
I've copy/pasted a ProcessTemplate generated from an Azure Solution linked to TFS, commited it to Git, deleted it from Git, restarted Visual Studio and magically the "Builds" Node in the Team Explorer appeared as well as the "Work Items".
I guess this is more like a bug in Visual Studio than a manipulation error.

A: I think you are on the "Source Control" pane. If you click the "Home" icon at the top of the Team Explorer window you should see "Source Code | Commit | Work Items | Build | Settings"... You can then delve into "Build" from there...


text:
Q: Passing member function that accepts void * I am working on code that needs to send a member function pointer to a logger method that accepts a void * as the parameter.  I cannot change it from void *.  I cannot use c++11 either.  Is there a way to get it to work without any warning.  For example:
logger.h
    #ifndef _LOGGER_H
    #define _LOGGER_H

    void logger( void *func );

    #endif /* _LOGGER_H */

logger.cpp
    #include <cstdio>
    #include "logger.h"

    void logger( void *func )
    {
        printf("%lx\n", (unsigned long)func);
    }

testCase.cpp
    #include "logger.h"

    class myClass
    {
        public:
            void testCase( void );
    };

    void myClass::testCase( void )
    {
        /* This works on my compiler, but gives warning */
        /* warning: converting from 'void (myClass::*)()' to 'void*' */
        /* I know this is bad and wrong. */
        logger((void *)&myClass::testCase);

        /* This compiles without warning */
        /* But doesnt work the way I need, gives ffff*/
        void (myClass::*ptr)( void ) = &myClass::testCase;
        void *m_ptr = ptr;
        logger(m_ptr);
    }

logger.h and logger.cpp cannot be changed.
This is being run a VxWorks and I need the address to look up in the symbol table.  When I try the second way I get ffff.  Although I get a real address when using other compilers, its different for VxWorks.
Can you think of another way to get this to work.
References

A: No, you can't make it happen. Standard prohibits converting pointers-to-members  to void*. The reason for this is their incompatibility with void* - they are usually double the size of the void*.
Your code has other issues as well, for example, (unsigned long)func is converting a void* to unsigned long, and this is undefined as well. For example, on many systems long is 32 bits in length, while void* is 64bit. To reliably convert void* to integer type, you need to use uintptr_t (provided your implementation has it).

A: I don't know about "double the size"; pointers are pointers and in my understanding, all pointers on a given system are the same size, regardless of what they point to...
However, looking in my copy of The C++ Programming Language, 3rd Edition, by Stroustrup (page 101):

Occurrances of void*s at higher levers of the system should be viewed with suspicion because they are likely indicators of design errors.  Where used for optimization, void* can be hidden behind a type safe interface (§13.5, §24.4.2).
Pointers to functions (§7.7) and pointers to members (§15.5) cannot be assigned to void*s.


text:
Q: Understanding a solution to counting hexagons on a soccer ball
Each face of a soccer ball is either a pentagon or a hexagon. Each
pentagonal face is adjacent to five hexagonal faces and each hexagonal
face is adjacent to three pentagonal and three hexagonal faces. If the
ball has 12 pentagonal faces, how many hexagonal faces are there?
A. 12 B. 20 C. 24 D. 8 E. None of the above

This is from math olympiad for middle school students. I tried to solve this but failed.
I found a solution for this problem but it is not possible to understand the solution. Could someone elaborate more about the existing solution or give an easier solution?

Each pentagon has 5 sides and each hexagon has 6 sides. Total number
of sides of the pentagons = 5 × 12 = 60. Total number of hexagons= 60/3
= 20. since each hexagonal face is adjacent to 3 hexagonal faces. Answer: (B)

When it says 60 it doesn't consider double counting of sides. Also, I can't understand the last two sentences of the solution (from total number...)

A: To make it a bit more explicit:  Let's count all of the edges that are shared by pentagons and hexagons.  We'll call such an edge a "5/6 edge".  (We don't need to worry about the edges between two different hexagons for this argument.)  We can count the 5/6 edges in two ways.

*

*Every pentagon has five "5/6 edges", since each pentagon borders five hexagons.  Since there are 12 pentagons, there are 60 "5/6 edges" on the soccer ball.

*Every hexagon has three "5/6 edges", since each hexagon borders three pentagons.  If there are $n$ hexagons, there are $3n$ "5/6 edges" on the ball.
But these two numbers must be equal, implying $3n = 60$ or $n = 20$.

A: Two givens:

*

*A pentagonal face is adjacent to 5 hexagons

*A hexagonal face is adjacent to 3 pentagons and 3 hexagons.

Suppose there are 12 pentagonal faces in all, each having 5 sides. By 1., no two pentagonal faces share a common side. Thus, the total number of sides of the pentagons is simply 12*5=60.
Great, so there are 60 distinct pentagon sides. Now, naively using 1. in isolation, we might first guess there are 60 hexagons, one for each pentagon side.  But this guess would be overcounting, because there is not a one-to-one mapping between pentagon sides and hexagons. In particular, counting three pentagon sides only corresponds with counting one hexagon (using 2.). Thus, 60 counts each hexagon thrice, so dividing our guess by 3 gives us our answer of 20 hexagons.
And in case the visual helps...


text:
Q: How to shift array elements after removing one? I need to add a shift function only with loops (it means I can't use any ListArray method et simila, so this is not a copy of any other question with those methods.) to this method which removes a specific integer from a given array, and put the outcome into another array, and then returning it.
public static int[] removeInt(int v, int[] in) {

    int length = 0;
    length = in.length;
    int[] toReturn = new int[length];

    for (int b = 0; b < length; b++) {
        toReturn[b] = 0;
    }

    for (int i = 0; i < length; i++) {
        if (in[i] != v) {
            toReturn[i] = in[i];
        }
    }

    return toReturn;
}

If the input for the array is {1, 2, 3, 4, 5}, and the number to remove is {2}, the output will be {1 0 3 4 5}, but it needs to be {1 3 4 5}, and I can't find a way to shift numbers to the left.
'v' comes from the main, user input. Same for 'in', fullfilled before by the user.

A: Have you considered using a LinkedList? This internally manages the array so you don't need to deal with moving the elements yourself; you can just call remove().

A: You will have to iterate over the array two times: The first time, you count how often v is contained in in. If count is 0, you can return in, otherwise you would have to create a new array of length in.length - count. Then again you have to iterate over in and add every value that is not v to your Array.
int count = 0;

    for(int i: in) {
        if (i==v) {
            count++;
        }
    }

    int[] result = new int[in.length-count];
    int pos=0;
    for(int i: in) {
        if (i!=v) {
            result[pos] = i;
            pos++;
        }
    }

But you could use Collections to make it easier:
public static void main(String[] args) {
    int v = 2;
    int[] in = new int[]{1, 2, 3, 4, 5};

    List<Integer> list = new ArrayList<>();
    for(int i: in) {
        if (i!=v) {
            list.add(i);
        }
    }

    Integer[] result = list.toArray(new Integer[]{});
}

The disadvantage of this, however, would be that you have an Array of Integer and not of int.


text:
Q: What is the justification for locking votes? Why am I not allowed to change my vote after some period of time? There are times when I go back to things I voted on, and decide they didn't deserve that specific vote. (I get wiser as I grow older)

A: Basically it's to stop people gaming the system.
One of the ways people did this was by down-voting rival answers and then removing that vote when their answer gains popularity. There are others.
See the following blog entries:
https://blog.stackoverflow.com/2008/12/vote-fraud-and-you/
https://blog.stackoverflow.com/2009/03/more-voting-anomalies/

A: The justification of Jeff to prevent the "tactical downvoting" is not good enough.
It could be prevented by different approach, as I suggested in https://meta.stackexchange.com/a/135243/163139
The time limit to undo  up-vote could be completely removed.
When user tries to undo downvote, it should be allowed after time limit(currently 5 min), but do not refund reputation point.
These changes will allow users to freely undo their up and down-votes but still will prevent unhonest "gamers" to restore points by undoing down-votes.


text:
Q: Separate text only up to the sixth bar in the value For values of this type:
https://int.testlink.com/international/europe/uefa-cup/20212022/3rd-qualifying-round/r63669/

I use this formula:
=ARRAYFORMULA(REGEXEXTRACT(A1:A,REGEXREPLACE(A1:A,"(https?:\/\/([\w.-]+\/){4})","($1)")))

To retrieve this type of value up to the sixth bar:
https://int.testlink.com/international/europe/uefa-cup/

But for this type of value it contains @@@@ and $$$$:
https://int.testlink.com/national/scotland/third-division/@@@@/regular-season/$$$$/

The result is an error, I would like to know how I should modify it to carry out the collection that deviates from the issue of special symbols.

A: Try:
=ARRAYFORMULA(REGEXEXTRACT(A1:A,REGEXREPLACE(A1:A,"(https?:\/\/([\w.-]+\/){4}).*","($1)")))


text:
Q: How to replace old document with new document in mobile storage using download manager? My question is I need to use sync function after every 15 minutes, So what I want is, I will send doc_id to web server and server will return a new doc_Id with some fields, what i want is to replace old document with new one.
my code:
 public void Updatefile(String Doc_Id)
{
    try
    {
        SoapObject Subfolderrequest = new SoapObject(NAMESPACE, UPDATE_FILE_METHOD);
        Subfolderrequest.addProperty("DocumentID", Doc_Id);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Subfolderrequest);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.debug = true;
        androidHttpTransport.call(SOAP_ACTION_UPDATE_FILE , envelope);
        SoapObject SubfolderResponse = (SoapObject)envelope.getResponse();
        Log.i("SubFolders", SubfolderResponse.toString());
        for(int i=0; i < SubfolderResponse.getPropertyCount(); i++)
        {
            SoapObject SingleSubFolder = (SoapObject)SubfolderResponse.getProperty(i);
            ID = SingleSubFolder.getProperty(0).toString();
            fileLongName = SingleSubFolder.getProperty(1).toString();
            UserFileName = SingleSubFolder.getProperty(2).toString();
            url = SingleSubFolder.getProperty(3).toString();
            fileExtension = SingleSubFolder.getProperty(4).toString();
            lastModifiedDate = SingleSubFolder.getProperty(5).toString();
            SubjectType = SingleSubFolder.getProperty(6).toString();

        }
        if(IsUpdated==true){
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setTitle(UserFileName);
            // in order for this if to run, you must use the android 3.2 to compile your app
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", UserFileName);
                    DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
                    manager.enqueue(request);
        }
        else
        {

        }
    }
    catch(Exception e)
    {
        Log.i("Hi", "Exception");
    }
}

What I want is, i will pass id's one by one and If document has been updated then it will check with Boolean value "isupdated" from web server, if "isUpdated" will be true then It will replace document otherwise not. Please let me know how to replace the document with existing one.
Also I am calling method in Broadcast receiver, which is giving error in line :
:    DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
 //error in getSystemService... thank you. :)


text:
Q: load js from filesystem into spring boot jar application (with thymeleaf) I have kind of a utility made with spring boot with bundled tomcat packaged into executable jar.
what i need is to have some js (or possibly json) files in the same folder as the jar file and be able to insert them into the thymeleaf template.
e.g.
<script type="text/javascript" src="somepath/myfile.js"></script>

I have managed to do this so far:
In controller:
String userDir = System.getProperty("user.dir");
model.addAttribute("userDir", "file://"+userDir+"/");

In template:
<script type="text/javascript" th:src="${userDir + 'myfile.js'}"></script>

at this moment I am able to see the code inside myfile.js via firebug html view, but not in scripts tab, nor the script is executed (any variable defined in this file is undefined).
How to do it?
I know I can create a json file and process it via java, but if solution I am searching for exists, Its much simpler and more convenient for me to use, moreover that way I can use custom js, not only json.
I also know this would be very unsafe in many cases, but in this case the app doesn't have to be safe at all, no matter what one wants to inject via the files.

A: You can customize the WebMvcConfigurationAdapter to add some file system folder to resource registry.
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Value("${resources}")
    private String resources;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        if (resources != null) {
            registry.addResourceHandler("/myresources/**").addResourceLocations("file:" + resources);
        }
        super.addResourceHandlers(registry);
    }

}

then provide --resources parameter when you are executing the jar. Please note trailing /

java -jar your_jar_file --resources=/path/to/resources/

Also note that resources from this path are registered against /myresources/ path so you need to modify your template as below
<script type="text/javascript" src="myresources/myfile.js"></script>

myfile.js should be present in path mentioned in --resources parameter
Update #1 (I have not tested this but you can try)
Just found that spring boot supports a property to customize the static locations
Refer Spring Common Properties Appendix
The Property you need to define in application.properties is below
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

Append your locations to it. You can use file resource also like
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/tmp/resources


text:
Q: $digest() called ten times when using custom filters I have the following angular markup:

    {{ dia[0].fecha }}

            {{hora}}

{{evento.cantidad}} {{ tipoAMedida(evento.tipo) }}

the line
 causes angular to throw the following error:
0x800a139e - JavaScript runtime error: 10 $digest() iterations reached. Aborting!
if I remove one of the filters, the code works fine. According to what I know, filters are chained properly. What could be causing this?
Here are the filters:
soloBloque:
function soloProp(prop) {
    return (function (prop) {
        return function () {
            return function (input, valor) {
                return _.filter(input, function (e) { return e[prop] === valor; });
            }
        }
    } (prop));
}

soloBloque = soloProp('bloque');
soloHora = soloProp('hora');

sacarHoras:
function sacarHoras () {
    return function (input) {
        return _(input).map('hora').unique();
    }
}

A: The problem was with lodash's method chaining. _(input) caused angular to trip up. I changed return _(input).map('hora').unique(); to return _.unique(_.map(input, 'hora')); in sacarHoras and now it's working fine.


text:
Q: Can a struct have several names? I am a beginner in C language, so I was seeking for some projects. And I found a project named bank management system. I went through the code and find this weird struct. Can anybody explain me this code snippet and how to use this kind of structs.
struct {
    char name[60];
    int acc_no,age;
    char address[60];
    char citizenship[15];
    double phone;
    char acc_type[10];
    float amt;
    struct date dob;
    struct date deposit;
    struct date withdraw;
}add, upd, check, rem, transaction;  // What are those names? Are they several names for the `struct`?

And also this struct is in a function called menu. Can we use this struct in another function without passing it to function?

A: Here add, upd, check, rem, transaction are all variables of that structure type. The structure itself has no name, also known as unnamed struct.
To elaborate, the syntax for a structure declaration is:
      struct-or-union-specifier:
              struct-or-union identifier(opt) { struct-declaration-list }

where you can see the identifier is optional. So we can have unnamed structs.

A: As Sourav explained, add et al. are variables of type struct. This is usually discouraged if more definitions are required of this type.
If re-use of structs are intended, then a name needs to be mentioned while defining the struct, like the following:
struct foo {
  int a; etc.
} add, upd;

and then later,
struct foo check;

The scope of this definition is the same scope it is defined in. As you mentioned it is declared in a function, the scope of this is only that function.


text:
Q: class declaration error I try to declare the following class in C++; however, I have gotten the following error. Is there something wrong with pointers?
class classFather{
public:
    int BmcCommand;
    int BmcDataLength;
    byte BmcDataBuffer[];

    classFather() {
        BmcCommand = 0;
        BmcDataLength = 0;
        BmcDataBuffer = new byte[CMD_LENGTHH];
    }

    classFather(byte s8Command, int siLength, byte as8Data[]) {
        BmcCommand = s8Command;
        BmcDataLength = siLength;
        int size = sizeof( as8Data ) / sizeof( as8Data[0] );
        BmcDataBuffer = new byte[size];
        for(int ii=0; ii< size; ii++)
            BmcDataBuffer[ii] = as8Data[ii];
    }
private:
    static const short CMD_LENGTHH = 255;
};

I'm getting the following error:
error: incompatible types in assignment of `byte*' to `byte[0u]'
C:\....\BluetoothClient\/msgCAN.h: In constructor `msgCANFather::msgCANFather(byte, int, byte*)':

A: You're missing a ; after byte BmcDataBuffer[] and the class declaration looks wrong, too: classFather{ should be class Father { I guess.

A:

byte BmcDataBuffer[]

Change that to
byte *BmcDataBuffer;

Oh, and by the way, these lines:

classFather(byte s8Command, int siLength, byte as8Data[]) {
     int size = sizeof( as8Data ) / sizeof( as8Data[0] );

are wrong also. You can't determine the length of a passed-in array that way.

A: by writing byte BmcDataBuffer[], you declare and array. An array is NOT a pointer, so you can not assign new byte[CMD_LENGTHH] to it. Change you declaration to byte *BmcDataBuffer will solve your compilation error.
By doing it, you need to remember to delete your newly allocated data when the object is destruct by doing something like
~classFather() {
   delete BmcDataBuffer;
}

otherwise, you would have memory leaks.

A: In addition,
int size = sizeof( as8Data ) / sizeof( as8Data[0] );

does not what you expect. The size of a C-style array passed to a function is always unknown.
You should have an additional parameter for size or use std::vector.

A: As others said, you try to assign a pointer to an array.
Better then writing memory leaks this way (I see a new but no delete), use a vector:
std::vector<byte> BmcDataBuffer;

Father(byte s8Command, int siLength, byte as8Data[]) {
    ...
    BmcDataBuffer.insert( BmcDataBuffer.begin(), asData, asData+size );
    ...
}

Note:
int size = sizeof( as8Data ) / sizeof( as8Data[0] );

Will always return sizeof( byte* ) / sizeof( byte* ), i.e. 1.
Note 2: you could use an initializer list to create the vector member in one go:
Father(byte s8Command, int siLength, byte as8Data[])
: BmcDataBuffer( asData, asData+size )
{
}

the vector constructor will copy all asData elements.


text:
Q: Use Silverlight Isolated Storage To Keep Authentication Token? I would like to hear some opinions about using the isolated storage in Silverlight for storing sensitive data. For example, is it OK to store an authentication token (some GUID that identifies a server-side session) in this storage, or is it better to use cookies?
The isolated storage gives an advantage over cookies in that it is shared across browsers, but it might be more difficult to handle expiry, and there might be some other issues (security?) that I am not aware of.
So... what are your opinions? Or do you know any great articles about the topic?
Thanks, Jacob

A: I've just started on a Silverlight project that uses Isolated Storage to store a login token that formerly was stored in a cookie when the app was written in ASP.NET.
The only thing I noticed with the end result was that each type of browser would remember the same user (as opposed to the cookie solution where every browser had it's own cookie store and it's own idea of who was logged in).
Security is not going to be substantially different - if you feel inclined to - encrypt the token.  Though really why would you bother?  If any process has access to a person's private AppData they're going to have access to all sorts of confidential information.
The app's url determines access, so no one can get at the data unless your domain name expires.

A: Other than the advantage of sharing the token across multiple browser instances, which I personally haven't ever seen the need for, I think I'll stick to using cookies for now. Why? Because they are better supported by intermediaries like proxy servers and HTTP accelerators. In general I adopt a "use the standard" rather than a "roll your own" approach - it results in less code to maintain and more familiar code for new developers.


text:
Q: Run sync code in async code - promise Im using the following code with promises, the thing which bother me is that I use readdirsync and
fs.statSync  inside promise, could it be wrong , I ask it since currently it works as expected but I wonder
If I can came into issue's .or there is better way to write it?
What I did is extract root folder and then I extract the Childs
function unzip(filePath, rootP, fileN) {

    return new Promise((resolve, reject) => {
        extract(filePath, {dir: rootP, defaultDirMode: '0777'}, (err) => {
            if (err) {
                reject(err);
            }
            fs.readdirSync(path.join(rootP, fileN
)).forEach((file) => {
                const zipPath = path.join(rootP, fileN
, file);
                if (fs.statSync(zipPath).isFile()) {
                    if (path.extname(file) === '.zip') {
                        let name = path.parse(file).name;
                        let rPath = path.join(rootP, fileN)
                        return unzipChilds(zipPath, rPath, name)
                            .then(() => {
                                return resolve("Done");
                            });
                    }
                }
            });

        });

    });
}

A: I would suggest using Promises and async/await for all your logic flow like this:
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const extractAsync = Promise.promisify(extract);

async function unzip(filePath, rootP, fileN) {
    await extractAsync(filePath, {dir: rootP, defaultDirMode: '0777'});
    let files = await fs.readdirAsync(path.join(rootP, fileN));
    for (let file of files) {
        const zipPath = path.join(rootP, fileN, file);
        let stats = await fs.statAsync(zipPath);
        if (stats.isFile() && path.extname(file) === '.zip') {
            let name = path.parse(file).name;
            let rPath = path.join(rootP, fileN);
            await unzipChilds(zipPath, rPath, name);
        }
    }
}

// usage:
unzip(...).then(() => {
    // all done here
}).catch(err => {
    // process error here
});

Advantages:

*

*Consistent and complete error handling.  Your version had multiple places where errors were not handled properly.

*All asynchronous I/O so it won't interfere with scaling for a server.

*async/await makes async logic flow simpler to follow


text:
Q: Comparing model fit with heteroscedastic data I am developing a physiological test using R that requires some parameters optimised.  In comparing the new method against the existing method, the values of individual readings correlate in a linear way but are very heteroscedastic - the variance approximately proportional to the mean.
I would like to compare the effects of various parameter changes by examining the goodness-of-fit of the linear models compared with each other.  Confidence intervals around the linear model parameters are not needed. Comparing  R squareds does not seem appropriate given the heteroscedasticity.  Would distance correlation or R squared after HCCM correction be appropriate ways to test if one method is superior to another ?


text:
Q: File naming convention in XCode While at WWDC I noticed a file naming convention in. One of the demos that I had not seen before.  The example had :
AppDelegate.h
AppDelegate.m
AppDelegate_animation.m

The _animation file semed to have all animation related code.
Is this naming convention documented anywhere?

A: I haven't seen any Docs on the underscore, but here's a good start:
https://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html

A: I don't think apple has much in terms of documenting something as arbitrary as naming your object code files ..
Its an interesting idea, not even using a category, simply splitting the object code out and have the same header file be in charge of them both. (I personally prefer categories, seems like a more formal interface)
ie:
AppDelegate+Animations.h
AppDelegate+Animations.m


text:
Q: What does "for relocation benefits" mean?
We will provide you $1,000, which you may use to cover expenses
  occurring as a result from your move, or for relocation benefits.

In this sentence, does the bold part mean:

You may use this money as relocation benefits

I am not sure to which part this "for relocation benefits" apply.

A: Without knowing the terms on which the money is being offered, it's impossible to say exactly what relocation benefits it covers.
In general, relocation benefits refer to the needs/comforts/investments that will be entailed on your move (relocation) from one place to another.
So while the actual expenses might cover such items as packing and transport costs, the relocation benefits might refer to obtaining essential services (TV, WIFI,) the necessary furniture or comforts in your new residence.
It is likely that any institution offering to subsidise a move would also specify what the money might be spent on - although $1,000 wouldn't go very far and might be just intended to cushion the overall cost of moving.


text:
Q: How to make Apache Solr disregard the size of documents when calculating their relevancy scores Is the ability to force Solr to disregard the size of documents when calculating their relevancy scores during a search a feature that's already built into Solr, or, is it otherwise simple to do so?

A: You can disable length normalization by setting omitNorms="true" for the field in question. Be advised that this also disables index time boosts.
From Field Type Definitions and Properties:

omitNorms
  If true, omits the norms associated with this field (this disables length normalization and index-time boosting for the field, and saves some memory). Defaults to true for all primitive (non-analyzed) field types, such as int, float, data, bool, and string. Only full-text fields or fields that need an index-time boost need norms.


text:
Q: Javascript: replace  with ? Is there any way to replace <select> tag to a <div> with hidden <div> that drops down when clicked?
Not a full solution, but maybe some js or jQuery library/plugin to do this. I can spend a day developing it, but maybe someone did have already did it?
The reason i need it is the joomla administrative interface — the dropdown list contains very long values, and i had to set fixed width to those <select>s
Thank you for any help!

A: I tried out quite a few select replacement JQuery plugins, and settled on select-box - be sure to check out the demo page as well. There's a wide variety of plugins for this purpose, so if this one doesn't meet your needs I'm sure you'll find one that does with a little Google-fu.


text:
Q: How show a few images on popup in Bootstrap I am working project in bootstrap. Can anyone please tell me How popup a few images on popover in Bootstrap ?

     SHOW ALL IMAGES

Jquery :
$(document).ready(function() {
  $('[data-toggle="popover"]').popover({
    container: 'body',
    html: true,
    placement: 'auto',
    trigger: 'hover',
    content: function() {
      // get the url for the full size img
      var url = $(this).data('full');
      return ''
    }
  });
});

this code just show one of images on popup i need to show all images...
MY FIDDLE
Thanks in advance
Regards,

A: Please use below code to display all images
  $(document).ready(function() {
  $('[data-toggle="popover"]').popover({
  container: 'body',
  html: true,
  placement: 'auto',
  trigger: 'hover',
  content: function() {
  // get the url for the full size img
   var url = $(this).data('full');
   var partsOfStr = url.split(',');

  var img_html ='';
  for(var i = 0; i < partsOfStr.length; i++) {
   var element = partsOfStr[i];
   img_html += '';

   }
    return img_html;
  //alert(img_html);

   }
  });
  });


text:
Q: Poisson Distribution. Probability k eggs laid given that n insects developed Let $X$ denotes the Number of eggs; poisson-distributed with parameter $\lambda$. Each egg hatches independently of the other eggs with probability $p$.
$Y$ denotes the number of the "developed" insects.
What's the probability that $k$ eggs laid given that $n$ insects developed ?
Obviously we have to use the formula of conditional-probability.
So I think that we have to start with:
$$ P( X=k | Y=n ) = \frac{P( {X=k} \cap {Y=n} )}{P ( Y = n )} $$ But I'm not sure. I know that $P$( $X$ = $k$ ) = $e^{-\lambda}$ $\frac{\lambda^k}{k!}$.

A: So we know that: $$ P( Y=n | X=k ) =  {k \choose n} * p^n * (1-p)^{k-n} $$ We also know:  $$ P (X = k) = e^{-\lambda} \frac{\lambda^k}{k!} $$ Moreover we know: $$ P(Y=n) = e^{-\lambda*p} \frac{(p*\lambda)^n}{n!} $$ We begin with: $$ P( X=k | Y=n ) = \frac{P( {X=k} \cap {Y=n} )}{P ( Y = n )} = \frac{P( Y=n | X=k )* P(X=k)}{P(Y=n)} $$ Now we use the equalities ( above ) : We get : $$ P( X=k | Y=n ) =  e^{-\lambda(1-p)} * \frac{ (\lambda * ( 1 - p ))^{k-n}}{(k-n)!} $$ Am I right or where is my mistake? Is this the probability?


text:
Q: How do I save a bitmap to my database? I have an bitmap in System.Drawing. I know it must be converted to a byte[] to be stored in my table.
My table field:
public class Task
public byte? TaskImage { get; set; }

I have this in line code so far:
MemoryStream ms = new MemoryStream();
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

Task.TaskImage =
db.SaveChanges();

I've been referenced to this:
public static byte[] ImageToByteArray(Image image)
{
var memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); // consider format
return memoryStream.ToArray();
}

but can't figure out how to apply it. This attempt doesn't work.
Task.TaskImage = Image.FromStream(ms.ToArray())

Can someone provide the code to go from the System.Drawing to Task.TaskImage= in inline code, or how to reference the function ImageToByteArray(Image image) in my code? In my MVC project, where is the proper place to put this function ImageToByteArray(Image image) if used?

A: You're on the right track.
One mistake I see is that
public byte? TaskImage { get; set; }

Needs to be a byte array. That is only a single nullable byte. Change it to
public byte[] TaskImage { get; set; }

What is an image and how do we store it?
In it's simplest form, an image is just a series of bits that are organised in a particular way (like any virtual object stored on a computer).
Databases aren't very good at storing complex types of data; they typically store strings (varchar, for example), integers of various sizes, floating point numbers, boolean values (a bit) and so on. In order to store something complex like an image we have to split the image up in to bytes and give that to the database (they can handle bytes (groups of bits) easily). You seem to know all of this.
In order to save an image to the database we need to know what format it's in and we need to be able to read all the bytes of the image.
Streams (What is a stream?) are useful here. They allow us to read and write a sequence of bytes. .NET classes like Image may also be useful for loading information about an image.
Reading an image from a database
Suppose we have an image stored as a byte array in a database. Entity Framework loads the object for us as a Task object.
public class Task
{
    public byte[] TaskImage { get; set; }
}

To load the image:
Task task;
var ms = new MemoryStream(task.TaskImage);
Image img = Image.FromStream(ms);

Or
Bitmap bmp = new Bitmap(ms);

Saving an image to a database
Task task = new Task();

MemoryStream ms = new MemoryStream();
Image img = Image.FromFile("...");
img.Save(ms, img.RawFormat);
ms.Position = 0;

task.TaskImage = new byte[ms.Length];
ms.Read(TaskImage, 0, (int)ms.Length);

dbContext.Tasks.Add(task);
dbContext.SaveChanges();


text:
Q: Tooltip within button is propagating to parent element onclick which is button I have a tooltip that is nested within a button. And in that tooltip, there is a 'read more' link inside the tooltip popup. The issue is when I click that 'read more' link that is within that tooltip, that is supposed to take you to an article. But it clicks the parent element, which is a button instead and triggers that onClick event instead of the read more link. I have tried doing e.stopPropagation() but that does not do the trick. Is there any other way to get around this?
render() {
    const { buttonStyleOverride, classes } = this.props;
    const { buttonDisabled } = this.state;
    return (
      <Button
        name="buyItem"
        variant="outlined"
        style={buttonStyleOverride}
        className={classes.button}
        color="primary"
        disabled={buttonDisabled}
        onClick={
          this.addItems,
          e => e.stopPropagation()
        }>
        Buy Pikafoods
        <TooltipIcon
          title="You can read more about pikafoods here."
          learnMoreLink="https://pokemon.com/articles/pikafoods"
          style={{ position: 'relative', top: '-2px' }} />
      </Button>
    );
  }
}

A: There are things that should not be done here.

*

*Using TooltipIcon instead of ToolTip

*Using TooltipIcon in a wrong way

*There is no learnMoreLink for Tooltip from the material. Which you can refer from here
This is the solution:
renderTooltipContent = () => (
  <>
    You can read more about pikafoods
    <a href="https://pokemon.com/articles/pikafoods">
      here
    </a>.
  </>
)

render() {
    const { buttonStyleOverride, classes } = this.props;
    const { buttonDisabled } = this.state;

    return (
        <>
            <Tooltip
                interactive
                title={this.renderTooltipContent()}
                style={{ position: 'relative', top: '-2px' }}
            >
                <Button
                    name="buyItem"
                    variant="outlined"
                    style={buttonStyleOverride}
                    className={classes.button}
                    color="primary"
                    disabled={buttonDisabled}
                    onClick={this.addItems}
                >
                    Buy Pikafoods
                </Button>
            </Tooltip>
        </>
    );
}

}


text:
Q: How to set the nav ul display to none when clicked second time on the hamburger? I am developing a responsive website in which when clicked on hamburger, displays a nav ul, but I have not been able to set the list display to none when clicked on the hamburger second time.
HTML

HTML

CSS

JS

FAQ

About

JS
function toggleHamburger(hamburg) {
    hamburg.classList.toggle("change");
    displayNavList();
}
function displayNavList(){
    var navList = document.getElementById("navlist");
    navList.style.display = "block";
}

So, basically I want to know that if there is any way in JS to call another function when clicked on the hamburger second time.
See the problem on AdiCodes, with the hamburger, it can open the nav list but cannot close it.

A: Is that what you want to achieve ? or did I misunderstand the question ?

var hamburger = document.querySelector('#hamburger'),
navList = document.querySelector('#navlist');

var toggleNav = function() {
  hamburger.classList.toggle('js-active')
  navList.classList.toggle('js-active')
}
hamburger.addEventListener('click', toggleNav)
#hamburger {
 color: red;
}

.js-active#hamburger {
color: green;
}

#navlist {
  display: none;
}

.js-active#navlist {
  display: block;
}

 HAMBURGER

HTML

CSS

JS

FAQ

About

A: You can define a global counter
var count = 0;

The first time you click it will show your nav, and the second time it will toggle.

var count = 0;
function toggleHamburger(hamburg) {
    if(count >= 1){
      var navList = document.getElementById("navlist");
      navList.style.display = "none";
    }else{
      hamburg.classList.toggle("change");
      displayNavList();
    }
    count ++;
}
function displayNavList(){
    var navList = document.getElementById("navlist");
    navList.style.display = "block";
}

test

test

test

HTML

CSS

JS

FAQ

About

A: Why don't you show/hide your list with a class, then you can toggle that class in your click handler too:
function toggleHamburger(hamburg) {
    hamburg.classList.toggle("change");
    var navList = document.getElementById("navlist");
    navList.classList.toggle("shown");
}

With the CSS:
#navlist:not(.shown) {
    display: none;
}


text:
Q: in .net, what programming model would be good for prototyping, but then reusable for production (for business logic/data access layers) In .NET land what would be a good approach for quick prototyping of a concept (i.e. development just on my PC) that could then be extended out to product (users across LAN/WAN), BUT in a fashion that the model/business logic code and data access layer code can be used as is?
One thought for example I had as to do:
(a) WinForms with business logic and Entity Framework layer to SQL Server Express on my PC, then
(b) Go then to ASP.net (using the business logic / data library) with SQL Server/IIS
Any comments? Other suggestions?

A: I would recommend trying a layered approach:

*

*put your entity data model and validation classes into a separate assembly

*put additional business logic into a separate business logic assembly

*put your services (WCF or WCF Data Services) into their own assembly

All those base layers are pretty much independent of what you choose as the UI frontend technology. You can make choices here (e.g. Linq-to-SQL vs. Entity Framework for your data access; do you need a WCF-based service layer, or does your app use direct DB access?) more or less independent of what you put on top of that for the UI layer.
And on top of those base assemblies:

*

*create your UI either as Winforms app, or as an ASP.NET (Webforms or MVC) web app (or both)

If you have layers and if you architect them well, you can reuse a large portion of your code and business rules.
Try to put only stuff that's specific for each UI technology (Winforms vs. ASP.NET) into those frontend presentation assemblies. Keep all the common business rules, validation rules, access and service layers separate.
And again: it seems you believe that "going ASP.NET" excludes using WCF/WCF Data Services - not at all ! You can easily use data from a WCF service in an ASP.NET app. You're not losing anything by layering your business and services layers - those can be easily reused in both Winforms and ASP.NET apps!

A: A few comments:
Prototyping as an approach to developing production quality software can be problematic, as the very nature of prototyping can mean that the software and design quality are not that great. Prototypes are not meant to be great quality by definition.
If the goals are to get some feedback from the intended customer\user during the early stages, it can often be a good idea to not prototype full vertical slices (e.g. UI -> Business -> DB), but work with UI mockups which can be used to explore ideas with users. The mockup is flexible and easy to change, but is not fully functional e.g. does not have business logic or persistence. This approach allows users to get some idea of functionality and be involved in the design and requirements gathering process. It will be quick to change the mocks as requirements change, especially as there is no business logic or database code that has to be changed with it. An example of a UI mocking tool is Balsamiq:
http://www.balsamiq.com/
If one of the overall goals of prototyping is to investigate and explore different technology choices, these can be done in isolation of UI mockups, and in a more abstract fashion i.e. pure technology investigation rather than geared at delivering the exact needs of a prototype which can be changing massively. The UI mockups may change a lot via user feedback, so having technology investigation as a different activity can make this process simpler i.e. there is less coupling as things will change a lot during the early discovery phase, and having to change the "backend" constantly because UI ideas are developing so rapidly, will slow you down.
In terms of speeding up the pace of software development, leverage third party libraries. If you are using a database for persistence, look at ORM solutions which could massively reduce the work needed to develop a data access layer e.g. nHibernate. Depending on what UI technology you use, look at third party control libraries.
In the industry, the approach that has very much replaced prototype driven development over the years is: Agile. It seeks to tackle the changing needs of users head-on by always striving to deliver features, but has a focus on developing high quality software through techniques such as TDD.


text:
Q: SQL Select Query For All Data In Single Column where date is getting increased by one by one month I am trying to fetch data from table where DateOfJoining is less than 2021-01-01 and i get the value.
Then I write another query to fetch the data from same table and now DateOfJoininng is less than 2021-02-01
I get the data but for 1 year I have to write it again and again but I want all data in single query in single output table  where date of joining in that month is getting change till the date I specify assume till 5 month so how will query look like please help!
Here is the query that i write for five months
select count()
from STAREdee221f287.EmployeeDetail
where EmpStatus = 1 and CompanyId =1 and DateOfJoining <'2021-01-01'

select count()
from STAREdee221f287.EmployeeDetail
where EmpStatus = 1 and CompanyId = 1 and DateOfJoining <'2021-02-01'

select count()
from STAREdee221f287.EmployeeDetail
where EmpStatus = 1 and CompanyId = 1 and DateOfJoining <'2021-03-01'

select count()
from STAREdee221f287.EmployeeDetail
where EmpStatus = 1 and CompanyId = 1 and DateOfJoining <'2021-04-01'

select count(*)
from STAREdee221f287.EmployeeDetail
where EmpStatus = 1 and CompanyId = 1 and DateOfJoining <'2021-05-01'

and here is the result I get after executing above query
result of query

A: You could use the count function as the following:
select count(case when DateOfJoining <'2021-01-01' then 1 end) m1,
       count(case when DateOfJoining <'2021-02-01' then 1 end) m2,
       count(case when DateOfJoining <'2021-03-01' then 1 end) m3,
       count(case when DateOfJoining <'2021-04-01' then 1 end) m4,
       count(case when DateOfJoining <'2021-05-01' then 1 end) m5
from EmployeeDetail
where EmpStatus = 1 and CompanyId =1

A: You can use a  calendar table. For the short list of dates you can use just VALUES to enumerate dates of interest. Alternatively it could be generated on the fly
with t0(n) as (
 select n
 from (
    values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
    ) t(n)
),ns as(
   select row_number() over(order by t1.n) - 1 n
   from t0 t1, t0 t2, t0 t3
),calendar as (
   -- replace 5 and '2021-01-01' with nmbr of months and starting date as needed
   select top(5) DATEADD(month, n, '2021-01-01' ) dt
   from ns
   order by n
)
select
    (SELECT COUNT(*)
     FROM EmployeeDetail
     WHERE EmpStatus = 1 and CompanyId = 1 and DateOfJoining < calendar.dt) AS CNT,
    'Before '+ cast(dt as varchar(10)) AS BeforeDateOfJoining
from calendar
order by dt

A: If you want to be able to customise your first month and last month (e.g., this query is from January to May 2021, the next one is from March to November 2021) then I think the simplest method is

*

*Create a table holding the relevant 'cutoff dates' (e.g., the 1st of every month from the first month to the last)

*Join that table to your EmployeeDetail table, but using a 'less than' in the join rather than an equals.

For example, say the table we want is called 'CutoffDates' and has one column
CREATE TABLE #CutoffDates (CutoffDate date PRIMARY KEY);

We could insert the dates 1 Jan 2021, 1 Feb 2021 ... 1 May 2021 into this table.
Then you could do your query as
select #CutoffDates.CutoffDate, COUNT(*) AS Num_Employees
from STAREdee221f287.EmployeeDetail AS ED
    INNER JOIN #CutoffDates ON ED.DateOfJoining < #CutoffDates.CutoffDate
where ED.EmpStatus = 1 and ED.CompanyId = 1
GROUP BY #CutoffDates.CutoffDate;

I believe (I cannot test it because I don't have your data) that the results would look like this
CutoffDate   Num_Employees
--------------------------
2021-01-01   427
2021-02-01   431
2021-03-01   438
2021-04-01   444
2021-05-01   451

To populate the #CutoffDates table, you can use multiple methods. The method below uses a 'numbers table' to aid in using DATEADD(month...) to get the 1st of every relevant month.
The method is also shown in this db<>fiddle. Note that there are two variables used - a date in the first month you want to start with, and a date in the last month (e.g., so for the January to May example above, the DateInFirstMonth should be any date in Jan 2021; the DateInLastMonth should be any date in May 2021).
-- Create a numbers table (0 to as many as you could possible need)
CREATE TABLE #Numbers (n int PRIMARY KEY);
INSERT INTO #Numbers (n) VALUES
  (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),
  (10),(11),(12),(13),(14),(15),(16),(17),(18),(19),
  (20),(21),(22),(23),(24);

-- Create a table used for the dates (e.g., 1 Jan 2021, 1 Feb 2021, etc to 1 May 2021)
CREATE TABLE #CutoffDates (CutoffDate date PRIMARY KEY);

-- Populate the table with dates based on 'date in first month' and 'date in last month'
DECLARE @DateInFirstMonth date = '20210112';
DECLARE @DateInLastMonth date = '20210523';

-- Convert 'date in first month' to 1st of the month
SET @DateInFirstMonth = DATEFROMPARTS(YEAR(@DateInFirstMonth), MONTH(@DateInFirstMonth), 1);

-- Use these to create dates in #CutOffDates
INSERT INTO #CutoffDates (CutoffDate)
  SELECT DATEADD(month, #Numbers.n, @DateInFirstMonth)
  FROM  #Numbers
  WHERE #Numbers.n <= DATEDIFF(month, @DateInFirstMonth, @DateInLastMonth);

Note - this is not the most efficient method (as, say, the initial employees are counted many times - once for every row). There are also some tweaks that can be done to improve it (e.g., the numbers table I created as simply as possible to make it easy to understand - @Serg's answer has a technically better way to make a numbers table).


text:
Q: how to find the System.Type from a complex full path string? For example, my Type is a complex type, it is a generic type.
public class TestType<T> : xxx
{
}

this is a generic class in Assmebly A.
my Assembly B reference A, there is another type TestObject.
so the actual type is :
TestType<TestObject>

....
if i save the fullname of this type, it is a very complex string, like this:
BluePrint.Core.CustomObjectConverter`1[[BluePrint.SGame.VInt2, BluePrint.SGame.Plugins, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], BluePrint.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

so, if i want to find the System.Type of this string, how to do this?
i use System.Type.GetType, it return null.
the generic type and the parameter type are in different assemblies.

A:     /// <summary>
    /// Gets the type associated with the specified name.
    /// </summary>
    /// <param name="typeName">Full name of the type.</param>
    /// <param name="type">The type.</param>
    /// <param name="customAssemblies">Additional loaded assemblies (optional).</param>
    /// <returns>Returns <c>true</c> if the type was found; otherwise <c>false</c>.</returns>
    public static bool TryGetTypeByName(string typeName, out Type type, params Assembly[] customAssemblies)
    {
        if (typeName.Contains("Version=")
            && !typeName.Contains("`"))
        {
            // remove full qualified assembly type name
            typeName = typeName.Substring(0, typeName.IndexOf(','));
        }

        type = Type.GetType(typeName);

        if (type == null)
        {
            type = GetTypeFromAssemblies(typeName, customAssemblies);
        }

        // try get generic types
        if (type == null
            && typeName.Contains("`"))
        {
            var match = Regex.Match(typeName, "(?<MainType>.+`(?<ParamCount>[0-9]+))\\[(?<Types>.*)\\]");

            if (match.Success)
            {
                int genericParameterCount = int.Parse(match.Groups["ParamCount"].Value);
                string genericDef = match.Groups["Types"].Value;
                List<string> typeArgs = new List<string>(genericParameterCount);
                foreach (Match typeArgMatch in Regex.Matches(genericDef, "\\[(?<Type>.*?)\\],?"))
                {
                    if (typeArgMatch.Success)
                    {
                        typeArgs.Add(typeArgMatch.Groups["Type"].Value.Trim());
                    }
                }

                Type[] genericArgumentTypes = new Type[typeArgs.Count];
                for (int genTypeIndex = 0; genTypeIndex < typeArgs.Count; genTypeIndex++)
                {
                    Type genericType;
                    if (TryGetTypeByName(typeArgs[genTypeIndex], out genericType, customAssemblies))
                    {
                        genericArgumentTypes[genTypeIndex] = genericType;
                    }
                    else
                    {
                        // cant find generic type
                        return false;
                    }
                }

                string genericTypeString = match.Groups["MainType"].Value;
                Type genericMainType;
                if (TryGetTypeByName(genericTypeString, out genericMainType))
                {
                    // make generic type
                    type = genericMainType.MakeGenericType(genericArgumentTypes);
                }
            }
        }

        return type != null;
    }

    private static Type GetTypeFromAssemblies(string typeName, params Assembly[] customAssemblies)
    {
        Type type = null;

        if (customAssemblies != null
           && customAssemblies.Length > 0)
        {
            foreach (var assembly in customAssemblies)
            {
                type = assembly.GetType(typeName);

                if (type != null)
                    return type;
            }
        }

        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (var assembly in loadedAssemblies)
        {
            type = assembly.GetType(typeName);

            if (type != null)
                return type;
        }

        return type;
    }

i have find solution here:
Loading a generic type by name when the generics arguments come from multiple assemblies

A: When you have generic types, you need to do this one step after the other.
First, get the generic type:
typeof(BluePrint.Core.CustomObjectConverter<>).FullName

this should give you
"BluePrint.Core.CustomObjectConverter`1"

you can pass this to GetType
var genericType = Type.GetType("BluePrint.Core.CustomObjectConverter`1")

and then get the specific type for it:
genericType.MakeGenericType("BluePrint.SGame.VInt2")

knowing this, and when you only have this string, you could parsing the string and building up your types one step after the next.
in case you have not yet loaded the assemblies into you space, you can use the overloads of GetType to find them: https://msdn.microsoft.com/en-us/library/ee332978(v=vs.110).aspx


text:
Q: Paypal Permission API. GetBasicPersonalData in php I have received "tokenSecret" and "response token".
    $apiCred_user = "XXXX.com";
    $apiCred_pass = "XXXX";
    $accessToken = "XXXXXXXXXXXXXXKl8OlQ";
    $tokenSecret = "XXXXXXXXXXXXXsRg6ULs";
    $url = "https://api.sandbox.paypal.com/nvp";

    $auth = new AuthSignature();
    $response = $auth->genSign($apiCred_user ,$apiCred_pass ,$accessToken,$tokenSecret,'POST',$url);

    $authString =
    "token=".$accessToken.
    ",signature=".$response['oauth_signature'].
    ",timestamp=".$response['oauth_timestamp'];

Using this call, the signature is received. My doubt, The given url is used to generate the signautre. The call is correct?
To get result from "GetBasicPersonalData" , I have used this below code
$headers = array(
"X-PAYPAL-REQUEST-DATA-FORMAT:NV",
"X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T",
"X-PP-AUTHORIZATION: " .$authString,
"X-PAYPAL-RESPONSE-DATA-FORMAT:json");

$url_api = "https://svcs.paypal.com/Permissions/GetBasicPersonalData";
$post_array = array(
    "attributeList"=>array("attribute"=>"http://axschema.org/contact/email"),
    "requestEnvelope.errorLanguage"=>"en_US");
$curl_session =  curl_init();
    curl_setopt($curl_session, CURLOPT_URL,$url_api );
    curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl_session, CURLOPT_POST, 1);
    curl_setopt($curl_session, CURLOPT_POSTFIELDS, http_build_query($post_array));
    curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($curl_session, CURLOPT_TIMEOUT, 10);
    //curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 0);
    $response = json_decode(curl_exec($curl_session));
    curl_close($curl_session);

The response result is "Error"
{"responseEnvelope":

{"timestamp":"2015-02-05T09:26:53.053-08:00","ack":"Failure","correlationId":

"c74e091e7944e","build":"2210301"},"error":

[{"errorId":"560022","domain":"PLATFORM","subdomain":"Application","severity":"Error","category":"Application","message":"The X-PAYPAL-APPLICATION-ID header contains an invalid value","parameter":["X-PAYPAL-APPLICATION-ID"]}]}

Thanks ! 123456

A: you forgot to ask for user's permission to get his personal data.
let's suppose you want to ask his permission to issue refunds, your request should look like this:
$data = array(
    'scope' => array(
        '0' => 'REFUND',
        '1' => 'ACCESS_BASIC_PERSONAL_DATA'
    ),
    'callback' => 'http://yoursite.com/page.php',  // The success page
    'requestEnvelope' => array(
        'errorLanguage' => 'en_US'    // Language used to display errors
    )
);

then you'll get the correct access token and token secret.
if you're still stuck, please ask for the complete code.


text:
Q: why does golang http ResponseWriter auto add content-length if it's no more than 2kb func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    var content string
    ...
    w.Write([]byte(content))
}

if len(content) <= 2048, the content-length will be added automatically in the response. And if it's over 2048, there is no content-length, and the Transfer-Encoding: chunked will be added.
I can't find where to determine the 2048.
I'm asking for help to find the source code that where to determine the 2048.

A: Let's look at the documentation of this feature in the http.ResponseWriter interface just for clarity:

[I]f the total size of all written data is under a few KB and there are no Flush calls, the Content-Length header is added automatically.

First, we can see that the number may not be exactly 2048 (2 KB), but that is in the range we would expect for "a few KB". Second, we can see that this behaviour has something to do with the Flush method, which is documented in the Flusher interface:

Flush sends any buffered data to the client.
The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.
The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime.

As it says, your ResponseWriter may support data buffering and flushing. What this means is that when you write data to the response writer, it does not immediately get transmitted over the connection. Instead, it first gets written into a buffer. Each time the buffer is too full to write to anymore, and when the ServeHTTP method returns, the whole buffer will get transmitted. This ensures that data gets transmitted efficiently even when you do lots of tiny writes, and that all data gets transmitted in the end. You also have the option of proactively emptying the buffer at any time with the Flush method. The HTTP headers must be sent before the body data, but there's no need to send them until the first time the buffer is emptied.
Putting all this together, you'll see that if the total amount written is no more than the buffer size, and we never call Flush, then the headers do not need to be sent until all the data is ready, at which point we know the content length. If the total amount written is more than the buffer size, then the headers must be sent before the content length is known, and so the ResponseWriter can't determine it automatically.
This is implemented in the source in net/http/server.go. Specifically, here are the declarations of the buffer size, and the chunkedWriter which implements part of the buffered writing behaviour:
// This should be >= 512 bytes for DetectContentType,
// but otherwise it's somewhat arbitrary.
const bufferBeforeChunkingSize = 2048

// chunkWriter writes to a response's conn buffer, and is the writer
// wrapped by the response.w buffered writer.
//
// chunkWriter also is responsible for finalizing the Header, including
// conditionally setting the Content-Type and setting a Content-Length
// in cases where the handler's final output is smaller than the buffer
// size. It also conditionally adds chunk headers, when in chunking mode.
//
// See the comment above (*response).Write for the entire write flow.
type chunkWriter struct {

Link to the source code for 1.19.5. Please note that the source code is subject to change with each Go release.

A: The value is defined here:
// This should be >= 512 bytes for DetectContentType,
// but otherwise it's somewhat arbitrary.
const bufferBeforeChunkingSize = 2048

The Life of a Write explains what happens:

If the handler didn't declare a Content-Length up front, we either go into chunking mode or, if the handler finishes running before the chunking buffer size, we compute a Content-Length and send that in the header instead.