text:
Q: What happens after testflight delivered app is released to app store We had external testers testing our app through test flight.  Then we sent it off for Apple to approve.  Testers are not getting notified that the app is published (I'm assuming this is right since they already have the latest version).  If they go into test flight, it says the app will expire in 18 days.  Do we need to tell them to do anything about the expiring app, or is TestFlight reporting something that isn't true?  Will they have problems after their testing period expires?

A: Well, basically it's as follow: after 90 days the Test Flight App will be disabled. They'll not be able to download it anymore, as it will expire. However if you've published your app to the App Store, they can easily download the newest version from there, that does not have an expiration date. They'll however not be notified that the app was released in the App Store as those are two separate processes. What you can do is when you have a new build, upload the new version to test flight and send them the new version for beta testing, which again will be available for 30 days before expiring.
Builds remain active for 90 days after upload.
Your TestFlight app users should not be able to launch the app 90 days after you release
Hope that helps,
Julian

A: You have 2 options.  1) Tell the testers to download it from the app store or 2) push a new build to test flight which they can update to.
After 30 days the app goes Kaput!  We had this error where I was trying to track down a mysterious crash on somebody's phone when we realized they were still running a defunct test flight build.


text:
Q: Slide in from left animation in Angular2 I am trying to build a progress bar component where the bar slides in from the left.
I have a solution where the width of the bar is fixed to 40%, however my component takes an input which is the desired percentage.
animations: [
    trigger('slide', [
        state('in', style({ width: '40%'})),
        transition('* => *', animate('1000ms ease-in'))
    ])
]

Is it possible to do something as above with a property containing the width? Or is there another or better way to do this?

A: set width to 40vw,it would determine your window width to calc the width.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA CriteriaQuery - access fields from connected table with ManyToOne My situation: A have a datatable called AuditDetail. This table is in ManyToOne connection with another table AuditHead. I display data in Primefaces datatable. My problem is with sorting and filtering. If I want to sort a field witch is in AuditHead table, I got an error: no such field exception.
The related code:
public List<AuditDetail> load(int first, int pageSize, String sortField, SortOrder     sortOrder, Map<String,String> filters) {

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AuditDetail> cq = cb.createQuery(AuditDetail.class);
Root<AuditDetail> from = cq.from(AuditDetail.class);
CriteriaQuery<AuditDetail> select = cq.select(from);

It works perfectly with AuditDetail fields, but I don't know how can I reach fields from AuditHead. If I use NamedQueries, I can simply say auditDetail.headId, but how can I get AuditHead fields, when I use CriteriaQuery?
I used NamedQueries before, then this code works perfectly:
filterBy="#{log.headId.tableName}" sortBy="#{log.headId.tableName}"

I'm here, because I have no idea anymore, I think tried everything. For example:
Fetch<AuditDetail, AuditHead> fetch = from.fetch(AuditDetail_.headId, JoinType.LEFT);

But I'm absolutely not sure how do I have to do this.
Every help appreciated!
Regards!


text:
Q: Are there any problems with changing the target of a function pointer from within the function? (C++) I have a program that defines changes the target function of a function pointer from within the function being called by said pointer, like so:
void increment(int&);
void superincrement(int&);

void (*fooncrement)(int&);

int main() {
    int j = 0;
    fooncrement = increment;
    while (true == true) {
        fooncrement(j);
    }
}

void increment(int& i) {
    static int counter = 0;

    i++;

    if (counter > 7)
        fooncrement = superincrement;
    counter++;
}

void superincrement(int& i) {
    i += 23;
}

A quick run through MSVC's debugger shows that the program more or less works as expected.  However, are there are any problems not immediately obvious here that might manifest if I tried something like this in a more complex environment?

A: This is well-defined.
In fact, this technique is often used to implement state machines.

A: No, there shouldn't be any problem. It's not like it clings to that pointer once you made the call.

A: This isn't thread-safe, but for single-threaded apps, no problems.  If you don't know what threading is, then you're not using it, so you have no problem.
More advanced programs use multiple "threads", each of which is basically it's own program, but they work together.  Imagine if you had int main(), but also int main1(), int main2(), int main3(), and they all ran at the same time.  Your program could do four things at once!  However, if one thread changes fooncrement, there will be a slight delay before the other threads see the updated value.  In the meantime, they'd use the old value, which might cause problems.


text:
Q: dropdownchoice with choicerenderer, how to get values i have problem trying to get some values. this is my situation (wicket)
i have a dropdownchoice study_template, i don't have problem populating the DDC, the problem is when i try to get some value (id or name). this is the code
ChoiceRenderer choiceRenderer = new ChoiceRenderer("name", "id");
study_template  = new DropDownChoice( "study_template",new PropertyModel( this, "selectedTemplate" ),template_names , choiceRenderer);

template_names is a list< SelectOption > with the values obtain from a DB. this works OK.
this is the class that i use to populate the DDC
public class SelectOption implements java.io.Serializable {
    private long id;
    private String  name;
    public SelectOption(long id, String name ) {
        this.id = id; this.name=name;
    }

     public long getId()
        {return id; }

        public String getName()
        {return name; }
}

normally i can get the value with study_template.getModelObject(), but in this case it doesn't work, i don't have any ideas about to obtain the id and the name , i know that i need GETID() and GETNAME(), but i don't know how to use it, any help will be appreciated

A: You could use something as below:

public class SpikePage extends WebPage {

    class Person {

        String id;
        String name;

        public Person(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public SpikePage() {

        Person employee = new Person("E001", "ABC");
        Person manager = new Person("E002", "XYZ");

        List personList = new ArrayList(2);
        personList.add(employee);
        personList.add(manager);

        Form form = new Form("form");

        final DropDownChoice personDropDownChoice = new DropDownChoice("person", new ArrayList(personList), new IChoiceRenderer() {
            @Override
            public Object getDisplayValue(Person object) {
                return object.getId().concat("-").concat(object.getName());
            }

            @Override
            public String getIdValue(Person object, int index) {
                return object.getId();
            }
        });

        personDropDownChoice.setOutputMarkupId(true);
        personDropDownChoice.setNullValid(false);
        form.add(personDropDownChoice);

        final Label label = new Label("name");
        label.setOutputMarkupId(true);
        form.add(label);

        personDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                Person selectedPerson = personDropDownChoice.getModelObject();
                label.setDefaultModelObject("Hi ".concat(selectedPerson.getName()));
                target.add(label);
            }
        });

        add(form);
    }
}

A: Thanks for your answer, i already get it work
i use this
private SelectOption selectedTemplate;

and then
selectedTemplate.getId();


text:
Q: How to assign materials for NXOpen FEM Parts from MatML Library I'm trying to assign material for FEM part from MatML Library.
Below are the Libraries used.
NXOpen.PhysMat.PhysicalMaterialListBuilder physicalMaterialListBuilder1;
        physicalMaterialListBuilder1 = workFemPart.MaterialManager.PhysicalMaterials.CreateListBlockBuilder();

        NXOpen.PhysMat.PhysicalMaterialAssignBuilder physicalMaterialAssignBuilder1;
        physicalMaterialAssignBuilder1 = workFemPart.MaterialManager.PhysicalMaterials.CreateMaterialAssignBuilder();

        NXOpen.NXObject[] objects1 = new NXOpen.NXObject[1];

        physicalMaterial1 = workFemPart.MaterialManager.PhysicalMaterials.LoadFromMatmlLibrary(AppDomain.CurrentDomain.BaseDirectory+"Material\\"+materialName+".xml", materialName);

        //NXOpen.CAE.CAEBody cAEBody1 = (NXOpen.CAE.CAEBody)workFemPart.FindObject("CAE_Body(1)");
        objects1[0] = (NXObject)nxObject1[0];
        physicalMaterialAssignBuilder1 = workFemPart.MaterialManager.PhysicalMaterials.CreatePhysicalMaterialInspectBuilder(physicalMaterial1);

        physicalMaterialAssignBuilder1.Destroy();
        physicalMaterialListBuilder1.Destroy();


text:
Q: Xamarin.iOS UIApperance setDefaultTextAttributes I'm trying to figure out how to implement following code in Xamarin:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil]     setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}];
But I cannot find a way to setDefaultTextAttributes on UIApperance class.

A: There are a number of missing UIAppearance features in Xamarin.iOS and in regards to your question, there is a missing API.

*

*This is a bug,  I wrote my own UIAppearance.cs to add the missing features and correct the missing API and assume no other Xamarin.iOS coders really use  the newer UIAppearance features as it has been broken since iOS 9 in Xamarin.

First, appearanceWhenContainedIn is deprecated and you should be using appearanceWhenContainedInInstancesOfClasses instead.

AppearanceWhenContainedIn - was deprecated in iOS 9 and is not recommended for use.

Second, appearanceWhenContainedInInstancesOfClasses is incorrectly defined within Xamarin.iOS as only available in tvOS and that is just not true.
#if TVOS
   // new in iOS9 but the only option for tvOS
   const string selAppearanceWhenContainedInInstancesOfClasses = "appearanceWhenContainedInInstancesOfClasses:";
   ~~~

UIAppearance.cs#L77

*

*Update: I submitted a Github issue regarding this.

*

*https://github.com/xamarin/xamarin-macios/issues/3230
Thus it is not available via the Xamarin.iOS wrapper API, but of course is available directly from the ObjC runtime as such:
var NSForegroundColorAttributeName = Dlfcn.GetStringConstant(UIKitLibraryHandle, "NSForegroundColorAttributeName");
var defaultAttributes = NSDictionary.FromObjectsAndKeys(new NSObject[] { UIColor.Red }, new NSObject[] { NSForegroundColorAttributeName });
var styleHandle = GetAppearanceEx(Class.GetHandle("UITextField"), typeof(UISearchBar));
void_objc_msgSend_IntPtr(styleHandle, Selector.GetHandle("setDefaultTextAttributes:"), defaultAttributes.Handle);

The next problem there are a number of Xamarin.iOS methods marked internal that are needed for the above code to function, so some copy/paste/modify of some source is needed:
public const string selAppearanceWhenContainedInInstancesOfClasses = "appearanceWhenContainedInInstancesOfClasses:";

public static readonly IntPtr UIKitLibraryHandle = Dlfcn.dlopen("/System/Library/Frameworks/UIKit.framework/UIKit", 0);

[DllImport("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")]
public static extern IntPtr IntPtr_objc_msgSend_IntPtr(IntPtr receiver, IntPtr selector, IntPtr arg1);

[DllImport("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")]
public static extern void void_objc_msgSend_IntPtr(IntPtr receiver, IntPtr selector, IntPtr arg1);

public static IntPtr GetAppearanceEx(IntPtr class_ptr, params Type[] whenFoundIn)
{
    var ptrs = TypesToPointers(whenFoundIn);
    var handles = NSArray.FromIntPtrs(ptrs);
    using (var array = handles)
    {
        return IntPtr_objc_msgSend_IntPtr(class_ptr, Selector.GetHandle(selAppearanceWhenContainedInInstancesOfClasses), array.Handle);
    }
}

public static IntPtr[] TypesToPointers(Type[] whenFoundIn)
{
    IntPtr[] ptrs = new IntPtr[whenFoundIn.Length];

    for (int i = 0; i < whenFoundIn.Length; i++)
    {
        if (whenFoundIn[i] == null)
            throw new ArgumentException(String.Format("Parameter {0} was null, must specify a valid type", i));
        if (!typeof(NSObject).IsAssignableFrom(whenFoundIn[i]))
            throw new ArgumentException(String.Format("Type {0} does not derive from NSObject", whenFoundIn[i]));

        var classHandle = Class.GetHandle(whenFoundIn[i]);
        if (classHandle == IntPtr.Zero)
            throw new ArgumentException(string.Format("Could not find the Objective-C class for {0}", whenFoundIn[i].FullName));
        ptrs[i] = classHandle;
    }
    return ptrs;
}


text:
Q: Android getLocationOnScreen always return 0 when called in ListView's onScroll callback     lv_msg.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            //do nothing
        }
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (v_filter_gender == null) {
                return;
            }
            v_filter_gender.getLocationOnScreen(header_location);
            int y = header_location[1];
            ......
        }
    });

the variable "y" is correct on 4.4.4 and 5.0.2 so far but on 4.1.2 it is always 0.
I tried to use onGlobalLayoutListener, but still can't get correct location.
Any idea?


text:
Q: webRTC blurred screen on iOS 13 webRTC blurred screen on iOS 13. How to fix.
I'm using libjingle_peerconnection,
https://cocoapods.org/pods/libjingle_peerconnection
connect with friend, I'm only see the blurred screen
but it work on iOS 12, just not work on iOS 13.

A: rtc_video_capture_ios_objc.mm: captureOutput
yPlaneBytesPerRow > CVPixelBufferGetWidth(videoFrame).
fix this stride issue with libyuv.


text:
Q: Why is Firestore still producing error after composite index creation? I have a firestore collection called "users".
here are three DB-reads I'm interested in executing:
1:
const onNewestChange = (dispatch) => {
    firebase
        .firestore()
        .collection('users')
        .where('role', '==', 'a')
        .where('active', '==', true)
        .orderBy('createdAt')
        .limit(10)
        .onSnapshot((querySnapshot) => {
            const newestProfiles = querySnapshot.forEach((queryDocSnapshot) => {
                const profile = queryDocSnapshot.data();
                newestProfiles.push(profile);
            });
            dispatch({ type: types.LOAD_NEWEST, payload: newestProfiles });
        });
};

2:
const onMostPopularChange = (dispatch) => {
    firebase
        .firestore()
        .collection('users')
        .where('role', '==', 'a')
        .where('active', '==', true)
        .orderBy('lifetimeInbox')
        .limit(10)
        .onSnapshot((querySnapshot) => {
            const popularProfiles = querySnapshot.forEach((queryDocSnapshot) => {
                const profile = queryDocSnapshot.data();
                popularProfiles.push(profile);
            });
            dispatch({ type: types.LOAD_POPULAR, payload: popularProfiles });
        });
};

3:
const onMostActiveChange = (dispatch) => {
    firebase
        .firestore()
        .collection('users')
        .where('role', '==', 'a')
        .where('active', '==', true)
        .orderBy('lifetimeRead')
        .limit(10)
        .onSnapshot((querySnapshot) => {
            const activeProfiles = querySnapshot.forEach((queryDocSnapshot) => {
                const profile = queryDocSnapshot.data();
                activeProfiles.push(profile);
            });
            dispatch({ type: types.LOAD_ACTIVE, payload: activeProfiles });
        });
};

An example "user" document has the following fields:

*

*username

*legalName

*role

*active

*createdAt

*lifetimeInbox

*lifetimeRead

I've created the following composite index :

Also tried:

My problem is the initial error I was trying to resolve still persists even after the composite index creation

Error: Firestore: Operation was rejected because the system is not in a state required for the operation's execution. (firestore/failed-precondition)

What can be done to resolve this?

A: After limiting my effort to just onNewestChange(), and playing with different composite indices, I realized that everything in the where() and orderBy() parameters need to be included as well as the collection being queried. so in my case...

*

*requires a composite index with fields

*

*role (asc)

*active (asc)

*createdAt (asc)

*requires composite index with fields

*

*role (asc)

*active (asc)

*lifetimeInbox (asc)

*requires composite index with fields

*

*role (asc)

*active (asc)

*lifetimeRead (asc)

Now the error is gone.


text:
Q: IUserPromptService message when trying to create an attribute relationship in Visual Studio (Microsoft Tutorial) I'm going through the Microsoft Multidimensional Modeling (Adventure Works Tutorial) and have come across the following error message when I try to create a new attribute relationship. I have tried uninstalling and reinstalling everything. I'm using the 2022 version of Visual Studio and the 2019 version of SSMS. I am connected through the localhost account (but had to use a specific Windows user name and password as it would not deploy through the service account). Any thoughts?enter image description here
===================================
Service provider has to support IUserPromptServive! (Microsoft Visual Studio)

Program Location:
at Microsoft.AnalysisServices.Design.AR.EditRelationshipsDataProvider.Init(Dimension inDimension, IServiceProvider inServiceProvider)
at Microsoft.AnalysisServices.Design.AR.EditRelationshipsDataProvider..ctor(Dimension inDimension, DimensionAttribute inAttribute, IServiceProvider inServiceProvider)
at Microsoft.AnalysisServices.Design.AR.CommonMenuHandlers.CreateAttributeRelationship(MenuCommand menuCommand, CommandHandlingArgs args)
at Microsoft.DataWarehouse.Design.CommandHandlingInfoMap.HandleCommand(MenuCommand menuCommand)
at Microsoft.AnalysisServices.Design.AR.CommonMenuHandlers.InvokeCommand(MenuCommand menuCommand)

A: Looking for information about the same problem, I found that this is a bug of VS 2022
https://developercommunity.visualstudio.com/t/service-provider-has-to-support-iuserpromptservive/1648082
To avoid this problem, the option is to use VS 2019 until Microsoft releases an update of VS 2022 with the fix


text:
Q: Количество последовательностей из цифр C++ Есть массив из 1 и 0 который заполняется
for (int i = 0; i < size; i++)
{
   mas[i] = rand() % 2;
   cout << mas[i] << endl;
}

Надо найти количество последовательностей из двух цифр (00, 01, 10, 11)
и количество последовательностей из трех цифр (000, 001, 010, и т.д.)
Не могу сделать цикл перебора, вот что вышло
void secondTask(int size, int mas[]) {
int zeroZeroCounter = 0;
int zeroOneCounter = 0;
int oneZeroCounter = 0;
int oneOneCounter = 0;
int first = 0;
int second = 0;

for (int i = 0; i < size-1; i++) {
 first = mas[i];
 second = mas[i+1];
    if ((first == 0) && (second == 0)) {
        zeroZeroCounter += 1;
    }
    if ((first == 0) && (second == 1)) {
        zeroOneCounter += 1;
    }
    if ((first == 1) && (second == 0)) {
        oneOneCounter += 1;
    }
    if ((first == 1) && (second == 1)) {
        oneOneCounter += 1;
    }
}
cout << "00 - " << zeroZeroCounter << endl;
cout << "01 - " << zeroOneCounter << endl;
cout << "11 - " << oneOneCounter << endl;
cout << "10 - " << oneOneCounter << endl;

}

оригинальная функция
Помогите с кодом или подтолкните в нужном направлении

A: Ну, я бы делал примерно так:
int counter[4] = {};

...

for (int i = 0; i < size-1; i++)
    counter[mas[i]*2+mas[i+1]]++;

Понятно, что в counter[0] - количество 00, в counter[1] - количество 01 и так далее...

A: Вот решение, на которое намекал Harry.
void secondTask(int size, int mas[]) {

    int zeroZeroCounter = 0;
    int zeroOneCounter = 0;
    int oneZeroCounter = 0;
    int oneOneCounter = 0;
    int first = 0;
    int second = 0;

    for (int i = 0; i < size - 1; i++) {
        first = mas[i];
        second = mas[i + 1];

        if ((first == 0) && (second == 0)) {
            zeroZeroCounter += 1;
            }

        if ((first == 0) && (second == 1)) {
            zeroOneCounter += 1;
            }

        if ((first == 1) && (second == 0)) {
            oneZeroCounter += 1;
            }

        if ((first == 1) && (second == 1)) {
            oneOneCounter += 1;
            }
        }

    cout << "00 - " << zeroZeroCounter << endl;
    cout << "01 - " << zeroOneCounter << endl;
    cout << "11 - " << oneOneCounter << endl;
    cout << "10 - " << oneZeroCounter << endl;
    }


text:
Q: How to make the default date format dd/mm/yyyy in SQL Server 2008? I have an Excel file that contains a column full of dates in the dd/mm/yyyy format. When I try to import it using openrowset, it said that there was a datatype mismatch. I have a table where the date is defined as type date. Now, I know that the default date format in SQL Server is yyyy-mm-dd. How can I avoid this conflict? Is there a way I can make the default date type be dd/mm/yyyy? I need to do this import operation everyday and it has to be automated and so I cannot afford it to fail in between. I tried using sp_addlanguage to make it British as the default date type is dd/mm/yyyy there, but it didn't work :(. I'm using SQL Server 2008 and Windows 7, if that is of any help. Please help me out! Thanks!

A: You could CONVERT the incoming data before you insert it. So, in the openrowset statement, where you select the field, you could surround it with a CONVERT statement. Here's an example:
print convert(date,'19/07/2010',103)

This is a UK style date, but if you run it you can see that it's converted it to SQL-friendly format.


text:
Q: Как определить установлен ли пакет? Необходимо определить установлены ли пакеты c zlib и openssl. aptitude отсутствует и невозможно установить пока что по определенным причинам, поэтому вариант, предлагавшийся на http://admin.hashcode.ru/questions/5794/linux-%D0%B8%D0%BC%D1%8F-%D0%BF%D0%B0%D0%BA%D0%B5%D1%82%D0%B0-%D0%B2-nexenta отпадает, да и zlib и openssl могли устанавливаться вручную. Эти программы необходимы для установки openssh (см. ftp://ftp.ca.openbsd.org/pub/OpenBSD/OpenSSH/portable/INSTALL), поэтому конечно можно просто попытаться установить его и если система выдаст ошибку на отсутствие таких программ, то значит, они не установлены, но хотелось бы это выяснить все таки перед попыткой установки openssh.P.S. В результате выполнения скрипта ./configure я получил следующий результат (помогите расшифровать относительно вопроса, который я задал, да и вообще необходима информация, что из указанного на ftp://ftp.ca.openbsd.org/pub/OpenBSD/OpenSSH/portable/INSTALL необходимо установить, я новичок в Linux, поэтому прошу отнестись с пониманием)checking for gcc... gccchecking whether the C compiler works... yeschecking for C compiler default output file name... a.outchecking for suffix of executables... checking whether we are cross compiling... nochecking for suffix of object files... ochecking whether we are using the GNU C compiler... yeschecking whether gcc accepts -g... yeschecking for gcc option to accept ISO C89... none neededchecking build system type... i386-pc-solaris2.11checking host system type... i386-pc-solaris2.11checking how to run the C preprocessor... gcc -Echecking for grep that handles long lines and -e... /usr/gnu/bin/grepchecking for egrep... /usr/gnu/bin/grep -Echecking for ANSI C header files... yeschecking for sys/types.h... yeschecking for sys/stat.h... yeschecking for stdlib.h... yeschecking for string.h... yeschecking for memory.h... yeschecking for strings.h... yeschecking for inttypes.h... yeschecking for stdint.h... yeschecking for unistd.h... yeschecking whether byte ordering is bigendian... nochecking for gawk... nochecking for mawk... nochecking for nawk... nawkchecking how to run the C preprocessor... gcc -Echecking for ranlib... ranlibchecking for a BSD-compatible install... /usr/gnu/bin/install -cchecking for egrep... (cached) /usr/gnu/bin/grep -Echecking for ar... /usr/gnu/bin/archecking for cat... /usr/gnu/bin/catchecking for kill... /usr/gnu/bin/killchecking for perl5... nochecking for perl... /usr/bin/perlchecking for sed... /usr/gnu/bin/sedchecking for ent... nochecking for bash... /usr/bin/bashchecking for ksh... (cached) /usr/bin/bashchecking for sh... (cached) /usr/bin/bashchecking for sh... /usr/gnu/bin/shchecking for groff... /usr/bin/groffchecking for nroff... /usr/gnu/bin/nroffchecking for mandoc... nochecking for groupadd... /usr/sbin/groupaddchecking for useradd... /usr/sbin/useraddchecking for pkgmk... yeschecking for special C compiler options needed for large files... nochecking for _FILE_OFFSET_BITS value needed for large files... 64checking for login... /usr/bin/loginchecking for passwd... /usr/bin/passwdchecking for inline... inlinechecking whether LLONG_MAX is declared... yeschecking whether SYSTR_POLICY_KILL is declared... nochecking whether RLIMIT_NPROC is declared... nochecking whether PR_SET_NO_NEW_PRIVS is declared... nochecking if gcc supports -Wall... yeschecking if gcc supports -Wpointer-arith... yeschecking if gcc supports -Wuninitialized... yeschecking if gcc supports -Wsign-compare... yeschecking if gcc supports -Wformat-security... yeschecking if gcc supports -Wpointer-sign... yeschecking if gcc supports -Wunused-result... nochecking if gcc supports -fno-strict-aliasing... yeschecking if gcc supports -D_FORTIFY_SOURCE=2... yeschecking gcc version... 4.4.4checking if gcc accepts -fno-builtin-memset... yeschecking if gcc supports -fstack-protector-all... yeschecking if -fstack-protector-all works... yeschecking bstring.h usability... nochecking bstring.h presence... nochecking for bstring.h... nochecking crypt.h usability... yeschecking crypt.h presence... yeschecking for crypt.h... yeschecking crypto/sha2.h usability... nochecking crypto/sha2.h presence... nochecking for crypto/sha2.h... nochecking dirent.h usability... yeschecking dirent.h presence... yeschecking for dirent.h... yeschecking endian.h usability... nochecking endian.h presence... nochecking for endian.h... nochecking features.h usability... nochecking features.h presence... nochecking for features.h... nochecking fcntl.h usability... yeschecking fcntl.h presence... yeschecking for fcntl.h... yeschecking floatingpoint.h usability... nochecking floatingpoint.h presence... nochecking for floatingpoint.h... nochecking getopt.h usability... yeschecking getopt.h presence... yeschecking for getopt.h... yeschecking glob.h usability... yeschecking glob.h presence... yeschecking for glob.h... yeschecking ia.h usability... nochecking ia.h presence... nochecking for ia.h... nochecking iaf.h usability... nochecking iaf.h presence... nochecking for iaf.h... nochecking limits.h usability... yeschecking limits.h presence... yeschecking for limits.h... yeschecking login.h usability... nochecking login.h presence... nochecking for login.h... nochecking maillock.h usability... yeschecking maillock.h presence... yeschecking for maillock.h... yeschecking ndir.h usability... nochecking ndir.h presence... nochecking for ndir.h... nochecking net/if_tun.h usability... nochecking net/if_tun.h presence... nochecking for net/if_tun.h... nochecking netdb.h usability... yeschecking netdb.h presence... yeschecking for netdb.h... yeschecking netgroup.h usability... nochecking netgroup.h presence... nochecking for netgroup.h... nochecking pam/pam_appl.h usability... nochecking pam/pam_appl.h presence... nochecking for pam/pam_appl.h... nochecking paths.h usability... yeschecking paths.h presence... yeschecking for paths.h... yeschecking poll.h usability... yeschecking poll.h presence... yeschecking for poll.h... yeschecking pty.h usability... nochecking pty.h presence... nochecking for pty.h... nochecking readpassphrase.h usability... nochecking readpassphrase.h presence... nochecking for readpassphrase.h... nochecking rpc/types.h usability... yeschecking rpc/types.h presence... yeschecking for rpc/types.h... yeschecking security/pam_appl.h usability... yeschecking security/pam_appl.h presence... yeschecking for security/pam_appl.h... yeschecking sha2.h usability... yeschecking sha2.h presence... yeschecking for sha2.h... yeschecking shadow.h usability... yeschecking shadow.h presence... yeschecking for shadow.h... yeschecking stddef.h usability... yeschecking stddef.h presence... yeschecking for stddef.h... yeschecking for stdint.h... (cached) yeschecking for string.h... (cached) yeschecking for strings.h... (cached) yeschecking sys/audit.h usability... nochecking sys/audit.h presence... nochecking for sys/audit.h... nochecking sys/bitypes.h usability... nochecking sys/bitypes.h presence... nochecking for sys/bitypes.h... nochecking sys/bsdtty.h usability... nochecking sys/bsdtty.h presence... nochecking for sys/bsdtty.h... nochecking sys/cdefs.h usability... nochecking sys/cdefs.h presence... nochecking for sys/cdefs.h... nochecking sys/dir.h usability... nochecking sys/dir.h presence... nochecking for sys/dir.h... nochecking sys/mman.h usability... yeschecking sys/mman.h presence... yeschecking for sys/mman.h... yeschecking sys/ndir.h usability... nochecking sys/ndir.h presence... nochecking for sys/ndir.h... nochecking sys/poll.h usability... yeschecking sys/poll.h presence... yeschecking for sys/poll.h... yeschecking sys/prctl.h usability... nochecking sys/prctl.h presence... nochecking for sys/prctl.h... nochecking sys/pstat.h usability... nochecking sys/pstat.h presence... nochecking for sys/pstat.h... nochecking sys/select.h usability... yeschecking sys/select.h presence... yeschecking for sys/select.h... yeschecking for sys/stat.h... (cached) yeschecking sys/stream.h usability... yeschecking sys/stream.h presence... yeschecking for sys/stream.h... yeschecking sys/stropts.h usability... yeschecking sys/stropts.h presence... yeschecking for sys/stropts.h... yeschecking sys/strtio.h usability... nochecking sys/strtio.h presence... nochecking for sys/strtio.h... nochecking sys/statvfs.h usability... yeschecking sys/statvfs.h presence... yeschecking for sys/statvfs.h... yeschecking sys/sysmacros.h usability... yeschecking sys/sysmacros.h presence... yeschecking for sys/sysmacros.h... yeschecking sys/time.h usability... yeschecking sys/time.h presence... yeschecking for sys/time.h... yeschecking sys/timers.h usability... nochecking sys/timers.h presence... nochecking for sys/timers.h... nochecking sys/un.h usability... yeschecking sys/un.h presence... yeschecking for sys/un.h... yeschecking time.h usability... yeschecking time.h presence... yeschecking for time.h... yeschecking tmpdir.h usability... nochecking tmpdir.h presence... nochecking for tmpdir.h... nochecking ttyent.h usability... nochecking ttyent.h presence... nochecking for ttyent.h... nochecking ucred.h usability... yeschecking ucred.h presence... yeschecking for ucred.h... yeschecking for unistd.h... (cached) yeschecking usersec.h usability... nochecking usersec.h presence... nochecking for usersec.h... nochecking util.h usability... nochecking util.h presence... nochecking for util.h... nochecking utime.h usability... yeschecking utime.h presence... yeschecking for utime.h... yeschecking utmp.h usability... yeschecking utmp.h presence... yeschecking for utmp.h... yeschecking utmpx.h usability... yeschecking utmpx.h presence... yeschecking for utmpx.h... yeschecking vis.h usability... nochecking vis.h presence... nochecking for vis.h... nochecking for lastlog.h... yeschecking for sys/ptms.h... yeschecking for login_cap.h... nochecking for sys/mount.h... yeschecking for obsolete utmp and wtmp in solaris2.x... yeschecking compiler and flags for sanity... yeschecking for yp_match... nochecking for yp_match in -lnsl... yeschecking for setsockopt... nochecking for setsockopt in -lsocket... yeschecking for dirname... yeschecking libgen.h usability... yeschecking libgen.h presence... yeschecking for libgen.h... yeschecking for getspnam... yeschecking for library containing basename... none requiredchecking zlib.h usability... yeschecking zlib.h presence... yeschecking for zlib.h... yeschecking for deflate in -lz... yeschecking for possibly buggy zlib... nochecking for strcasecmp... yeschecking for utimes... yeschecking libutil.h usability... nochecking libutil.h presence... nochecking for libutil.h... nochecking for library containing fmt_scaled... nochecking for library containing login... nochecking for library containing logout... nochecking for library containing logwtmp... nochecking for library containing openpty... nochecking for library containing updwtmp... none requiredchecking for fmt_scaled... nochecking for login... nochecking for logout... nochecking for openpty... nochecking for updwtmp... yeschecking for logwtmp... nochecking for strftime... yeschecking for GLOB_ALTDIRFUNC support... nochecking for gl_matchc field in glob_t... nochecking for gl_statv and GLOB_KEEPSTAT extensions for glob... nochecking whether GLOB_NOMATCH is declared... yeschecking whether struct dirent allocates space for d_name... nochecking for /proc/pid/fd directory... yeschecking for arc4random... nochecking for arc4random_buf... nochecking for arc4random_uniform... nochecking for asprintf... yeschecking for b64_ntop... nochecking for __b64_ntop... nochecking for b64_pton... nochecking for __b64_pton... nochecking for bcopy... yeschecking for bindresvport_sa... nochecking for clock... yeschecking for closefrom... yeschecking for dirfd... yeschecking for fchmod... yeschecking for fchown... yeschecking for freeaddrinfo... yeschecking for fstatvfs... yeschecking for futimes... nochecking for getaddrinfo... yeschecking for getcwd... yeschecking for getgrouplist... nochecking for getnameinfo... yeschecking for getopt... yeschecking for getpeereid... nochecking for getpeerucred... yeschecking for _getpty... nochecking for getrlimit... yeschecking for getttyent... nochecking for glob... yeschecking for group_from_gid... nochecking for inet_aton... yeschecking for inet_ntoa... yeschecking for inet_ntop... yeschecking for innetgr... yeschecking for login_getcapbool... nochecking for md5_crypt... nochecking for memmove... yeschecking for mkdtemp... yeschecking for mmap... yeschecking for ngetaddrinfo... nochecking for nsleep... nochecking for ogetaddrinfo... nochecking for openlog_r... nochecking for poll... yeschecking for prctl... nochecking for pstat... nochecking for readpassphrase... nochecking for realpath... yeschecking for recvmsg... yeschecking for rresvport_af... yeschecking for sendmsg... yeschecking for setdtablesize... nochecking for setegid... yeschecking for setenv... yeschecking for seteuid... yeschecking for setgroupent... nochecking for setgroups... yeschecking for setlinebuf... yeschecking for setlogin... nochecking for setpassent... nochecking for setpcred... nochecking for setproctitle... nochecking for setregid... yeschecking for setreuid... yeschecking for setrlimit... yeschecking for setsid... yeschecking for setvbuf... yeschecking for sigaction... yeschecking for sigvec... nochecking for snprintf... yeschecking for socketpair... yeschecking for statfs... yeschecking for statvfs... yeschecking for strdup... yeschecking for strerror... yeschecking for strlcat... yeschecking for strlcpy... yeschecking for strmode... nochecking for strnlen... yeschecking for strnvis... nochecking for strptime... yeschecking for strtonum... nochecking for strtoll... yeschecking for strtoul... yeschecking for swap32... nochecking for sysconf... yeschecking for tcgetpgrp... yeschecking for timingsafe_bcmp... nochecking for truncate... yeschecking for unsetenv... yeschecking for updwtmpx... yeschecking for user_from_uid... nochecking for vasprintf... yeschecking for vhangup... yeschecking for vsnprintf... yeschecking for waitpid... yeschecking for library containing dlopen... none requiredchecking for gai_strerror... yeschecking for library containing nanosleep... none requiredchecking whether getrusage is declared... nochecking whether strsep is declared... yeschecking for strsep... yeschecking whether tcsendbreak is declared... yeschecking whether h_errno is declared... yeschecking whether SHUT_RD is declared... yeschecking whether O_NONBLOCK is declared... yeschecking whether writev is declared... yeschecking whether MAXSYMLINKS is declared... yeschecking whether offsetof is declared... yeschecking for setresuid... nochecking for setresgid... nochecking for gettimeofday... yeschecking for time... yeschecking for endutent... yeschecking for getutent... yeschecking for getutid... yeschecking for getutline... yeschecking for pututline... yeschecking for setutent... yeschecking for utmpname... yeschecking for endutxent... yeschecking for getutxent... yeschecking for getutxid... yeschecking for getutxline... yeschecking for getutxuser... nochecking for pututxline... yeschecking for setutxdb... nochecking for setutxent... yeschecking for utmpxname... yeschecking for getlastlogxbyname... nochecking for daemon... yeschecking for getpagesize... yeschecking whether snprintf correctly terminates long strings... yeschecking whether snprintf can declare const char *fmt... yeschecking for (overly) strict mkstemp... nochecking whether getpgrp requires zero arguments... yeschecking OpenSSL header version... 1000004f (OpenSSL 1.0.0d 8 Feb 2011)checking OpenSSL library version... 1000004f (OpenSSL 1.0.0d 8 Feb 2011)checking whether OpenSSL's headers match the library... yeschecking if programs using OpenSSL functions will link... yeschecking for RSA_generate_key_ex... yeschecking for DSA_generate_parameters_ex... yeschecking for BN_is_prime_ex... yeschecking for RSA_get_default_method... yeschecking for HMAC_CTX_init... yeschecking whether OpenSSL has crippled AES support... nochecking if EVP_DigestUpdate returns an int... yeschecking for SHA256_Update... yeschecking for EVP_sha256... yeschecking whether OpenSSL has complete ECC support... nochecking for ia_openinfo in -liaf... nochecking whether OpenSSL's PRNG is internally seeded... yeschecking if select works with descriptor rlimit... nochecking if setrlimit RLIMIT_FSIZE works... yeschecking for long long... yeschecking for unsigned long long... yeschecking for long double... yeschecking size of short int... 2checking size of int... 4checking size of long int... 4checking size of long long int... 8checking for u_int type... yeschecking for intXX_t types... yeschecking for int64_t type... yeschecking for u_intXX_t types... nochecking for u_intXX_t types in sys/socket.h... nochecking for u_int64_t types... nochecking for u_int64_t type in sys/bitypes.h... nochecking for uintXX_t types... yeschecking for uintXX_t types in stdint.h... yeschecking for u_char... yeschecking for socklen_t... yeschecking for sig_atomic_t... yeschecking for fsblkcnt_t... yeschecking for fsfilcnt_t... yeschecking for in_addr_t... yeschecking for in_port_t... yeschecking for size_t... yeschecking for ssize_t... yeschecking for clock_t... yeschecking for sa_family_t... yeschecking for pid_t... yeschecking for mode_t... yeschecking for struct sockaddr_storage... yeschecking for struct sockaddr_in6... yeschecking for struct in6_addr... yeschecking for struct sockaddr_in6.sin6_scope_id... yeschecking for struct addrinfo... yeschecking for struct timeval... yeschecking for struct timespec... yeschecking for ut_host field in utmp.h... nochecking for ut_host field in utmpx.h... yeschecking for syslen field in utmpx.h... yeschecking for ut_pid field in utmp.h... yeschecking for ut_type field in utmp.h... yeschecking for ut_type field in utmpx.h... yeschecking for ut_tv field in utmp.h... nochecking for ut_id field in utmp.h... yeschecking for ut_id field in utmpx.h... yeschecking for ut_addr field in utmp.h... nochecking for ut_addr field in utmpx.h... nochecking for ut_addr_v6 field in utmp.h... nochecking for ut_addr_v6 field in utmpx.h... nochecking for ut_exit field in utmp.h... yeschecking for ut_time field in utmp.h... yeschecking for ut_time field in utmpx.h... yeschecking for ut_tv field in utmpx.h... yeschecking for struct stat.st_blksize... yeschecking for struct __res_state.retrans... yeschecking for ss_family field in struct sockaddr_storage... yeschecking for __ss_family field in struct sockaddr_storage... nochecking for pw_class field in struct passwd... nochecking for pw_expire field in struct passwd... nochecking for pw_change field in struct passwd... nochecking for msg_accrights field in struct msghdr... yeschecking if struct statvfs.f_fsid is integral type... yeschecking for msg_control field in struct msghdr... nochecking if libc defines __progname... yeschecking whether gcc implements __FUNCTION__... yeschecking whether gcc implements __func__... yeschecking whether va_copy exists... yeschecking whether __va_copy exists... yeschecking whether getopt has optreset support... nochecking if libc defines sys_errlist... yeschecking if libc defines sys_nerr... yeschecking for library containing getrrsetbyname... nochecking for library containing res_query... -lresolvchecking for library containing dn_expand... none requiredchecking if res_query will link... yeschecking for _getshort... yeschecking for _getlong... yeschecking whether _getshort is declared... nochecking whether _getlong is declared... nochecking for HEADER.ad... nochecking if struct __res_state _res is an extern... yeschecking for xauth... nochecking Discovering system mail directory... Using: /var/mail from _PATH_MAILDIRchecking for "/dev/ptmx"... yeschecking for "/dev/ptc"... nochecking for nroff... (cached) /usr/gnu/bin/nroffchecking if the systems has expire shadow information... yeschecking for "/etc/default/login"... yesconfigure: WARNING:If PATH is defined in /etc/default/login, ensure the path to scp is included,otherwise scp will not work.Adding /usr/local/bin to USER_PATH so scp will workchecking if we need to convert IPv4 in IPv6-mapped addresses... no (default)checking if your system defines LASTLOG_FILE... nochecking if your system defines _PATH_LASTLOG... nochecking if your system defines UTMP_FILE... yeschecking if your system defines WTMP_FILE... yeschecking if your system defines WTMPX_FILE... yeschecking whether BROKEN_GETADDRINFO is declared... noconfigure: creating ./config.statusconfig.status: creating Makefileconfig.status: creating buildpkg.shconfig.status: creating opensshd.initconfig.status: creating openssh.xmlconfig.status: creating openbsd-compat/Makefileconfig.status: creating openbsd-compat/regress/Makefileconfig.status: creating survey.shconfig.status: creating config.hconfig.status: config.h is unchangedOpenSSH has been configured with the following options:                     User binaries: /usr/local/bin                   System binaries: /usr/local/sbin               Configuration files: /usr/local/etc                   Askpass program: /usr/local/libexec/ssh-askpass                      Manual pages: /usr/local/share/man/manX                          PID file: /var/run  Privilege separation chroot path: /var/empty            sshd default user PATH: /usr/ccs/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin   (If PATH is set in /etc/default/login it will be used instead. If   used, ensure the path to scp is present, otherwise scp will not work.)                    Manpage format: doc                       PAM support: no                   OSF SIA support: no                 KerberosV support: no                   SELinux support: no                 Smartcard support:                      S/KEY support: no              TCP Wrappers support: no              MD5 password support: no                   libedit support: no  Solaris process contract support: no           Solaris project support: no       IP address in $DISPLAY hack: no           Translate v4 in v6 hack: no                  BSD Auth support: no              Random number source: OpenSSL internal ONLY             Privsep sandbox style: none              Host: i386-pc-solaris2.11          Compiler: gcc    Compiler flags: -g -O2 -Wall -Wpointer-arith -Wuninitialized -Wsign-compare -Wformat-security -Wno-pointer-sign -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -fno-builtin-memset -fstack-protector-all Preprocessor flags:       Linker flags:  -fstack-protector-all         Libraries: -lresolv -lcrypto -lz -lsocket -lnslSVR4 style packages are supported with "make package"
A: В вашем же списке:...checking zlib.h usability... yeschecking zlib.h presence... yeschecking for zlib.h... yeschecking for deflate in -lz... yeschecking for possibly buggy zlib... no...checking OpenSSL header version... 1000004f (OpenSSL 1.0.0d 8 Feb 2011)checking OpenSSL library version... 1000004f (OpenSSL 1.0.0d 8 Feb 2011)...
A: стандартно в solaris для этого есть pkginfo
/usr/bin/pkginfo

можно установить pkgutil, если необходимо устанавливать новые пакеты (это если не хочешь скомпилить пакет сам =))
Для  solaris 10  и 11:
pkgadd -d http://get.opencsw.org/now
/opt/csw/bin/pkgutil -U
/opt/csw/bin/pkgutil -y -i pkgutil
/usr/sbin/pkgchk -L CSWpkgutil # list files

дальше с помощью этой улилиты можешь смотреть, устанавливать и т.д пакеты.
pkgutil --list

A: а ОС какая? Попробуй - whereis openssl
A: Можно ещё вот так:dpkg --get-slections | grep ssl


text:
Q: using division in awk script I have a file describing allele frequencies and I am trying to use awk to print lines if either one of the frequencies in the two last columns are equal or greater than 0.01. Below is the format of the frequency file: I am interested in the last two frequencies.
2L      10000133        A      125/125 115/131 0/125   16/131
2L      10000374        A      121/124 143/143 3/124   0/143

From my limited knowledge of awk, I wrote the following code.
cat myfile.txt |
awk ' BEGIN { {FS="/"}{OFS="\t"}
     if( ($8>0) && ($8/$9 >= "0.01") || ($10>0) && ($10/$11 >= "0.01"))
             { print $1,$2 }
            }' > myfilteredfile.txt

However, the output file myfilteredfile.txt is empty. I expected that the output file would have printed:
2L      10000133
2L      10000374

...Because both lines contain a frequency in the last two columns that is equal or greater than 0.01. Any advice?

A: There are two issues with your existing script.
The first is the separator: you want to split on runs of spaces, and slash; so you need to specify a regular expression which matches that, and use that as FS: FS="[ /]+".
The second is that all your code is in the BEGIN block. You need to initialise the separators in the BEGIN block (or elsewhere, e.g. using specific AWK parameters), then use a matcher block to process the lines.
This version works:
awk 'BEGIN { FS="[ /]+"; OFS="\t" }
     (($8>0) && ($8/$9 >= "0.01") || ($10>0) && ($10/$11 >= "0.01")) {
         print $1, $2
     }' myfile.txt

Strictly speaking it would be better to use 0.01 instead of "0.01" since you're matching numeric values:
awk 'BEGIN { FS="[ /]+"; OFS="\t" }
     (($8>0) && ($8/$9 >= 0.01) || ($10>0) && ($10/$11 >= 0.01)) {
         print $1, $2
     }' myfile.txt

A: In awk's BEGIN{...} parts is running before reading input line from input, so in your code actually awk not reading any input, that's why it's returning nothing. if you want to feed it you need to use getline but it will read only one line, you can use for loop to read all.
another problem is when you use FS="/" it splitting the lines into the fields which delimited by /, but the problem is $8 doesn't exit since max fields are only 5 and those the filed is like this 125 115, 131 0, 125 16, etc.
You can use this code instead to achieve what you want. also note that awk can read from file directly not required using cat there
awk -F'[/ ]+' 'BEGIN{ OFS="\t"}
    {if( ($8>0) && ($8/$9 >= 0.01) || ($10>0) && ($10/$11 >= 0.01))
    { print $1,$2 }
}'  infile

A: $  awk '{ split($(NF-1),a,/\//) } { split($NF,b,/\//) } a[1]/a[2] > 0.01 || b[1]/b[2] > 0.01 { print $1, $2 }' file.in
2L 10000133
2L 10000374

This splits the last two fields individually on the / character and stores the parts in the two arrays a and b. If either division, when carried out, results in a number greater than 0.01, the two first fields are outputted.
$NF is the value of the last field (column) in the input record (line). and $(NF-1) is the second to last field's value.

The issue with your code is that you're doing everything in a BEGIN block.  This block is mainly for initialization and will be executed before any data has actually been read. There is also an issue with the chosen value of FS that the other answers points out.
You also do not need to quote numbers when they are used as numbers.


text:
Q: How to retrieve start address of a thread using its ID? I want to get the start address of a thread using it's ID. Is it possible?

A: All you need is to OpenThread and call NtQueryInformationThread
with second parameter set to ThreadQuerySetWin32StartAddress
Also refer to this article

A: Well, this is not really trivial for the following reason: in the Win32 subsystem all threads have the same start address. In Windows up to (but not including) Vista it was inside kernel32.dll (named BaseThreadStartThunk according to the official symbols). In Windows versions starting with Vista, the common start address is now RtlUserThreadStart in ntdll.dll (and BaseThreadStartThunk got renamed to BaseThreadInitThunk and seemingly only does the Win32-specific tasks now).
However, what you could attempt is to suspend the thread, retrieve its CONTEXT (using GetThreadContext) and from that traverse the stack back to its top to investigate the parameters there. It will require some reverse-engineering of each implementation of the kernel32.dll thread start routine, but it should be doable.
An alternative is to use the undocumented native API NtQueryInformationThread with ThreadQuerySetWin32StartAddress. There is also an MSDN page about the function, but it is far from complete.


text:
Q: Is there way to use `respected` in passive voice with object pronoun I want to say that there two persons who came to do something and I highly respect them and I want to call them by name in the same sentence.
I thought it should be like this: "Deeply respected by me, Henry and Jack are well known, they came there to tell you something."
or
"Well known people Henry and Jack, deeply respected by me, came here to tell you something."

A: For non-experts in English: You will get into less trouble if you put the subject of the sentence first.
These are clumsy:

Deeply respected by me, Henry and Jack are well known, they came there to tell you something.
  Well known people Henry and Jack, deeply respected by me, came here to tell you something.

To make them clear, start with the subject:

Henry and Jack, who are well known and deeply respected by me, came here to tell you something.

Another way to write clearly would be to separate it into two sentences.

Henry and Jack came here to tell you something.  They are well known, and I deeply respect them.


text:
Q: Ifstream failing to interpret EOF char buf[25];
ifstream fin("test.txt", ifstream::binary);
while (!fin.eof()) {
    bzero(buf, sizeof(buf));
    fin.read(buf, sizeof(buf));
}

The file test.txt contains 75 characters, no newlines or any other special character. Given the code, the while loop should only iterate 3 times, but it ends up iterating 4 times. During the last iteration, nothing is being stored in the buf variable. Why is this happening?

A: fstream.eof only becomes true when you have passed the end-of-file. The fourth iteration occurs because you have read exactly the contents of the file and have not yet reached the eof.


text:
Q: Systemd tomcat.service failed with no errors I have Tomcat configured to run as a service using Systemd on CentOS 7.2. I can start Tomcat with no problems:
sudo systemctl start tomcat

I can access the splash screen, the manager app, and even deploy applications. Then I shut down Tomcat:
sudo systemctl stop tomcat

I don't see any errors. But then I check the status:
sudo systemctl status tomcat

● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Sun 2016-10-30 17:27:19 UTC; 2s ago
  Process: 10833 ExecStop=/bin/kill -TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 10785 ExecStart=/opt/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 10795 (code=exited, status=143)

Oct 30 17:26:31 java2016 systemd[1]: Starting Apache Tomcat Web Application Container...
Oct 30 17:26:31 java2016 startup.sh[10785]: Existing PID file found during start.
Oct 30 17:26:31 java2016 startup.sh[10785]: Removing/clearing stale PID file.
Oct 30 17:26:31 java2016 systemd[1]: Started Apache Tomcat Web Application Container.
Oct 30 17:27:19 java2016 systemd[1]: Stopping Apache Tomcat Web Application Container...
Oct 30 17:27:19 java2016 systemd[1]: tomcat.service: main process exited, code=exited, status=143/n/a
Oct 30 17:27:19 java2016 systemd[1]: Stopped Apache Tomcat Web Application Container.
Oct 30 17:27:19 java2016 systemd[1]: Unit tomcat.service entered failed state.
Oct 30 17:27:19 java2016 systemd[1]: tomcat.service failed.

It shows that kill functioned just fine. And /opt/tomcat/logs/catalina.out doesn't show any problems, either:
30-Oct-2016 17:27:19.268 INFO [Thread-5] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
30-Oct-2016 17:27:19.324 INFO [Thread-5] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
30-Oct-2016 17:27:19.375 INFO [Thread-5] org.apache.catalina.core.StandardService.stopInternal Stopping service Catalina
30-Oct-2016 17:27:19.491 INFO [Thread-5] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
30-Oct-2016 17:27:19.493 INFO [Thread-5] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
30-Oct-2016 17:27:19.494 INFO [Thread-5] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
30-Oct-2016 17:27:19.495 INFO [Thread-5] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]

Why does Systemd consider Tomcat "failed"? Does it have anything to do with that "stale PID file" message?

A: Ah, never mind; this has been answered already on serverfault for general Java applications.
Basically Java programs sometimes don't send back the expected exit status when shutting down in response to SIGTERM. Adding the following to the tomcat.service file fixes the problem:
[Service]
SuccessExitStatus=143


text:
Q: Stacking column indices on top of one another using Pandas I'm looking to stack the indices of some columns on top of one another, this is what I currently have:

            Buy     Buy Currency   Sell     Sell Currency
Date
2013-12-31  100     CAD            100      USD
2014-01-02  200     USD            200      CAD
2014-01-03  300     CAD            300      USD
2014-01-06  400     USD            400      CAD

This is what I'm looking to achieve:
Buy/Sell     Buy/Sell Currency

100          USD
100          CAD
200          CAD
200          USD
300          USD
300          CAD

And so on, Basically want to take the values in "Buy" and "Buy Currency" and stack their values in the "Sell" and "Sell Currency" columns, one after the other.
And so on. I should mention that my data frame has 10 columns in total so using
df_pl.stack(level=0)

doesn't seem to work.

A: One option is with pivot_longer from pyjanitor, where for this particular use case, you pass a list of regular expressions (to names_pattern) to aggregate the desired column labels into new groups (in names_to):
# pip install pyjanitor
import pandas as pd
import janitor

df.pivot_longer(index=None,
                names_to = ['Buy/Sell', 'Buy/Sell Currency'],
                names_pattern = [r"Buy$|Sell$", ".+Currency$"],
                ignore_index = False,
                sort_by_appearance=True)

            Buy/Sell Buy/Sell Currency
Date
2013-12-31       100               CAD
2013-12-31       100               USD
2014-01-02       200               USD
2014-01-02       200               CAD
2014-01-03       300               CAD
2014-01-03       300               USD
2014-01-06       400               USD
2014-01-06       400               CAD

A: using concat
import pandas as pd

print(pd.concat(
    [df['Buy'], df['sell']], axis=1
).stack().reset_index(1, drop=True).rename(index='buy/sell')
)

output:
0    100
0    100
1    200
1    200
2    300
2    300
3    400
3    400

A: # assuming that your data has date as index.
df.set_index('date', inplace=True)

# create a mapping to new column names
d={'Buy Currency': 'Buy/Sell Currency',
   'Sell Currency' : 'Buy/Sell Currency',
   'Buy' : 'Buy/Sell',
   'Sell' :'Buy/Sell'
  }
df.columns=df.columns.map(d)

# stack first two columns over the next two columns
out=pd.concat([ df.iloc[:,:2],
            df.iloc[:,2:]
          ],
           ignore_index=True
          )
out

    Buy/Sell    Buy/Sell Currency
0   100     CAD
1   200     USD
2   300     CAD
3   400     USD
4   100     USD
5   200     CAD
6   300     USD
7   400     CAD


text:
Q: Which properties yield the exponential family of distributions? It seems like every resource that discusses exponential families simply defines the family of distributions, explains why it's useful and then derives some of its properties.
I have only seen one resource which seems to derive the exponential family through geometry. Specifically, "Differential Geometry and Statistics" by Murray and Rice. I don't have the background to understand this exposition, but I still want to understand where the exponentially family comes from.
How can one arrive at the form exponential family of distributions from first principles without prior knowledge of what it looks like?
I'd like to know what question does the form of the exponential family answer?
The answer I'm looking for would follow along these lines:

*

*What distributions have X,Y,Z properties?

*Writing down assumptions based on this question, we'd "solve" for the set of distributions satisfying these properties.

*Arrive at an equation describing the set defined in step one which happens to be algebraically equivalent to the exponential family of distributions.

A: From a practical point of view I would guess that people realized that presumably different distributions have astonishingly similar properties so that they searched for a 'common root cause' of these properties. Then they started to 'fuse' single pairs of these 'presumably different' distributions and figured out that the 'root cause' for the similarities is that they surprisingly arise from the same family just with different parameters.
So they continued in that way and fused and fused until they arrived at the stage today: the exponential family.
It is consistent in an important sense: if I do not misinterpret the wikipedia page then it means that the family stays consistent under using the Bayesian framework, i.e. if one chooses the prior correctly then the posterior of a member of the exponential family is again a member of the exponential family...
Now this property also holds for smaller families so you might ask: why did people stop here, i.e. why is the exp. family the 'right thing' or: why don't we enlarge it? This hints at the other questions: They maximize the entropy w.r.t. a reference measure dH, i.e. take some measure dH (probably it needs to satisfy mild assumptions) and take some other random variables T_1,...,T_n (also satisfying some mild conditions like that they are integrable and so on) then what is the measure dF such that this crazy integral in 'Maximum entropy derivation' in the wikipedia page with the additional constraint that the expected value of the T_i w.r.t. that measure dF is some fixed value t_i is a member of the exp. family that you construct from this input data. These are the equations that you search for (they are not easy though!)...
Maximum Entropy means 'contains the most information' somewhat...


text:
Q: HttpClient 502 Bad Gateway Async only I am having trouble with calling a web service asynchronously. I have called it synchronously without error hundreds of times inside a loop, but when I call it asynchronously, I get a 502 Bad Gateway error, usually after about 250 asynchronous calls. As you can see, I've tried waiting 50ms with Thread.Sleep() and retrying up to 5 times per record. The 404 Not Found error is expected when I'm unable to validate a record. My framework is netstandard2.0.
class Program
    {
        static void Main(string[] args)
        {
            List<OriginalRecord> originalRecords = new List<OriginalRecord>();
            originalRecords.Add(new OriginalRecord()
            {
                Id = "IdOne",
                Foo = "fooOne"
            });
            originalRecords.Add(new OriginalRecord()
            {
                Id = "IdTwo",
                Foo = "fooTwo"
            });

            List<RecordValidation> unvalidatedRecords = new List<RecordValidation>();

            try
            {
                RecordValidator validator = new RecordValidator("myAccessToken", "myBarId");
                var task = validator.ValidateRecordsAsync(originalRecords.Select(r => r.Id).ToList());
                task.Wait();
                unvalidatedRecords = task.Result;
            }
            catch
            {
                throw;
            }
        }
    }
    public class RecordValidator
    {
        public RecordValidator(string AccessToken, string BarId)
        {
            httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("MessageService/3.1");

            httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);

            httpClient.DefaultRequestHeaders.Add("Accept", "application/hal+json");
            httpClient.DefaultRequestHeaders.ExpectContinue = false;

            barId = BarId;
        }

        private static HttpClient httpClient { get; set; }

        public string barId { get; set; }

        public async Task<List<RecordValidation>> ValidateRecordsAsync(List<string> Records)
        {
            List<Task<RecordValidation>> tasks = new List<Task<RecordValidation>>();

            foreach (var record in Records)
            {
                tasks.Add(Task.Run(() => ValidateRecordAsync(record)));
            }

            var results = await Task.WhenAll(tasks);
            return results.Where(r => !r.Validated).ToList();
        }

        private async Task<RecordValidation> ValidateRecordAsync(string Record)
        {
            string url = $"https://data.somewebapp.com/api/bar/{barId}/record/{Uri.EscapeDataString(Record)}";
            int retries = 0;
            bool success = false;
            HttpResponseMessage response = new HttpResponseMessage();
            try
            {

                do
                {
                    response = await httpClient.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        success = true;
                    }
                    else
                    {
                        Thread.Sleep(50);
                        retries++;
                    }
                } while (retries < 5 && !success);

                response.EnsureSuccessStatusCode();

                string responseString = await response.Content.ReadAsStringAsync();

                var output = JsonConvert.DeserializeObject<RecordValidation>(responseString);

                if (!string.IsNullOrEmpty(output.RecordId))
                    output.Validated = true;
                return output;
            }

            catch (HttpRequestException ex) when (ex.Message == "Response status code does not indicate success: 404 (Not Found).")
            {
                return new RecordValidation()
                {
                    RecordId = Record,
                    Validated = false
                };
            }

            catch
            {
                throw;
            }
        }
    }
    public class RecordValidation
    {
        public RecordValidation()
        {
            RecordId = string.Empty;
            Validated = false;
        }

        [JsonProperty("id")]
        public string RecordId { get; set; }

        public bool Validated { get; set; }
    }

    public class OriginalRecord
    {
        public string Id { get; set; }
        public string Foo { get; set; }
    }
}

A: A 502 response is an actual response. Your HTTP request succeeded, and the server returned a 502 response. It's likely because you're hitting the server too fast and hard and it's cutting you off.
When you do it synchronously, it will send the request and wait for a response before moving on to the next one.
But in this loop:
foreach (var record in Records)
{
    tasks.Add(Task.Run(() => ValidateRecordAsync(record)));
}

You're creating a new thread for each request, which has the effect of sending every request almost simultaneously. Clearly the server does not like that.
You don't need to create a new thread for each request. You could start them asynchronously without Task.Run(), like:
foreach (var record in Records)
{
    tasks.Add(ValidateRecordAsync(record));
}

That will slow it just a little bit, but not much. This would run ValidateRecordAsync() on the same thread up until the HTTP request is sent before moving to the next iteration of the loop and starting the next. But that might still be too fast for the server, since you're still sending all the requests before the previous is complete.
You will likely have to throttle your requests. If you want it to be as fast as possible, you can find out how many requests the web service will allow you to send, you can tailor your code to the web service. Otherwise, you'll just be guessing.
You could send, say 10 at a time and add a pause in between.
foreach (var record in Records)
{
    tasks.Add(ValidateRecordAsync(record));
    if (tasks.Count % 10 == 0) await Task.Delay(100);
}

Or wait until those 10 complete before moving on:
foreach (var record in Records)
{
    tasks.Add(ValidateRecordAsync(record));
    if (tasks.Count % 10 == 0) await Task.WhenAll(tasks);
}

You can call Task.WhenAll on the same list of tasks multiple times.

A: 250 parallel calls are way too much. It should be rather 10-30. Default max number of concurrent requests for the C# Http client is 10, so if you aren't overriding that value, it doesn't make sense to try to open more than 10 socket connections simultaneously. Also, keep in mind, 502 status is most likely returned by reverse proxy, which means you aren't really hitting the web API, proxy is telling you "slow down, I cannot handle that anymore". So in your case, it's not really HttpClient issue, otherwise, you would get some exception, like SocketException due to socket exhaustion, which you aren't probably getting due to HttpClient limitting concurrency to 10. Also, you have plenty of thread blocking code, like Thread.Sleep() or task.Wait(), change your main method signature to static async Task Main() and use await everywhere, otherwise, you will run into other types of issues, like thread exhaustion


text:
Q: hibernate + jersey2 + Json + blob image I want to be able to upload a file along with Json. I'm using hibernate and jersey2.
I already tried sending req. with postman, but nothing seems to work.
I'm getting errors like:
Can not construct instance of java.sql.Blob: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@908c4c5; line: 9, column: 28] (through reference chain: entity.Car["pictures"]->java.util.ArrayList[0]->entity.Picture["image"])
Car entity:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "car_id")
private int id;
@Column(name = "km")
private int km;
@Column(name = "modelyear")
private int modelyear;
@Column(name = "make")
private String make;
@Column(name = "model")
private String model;
@Column(name = "motorsize", columnDefinition = "DECIMAL(2,1)")
private float motorsize;
@Column(name = "motortype")
private String motortype;
@Column(name = "fueltype")
private String fueltype;
@Column(name = "price")
private int price;

@Transient
List<ResourceLink> links = new ArrayList<ResourceLink>();

@JsonProperty("pictures")
@OneToMany(fetch = FetchType.EAGER, mappedBy = "car", cascade = CascadeType.ALL)
List<Picture> pictures = new ArrayList<Picture>();

Picture entity:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "picture_id")
private int pictureId;

@Lob
@Column(name = "picture", columnDefinition = "mediumblob")
private Blob image;

@ManyToOne()
@JoinColumn(name = "car_id")
private Car car;

Hibernate imp:
public void create(Car entity) {
    Session session = SessionUtil.getSession();
    Transaction transaction = session.beginTransaction();
    session.save(entity);
    transaction.commit();
    session.close();
}

public Car findById(Integer id) {
    Session session = SessionUtil.getSession();
    Car car = session.get(Car.class, id);
    session.close();
    return car;
}

Car service:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createCar(Car car, @Context UriInfo uriInfo) {
    carDAO.create(car);
    BigInteger id = carDAO.findLatestId();
    URI uri = uriInfo.getAbsolutePathBuilder().path(String.valueOf(id)).build();
    return Response.created(uri).build();
}


text:
Q: Mocking Domain Model & Building Tests Without Repetition Looking for some clarification regarding testing. I have the following method in my Service layer:
readonly IDomainModelRepository domainModelRepository;

public DomainModelDetailsDto Edit(int DomainModelID, IPrincipal User)
{
    DomainModel myDomainModel = domainModelRepository.Find(DomainModelID);
    if ((myDomainModel == null) || (!myDomainModel.UserCanEdit(User)))
        throw new UnauthorisedException();

    // Other stuff here...
}

Now I am building a suite of tests but have hit a couple of snags.

*

*The call to myDomainModel.UserCanEdit(User) cannot be mocked as DomainModel is not implementing any interface. It becomes even more complicated because the logic contained within UserCanEdit actually checks fields on other domain models within its graph. So how can I easily set this up to return a set value to allow me to test the Service?

*I am testing that the method correctly responds if the repo does not find the DomainModel item. Then I test it correctly responds if the User cannot edit (well I will be when I solve point 1 above!). But after that, each test I write for the "Other stuff here" requires that I correctly set up the test to pass these first two checks. This seems cumbersome, and makes each test repeat the same code. Is there a better way?

Perhaps the problem is that my code itself needs to be refactored in order to facilitate easier testing. If so, all advice appreciated!

A: If you want to test I think you need to use an interface on the myDomainModel otherwise you cant mock it.
I know this is a very controversial opinion but more and more people think Repository patter is an anti patter because it creates more problems than it resolves.
I personally use Entity Framework and change the TT files to generate the Context and the interface than in all my application I only use the interface.
To test I just mock the interface and I'm able to test everything. One of the changes I do is to change all the DbSet<T> with IDbSet<T>. Finally I created a Test Helper with a function that receives an ObservableCollection and returns an IDbSet and I'm able to validate everything.

A: You can stub UserCanEdit by making that method virtual and having a derived test class which overrides it. Your mocked repository can then return an instance of this test class set to return true or false depending on what you want to test.


text:
Q: BackgroundDownloader only downloading 5 at once I create 1,000 downloads using BackgroundDownloader.CreateDownload, then I queue up 100 of them by doing DownloadOperation.Start. If I watch the traffic in fiddler, only 5 of them at actually send out at once. When one finishes, another is sent out.
Is there a way to have more sent out concurrently?

A: Yes, there is a limit of 5 downloads at a time within Windows.Networking.BackgroundTransfer.
You can extend it to up to 6 downloads at a  time if you mark all your downloads as High Priority, i.e.:
var download = backgroundDownloader.CreateDownload(...);
download.Priority = BackgroundTransferPriority.High;
Task<DownloadOperation> task = download.StartAsync(...).AsTask();

A: This could be a limitation of the server you are downloading from, not necessarily the code you are writing. With .htaccess rules the admin of the server could do something like this in order to limit concurrent connections:
    MaxClients < number-of-connections>


text:
Q: makefile calling function inside a function This might be a very basic but I need to call a function within a function but I cannot figure it out:
chmod-prod:

    chown git:git-R ./

composer-dev:

    [who do I how chmod-prod: within here]

Any help would be appreciated

A: Note that chmod-prod and composer-dev are known as a targets in make terminology.
Using targets
If the result of chmod-prod needs to happen before the rest of the "recipe" in composer-dev then the most natural way in make would be to add it as a dependency.
composer-dev: chmod-prod
    [the rest of composer-dev recipe]

Given that both these targets do not lead to the creation of a file with their name it would be good practice to declare them as .PHONY:
.PHONY: chmod-prod
.PHONY: composer-dev

This ensures that the targets will not be affected if someone adds a file with the same name.
Using a variable
Another route would be store the command in a variable:
chmod_prod_cmd:=chown git:git-R ./

Which could then be used in the recipes of both your targets:
composer-dev:
    $(chmod_prod_cmd)

composer-dev:
    $(chmod_prod_cmd)
    [presumably some more recipe]

Canning a multi-line recipe
If the bit of recipe you want to reuse involves multiple lines then you will need to use the define directive instead of a normal variable assignment:
define chmod_prod_cmd
    echo Doing something
    chown git:git-R ./
endef

A: Assuming those need to be targets (and they sequence that way) then PeterSW has the right answer.
If they need finer-grained sequencing within the body of the composer-dev recipe then you could always just run make again (e.g. $(MAKE) chmod-prod) though I wouldn't suggest this structure of makefiles as it is expensive (to say the least).
That being said if the recipe body of chmod-prod is actually just a simple single (or series) of shell commands (that don't need to be run externally manually i.e. as make chmod-prod) then using a make variable/define instead of a target.
Something like this
chmod-prod := chown git:git-R ./

or this
define chmod-prod
    chown git:git-R ./
endef

and used like this
composer-dev:
        some_command
        $(chmod-prod)
        other_command


text:
Q: Radarchart in R - axes labels I was following this tutorial to create a radar chart in R. I take the last chart in the tutorial (before ggplot is introduced), where the "average" profile is compared across cases. I set up my data in the way that is suggested by the tutorial, with the exception that I wanted to have the same max and min values across the "facets", so I fixed that to an overall min and an overall max.
The data is:
plot_dat_sameaxis <- structure(list(pol_demo = c(30, 0, 8.97007879362473, 11.0085519474347,
                            8.53571259274138, 11.2005365744873, 8.71195021047779, 9.7436080644818,
                            10.399697356034, 7.20225368831287, 7.19846449682537), pol_demo_online = c(30,
                                                                                0, 9.98019651039727, 11.2121387931753, 10.3544128960645, 12.9789806839878,
                                                                                10.9067032818662, 10.0244169530494, 10.0412566166562, 9.15927081711705,
                                                                                7.82259925448071), pol_post_online = c(30, 0, 20.4990544471384,
                                                                                22.7970962322516, 20.1055172731424, 24.8459684814346, 20.1141933651088,
                                                                                15.3678777437076, 21.1504832571486, 23.2280265873052, 21.5491092364356
                                                                                ), pol_petition = c(30, 0, 22.4291973933483, 19.4974718426517,
                                                                                19.2697196682787, 24.3023818310391, 19.5669419418758, 22.3942976741465,
                                                                                18.8415089525096, 25.983262468582, 28.842684781718), pol_cntct_polit = c(30,
                                                                                0, 10.7532765882399, 10.815449497248, 12.7134692760538, 7.23126866059413,
                                                                                11.2047622893094, 11.4708587897729, 9.33114630516778, 9.60620574567012,
                                                                                10.6909820573769), pol_party = c(30, 0, 8.74403983440336, 7.77898781617009,
                                                                                9.02365487435948, 7.5573005918663, 9.55902871932231, 10.3628637158336,
                                                                                9.8557831406188, 7.67193215789611, 7.08669448709292), pol_other = c(30,
                                                                                0, 11.949458207316, 9.43079720266811, 12.5014350323826, 9.03630081302701,
                                                                                12.9221923230867, 11.5716131017492, 12.1911878955728, 14.0101290367095,
                                                                                11.8331630213764), pol_demo_illegal = c(30, 0, 6.67469822553204,
                                                                                7.45950666840047, 7.49607838697717, 2.84726236356375, 7.01422786895309,
                                                                                9.0644639572591, 8.18893647629205, 3.13891949840709, 4.97630266469401
                                                                                )), row.names = c("Max", "Min", "Average", "Only corona freedom",
                                                                                "Only corona economic", "Corona both", "Corona and other", "Only climate prot.",
                                                                                "Only racism", "Both racism and climate", "Other"), class = "data.frame")

I combine the axes customization from the tutorial with the last plot code. So I first take the function create_beautiful_radarchart from the website:
create_beautiful_radarchart <- function(data, color = "#00AFBB",
                                        vlabels = colnames(data), vlcex = 0.7,
                                        caxislabels = NULL, title = NULL, ...){
  radarchart(
    data, axistype = 1,
    # Customize the grid
    cglcol = "grey", cglty = 1, cglwd = 0.8,
    # Customize the axis
    axislabcol = "grey",
    # Variable labels
    vlcex = vlcex, vlabels = vlabels,
    caxislabels = caxislabels, title = title, ...
  )
}

Then the code to create the figure is:
opar <- par()
# Define settings for plotting in a 3x4 grid, with appropriate margins:
par(mar = rep(0.8,4))
par(mfrow = c(3,3))
# Produce a radar-chart for each student
for (i in 4:nrow(plot_dat_sameaxis)) {
  create_beautiful_radarchart(
    plot_dat[c(1:3, i), ],
    pfcol = c("#99999980",NA),
    pcol= c(NA,2), plty = 1, plwd = 1,
    title = row.names(plot_dat_sameaxis)[i],
    caxislabels = c(0, 7.5, 15, 22.5, 30)
  )
}

I set the values in caxislabels to four equal segments by setting the caxislabels vector values. Firstly I wanted to have six to avoid the decimals, but I got an error. If someone can help with that, that's also appreciated.
However, the bigger issue is that after I run this code, the values that I get on the chart, don't reflect the average values from the dataset (the middle, shaded area). For example based on the chart, the average for pol_party should be roughly 15, but it's actually 8.74 in the dataset. I don't understand where the difference comes from, but the axis labels are obviously wrong.
So my question is, can anyone help to sort out the axis labels in a way that they reflect the underlying dataset and maybe also have six instead of five breaks? Thanks in advance!


text:
Q: Product.find(query).distinct('field'). Как подсчитать количество уникальных полей? Product.find(query)
    .distinct('brand')
С помощью такого запроса я получаю массив из всех уникальных значений с ключом brand.
А каким способом можно получить информацию о том сколько каждых уникальных значений есть в коллекции?
Допустим такая коллекция
  {brand: adidas},
  {brand: nike},
  {brand: NB},
  {brand: adidas},
  {brand: adidas},

И мне нужен не просто массив ['adidas', 'nike', 'NB']
а что то вроде этого:
   [{adidas: 3}, {nike: 1}, {NB: 1}]

A: Используйте аггрегации https://docs.mongodb.com/v4.0/aggregation/
Product.aggregate([
    {$group: {_id: "$brand", count: {$sum: 1}}
])

Получите массив вида:
[
  {_id: "adidas", count: 3},
  {_id: "nike", count: 1},
  {_id: "NB", count: 1}
]


text:
Q: Converted Array from Object (with properties) returns 0 length I have this code in my javascript file:
var items = {
    first: 'Item 1',
    second: 'Item 2',
    third: 'Item 3'
};
var arr = Array.prototype.slice.call(items);

console.log(arr.length);

I want to convert an object into an array. My question is, when the object was converted into array, why does javascript return 0 when the object already has properties? I hope someone could help me and if anyone wouldn't mind, I want it to be corrected without using jQuery.

A: You can use Object.entries() to create an array of arrays of properties, values from original object or an array of objects reflecting properties, values of original object.

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

var items = {
    first: 'Item 1',
    second: 'Item 2',
    third: 'Item 3'
};

var arr = Object.entries(items);

console.log(arr);

var arr1 = Object.entries(items)
           .map((value, index) => {
              return {[value.shift()]: value.pop()}
           });

console.log(arr1);


text:
Q: Why am I unable to receive text messages with Twilio and Parse? I'm trying to receive text messages sent to my Twilio number using Parse and Parse's cloud code Twilio Module. I have followed the instructions here.
I set the SMS request URL for the Twilio number I want to receive text messages from to
https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/receiveSMS
and of course I used my parse app ID and my parse javascript key.
I then created the cloud function in Parse:
Parse.Cloud.define("receiveSMS", function(request, response) {
response.success("Received a new text: " + request.params.From);
});

and then I have a little webpage with some jquery calling that cloud function
$('button').on('click', function() {
alert('button');

Parse.Cloud.run('receiveSMS', {

    }, {
        // Success handler
        success: function(message) {
            alert('Success: ' + message);
        },
        // Error handler
        error: function(message) {
            alert('Error: ' + message);
        }
    });

});

I tried texting my Twilio number and then used my page with the code above to call the cloud code function "receiveSMS". The response is successful and I get the message "Received a new text:undefined". So it seems like I'm able to detect a new text message was sent but I'm getting undefined instead of the number the text message was from. I'd also like to get the message too. What am I doing wrong? Thanks

A: Ok, I know what's happened now, thanks for getting me more details in the comments.
You are calling your receiveSMS function in two ways. Firstly, it gets called when you send an SMS to your Twilio number. When that request is received you do get all the parameters logged out and your log will show "Received a new text: +YOUR_PHONE_NUMBER".
The problem is when you are calling your receiveSMS function from a web page. At that point, there are no parameters in the request and it is why you see undefined in the log. The receiveSMS function is for Twilio's benefit really, in that you are able to respond with TwiML to tell Twilio to do about the message.
If you want to get back the details of SMS messages sent to your Twilio number, you can retrieve the data using our REST API in a different Cloud Function like so:
var client = require('twilio')('TWILIO_SID', 'TWILIO_AUTH_TOKEN');

Parse.Cloud.define('fetchSMS', function(request, response) {
  client.messages.list({ to: YOUR_TWILIO_NUMBER }, function(err, data){
    numbers = data.messages.map(function(message){
      return message.from;
    }).join(', ');
    response.success("Received messages from: " + numbers);
  })
});

Then, if you change your webpage to call Parse.Cloud.run('fetchSMS', { ... }) instead then your response should be a list of numbers you have received SMS messages from. Hopefully you can build on that.
Do let me know if this helps.


text:
Q: Always active the first ul list and the first div for certain id using jQuery Problem:
I have jQuery code that switch perfectly between tabs. However, I am wondering how it can be extended so that it also activates the first sub element of each id.
Code for HTML tab navigation:

        Start
        Essay
        Criteria
        Time

Code for example tab:

Participants

Criteria

Text

Text

jQuery code:
$('#navtabs a[data-toggle="tab"]').on('shown', function () {
    $('#navtabs a[data-toggle="tab"]').attr('class','btn btn-info');
    $(this).attr('class','active btn btn-info');
})

Scenario:
When I click on the second tab (#tab2), I would like in addition to what the jQuery does now also:
(1) activate the first li element in #myTab
(2) activate the first div element in #myTabContent.
That is to say, always make sure that there is a "class=active" for the first li element and "class=tab-pane fade in active" for the first div.

A: Try this:
$('#navtabs a[data-toggle="tab"]').on('shown', function () {
    $('#navtabs a[data-toggle="tab"]').attr('class','btn btn-info');
    $(this).attr('class','active btn btn-info');

    var tabID = $(this).attr('href');
    var lis = $(tabID).find('#myTab li');//Get collection of li's
    $.each(lis, function(){
        $(this).removeClass('active'); //Remove the active class from each li
    });
    $(tabID).find('#myTab li:eq(0)').addClass('active');//Add active class

    //Same process for divs
    var divs = $(tabID).find('#myTabContent div');
    $.each(divs, function(){
        $(this).removeClass('in active');
    });
    $(tabID).find('#myTabContent div:eq(0)').addClass('in active');

});

A: This is what I came up with and it works just fine. I just had to get which tab it was using the following:
$(this).attr('href')

And the final code looks like this:
$('#navtabs a[data-toggle="tab"]').on('shown', function ()
{
    $('#navtabs a[data-toggle="tab"]').attr('class','btn btn-info');
    $(this).attr('class','active btn btn-info');

    var lis = $($(this).attr('href')).find('#myTab li');

    $.each(lis, function(){
        $(this).removeClass('active');
    });

    $($(this).attr('href')).find('#myTab li:eq(0)').addClass('active');

    var divs = $($(this).attr('href')).find('#myTabContent div');

    $.each(divs, function(){
        $(this).removeClass('in active');
    });

    $($(this).attr('href')).find('#myTabContent div:eq(0)').addClass('in active');

});


text:
Q: Could the default value of a TensorFlow op attribute be NaN or Inf? My case is to add vmin and vmax attributes to the TensorFlow ImageSummary Op. Here is my code for this op registration:
REGISTER_OP("ImageSummary")
    .Input("tag: string")
    .Input("tensor: T")
    .Output("summary: string")
    .Attr("vmin: float = NaN")
    .Attr("vmax: float = NaN")
    .Attr("clip: bool = false")
    .Attr("max_images: int >= 1 = 3")
    .Attr("T: {uint8, float, half, float64} = DT_FLOAT")
    .Attr(
        "bad_color: tensor = { dtype: DT_UINT8 "
        "tensor_shape: { dim { size: 4 } } "
        "int_val: 255 int_val: 0 int_val: 0 int_val: 255 }")
    .SetShapeFn(shape_inference::ScalarShape);

Although this works for the C++ test code, there were some errors when building the whole project:
bazel-out/darwin-opt/genfiles/tensorflow/cc/ops/logging_ops.h:237:19: error: cannot initialize a member subobject of type 'float' with an lvalue of type 'float (const char *)'
    float vmin_ = nanf;
                  ^~~~
bazel-out/darwin-opt/genfiles/tensorflow/cc/ops/logging_ops.h:238:19: error: cannot initialize a member subobject of type 'float' with an lvalue of type 'float (const char *)'
    float vmax_ = nanf;

I think it should be float vmin = nanf("") and float vmax = nanf("") in logging_ops.h. Is this an issue in TensorFlow compiler? Or I may have some misunderstanding of the grammar for setting the default value?
Are there any suggestions for my case?


text:
Q: Unbiased, positive estimator for the square of the mean Assume we have access to i.i.d. samples from a distribution with true (unknown) mean and variance $\mu, \sigma^2$, and we want to estimate $\mu^2$.
How can we construct an unbiased, always positive estimator of this quantity?
Taking the square of the sample mean $\tilde{\mu}^2$ is biased and will overestimate the quantity, esp. if $\mu$ is close to 0 and $\sigma^2$ is large.
This is possibly a trivial question but my google skills are letting me down as estimator of mean-squared only returns mean-squarred-error estimators

If it makes matters easier, the underlying distribution can be assumed to be Gaussian.

Solution:

*

*It is possible to construct an unbiased estimate of $\mu^2$; see knrumsey's answer

*It is not possible to construct an unbiased, always positive estimate of $\mu^2$ as these requirement are in conflict when the true mean is 0; see Winks' answer

A: It should not be possible produce an estimator that is both unbiased and always positive for $\mu^2$.
If the true mean is 0, the estimator must in expectation return 0 but is not allowed to output negative numbers, therefore it is also not allowed to output positive numbers either as it would be biased. An unbiased, always positive estimator of this quantity must therefore always return the correct answer when the mean is 0, regardless of the samples, which seems impossible.
knrumsey's answer shows how to correct the bias of the sample-mean-squarred estimator to obtain an unbiased estimate of $\mu^2$.

A: Note that the sample mean $\bar{X}$ is also normally distributed, with mean $\mu$ and variance $\sigma^2/n$. This means that
$$\operatorname E(\bar{X}^2) = \operatorname E(\bar{X})^2 + \operatorname{Var}(\bar{X}) = \mu^2 + \frac{\sigma^2}n$$
If all you care about is an unbiased estimate, you can use the fact that the sample variance is unbiased for $\sigma^2$. This implies that the estimator
$$\widehat{\mu^2} = \bar{X}^2 - \frac{S^2}n$$
is unbiased for $\mu^2$.


text:
Q: I can't set a new variable on mysql I want to increase  max_allowed_packet variable on my server and I don't know why, when I add the sentence in /etc/my.cnf, it doesn't work!! This is the line I added:
max_allowed_packet=62M

But when I check the current value through mysqladmin variables, it shows 10M!! I've even restarted my server! And nothing happens!
What happens here?

A: The settings file will normally have several sections (what MySQL calls groups). You're possibly disregarding that fact:
# The following options will be passed to all MySQL clients
[client]
port        = 3306
socket      = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /tmp/mysql.sock
skip-external-locking
key_buffer_size = 384M
max_allowed_packet = 1M


text:
Q: How to insert big chunk of data into db? I am using nopcommerce and arvixe hosting.
I have a xml file that contains all the products for my site (about 26000 records). I wrote a plugin that allows me to add records using sql script.
The problem is:
Time of request ends and only first 500 - 1000 records appears in db. What would you recommend?  Maybe I should move my code to different place (not in plugin)?

A: Try SqlBulkCopy:
using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
    destinationConnection.Open();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
    {
        bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";
        try
        {
            // The reader is a SqlDataReader which has all 26000 records
            bulkCopy.WriteToServer(reader);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            reader.Close();
        }
    }
}


text:
Q: Accidentally set the FileZilla option to "Upload overwrite everything" How can I change that setting?
I want to upload files only if they are newer than the version in the FTP server.
Is there a reset setting options that I can use without erasing my FTP connection settings?

A: Yes, there is a setting that you can change.  It is under Edit > Settings > Transfers > File Exists Action
In your case you would change the setting that said "Uploads" to "Overwrite file if source file newer"

A: In the latest version, you can find the settings at Transfer > Default File Exists Action

A: October 2017 - It is
Transfer
Default File Exists Action

Then you can set it however you like.
BUT, your question is about the concern of overwriting the FTP connection settings.
And here's the rub:  It does not save this setting in the FTP connection.  It is session-wide, regardless of which connections you use, or how many are used before FileZilla is closed...
In other words, you have to set it every time you start FileZilla.  If you forget and begin a transfer, you can change it while it is transferring, and wherever it is in the queue it will then begin using the new setting.
So your answer is that you do not need to worry about it resetting your FTP connection, nor its settings.


text:
Q: How to show relationships between Todo-lists? How can I show relations between ToDo-lists? I am using Devtodo.
I will give an example. I have my MIT humor in one XML-file:

 <todo version="0.1.19">
     <note priority="low" time="1237320287">
         see the MIT humor-video
     </note>
 </todo>

Other file is about Usenet-humor

 <todo version="0.1.19">
     <note priority="verylow" time="1237321441">
         read about Usenet Humor
     </note>
 </todo>

When I change one of my humor-file, I would like to have an alert that shows me my other Todo-lists that have a word "humor" in the title.
Partial Solution
I tried to add a property to the cd-command in my .bashrc that keep showing me my main Todo-lists:

alias='ls (); find /* -name mainlist'

but I feel I am doing the job in a hard way. How are you managing your Todo-lists between folders? Have you got a lot of scripts to show relationships between Todo-lists?

A: I think I would  markup some words as keys say with a '<topic>humor</topic> tag then write some thing that would search through the todos to find the related ones   .
but I'm thinking that the topics would be fewer. So just keep an index by topic of all open todos with those topics in your app, not in the XML.


text:
Q: Urn problem with balls Say you have $2n$ black balls and an additional blue and a red ball.
If there exist two urns and you randomly throw $n+1$ balls in each, then what is the probability that you do not have both the blue and the red balls in the same urn?

A: There are $\binom{2n+1}{n+1}$ ways to fill the first urn. But we only want those in which urn $1$ has both colored balls or none of them.
There are $\binom{2n-2}{n-1}$ which have both red and blue.
There are $\binom{2n-2}{n+1}$ which have neither.
Thus the answer is $$\frac{\binom{2n-2}{n-1}+\binom{2n-2}{n+1}}{\binom{2n+2}{n+1}}$$

A: Carry out the splitting and then color the balls.
Specifically, split $2n+2$ black balls between the urns and then randomly and independently color one ball blue and the other red.  The chance they are both in the same urn is the number of ways to choose two balls from one urn, plus the number of ways to choose them from the other urn, all divided by the number of ways in toto to choose two balls.  Subtracting this from $1$ gives the chance they are in different urns:
$$1 - \left(\binom{n+1}{2} + \binom{n+1}{2}\right) / \binom{2n+2}{ 2} = \frac{n+1}{2n+1} = \frac{1}{2} + \frac{1}{2(2n+1)}.$$
This formula, because it is simpler than others that might be derived from the original description, lends itself to easy simplification and clearly shows just how close to $1/2$ the chance is.

A: This looks like a hypergeometric distribution. We choose for Urn 1, which fixes Urn 2. There are $2n$ black balls, and we choose $n$. Then we choose $1$ of the $2$ remaining balls, and divide out by the number of ways to choose $n+1$ balls:
$$\frac{ \binom{2n}{n} \binom{2}{1} } { \binom{2n+2}{n+1} }$$