text:
Q: Implementing a Dispatch Table in Objective-C: how to declare an array of selectors I'm trying to implement a dispatch table, so that I can call a selector with the following example code:
NSInteger i = 2;
[myObject performSelector:selectors[i]];

I'm trying to store user preferences which affect which method of an API gets called. Right now, I use the string name of the selector and use NSSelectorFromString, but that's a bit messy. If I use a dispatch table, then I can store an enum instead.
How can I make an array of selectors, or a dispatch table in Objective-C?
Edit:
The compiler complains when I try to set an array of selectors as a property. @property SEL[] won't compile.
Edit2:
I'm using my KosherCocoa API library and I want to call a single method at once, based on a saved user setting. I'm saving to and reading from a Plist file.

A: You can use the SEL type to hold selectors. Simply:
SEL dispatchTable[3] = { @selector(doThis:),
                         @selector(doThat:),
                         @selector(doTheOther:)
                       };

To your edit, use an NSArray/NSDictionary/etc of selectors as your property instead. You are not allowed to use C arrays as properties in Objective C; they are not one of the supported types (which are ObjC objects, CF types and basic C 'Plain Old Data' types.)
OK, on our comments below, you need to wrap the selector in an NSValue to allow you to use it in an objc container (because SEL is a C pointer type):
NSMutableArray * dispatchTable2 = [[NSMutableArray alloc] initWithCapacity:3];
SEL selIn = @selector(doThis:);

// Wrap the selector in an NSValue instance
[dispatchTable2 addObject:[NSValue valueWithPointer:selIn]];

// On extracting:
NSValue * valOut = [dispatchTable2 objectAtIndex:0];
SEL selOut = [[dispatchTable2 objectAtIndex:0] pointerValue];
[anObject performSelector:selOut];

So now your table is an objc container stored as a property or ivar, and you use NSValue to wrap SEL pointers with valueWithPointer: and get the SEL out with pointerValue.

A: I would recommend using NSInvocation instead of selectors. They are far more flexible, as you can send the same invocation to many objects and you can change its properties as you go.

A: One way to do this is using an array of NSStrings, then converting those to SELs at runtime, if that increases readability for you..
NSString *selectors[] = { ... }

[myObject performSelector:NSSelectorFromString(selectors[i])];

To use this as a property, use
@property(nonatomic, assign) NSString **selectors;


text:
Q: Delete firebase query result What I'm trying to accomplish is deleting a whole Firebase db query result entirely, without having to delete all records one by one.
I've read the documentation both on deleting and queries and the most similar question on SO i found buth none of then was helpful.
This is my code on Firebase Cloud Functions:
const relatedElementsRef = databseRef.child('related_elements');

exports.onElementDeleted = functions.database
    .ref('elements/{user_id}/{element_id}')
    .onDelete(function (event) {
        var deletedElement = event.data.previous.val();

        const relatedElementsQuery = relatedElementsRef
            .child(event.params.user_id)
            .orderByChild('element_id')
            .equalTo(event.data.key)

        relatedElementsQuery.on("child_added", (relatedElementSnap, prevChildKey) => {
            relatedElementSnap.ref
                .remove()
                .then(()) => {
                    console.log("Related element deleted");
                });
        })
    });

What i would like to obtain is something similar to this:
//above code identical
        relatedElementsRef
            .child(event.params.user_id)
            .orderByChild('element_id')
            .equalTo(event.data.key)
            .remove()
            .then(() => {
                console.log("Related elements deleted");
            });
//below code identical

Below a simplified structure of the database:
{
    "elements" : {
        "user_id" : {
          "element_id" : {
                "name" : "This is an element",
                ...
            },
            ...
        },
        ...
    },
    ...
    "related_elements": {
        "user_id" : {
          "related_element_id" : {
                "element_id" : "element_id", //Key of the object above
                "name" : "This is a related element",
                ...
            },
            ...
        },
        ...
    },
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: При нажатии в ListBox поставить галочку CheckBox Как забиндить ListCheckBox в WPF? Ситуация такая что ширина чекбокса равна длине текста в нем (меньше чем ListBox, и соответственно чтобы сработал Checked нужно навести на текст и клацнуть (сделал костыли увеличил ширину чекбокса до ширины listbox). Но хотелось бы забиндить их, а не использовать костыль.
<ListBox x:Name="listbox_products" Width="200" Height="300" Background="DarkGray" Margin="5,5,5,5" ItemsSource="{Binding GetAvailProductsOnProject}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox x:Name="CheckBox_CheckProduks" Width="300" IsChecked="{Binding IsSelected}" Content="{Binding Продукт}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: Все элементы, помещенные в ListBox, оборачиваются в ListBoxItem, поэтому вам нужно растянуть именно ListBoxItem`ы. Сделать это можно так:
<ListBox ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>

Ширину CheckBox устанавливать явно при этом не нужно, уберите установку Width из разметки. CheckBox будет растянут на всю ширину контейнера (ListBoxItem) и, соответственно, на всю ширину ListBox.

A: Проблем тут несколько. Во-первых, вам нужно растянуть ячейку на всю ширину. Во-вторых, вам нужно, чтобы контент вашего checkbox'а не выходил за правую границу.
Для этого делаем так:
<ListBox x:Name="listbox_products" Width="200" Height="300"
         Background="DarkGray" Margin="5,5,5,5"
         ItemsSource="{Binding GetAvailProductsOnProject}"
         HorizontalContentAlignment="Stretch"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsSelected}">
                <TextBlock Text="{Binding Продукт}" TextWrapping="Wrap" />
            </CheckBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


text:
Q: Finding the type of variable, knowing it's a primitive datatype I read this post here that allows us to tell us what data type the object entails.
Is there a way to do that with primitive data types? Does that mean I would have to autbox the variable then apply some method to it? For instance:
float d1 = 10;
float d2 = 10.1f;
double d3 = d1 + d2;

Is there a way for me to print d3's data type?
TIA

A: You can have a helper method in order to perform boxing, and use getClass()
public static <T> Class<?> typeOf(final T value) {
  return value.getClass();
}

jshell> double x = 10.0;
x ==> 10.0
jshell> float y = 10.0f;
y ==> 10.0
jshell> typeOf(y)
$4 ==> class java.lang.Float
jshell> typeOf(x)
$5 ==> class java.lang.Double


text:
Q: How to store multiple emails in Ruby hash in MySQL? I built my own comments in my rails app without threading and I want to be able to send reply all notifications for new comments on a project. Would it be best to just store emails into a ruby hash in MySQL and then read from it when necessary? I'm trying to figure out how to insert emails into a hash with keys I don't have to define, any help?

A: Assuming you have some column with string type in some mysql table.
Use json gem. If you don't have json gem install it by gem install json.
require 'json'
reply_emails_list = ["a@gmail.com", "b@gamil.com"]
obj.column_name = {:emails => reply_emails_list}.to_json  #storing ruby hash as string in mysql

To get ruby hash back use `JSON.parse(obj)'
emails_list = JSON.parse(obj.column_name)  #ruby hash

or
In rails way. In model you can do like this:
YourModel < ActiveRecord::Base
  serialize :column_name, Array  #If don't want hash
  serialize :column_name     #you can store key value pair as I shown above
end

Using second will avoid converting from hash to json and vice versa

A: In Postgres, there is an array extension you can use to get actual array storage.  Unfortunately, this doesn't work for MySQL.
The best thing for data like e-mails would be to serialize your list of emails as a String field and provide a synthetic attribute that provides an array accessor (if needed).  You can then put callbacks on your comment to update the email list when Comments are added to this Project.
class Project < ActiveRecord::Base
  # db String field email_list
  attr_accessor :emails

  def emails
    email_list.split(',')
  end

  def emails=(email_ary)
    self.email_list = email_ary.join(',')
  end
end

This can be a good alternative to using a JSON blob, as it allows easier text searching and handling of a comma separated list.  I don't know if split() or JSON.parse provide an advantage in terms of serialization performance.

A: According to ActiveRecord::Base you can serialize a column:
class MyModel < ActiveRecord::Base
  serialize :emails
end

User.create(:emails => %w( email1@a.com email2@b.com email3@c.com )


text:
Q: Create Google Calendar Event from Java Backend from OAuth authenticated Users only Working on creating a Google Calendar Event on a specific Calendar from backend. Like when someone generate a meeting in a web application, it should be added to the shared google calendar from backend (running using JAVA - Spring boot).
User who is generating event must be an authorized user to do so.
I have followed this docs for initial set up in java.
JAVA docs -  initial setup
Dependancies that I've used,
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-calendar:v3-rev305-1.23.0'

Then to create a event I've tried this one,
public String createCalendarEvent() throws GeneralSecurityException, IOException {

    String calendarId = "primary";

    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
        .setApplicationName(APPLICATION_NAME)
        .build();

    Event event = new Event()
        .setSummary("Testing Event Creation 1")
        .setLocation("India")
        .setDescription("Testing Event Creation");

    EventDateTime start = new EventDateTime()
        .setDate(new DateTime("2019-02-26"));
    event.setStart(start);

    EventDateTime end = new EventDateTime()
        .setDate(new DateTime("2019-02-28"));
    event.setEnd(end);

    event = service.events().insert(calendarId, event).execute();
    log.debug("Event is created and HTML link is: " + event.getHtmlLink());
    return event.getHtmlLink();
}

getCredential() method is taking care of Authorization as below:
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = CalendarEventService.class.getClassLoader().getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
        .setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
        .setAccessType("offline")
        .setApprovalPrompt("force")
        .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    return credential;
}

The required OAuth ClientID and ClientSecret are located at CREDENTIALS_FILE_PATH. While running it generates AUTH_TOKEN inside TOKENS_DIRECTORY_PATH and create an event in Calendar.
Now subsequent execution execute without any issue If user changes.
I require to create Event in Calendar by the User who is currently logged in (Should be checked for OAuth) and from backend as this one.

A: server to server communication without consent
You need to understand that private user data will always require you to have access.  You cant access a users account without that users permission.  Oauth2 gives us as developers a way of requesting consent of users to access their data.  There is no way around that you will always have to have permission of the user to access their data.
Now if you have a gsuite account you can use a service account and set up domain wide delegation to allow the service account access to all of the users on the domain then it will be able to preform actions on behalf of the users without having to prompt anyone.
If you are only accessing a single account that you personally have control over then you could also use a service account and share the calendar with the service account and then the service account will have access to that account and be able to preform actions upon it.
Credential storage
new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)

denotes where the credentials are stored "user" is a string denoting the user who you are storing credentials for.


text:
Q: Wget - Download pics with particular url string Is there a Wget command that will allow me to download all jpegs that include the following url:
http://www.sample.com/images/imag/
So all jpegs under that particular url will be downloaded, such as the following:

*

*http://www.sample.com/images/imag/%281665%29-253.jpg

*http://www.sample.com/images/imag/(2816)-2234.jpg

*http://www.sample.com/images/imag/32r4344sdfa.jpg

*http://www.sample.com/images/imag/dwedjpao.jpg
Regardless of whether the jpegs have different naming conventions.

A: Depends on how you "get" http://www.sample.com/images/imag/ image list.
If it is a page that include the images in a HTML document you could try something like this:
wget -nd -p -A jpg,jpeg -e robots=off http://...

Where:

*

*-nd : No directories. --no-directories

*-p : Include images (Page requisites) --page-requisites

*-A : Comma separated list of file name suffixes or patterns to accept. --accept

*-e : Execute command as if part of .wgetrc. --execute

*

*Here; robots=off

Some servers only delivers compressed HTML, i.e. gzip. Then you have to take some extra measures as wget won't unpack and parse these (AFAIK). A rather quick and painless solution is using Privoxy.
After install make wget use the proxy by:
export http_proxy="http://localhost:8118"

then run command again.

A: wget -r -A jpg,jpeg http://www.sample.com/images/imag/
This will create the entire directory tree.  If you don't want a directory tree, use:
wget -r -A jpg,jpeg -nd http://www.sample.com/images/imag
Alternatively, connect to sample.com (e.g. via ssh) and locate the /images/imag folder ls *.jp* > foo.txt, wget -i -F foo.txt -B http://www.sample.com/images/imag/foo.jpg.


text:
Q: Raised "processing.app.debug.RunnerException" Exception while uploading the sketch I am unable to upload the empty sketch to Arduino Leonardo pro micro
I am facing this problem after I have been uploaded the last sketch

Now when I am trying to upload the sketch I am getting the following error.

I have followed all the instructions to setup for Arduino development listed here. And as I said earlier, I was able to upload the sketches, and no /dev/ttyACM0 is listed

A: There are several reasons but in this case, its the USB stack crashes.
Press reset (short RST and GND), click upload, wait for the code to compile and for the status bar to say 'Uploading...' and then release the button (RST and GND) on the board.


text:
Q: Not able to autofit rowhight of cells I have to autofit hight of row after adjusting column width and wrapping text.
I have written below code:
Sub mycode()

Sheet1.Columns("A:A").ColumnWidth = 30
Sheet1.Columns("A:A").WrapText = True
Sheet1.Cells.EntireRow.AutoFit

End Sub

Code works fine when data of cell have less content.
 But when cell data is large, all data is not shown correctly.
cell misses some data.
Please help me. Thanks in advance.

A: This question has appeared over on the SuperUser site (here) prior to your question.
My suggestion is to try the chosen answer from that post first. I hope it helps.

User NickCarrington's Answer:
A method I just found (extending the previous post a little):

*

*Select the whole sheet.

*Resize a column a little wider (because the
whole sheet is selected, all the columns will get wider)

*Double-click a row separator - the row height will be auto-fitted

*Double-click a column separator - the column widths will be auto-fitted

Voila!


text:
Q: SignaIR - C# - Resposta em Tempo Real Estou usando C#, Asp .Net, SQL Server.
Tenho a seguinte dúvida, estou criando uma aplicação web e mobile para se comunicar com um WebApi porém me deparei com o problema de informações e/ou dados em real-time, através de pesquisas encontrei o signalr, até ai tudo bem, criando o o projeto signalr é bem simples e tal, agora como faço para hospedá-lo?
-Tenho que por em um servidor próprio?
-Se sim, alguém conhece máquinas virtuais baratas (que não sejam Azure e Google Cloud pois são caras demais para mim lançar um produto novo no mercado)?
Procurei em vários lugares mas não encontrei nada referente a minha dúvida.


text:
Q: String duplicates when printed to text file I'm trying to write a sentence string to a text file, but it duplicates or something when I do so. Why is this, and how do I get it to only print once?
Program excerpt:
FILE *memberAdd;

typedef struct {
char id[5], name[100];
} Member;
Member reg;

strcpy(reg.id, "M0001");
printf("Name: ");
rewind(stdin);
scanf("%[^\n]", reg.name);

memberAdd = fopen("member.txt", "a");
fprintf(memberAdd, "%s %s\n", reg.id, reg.name);
fclose(memberAdd);

Output in text file when I run the above (reg.name input is Test Name):

M0001Test Name Test Name

A: This:
char id[5];

strcpy(reg.id, "M0001");

is a buffer overflow, strpcy() will write the 0-termination character at the end, overflowing the ìd array. You're getting undefined behavior. To fix it make the ID string shorter, or increase the size of the array of course.

A: In your code
  strcpy(reg.id, "M0001");

is off-by-one. you cannot store a string like "M0001" (5 chars and a null-terminator) in an array of 5 chars using strcpy(). You're accessing beyond the allocated memory, this causes undefined behavior.
Quoting C11, chapter §7.24.2.3

The strcpy function copies the string pointed to by s2 (including the terminating null
  character) into the array pointed to by s1. [...]

So, it's implied, that the destination must be able to hold the source string, including the null terminator. You're running short of memory here, it's proved. :)
You need to have the memory to store the null terminator also, if you plan to use a char array as a string. In this case, you can increase the member id dimension to hold the terminating null, like
 char id[6];

A: Every C string needs to be terminated by some NUL byte (i.e. (char)0).
So "M0001" takes six (not 5!) bytes. And your char id[5] field is not wide enough. You get a buffer overflow, an instance of undefined behavior. You should have declared
 char id[6];

at least as a field in Member. I actually recommend making it bigger, perhaps char id[8];


text:
Q: How to make fixed background to cover entire screen in mobile browsers? I am using following CSS hack
html {
    background: url(background.jpg) no-repeat center center fixed;
    webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

But when using mobile browsers , the height is of website is not covering the entire screen display ! what to do ??

A: You need to make the page the full height/width of the screen.
html,
body {
  width:100%;
  height:100%;
}

A: In addition to specifying the height and width, note that "background-attachment: fixed" is not supported in some mobile browsers. See the full browser support list (click the "known issues" tab at the bottom).
One way to work around this on mobile (but continue using "fixed" for other browsers) is to revert to "background-attachment: scroll" for mobile widths using a media query. For example:
If your original CSS was
#some-div
{
     background: url("background.jpg") no-repeat center fixed;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
}

Then your media query might look like this:
@media (min-width : 320px) and (max-width : 767px)
{
    #some-div {
        background-attachment: scroll;
    }
}

Of course, if you don't need "background-attachment: fixed" in the first place, then just removing "fixed" from your first line might help.


text:
Q: Typescript error Object is possibly null? Why, how to disable? I have the following code:
private extractInitials(fullname: string): string {
    const initials = fullname
        .replace(/[^a-zA-Z- ]/g, '')
        .match(/\b\w/g)
        .join('')
        .toUpperCase();
    return initials.substring(0, 2);
}

I'm getting an error

[ts] Object is possibly 'null'. [2531]
So I tried
if fullname { const initials .... return ... } else return '';
Turns out typescript was complaining about this guy
fullname.replace(/[^a-zA-Z- ]/g, '')
Which makes sense because this might end up being an empty string
So I did
const t = fullname.replace(/[^a-zA-Z- ]/g, '')
if(t) { /* do the rest */ } else return ''

and it still gave me the object is possibly null error. I know it's not. How do I fix?

A: I run into a similar issue, in my case, all I did was to add the following rule to the tsconfig.json
"strictNullChecks": false
"noImplicitAny": false,

That should do the work

A: The issue is that match can return null. If you want a blank string as as result, just use the || trick¹ to do || [] on the result of match:
private extractInitials(fullname: string): string {
    const initials =
        (fullname
        .replace(/[^a-zA-Z- ]/g, '')
        .match(/\b\w/g)
        || []
        )
        .join('')
        .toUpperCase();
    return initials.substring(0, 2);
}

If you want to return null in that case instead, you can use the && trick¹ to return the null if the match result is null, otherwise continuing on with your join etc.:
private extractInitials(fullname: string): string {
    const parts = fullname
        .replace(/[^a-zA-Z- ]/g, '')
        .match(/\b\w/g);
    return parts && parts.join('').toUpperCase().substring(0, 2);
}

¹ The || trick is that || evaluates its left-hand operand and, if it's truthy², takes that value as its result; otherwise it evaluates its right-hand operand and takes that value as its result. The && trick is similar, just the other way around: It evaluates its left-hand operand, and if it's falsy³, takes that value as its result; otherwise, it evaluates its right-hand operand and takes that value as its result.
² falsy - null, undefined, "", 0, NaN, or (of course) false
³ truthy - not falsy

A: One possible solution to remove the null check error could be to use Optional Chaining.
const extractInitials = (fullname: string): string  => {
    const initials = fullname.replace(/[^a-zA-Z- ]/g, '').match(/\b\w/g)?.join('').toUpperCase();
    return initials?.substring(0, 2) || '';
}

This will return an empty string if the result of regex match is null, otherwise will return the expected output.
You can try running it with different values in the TS playground here.
This has been explained in another answer here as well.


text:
Q: How to get process id of spring cloud task triggered from Spring cloud dataflow How to get process id of spring cloud task triggered from Spring cloud dataflow.
If we triggered a job from Spring cloud dataflow an execution id will be assigned for every task ,but I need to get process id of triggered job.
When we triggered spring cloud task  due to some exception it will maintain unknown status in SCDF.
we need to get the process id and kill that process.


text:
Q: Acumatica Report: How to populate Vendor Location as parameter? I have multiple branches/Locations for Vendors and need it as parameter but when I tried to populate the lookup it returns empty.
Report Parameter
Location View name I used:
=Report.GetFieldSchema('Location.LocationCD')

The result

A: You can reuse an existing DAC but for more control you may create a Parameter DAC
using PX.Data;
using PX.Objects.CS;
using PX.Objects.GL;
using PX.Objects.CR;
using System;

namespace PX.Objects.AP
{
    public class APVendorParameters : IBqlTable
    {
        #region ActiveVendorID
        public abstract class activeVendorID : PX.Data.IBqlField { }

        [Vendor]
        [PXRestrictor(typeof(Where<Vendor.status, NotEqual<BAccount.status.inactive>>),
            Messages.VendorIsInStatus,
            typeof(Vendor.status))]
        public virtual int? ActiveVendorID { get; set; }

        #endregion

        #region VendorLocationID
        public abstract class vendorLocationID : PX.Data.IBqlField { }
        [PXDBInt]
        [PXSelector(typeof(Search<Location.locationID, Where<Location.bAccountID, Equal<Optional<activeVendorID>>>>), SubstituteKey = typeof(Location.locationCD), DescriptionField = typeof(Location.locationCD))]
        [PXUIField(DisplayName = "Location")]
        public virtual Int32? VendorLocationID { get; set; }
        #endregion
    }
}

In report add 2 parameters:
VendorID (string) ViewName=Report.GetFieldSchema('APVendorParameters.ActiveVendorID')
LocationID (string) ViewName=Report.GetFieldSchema('APVendorParameters.VendorLocationID,VendorID')
The secret stais in

,VendorID')

syntax


text:
Q: Hibernate is mapping again all .hbm files in every new tomcat session I am working on a messy web java project, with hibernate and  tomcat server. First time i deploy the war on the server i can see the following log:
...
ContextLoader:273 - Root WebApplicationContext: initialization started XmlWebApplicationContext:495 - Refreshing Root WebApplicationContext: startup date [Wed Aug 06 14:18:37 COT 2014]; root of context hierarchy
XmlBeanDefinitionReader:315 - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
DefaultListableBeanFactory:557 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4fba4e8c: defining beans [dataSource,sessionFactory,jdbcExceptionTranslator,hibernateTemplate,transactionManager,AbstractSpringDao,.......]; root of factory hierarchy
Environment:514 - Hibernate 3.2.5
Environment:547 - hibernate.properties not found
Environment:681 - Bytecode provider name : cglib
Environment:598 - using JDK 1.4 java.sql.Timestamp handling
HbmBinder:300 - Mapping class: co.com...bean1...
HbmBinder:300 - Mapping class: co.com...bean2...
HbmBinder:300 - Mapping class: co.com...bean3...
HbmBinder:300 - Mapping class: co.com...bean4...
...

but every time i open the home page on a new browser window.... i see this log:
FileSystemXmlApplicationContext:495 - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@4f8e9bee: startup date [Wed Aug 06 14:40:30 COT 2014]; root of context hierarchy
XmlBeanDefinitionReader:315 - Loading XML bean definitions from file [/home/david/Documents/INTERKONT/siccu/siente/build/web/WEB-INF/applicationContext.xml]
DefaultListableBeanFactory:557 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6b8616ff: defining beans [dataSource,sessionFactory,jdbcExceptionTranslator,hibernateTemplate,transactionManager,AbstractSpringDao .......]; root of factory hierarchy
HbmBinder:300 - Mapping class: co.com....bean1...
HbmBinder:300 - Mapping class: co.com....bean2...
HbmBinder:300 - Mapping class: co.com....bean3...
...

Any ideas????
this is my applicationContext.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:p="http://www.springframework.org/schema/p"
               xmlns:aop="http://www.springframework.org/schema/aop"
               xmlns:tx="http://www.springframework.org/schema/tx"
               xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

            <!-- DataSource Definition -->
            <bean id="dataSource"
                  class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName">
                    <value>org.postgresql.Driver</value>
                </property>
                <property name="url">
                    <value>jdbc:postgresql:DBDBDBDBDB</value>
                </property>
                <property name="username">
                    <value>XXXX</value>
                </property>
                <property name="password">
                    <value>YYYYYYYY</value>
                </property>
            </bean>
            <!-- Hibernate SessionFactory Definition -->
               <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                <property name="mappingResources">
                    <list>

                        <value>co/com/....bean1.hbm.xml</value>
                        <value>co/com/....bean2.hbm.xml</value>
                        <value>co/com/....bean3.hbm.xml</value>
                        ...
                        ...

                    </list>
                </property>
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                        <prop key="hibernate.show_sql">true</prop>
                        <prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
                        <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
                    </props>
                </property>
                <property name="dataSource">
                    <ref bean="dataSource" />
                </property>
            </bean>
    <!-- Spring Data Access Exception Translator Defintion -->
        <bean id="jdbcExceptionTranslator"
              class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
            <property name="dataSource">
                <ref bean="dataSource" />
            </property>
        </bean>

        <!-- Hibernate Template Defintion -->
        <bean id="hibernateTemplate"
              class="org.springframework.orm.hibernate3.HibernateTemplate">
            <property name="sessionFactory">
                <ref bean="sessionFactory" />
            </property>
            <property name="jdbcExceptionTranslator">
                <ref bean="jdbcExceptionTranslator" />
            </property>
        </bean><!-- Hibernate Transaction Manager Definition -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory">
                <ref local="sessionFactory" />
            </property>
        </bean>
       <bean id="AbstractSpringDao" abstract="true" class="cobra.dao.AbstractSpringDao" scope="prototype">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate" />
        </property>
       </bean>
        ...
        ...

A: In the first block off log lines, you see the correct way to configure spring in a web application: the context is loaded through the ContextLoader either from a listener or from a (Dispatcher)Servlet.
In the second block, the same application context is loaded again directly from disk. This is not correct.
The second load probably happens in a Servlet.service(...) method.
Instead of reloading the application context on every request, you could use WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); to access the one loaded previously.
This is not the preferred way to use spring in a web application (You should read about spring web), but it is probably the easiest way to fix your setup.

A: it seems you are creating application context in your controller.
move this code outside of the controller.

ApplicationContext ctx = new FileSystemXmlApplicationContext("WEB-INF/applicationContext.xml");

and configure in your web.xml similer to below
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


text:
Q: How to show all numbers in this string I want to show only numbers from a string.
This is my input:

"aa[12]bb[34]cc[56]dd[78]"

My code so far:
Dim total As String
total = TextBox1.Text
Dim istart As String
Dim iend As String
Dim first As String
Dim second As String
Dim third As String
Dim four As String
Dim icount As String
icount = Len(total)
Do While icount > 0
    istart = total.IndexOf("[")
    iend = total.IndexOf("]") '
    If iend > 0 Then
        first = total.Substring(istart + 1, iend - istart - 1)
        MessageBox.Show(first)

        second = total.Substring(iend + 1, icount - iend - 1)
        MessageBox.Show(second)

        third = second.Substring(istart + 1, iend - istart - 1)
        MessageBox.Show(third)

    Else
        icount = 0
    End If
Loop

I expect the output

12
  34
  56
  78

A: Here's an easy way with Regex:
Dim text As String = "aa[12]bb[34]cc[56]dd[78]"

Dim numbers As String() = _
    Regex _
        .Matches(text, "(\d+)") _
        .Cast(Of Match)() _
        .Select(Function(x) x.Value) _
        .ToArray()

Or if the [ and ] are important:
Dim numbers As String() = _
    Regex _
        .Matches(text, "\[(\d+)]") _
        .Cast(Of Match)() _
        .Select(Function(x) x.Groups(1).Value) _
        .ToArray()
For Each number In numbers
    Console.WriteLine(number)
Next

Here's what you get:

12
34
56
78

A: I got inspired by this post.
Private Function StackOverflowTest() As String
    Dim x As String = "aa[12]bb[34]cc[56]dd[78]"
    Dim FinalString As String = ""
    Dim NumberFound As Boolean = False
    For Each ch As Char In x.ToCharArray()
        If Char.IsDigit(ch) Then
            FinalString += ch
            NumberFound = True
        Else
            If NumberFound Then FinalString += " "
            NumberFound = False
        End If
    Next

    FinalString = FinalString.Remove(FinalString.Length - 1, 1)
    MsgBox(FinalString)

    Return FinalString
End Function

A: A non linq way. Not sure if he wanted the result in a string or an array. This produces a string.
Dim SourceString As String = "aa[12]bb[34]cc[56]dd[78]"
Dim FinalString As String = String.Empty
Dim Chars() = SourceString.Split("["c)
Dim SecondString = Join(Chars)
Dim NextChars() = SecondString.Split("]"c)
For Each Str As String In NextChars
    FinalString &= System.Text.RegularExpressions.Regex.Replace(Str, "[^\d]", "") & Environment.NewLine
Next

A: Dim numbers As String() = _
    Regex _
        .Matches(text, "\[(\d+)]") _
        .Cast(Of Match)() _
        .Select(Function(x) x.Groups(1).Value) _
        .ToArray()
For Each number In numbers
    Console.WriteLine(number)
Next


text:
Q: Add percentage labels inside bars in circos.barplot in Circlize
I was able to create a stacked bar chart like this:
library(circlize)
library(vegan) # for `reorder.hclust` (may be masked by the library `seriation`)
library(dendextend) # for `color_branches`

t=read.table(text="Kalmyk 0.119357 0.725057 0.000010 0.037803 0.117774
Kyrgyz_China 0.039367 0.512079 0.230150 0.095038 0.123366
Altaian_Chelkan 0.034095 0.000010 0.919478 0.000010 0.046407
Azeri 0.051638 0.004671 0.010727 0.902646 0.030318
Uzbek 0.102725 0.273261 0.001854 0.452126 0.170033
Salar 0.000010 0.539636 0.460334 0.000010 0.000010
Tatar_Kazan 0.113456 0.057026 0.000010 0.099336 0.730171
Tatar_Siberian 0.251376 0.221389 0.000010 0.077505 0.449721
Finnish 0.007214 0.000010 0.000010 0.015174 0.977592
Yakut 0.505434 0.473202 0.000010 0.002914 0.018440
Mansi 0.572791 0.000010 0.000010 0.000010 0.427179
Altaian 0.222424 0.335614 0.358801 0.032694 0.050468
Shor_Mountain 0.233984 0.000010 0.724596 0.000010 0.041400
Chuvash 0.180171 0.011056 0.000010 0.006462 0.802301
Enets 0.920409 0.000010 0.000010 0.000010 0.079561
Yukagir_Tundra 0.710359 0.289611 0.000010 0.000011 0.000010
Kyrgyz_Tajikistan 0.104000 0.563708 0.000010 0.125799 0.206483
Khakass_Kachin 0.254253 0.416760 0.174200 0.005262 0.149525
Tuvinian 0.448940 0.448899 0.000010 0.031803 0.070348
Besermyan 0.209841 0.001487 0.000010 0.000460 0.788202
Nogai_Astrakhan 0.062497 0.463590 0.000010 0.183203 0.290701
Todzin 0.725173 0.257670 0.000010 0.005836 0.011312
Kazakh 0.067027 0.518213 0.087979 0.114550 0.212231
Tofalar 0.815599 0.110299 0.000010 0.009693 0.064398
Karakalpak 0.009983 0.316964 0.389103 0.158275 0.125676
Estonian 0.000010 0.000010 0.000010 0.004409 0.995561
Dolgan 0.694025 0.255361 0.000010 0.049624 0.000979
Tatar_Siberian_Zabolotniye 0.521637 0.020132 0.000010 0.000010 0.458212
Uyghur 0.043578 0.486742 0.000010 0.318983 0.150687
Udmurt 0.256391 0.000010 0.001010 0.000010 0.742579
Evenk_FarEast 0.241328 0.606202 0.000010 0.000010 0.152451
Selkup 0.804662 0.000010 0.000010 0.000010 0.195308
Kumyk 0.060751 0.000112 0.000010 0.823905 0.115222
Hungarian 0.000010 0.000010 0.000010 0.244311 0.755659
Tubalar 0.159517 0.009457 0.802778 0.000010 0.028238
Turkmen 0.123631 0.226543 0.000010 0.529793 0.120023
Karelian 0.012854 0.000010 0.000010 0.000010 0.987116
Kazakh_China 0.074285 0.573009 0.152931 0.069362 0.130412
Mongol 0.033174 0.847004 0.025135 0.005178 0.089509
Daur 0.000010 0.995215 0.000010 0.000010 0.004755
Evenk_Transbaikal 0.611414 0.388556 0.000010 0.000010 0.000010
Nogai_Karachay_Cherkessia 0.119988 0.120774 0.000010 0.617261 0.141967
Veps 0.026887 0.000010 0.000010 0.000010 0.973083
Even 0.441349 0.278457 0.000010 0.015239 0.264946
Nganasan 0.999960 0.000010 0.000010 0.000010 0.000010
Bashkir 0.114088 0.056493 0.251488 0.030390 0.547542
Xibo 0.000010 0.985541 0.000010 0.000362 0.014077
Khakass 0.202707 0.171413 0.530905 0.007675 0.087300
Shor_Khakassia 0.258218 0.000010 0.694889 0.000010 0.046873
Nanai 0.105903 0.894067 0.000010 0.000010 0.000010
Buryat 0.064420 0.848458 0.017066 0.001696 0.068360
Yukagir_Forest 0.379416 0.096266 0.000010 0.003580 0.520728
Karachai 0.067138 0.004534 0.000010 0.798982 0.129336
Mordovian 0.022303 0.001193 0.000010 0.025251 0.951243
Turkish_Balikesir 0.092314 0.038550 0.000010 0.804964 0.064163
Turkish 0.040918 0.012255 0.000010 0.873179 0.073639
Kyrgyz_Kyrgyzstan 0.090129 0.607265 0.000010 0.122885 0.179711
Balkar 0.075115 0.000010 0.000010 0.829730 0.095136
Gagauz 0.000010 0.027887 0.015891 0.601619 0.354593
Nogai_Stavropol 0.070584 0.403817 0.000010 0.244701 0.280888
Negidal 0.248518 0.751452 0.000010 0.000010 0.000010
Tatar_Mishar 0.066112 0.037441 0.010377 0.138008 0.748062",row.names=1)

hc=reorder(hclust(dist(t)),-as.matrix(t)%*%seq(ncol(t))^2)

labelcolor=hcl(c(260,90,120,60,0,210,180,310)+15,60,70)
barcolor=hcl(c(310,260,120,60,210)+15,60,70)

labels=hc$labels[hc$order]
cut=cutree(hc,8)
dend=color_branches(as.dendrogram(hc),k=length(unique(cut)),
  col=labelcolor[unique(cut[labels])])

circos.clear()
png("a.png",w=2000,h=2000,res=200)
circos.par(cell.padding=c(0,0,0,0))
circos.initialize("a",xlim=c(0,nrow(t)))

circos.track(ylim=c(0,1),track.height=.2,track.margin=c(0,0),bg.border=NA,
  panel.fun=function(x,y)for(i in 1:nrow(t))circos.text(i-.5,0,labels[i],adj=c(0,.5),
    facing="clockwise",niceFacing=T,cex=.75,col=labelcolor[cut[labels[i]]]))

circos.track(ylim=c(0,1),track.height=.3,track.margin=c(0,.01),bg.border=NA,
  panel.fun=function(x,y)circos.barplot(as.matrix(t)[hc$order,],-.5+1:nrow(t),
    col=barcolor,bar_width=1,lwd=.3,border="gray20"))

circos.track(ylim=c(0,attr(dend,"height")),track.height=.4,track.margin=c(0,0),
  bg.border=NA,panel.fun=function(x,y)circos.dendrogram(dend))

circos.clear()
dev.off()

How can I additionally add text for the percentage of each bar in the middle of the bar? I'd like to display the percentages as rounded to an integer, with percentages of 0 or 1 omitted.

A: I figured it out by modifying the code of the circos.barplot function.
The labels are drawn in a second loop after the rectangles so that the rectangles are not drawn over the labels.
library(circlize)
library(vegan) # for reorder.hclust (may be masked by `seriation`)
library(dendextend) # for color_branches

t=read.table(text="Kalmyk 0.119357 0.725057 0.000010 0.037803 0.117774
Kyrgyz_China 0.039367 0.512079 0.230150 0.095038 0.123366
Altaian_Chelkan 0.034095 0.000010 0.919478 0.000010 0.046407
Azeri 0.051638 0.004671 0.010727 0.902646 0.030318
Uzbek 0.102725 0.273261 0.001854 0.452126 0.170033
Salar 0.000010 0.539636 0.460334 0.000010 0.000010
Tatar_Kazan 0.113456 0.057026 0.000010 0.099336 0.730171
Tatar_Siberian 0.251376 0.221389 0.000010 0.077505 0.449721
Finnish 0.007214 0.000010 0.000010 0.015174 0.977592
Yakut 0.505434 0.473202 0.000010 0.002914 0.018440
Mansi 0.572791 0.000010 0.000010 0.000010 0.427179
Altaian 0.222424 0.335614 0.358801 0.032694 0.050468
Shor_Mountain 0.233984 0.000010 0.724596 0.000010 0.041400
Chuvash 0.180171 0.011056 0.000010 0.006462 0.802301
Enets 0.920409 0.000010 0.000010 0.000010 0.079561
Yukagir_Tundra 0.710359 0.289611 0.000010 0.000011 0.000010
Kyrgyz_Tajikistan 0.104000 0.563708 0.000010 0.125799 0.206483
Khakass_Kachin 0.254253 0.416760 0.174200 0.005262 0.149525
Tuvinian 0.448940 0.448899 0.000010 0.031803 0.070348
Besermyan 0.209841 0.001487 0.000010 0.000460 0.788202
Nogai_Astrakhan 0.062497 0.463590 0.000010 0.183203 0.290701
Todzin 0.725173 0.257670 0.000010 0.005836 0.011312
Kazakh 0.067027 0.518213 0.087979 0.114550 0.212231
Tofalar 0.815599 0.110299 0.000010 0.009693 0.064398
Karakalpak 0.009983 0.316964 0.389103 0.158275 0.125676
Estonian 0.000010 0.000010 0.000010 0.004409 0.995561
Dolgan 0.694025 0.255361 0.000010 0.049624 0.000979
Tatar_Siberian_Zabolotniye 0.521637 0.020132 0.000010 0.000010 0.458212
Uyghur 0.043578 0.486742 0.000010 0.318983 0.150687
Udmurt 0.256391 0.000010 0.001010 0.000010 0.742579
Evenk_FarEast 0.241328 0.606202 0.000010 0.000010 0.152451
Selkup 0.804662 0.000010 0.000010 0.000010 0.195308
Kumyk 0.060751 0.000112 0.000010 0.823905 0.115222
Hungarian 0.000010 0.000010 0.000010 0.244311 0.755659
Tubalar 0.159517 0.009457 0.802778 0.000010 0.028238
Turkmen 0.123631 0.226543 0.000010 0.529793 0.120023
Karelian 0.012854 0.000010 0.000010 0.000010 0.987116
Kazakh_China 0.074285 0.573009 0.152931 0.069362 0.130412
Mongol 0.033174 0.847004 0.025135 0.005178 0.089509
Daur 0.000010 0.995215 0.000010 0.000010 0.004755
Evenk_Transbaikal 0.611414 0.388556 0.000010 0.000010 0.000010
Nogai_Karachay_Cherkessia 0.119988 0.120774 0.000010 0.617261 0.141967
Veps 0.026887 0.000010 0.000010 0.000010 0.973083
Even 0.441349 0.278457 0.000010 0.015239 0.264946
Nganasan 0.999960 0.000010 0.000010 0.000010 0.000010
Bashkir 0.114088 0.056493 0.251488 0.030390 0.547542
Xibo 0.000010 0.985541 0.000010 0.000362 0.014077
Khakass 0.202707 0.171413 0.530905 0.007675 0.087300
Shor_Khakassia 0.258218 0.000010 0.694889 0.000010 0.046873
Nanai 0.105903 0.894067 0.000010 0.000010 0.000010
Buryat 0.064420 0.848458 0.017066 0.001696 0.068360
Yukagir_Forest 0.379416 0.096266 0.000010 0.003580 0.520728
Karachai 0.067138 0.004534 0.000010 0.798982 0.129336
Mordovian 0.022303 0.001193 0.000010 0.025251 0.951243
Turkish_Balikesir 0.092314 0.038550 0.000010 0.804964 0.064163
Turkish 0.040918 0.012255 0.000010 0.873179 0.073639
Kyrgyz_Kyrgyzstan 0.090129 0.607265 0.000010 0.122885 0.179711
Balkar 0.075115 0.000010 0.000010 0.829730 0.095136
Gagauz 0.000010 0.027887 0.015891 0.601619 0.354593
Nogai_Stavropol 0.070584 0.403817 0.000010 0.244701 0.280888
Negidal 0.248518 0.751452 0.000010 0.000010 0.000010
Tatar_Mishar 0.066112 0.037441 0.010377 0.138008 0.748062",row.names=1)

hc=hclust(dist(t))
hc=reorder(hc,-(t[,1]+t[,2]-t[,4]-2*t[,5]))

labelcolor=hcl(c(260,90,120,60,0,210,180,310)+15,60,70)
barcolor=hcl(c(310,260,120,60,210)+15,60,70)

labels=hc$labels[hc$order]
cut=cutree(hc,8)
dend=color_branches(as.dendrogram(hc),k=length(unique(cut)),col=labelcolor[unique(cut[labels])])
t=t[hc$labels[hc$order],]

circos.clear()
png("a.png",w=2500,h=2500,res=300)
circos.par(cell.padding=c(0,0,0,0),gap.degree=5,points.overflow.warning=F)
circos.initialize("a",xlim=c(0,nrow(t)))

circos.track(ylim=c(0,1),bg.border=NA,track.height=.28,track.margin=c(.01,0),
  panel.fun=function(x,y)for(i in 1:nrow(t))circos.text(i-.5,0,labels[i],adj=c(0,.5),facing="clockwise",niceFacing=T,cex=.65,col=labelcolor[cut[labels[i]]]))

circos.track(ylim=c(0,1),track.margin=c(0,0),track.height=.35,bg.lty=0,panel.fun=function(x,y){
  mat=as.matrix(t)
  pos=1:nrow(mat)-.5
  barwidth=1
  for(i in 1:ncol(mat)){
    seq1=rowSums(mat[,seq(i-1),drop=F])
    seq2=rowSums(mat[,seq(i),drop=F])
    circos.rect(pos-barwidth/2,if(i==1){0}else{seq1},pos+barwidth/2,seq2,col=barcolor[i],border="gray20",lwd=.1)
  }
  for(i in 1:ncol(mat)){
    seq1=rowSums(mat[,seq(i-1),drop=F])
    seq2=rowSums(mat[,seq(i),drop=F])
    lab=round(100*t[,i])
    lab[lab<=1]=""
    circos.text(pos,if(i==1){seq1/2}else{seq1+(seq2-seq1)/2},labels=lab,col="gray10",cex=.4,facing="downward")
  }
})

circos.track(ylim=c(0,attr(dend,"height")),bg.border=NA,track.margin=c(0,.0015),track.height=.35,panel.fun=function(x,y)circos.dendrogram(dend))

circos.clear()
dev.off()


text:
Q: Four balls in a bag Four balls are randomly dropped into four boxes, where any ball is equally likely to fall into each box.
For a fixed $=0,1,2,3,$ let $_$ denote the event that exactly $$ boxes are empty. Compute $(_)$ for each $=0,1,2,3$.
I have computed $(_0)$ and $(_3)$ which are $\dfrac{4!}{4^4}=\dfrac{3}{32}$ and $\dfrac{4}{4^4}=\dfrac{1}{64}$ respectively. But I don't know how to find $(_1)$ and $(_2)$. Could anybody help me?

A: $N$ balls dropped in $M$ boxes, the probability of $k$ boxes being empty (i.e. $M-k$ boxes having at least one) will be:
$$\Pr(A_k)=\dfrac{\binom{M}{k}{N\brace M-k}(M-k)!}{M^N}$$
We come to this expression by first picking which $k$ of the boxes will be empty in $\binom{M}{k}$ ways.  Then, choosing how to separate the $N$ balls into $M-k$ non-empty piles using Stirling Numbers of the Second Kind, and then choosing which designated non-empty box each pile goes into in $(M-k)!$ ways.  This, all, taken out of the $M^N$ total ways of distributing the $N$ balls into the $M$ boxes.
In the case of $N=M=4$, that would be $\Pr(A_1)=\dfrac{4\cdot 6\cdot 3!}{4^4}=\dfrac{9}{16}$ and $\Pr(A_2)=\dfrac{6\cdot 7\cdot 2!}{4^4}=\dfrac{21}{64}$
As a sanity check, $\frac{3}{32}+\frac{9}{16}+\frac{21}{64}+\frac{1}{64}=1$, as expected.

A: As a standard approach, follow Stirling Number of the second kind or Principle of Inclusion Exclusion.
In this case, as there are less number of balls and boxes, we can compute directly too.

*

*Number of arrangements where exactly one box is empty -

$ = \displaystyle \small 4 \cdot 3 \cdot {4 \choose 2} \cdot 2 = 144$
where there are $4$ ways to choose which box is empty, $3$ ways to choose which box will have two balls, $\displaystyle {4 \choose 2}$ ways to choose two balls and then $2$ ways to place remaining two balls into two boxes.
Or using Stirling Number of Second kind,
$ = \displaystyle \small 4 \cdot 3! \cdot StirlingS2[4,3]$

*

*Number of arrangements where exactly two boxes are empty -

$ = \displaystyle \small {4 \choose 2} \cdot (2^4 - 2) = 84$
where there are $\displaystyle {4 \choose 2}$ ways to choose empty boxes and $(2^4 - 2)$ ways to distribute $4$ balls in two boxes. Please note we subtract $2$ from $2^4$ as there are two arrangements in $2^4$ where one of the boxes is empty.
Using Stirling Number of Second kind,
$ = \displaystyle \small {4 \choose 2} \cdot 2 \cdot StirlingS2[4,2]$
To find probability in both cases, we divide by total number of arrangements, which is $4^4$.


text:
Q: How to handle date picker dialog not to set in edittext when clicked outside of dialog android? When I click edittext, date picker dialog opens. without clicking done button in date picker and clicked outside of dialog, it sets in edittext.
I checked this but this works for first time. When selecting second time by choosing dialog and without clicking done button, it fails.
private final DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
       private boolean fired;
         public void resetFired(){
                fired = false;
            }
            @Override
            public void onDateSet(DatePicker view, int selectedYear,
                    int selectedMonth, int selectedDay) {
                if (fired) {
                    Log.e("DatePicker", "Ignoring for first time");
                    birthDayValue = selectedDay;
                    birthMonthValue = selectedMonth;
                    birthYearValue = selectedYear;
                    String birthDayDateFormt = Utils.getBirthDayDate(selectedYear,
                            selectedMonth, selectedDay);
                    dateOfBirth.setText(birthDayDateFormt);
                    dateOfBirth.setError(null);
                    return;//ignore and return.
                }
                fired = true;//first time fired
            }
    };

};

How to solve this issue?

A:         @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
        if(view.isShown()) {
            if (fired) {
                Log.e("DatePicker", "Ignoring for first time");
                birthDayValue = selectedDay;
                birthMonthValue = selectedMonth;
                birthYearValue = selectedYear;
                String birthDayDateFormt = Utils.getBirthDayDate(selectedYear,
                        selectedMonth, selectedDay);
                dateOfBirth.setText(birthDayDateFormt);
                dateOfBirth.setError(null);
                return;//ignore and return.
            }
            fired = true;//first time fired
          }
        }

if(view.isShown()) add code in this condition,
its a simple step do it and check output


text:
Q: Pyramid chart with highcharts Have managed to get a pyramid chart like bellow, but as the percentage data will vary, the pyramid shape will get distorted. I need to maintain the pyramid shape even if percentage data is varying. jsfiddle Thanks in advance

Code:
$('#container').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Pyramid Chart'
        },
        subtitle: {
            text: ''
        },
        xAxis: {
            categories: ['1', '2', '3', '4','5','6','7','8','9','10','11'],
            tickmarkPlacement: 'off',
            title: {
                enabled: false
            }
        },
        yAxis: {
            title: {
                text: 'Percentage'
            },
            labels: {
                formatter: function() {
                    return this.value;
                }
            }
        },
        tooltip: {
            valueSuffix: ' millions'
        },
        plotOptions: {
            area: {
                lineColor: '#666666',
                lineWidth: 1,
                marker: {
                    enabled: false
                }
            }
        },
        series: [{
            name: 'A',
            zInxed:555555,
            data: [null,null,null,null,80,100,80,null,null,null,null]
            },
            {
            name: 'B',
            zInxed:666666,
            data: [null,null,null,60,80,80,80,60,null,null,null]
            },
            {
            name: 'C',
            zInxed:777777,
            data: [null,null,40,60,60,60,60,60,40,null,null]
            },
            {
            name: 'D',
            zInxed:888888,
            data: [null,20,40,40,40,40,40,40,40,20,null]
            },
            {
            name: 'E',
            zInxed:999999,
            data: [0,20,20,20,20,20,20,20,20,20,0]
        }]
    });


text:
Q: jQuery .load div id conflict I am using links in an HTML template to load HTML files(e.g. inc_1.html and inc_2.html) as per below code. These HTML files are very similar forms which have the same div and checkbox id's. The purpose of each form is to calculate the cost of a service. JavaScript and jQuery is used to do the math. Users check the items they want using a checkbox and they get a total cost.

...as the user clicks on a link e.g. form1 or form2
it loads the html file into a

 in the main template.
The problem is that the first form they click on all the calculations they make are correct but the second form they click on the values are off. I assume there's conflicts with the id's and values being set by interactions with the first form that was loaded.
Can I use an unbindmethod or something to reset the files as they get loaded into the main template? A forced refresh of the page would work but i don't want to do that.
The gist of the main template is like:
<!doctype html>

   <title>Samp</title>

</script>

        form1
        form2

Sample js calc:
function t1() {
    tuition = tuition === 0 ? 53498 : 0;
    document.getElementById('t1').innerText = '$' + tuition;
    document.getElementById('t1-total').innerText = '$' + tuition;
    document.getElementById('total').innerText = '$' + (tuition + activity + program + orient + health + laboratory + room * roomMonths + personal * personalMonths + education * educationMonths + transport * transportMonths);
  }

Any advise appreciated! Thanks!


text:
Q: Loading time of each page with selenium python Helllo everyone,
Can you please anyone help to calculate the load time of each page. I want to do with performance analysis of web page. This below code works with the Complete execution time. But i want to calculate the each loading page after everyclick.
navigationStart = driver.execute_script("return window.performance.timing.navigationStart")
responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")

backendPerformance_calc = responseStart - navigationStart
frontendPerformance_calc = domComplete - responseStart

print("Back End: %s" % backendPerformance_calc)
print("Front End: %s" % frontendPerformance_calc)

Can you anyone help me solve this problem.

A: You can use this js to perform this check:
state = driver.execute_script(" return document.readyState; ")

Or, you can simple add an explicit wait after a specific element and see when it was displayed, then do some math (when you clicked and when the element was displayed)


text:
Q: order by with the number of correct condition I have 16 condition.I want to order by at number of TRUE condition. that's mean the record with 16 TRUE condition be higher then the record with 15 TRUE condition.
if I do the following:
select * from tbluser
order by case
when field1 like 'abc' AND field2 like 'aaa' AND ... field16 like 'bbb' then 1
when field1 like 'abc' AND field2 like 'aaa' AND ... field15 like 'ccc' then 2
.
.
.
when field2 like 'aaa' then 255
when field1 like 'abc' then 256

as you see, I should write 256 when that each of them has several condition.
considering the fact that just the number of correct condition is important and there is no other priority , is there a better solution?

A: Your question isn't very clear but it sounds like you just want to order on an aggreated field....so here's a simple example of doing so.....
Create table #tmp (f1 int, f2 bit)
INSERT INTO #tmp SELECT  1, 1
INSERT INTO #tmp SELECT  1, 1
INSERT INTO #tmp SELECT  1, 1
INSERT INTO #tmp SELECT  2, 1
INSERT INTO #tmp SELECT  2, 1
INSERT INTO #tmp SELECT  3, 1
INSERT INTO #tmp SELECT  4, 1
INSERT INTO #tmp SELECT  4, 1
SELECT f1, count(f2)
FROM #tmp
WHERE f2 = 1  --TRUE
GROUP BY f1
ORDER BY 2 DESC, 1
You'll have to decide on rules for if the counts are equal.

A: For an ANSI SQL solution, you could just assign a true predicate 1, and false 0, and add up the conditions, and order by this descending:
ORDER BY
        CASE WHEN Field1 LIKE 'abc' THEN 1 ELSE 0 END +
        CASE WHEN Field2 LIKE 'aaa' THEN 1 ELSE 0 END +
        ...
        CASE WHEN Field16 LIKE 'bbb' THEN 1 ELSE 0 END DESC;

Since it is MySQL you can take a slight shortcut since it allows addition on booleans:
ORDER BY (Field1 LIKE 'abc') + (Field2 LIKE 'aaa') ... + (Field16 LIKE 'bbb') DESC;


text:
Q: Tools for Dealing with Stack Corruption in c++ EDIT: Due to a comment that was right about my example I removed it and turn this into a generic question:
Some times in my projects I come across stack corruption. No matter how much I fight to write code to avoid it, sometimes it is just unavoidable. But when it happens what are the ways to fight it?
I found one macro given by the good fellow in this blog: http://rxwen.blogspot.com/2009/04/detect-stack-corruption.html which reads the ebp register value to detect corruption.
But there are bound to be more sophisticated tools to help with not shooting yourself on the foot. I am programming in Windows using Codeblocks and the gcc compiler. The reason I make this question is to find tools which I can use under my programming environment to help me detect such mistakes and correct them. Any suggestions?
Thanks for any answers and for taking the time to read my question.

A: It's far from unclear that you are having stack corruption.  But I accept there is some data corruption.
A reasonably effective technique is to add guard fields around the suspect field(s):
...
long   namecheck1;
Artist artist;
long   namecheck2;
...

Have the constructor initialize these to most anything, but without knowing the nature of the corruption something non-zero seems more satisfying.
myclass::myclass() : namecheck1(0x12345678), namcheck2(0x12345678) ...

Add a consistency check member function:
void myclass::isokay()
{
       if (namecheck1 != namecheck2  ||
           namecheck2 != 0x12345678)
             cerr << "the object is corrupted";
         ... // maybe wait for input, cause core dump, etc.
}

Then pepper the code with calls to this, especially near suspicious logic.  If you are comfortable with a debugger, place a breakpoint on the error message.  By unraveling the stack, you can ascertain what the program has done recently and gather clues as to what bit of code is probably writing outside the proper bounds.

A: Valgrind finds all kinds of memory corruption.
GCC has mudflap (-fmudflap and friends) and -fstack-protector to catch memory access problems. Other compilers probably do, too.


text:
Q: Windows 10 and Ubuntu Dual Boot not letting me boot into Windows 10 I have installed Ubuntu on my Windows 10 Computer through an USB, after some basic setting up of Ubuntu I try to boot back into windows, but it drops me an error
error: can't find command drivemap
I can easily boot into ubuntu


text:
Q: TextBox - Only allow Numeric and ONE full stop (representing a decimal number) VB.NET I have the following code, and am looking to add in the fact it can allow only one decimal point (full stop) to be added anywhere within the string.
If Asc(e.KeyChar) <> 8 Then
    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
        e.Handled = True
    End If
End If

It will work by only accepting numeric numbers, so how can I incorporate ONE decimal point in this piece of code?
Thanks

A: The Asc function is an old VB6 function which should be avoided when writing new .NET code.  In this case, you could compare the character to see if it is in a certain range, like this:
If e.KeyChar <> ControlChars.Back Then
    If (e.KeyChar < "0"c) Or (e.KeyChar > "9"c) Then
        e.Handled = True
    End If
End If

However, I would suggest simply listing the valid characters, like this:
e.Handled = ("0123456789.".IndexOf(e.KeyChar) = -1)

As far as checking for multiple decimal points, you could do something in the key press event, like this:
If e.KeyChar = "."c Then
    e.Handled = (CType(sender, TextBox).Text.IndexOf("."c) <> -1)
ElseIf e.KeyChar <> ControlChars.Back Then
    e.Handled = ("0123456789".IndexOf(e.KeyChar) = -1)
End If

However, while it's nice to have the ability to filter out invalid key strokes, there are many problems with doing so.  For instance, even with all of that checking, the following entries would all still be allowed, even though they, likely, should all be invalid:

*

*12.

*0000

*0001.

The other big problem is that your code will be culture dependent.  For instance, in Europe, often a comma is used as the decimal point.  For these reasons, I would recommend, if possible, simply using Decimal.TryParse in the Validating event, like this:
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
    Dim control As TextBox = CType(sender, TextBox)
    Dim result As Decimal = 0
    Decimal.TryParse(control.Text, result)
    control.Text = result.ToString()
End Sub

A: Parse the string (text of the TextBox or whatever) to see whether it already contains a decimal point. Dont handle the keypress if thats the case:
VB.NET:
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim FullStop As Char
    FullStop = "."

    ' if the '.' key was pressed see if there already is a '.' in the string
    ' if so, dont handle the keypress
    If e.KeyChar = FullStop And TextBox1.Text.IndexOf(FullStop) <> -1 Then
        e.Handled = True
        Return
    End If

    ' If the key aint a digit
    If Not Char.IsDigit(e.KeyChar) Then
        ' verify whether special keys were pressed
        ' (i.e. all allowed non digit keys - in this example
        ' only space and the '.' are validated)
        If (e.KeyChar <> FullStop) And
           (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
            ' if its a non-allowed key, dont handle the keypress
            e.Handled = True
            Return
        End If
    End If

End Sub

C#:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar == '.') && (((TextBox)sender).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
        return;
    }

    if (!Char.IsDigit(e.KeyChar))
    {
        if ((e.KeyChar != '.') &&
            (e.KeyChar != Convert.ToChar(Keys.Back)))
        {
            e.Handled = true;
            return;
        }
    }
}

A: How about using Regex?
This will validate a decimal number or whole number:
VB
If New Regex("^[\-]?\d+([\.]?\d+)?$").IsMatch(testString) Then
    'valid
End If

C#
if (new Regex(@"^[\-]?\d+([\.]?\d+)?$").IsMatch(testString))
{
    //valid
}

A: A little convoluted.  Looks to make sure the character you just pressed is either numeric of a decimal and that there are no previous decimals.
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If Char.IsDigit(e.KeyChar) Or (Asc(e.KeyChar) = Asc(".")) And Me.TextBox1.Text.Count(Function(c As Char) c = ".") = 0 Then e.Handled = False Else e.Handled = True
End Sub


text:
Q: Wpf screen edge swipe detect I have a basic wpf app that basically detects a touch input and moves a rectangle according to the input. My problem is that if  that touch comes outside the screen(For example: I touch the bottom bezel of the screen and slide it in the touch area) it won't be detected. Is there a way to get over this problem? I want to detect edge swipes as well.
XAML:
<Window x:Class="touch_test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:touch_test"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        Stylus.IsPressAndHoldEnabled="False"
        >
    <Canvas>
        <Rectangle Width="50" Height="50" x:Name="rect" Fill="Red"/>
    </Canvas>

</Window>

Cs:
    protected TouchPoint TouchStart;
    public MainWindow()
    {
        InitializeComponent();

        this.PreviewTouchDown += new EventHandler<TouchEventArgs>(BasePage_TouchDown);
        this.PreviewTouchMove += new EventHandler<TouchEventArgs>(BasePage_TouchMove);
        WindowState = WindowState.Maximized;
        WindowStyle = WindowStyle.None;
    }
    void BasePage_TouchDown(object sender, TouchEventArgs e)
    {
        TouchStart = e.GetTouchPoint(this);
    }
    void BasePage_TouchMove(object sender, TouchEventArgs e)
    {
        Rectangle rectToMove = rect;
        rectToMove.RenderTransform = new MatrixTransform();
        Matrix matr = ((MatrixTransform)rectToMove.RenderTransform).Matrix;
        var currentTouchPoint = e.GetTouchPoint(this);

        matr.Translate(currentTouchPoint.Position.X, currentTouchPoint.Position.Y );

        rectToMove.RenderTransform = new MatrixTransform(matr);

    }


text:
Q: Quasi-isometry between an once-punctured torus and the Loch Ness Monster under suitable metrics I was wondering if there are quasi-isometric (complete) metrics on the once-punctured torus and the Loch Ness Monster. By an once-punctured torus I mean the 1-genus surface with one puncture and by the Loch Ness Monster I mean the orientable surface of infinite genus with an unique end (see this question of mine for concrete definitions) which is necessarily non-planar.
For instance, the once-punctured torus admits a hyperbolic metric for which the puncture is identified with a hyperbolic cusp isometric to the product $S^1\times [1,+\infty)$, where $S^1$ is the circle equipped with a flat metric $dx$ and the metric on the product is given by the Riemannian metric
$$\frac{dx^2+dt^2}{t^2}.$$
Thus, according to Sam Nead's answer on this post, the once-punctured torus is quasi-isometric to a ray.
On the other hand, thinking on the end space of the Loch Ness Monster in terms of proper rays (See my previously cited post for a concrete description), I would be tempted to suppose that the Loch Ness Monster carries a metric for which a geodesic ray escaping to its unique end makes the surface quasi-isometric to a ray as well, in analogy with the once-punctured torus and the geodesic rays escaping to its hyperbolic cusp.
In case that my question had a negative answer, at least can we find a metric in the infinitely non-orientable surface of infinite genus with an unique end (which is necessarily non-orientable) quasi-isometric to either of the two surfaces above under suitable (complete) metrics?.


text:
Q: Bulk Capacitor Ripple Current as a Function of Capacitance When you have a bulk capacitor on a time varying load, what is the relationship between the capacitance of the bulk capacitor, the ESR of the bulk capacitor and the ripple current through the bulk capacitor?
CAPACITANCE
It is my understanding that as you increase the capacitance, the voltage ripple will decrease, but the ripple current in the capacitor will increase (assuming a constant load and constant ESR).  The voltage ripple is caused by the voltage drop of I_source flowing through R_source (neglecting source inductance for this explanation).  Therefore, if the voltage ripple decreases (like when you increase the bulk capacitance), then the ripple on I_source has also decreases, because of ohms law. And if I_load is constant, then I_cap must increase because I_load = I_source + I_cap.  Therefore, it would seem, that increasing the bulk capacitance would actually increase the the ripple current in the capacitor.

Is this correct?  I am working on project where we need to decrease the ripple current in the capacitor, and everyone is talking about increasing the value of the capacitor.  Either I'm an idiot and missing something very fundamental, or everyone is gaslighting me.
I guess another way to think about it would be if you decreased the capacitor value to a tiny number, like 10pF, the ripple current wouldn't skyrocket, it would get tiny also.
ESR
Based on datasheets I've seen, ESR decreases as capacitance increase, within a given series or electrolytic capacitors.  Is ripple current through the capacitor proportional to ESR or inversely proportional to ESR?  I would think that capacitor ripple current would decrease as ESR increased because you can think of the capacitor as a parallel voltage source and the ESR as the source impedance.  As you increase ESR, more of the load current will come from the actual voltage source, and less from the capacitor.

A: You are correct.
The capacitor and the source impedance (R2 in your diagram) form a current divider. The equivalent conductance of the load (seen as a Norton source) forms another branch of the current divider that you haven't shown in your diagram.
If you reduce the impedance of the capacitor without changing any of the other components in the divider, then the AC current through it will increase.
But usually you only care about capacitor ripple current if it is causing excessive \$I^2R\$ losses in the capacitor itself, or if it is causing excessive voltage ripple. If the first is the important concern then it's more important to find a capacitor with lower ESR, or use multiple capacitors in parallel to reduce the ESR. If the second, then you should consider both ESR and capacitor value in choosing a new part, but a higher value capacitor may in fact be part of the solution.


text:
Q: Submit form using ajax, and then disable button My script is working, but there is one thing I can not solve.
  $(function () {
        $('#form_<?php echo $i; ?>' ).on('submit', function (e) {
          e.preventDefault();
          $.ajax({
            type: 'post',
            url: 'akcija_gaz_2l_insert.php',
            data: $('#form_<?php echo $i; ?>').serialize(),
            success: function () {
                //alert('form is submited');
            }
          });
          $("submit, input[type='submit']").click(function()
          {
          $(this).prop('disabled', true);
          $(this).css("color", "#15FF00");
          });
        });
      });

On first click it's submitting the form and on 2nd click it is disabling the button and changing the color to green. Can someone explain to me why it requires two clicks for this function? I want to do both on one click.

A: It requires two clicks because you are handling click event only when submit has happened. You should handle button change in the success function, or directly in the submitting function.
$(function () {
    $('#form_<?php echo $i; ?>' ).on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'post',
        url: 'akcija_gaz_2l_insert.php',
        data: $('#form_<?php echo $i; ?>').serialize(),
        success: function () {
            //alert('form is submited');
            $("submit, input[type='submit']").prop('disabled', true);
            $("submit, input[type='submit']").css("color", "#15FF00");
        }
      });
    });
  });

A: Try this,in your success function disable the button and change the button color like below
success: function(){
     $("#bttonID").attr("disabled", true);
     $("#bttonID").css("background","#15FF00");
},


text:
Q: No available mirrors for yaml-cpp I'm trying to install mongodd using yaourt on archlinux which require the yaml-cpp lib to be installed.
The thing is, yaourt is unable to find a valid mirror to download from
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from ftp.swin.edu.au : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from ftp.acc.umu.se : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirror.neuf.no : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirrors.ustc.edu.cn : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirror.23media.de : The requested URL returned error: 404
(4/4) checking keys in keyring                            [##############################] 100%
(4/4) checking package integrity                          [##############################] 100%
error: yaml-cpp: signature from "Levente Polyak (anthraxx) <levente@leventepolyak.net>" is invalid

I tried building the lib manually from source and putting it in /usr/lib but it doesn't work either.
What can I do here ?
Thanks

A: You must update your Arch Linux before installing any new package.
The following command are fine:

*

*pacman -Syu  followed by  pacman -S yaml-cpp

*pacman -Syu yaml-cpp
You must not do this (it may break your system):

*

*pacman -Sy  followed by  pacman -S yaml-cpp

*pacman -Sy yaml-cpp


text:
Q: Odd limitation on pipes in batfile on XP A BAT file I created on my XP Pro SP3 system works perfectly every time.
Installed on another XP [also Pro SP3] system it fails ("hangs up") every time.
The problem turns out to be in a multistep pipe.
To isolate it I kept simplifying until I arrived at this minimal [and artificial] test case
    echo. | date | find "/" | find "/" | find "/"
Note: the first two steps are not shortened to date /t because some of the user's systems are pre-XP [and thus lack Command Extensions].  Also: careful testing shows that date is executing the MS-DOS internal DATE command and find is executing the vanilla "FIND.EXE, Aug  4 2004, 9216" found in
 "C:\WINDOWS\system32\" [and identical to the safety copy in "C:\i386\"].
On the failing system, every command with 4 or more |s hangs in the fifth step, even when - as here - the programs are simple and the amount of text they are handling is minuscule.
I did some further testing on the user's system yesterday and discovered a subtlety of which I was unaware.  I entered the simplified command [above] at the command prompt.  It failed ["hung"] as expected.  However, when I rebooted and tried again before doing anything else [a case which would never occur in the user's normal operation], I got a shock:  it worked [i.e., the output of the MS-DOS DATE command appeared as expected].  It worked again.  Then on the third try the failure mode re-appeared, and remained consistent thereafter.  I confirmed that files=40 is in effect on both systems, and gave up.  I'm still curious but I can't spend a lot of time on a small project for a pro bono client analyzing a problem for which I have easy work-arounds.
Thank you everyone here for your quick and useful responses.
On the original system, commands with 4 or more |s work properly regardless of which programs are invoked and how much text [within reason] they are handling.
Once the limitation is recognized there are many trivial workarounds, so my question is solely one of curiosity:  can anyone suggest where the limit comes from and whether there is a setting [in XP] that will raise/eliminate it?
Note:  Neither HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun nor HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun exists on either system.
Also:  I apologize for answering comments by repeatedly editing my original post but no matter which browser I use to log in, the "add comments" popup [or whatever it is supposed to be] never appears.  Perhaps my understanding that adding a comment to my own post doesn't require reputation points is mistaken.  However, now I see that "show # more comments" isn't working either.
Finally:  The problem I am having using this site [the primary symptom of which is the javascript console message "Uncaught ReferenceError: StackExchange is not defined "] is the same one discussed here https://meta.stackexchange.com/questions/117730/stack-overflow-onclick-actions-broken about a year ago.

A: Use the ^ to avoid the special character
example
echo. ^| date ^| find "/" ^| find "/" ^| find "/"
http://www.robvanderwoude.com/escapechars.php

A: Sometimes , if something in registry is missing , You have to add it by hand to make it working. Or , get some advanced windows BAT editor , which will extend possibilities of Your batch script beyound standard windows commands and such. As for this , they usually append and turn Your batch file to exe , since , the executable is engine for extending capabilities. Most of them are shareware , but , notice their specifications , in this case , all You need is simple editor with engine which extracts batch file to temp directory and executes it. You probably don't need something which is made for obfuscating Your batch file.


text:
Q: Generate optparse-applicative parser from free alternative functor Consider the following type signatures:
data Foo x = Foo {
    name :: String
  , reader :: String -> x
}

instance Functor Foo where
  fmap f (Foo n r) = Foo n $ f . r

Now I show a natural transformation from Foo to optparse-applicative's Parser type:
import qualified Options.Applicative as CL

mkParser :: Foo a -> CL.Parser a
mkParser (Foo n _) = CL.option CL.disabled ( CL.long n )

(Okay, it's a bit useless, but it'll serve for discussion).
Now I take Bar to be the free alternative functor over Foo:
type Bar a = Alt Foo a

Given this is a free functor, I should be able to lift mkParser into a natural transformation from Bar to Parser:
foo :: String -> (String -> x) -> Bar x
foo n r = liftAlt $ Foo n r

myFoo :: Bar [String]
myFoo = many $ foo "Hello" (\_ -> "Hello")

clFoo :: CL.Parser [String]
clFoo = runAlt mkParser $ myFoo

And indeed, this works and gives me a Parser back. However, it's a pretty useless one, because trying to do much with it results in an infinite loop. For example, if I try to describe it:
CL.cmdDesc clFoo
> Chunk {unChunk =

And hangs until interrupted.
The reason for this seems to be that optparse-applicative cheats in its definitions of many and some: it uses monadic parsing under the covers.
Am I doing something wrong here? I don't see how, given this, it's possible to construct a parser in this way. Any ideas?

A: As pointed in comments, you have to handle many explicitly. Approach copied from Earley:
#!/usr/bin/env stack
-- stack --resolver=lts-5.3 runghc --package optparse-applicative
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Applicative
import qualified Options.Applicative as CL
import qualified Options.Applicative.Help.Core as CL

data Alt f a where
  Pure   :: a                             -> Alt f a
  Ap     :: f a       -> Alt f (a -> b)   -> Alt f b
  Alt    :: [Alt f a] -> Alt f (a -> b)   -> Alt f b
  Many   :: Alt f a   -> Alt f ([a] -> b) -> Alt f b

instance Functor (Alt f) where
  fmap f (Pure x)   = Pure $ f x
  fmap f (Ap x g)   = Ap x $ fmap (f .) g
  fmap f (Alt x g)  = Alt x $ fmap (f .) g
  fmap f (Many x g) = Many x $ fmap (f .) g

instance Applicative (Alt f) where
  pure = Pure

  Pure f   <*> y = fmap f y
  Ap x f   <*> y = Ap x $ flip <$> f <*> y
  Alt xs f <*> y = Alt xs $ flip <$> f <*> y
  Many x f <*> y = Many x $ flip <$> f <*> y

instance Alternative (Alt f) where
  empty = Alt [] (pure id)
  a <|> b = Alt [a, b] (pure id)
  many x  = Many x (pure id)

-- | Given a natural transformation from @f@ to @g@, this gives a canonical monoidal natural transformation from @'Alt' f@ to @g@.
runAlt :: forall f g a. Alternative g => (forall x. f x -> g x) -> Alt f a -> g a
runAlt u = go where
    go :: forall b. Alt f b -> g b
    go (Pure x)    = pure x
    go (Ap x f)    = flip id <$> u x                           <*> go f
    go (Alt xs f)  = flip id <$> foldr (<|>) empty (map go xs) <*> go f
    go (Many x f)  = flip id <$> many (go x)                   <*> go f

-- | A version of 'lift' that can be used with just a 'Functor' for @f@.
liftAlt :: (Functor f) => f a -> Alt f a
liftAlt x = Ap x (Pure id)

mkParser :: Foo a -> CL.Parser a
mkParser (Foo n r) = CL.option (CL.eitherReader $ Right . r) ( CL.long n CL.<> CL.help n )

data Foo x = Foo {
    name :: String
  , reader :: String -> x
}

instance Functor Foo where
  fmap f (Foo n r) = Foo n $ f . r

type Bar a = Alt Foo a

foo :: String -> (String -> x) -> Bar x
foo n r = liftAlt $ Foo n r

myFoo :: Bar [String]
myFoo = many $ foo "Hello" (\_ -> "Hello")

clFoo :: CL.Parser [String]
clFoo = runAlt mkParser $ myFoo

main :: IO ()
main = do
  print $ CL.cmdDesc clFoo
  print $ CL.cmdDesc $ mkParser (Foo "Hello" $ \_ -> "Hello")


text:
Q: WebDriverError: unknown error: Element is not clickable at point (330, 367) even after using EC.elementToBeClickable I am writing test cases in protractor using chromedriver
I have a link which when clicked gives an overlay div pop up where I can enter few details and Add details. After adding the details again the main page and link is visible. But when I am trying to click on the main link second time I am getting
WebDriverError: unknown error: Element is not clickable at point (330, 367). Other element would receive the click:
I tried using the below code still issue is not resolved
    browser.wait(EC.elementToBeClickable(link)).then(function(){
        link.click().then(function(){
            browser.sleep(3000).should.notify(next);
        });
    });

Can someone please help

A: I have seen this in my application before, Once you close the pop-up you have to wait for the window closing animation to finish. Your flow should be something like below
 browser.wait(EC.elementToBeClickable(link),5000)
//Fill the pop-up
 element(by.css('.textArea')).sendKeys('jhghaskjdhkjasd')
//close the pop-up
element(by.css('.close')).click()
//wait for the pop-up to close
browser.wait(ExpectedConditions.invisibilityOf(element(by.css('.pop-up'))),5000)

Also as a side point, you don't need to chain all webdriverJs promises.They are already placed in queue using Protractor control flow


text:
Q: Pass variable from jinja2 template to python Sorry if this is a noob question I am still learning. I have passed a variable from python code to a jinja2 HTML template to set up a URL, like this:
Delete
When this link is pressed it should run a query that deletes the entity with that ID. But when the link is pressed it goes to /delete/1827424298 for example, which results in a 404 error as the request handler doesn't exist.
I need to pass that ID back into my python code so it can run a method to delete the entity with that same ID. How do I go about doing this? Using webapp2 if that is important.
class DeleteRequestHandler(webapp2.RequestHandler):

def get():

    template = template_env.get_template('myrequests.html')
    context = {

        'results': results.key.id()

    }

    self.response.out.write(template.render(context))

EDIT: I've added my delete handler - it is incomplete as I have yet to add the query to delete the entity. My thinking behind it so far is I can grab the results.key.id() from the jinja2 template and put it into results but I am not sure if this would work.

A: So I think what you're confused about is how to set up a route handler with a dynamic part to the URL. It's a shame that this is completely skipped over in the webapp2 tutorial, as it's a fundamental part of writing any web application. However, it is covered well in the guide to routing, which you should read.
At its simplest, it's just a matter of putting a regex in the route:
app = webapp2.WSGIApplication([
    ...
    (r'/delete/(\d+)', MyDeleteHandler),
])

which will now route any URL of the form /delete/<number>/ to your deletion handler.
The ID that you pass in the URL will be the first positional argument to the handler method:
class MyDeleteHandler:
    def get(self, item_id):
        key = ndb.Key(MyModel, item_id)   # or whatever


text:
Q: sensible, sensitive, and sentient Despite the apparently same meanings of the three words (which I looked up in Wiktionary), I would like to know if my interpretation is correct regarding their differences.
"sensible" is used to describe a person who can be perceived and understood by other people.
"sensitive" is used to describe a person who can perceive other people or things.
I am not sure about "sentient". Is it the same as "sensible" or "sensitive"?

A: Where did you find definitions that show the words to be synonyms? They are hardly even close:

sen·tient

*

*Having sense perception; conscious: "The living knew themselves just sentient puppets on God's stage" (T.E. Lawrence).

*Experiencing sensation or feeling.

sen·si·tive

*

*Capable of perceiving with a sense or senses.

*Responsive to external conditions or stimulation.

*Susceptible to the attitudes, feelings, or circumstances of others.

*Quick to take offense; touchy.

*Easily irritated: sensitive skin.

*Readily altered by the action of an agent: film that is sensitive to light.

*Registering very slight differences or changes of condition. Used of an instrument.

*Fluctuating or tending to fluctuate, as in price: sensitive stocks.

*Of or relating to classified information: sensitive defense data; holds a sensitive position in the State Department.

sen·si·ble

*

*Perceptible by the senses or by the mind.

*Readily perceived; appreciable.

*Having the faculty of sensation; able to feel or perceive.

*Having a perception of something; cognizant: "I am sensible that a good deal more is still to be done" (Edmund Burke). See Synonyms at
aware.

*Acting with or exhibiting good sense: a sensible person; a sensible choice.

In everyday usage, sentient means conscious or self-aware (in the sci-fi world, it is often used to differentiate intelligent life forms from animals). Sensitive means being receptive to stimuli/ For example, I have sensitive eyes and bright lights bother me. Sensible means reasonable, possessing common sense.
The three words share common origins but do not really have similar, let alone identical, meanings.

A: To steal your method for defining, I would say:
"sentient" is used to describe a person who has the capacity to perceive and understand.
Oxford's definition - able to perceive or feel things


text:
Q: Raw pointer to Trait in Rust How can I initialize a raw pointer to a trait?
Seems like I can not with null() nor null_mut().
Thanks.
trait State {}

struct Warrior {
  state: *mut dyn State
}

impl Warrior {
  fn new() -> Self {
    Self { state: null_mut() } // cannot infer type for type parameter `T`
  }
}


text:
Q: How to create a group with PIM elevation in Azure I'm new to Azure AD. and trying to create access package.
My requirement is to Create a group 1st then elevate that group for PIM, then create access package, and then assign groups to scope.
I'm not sure, if there is any setting that needs to be enabled for PIM elevation during group creation. I searched the web but didn't get appropriate steps.
Edit
Particularly for assign groups to scope:
I think, this (assign groups to scope) can be done from the subscription -> Access control(IAM) -> "Role assignment" ; where my scope is showing  "this resource" where as it should be a resource group name. Anything I am missing here?

A: For elevate that group for PIM and create access package You should have Azure AD Premium P2 license
Please refer this Microsoft Document for PIM and Access Package.
Once you have above licence you can follow this Document for PIM of a Group
Edit--

I think, this(assign groups to scope) can be done from the
subscription -> Access control(IAM) -> "Role assignment" ; where my
scope is showing "this resource" where as it should be a resource
group name. - Anything Am I missing here?

If you are assiging the group to a scope on subscription level then if you go IAM ->Role Assigment it will show you This Resouce only and if you to your resource it will show subscription[inherited].
Likewise if you are assigning a scope to resource group level then if you go to resourcegroup-> role assigment it will show this resource and if you check inside the resources present in your resource group it will be resource group[Inherited].

A: This is how it's done.
Go to "Group" and search for "assignment group" that is created. Let's say "xxx_contributor" -> select and click on that -> then click on "Privileged access (Preview) [from left blade] -> Click on "Enable privilege access" -> click on "add assignment" -> select "role" as "member" -> click on "select member" -> search for the member, let's say "xxx_contributor_eligible" -> click " next" and click "assign".


text:
Q: Jquery Validation Central Message Many Errors I have a form that is being valdated with the Jquery Validation Plugin.
I have managed to get a centeral message "Please Recheck the form", and to have the input focus on the first error. To get this, I had to override the default message of each of the errors.
I was wondering if anyone could help me figure out how I can have it display the error message associated with the first error input instead of a general error message. Here is the code:
$("#Help-A-Noobie-Form" ).validate({

 invalidHandler: function(form, validator) {
     $(this).find(":input.error:first").focus();
     var message = 'Please Recheck The Form' ;
    $("#Help-A-Noobie-Form #Message p").addClass('red').html(message);
   },

showErrors: function(errorMap, errorList) {

this.defaultShowErrors();
       },
rules: {
          required:true,
          email: {email:true},
          phone: {digits:true}
           },
messages: {
             email: "",
             phone: "",
             lastname: "",
             firstname: "",
              required:""
                      }
})

A: $("#Help-A-Noobie-Form" ).validate({
    onfocusout: false,
    onkeyup: false,
    showErrors: function(errorMap, errorList) {
        if (errorList.length > 0) {
            jQuery('.errors').html('
' + errorList[0].message + '
');
        }
    },
    rules: {
        email: { email:true },
        phone: { digits:true }
    },

    messages: {
        email: { email: 'please enter a valid email' },
        phone: { digits: 'please enter a valid phone' }
    }
});


text:
Q: How to Change Mail in a Box Index Good day,
Sorry if this is off, but i have installed mail in a box on a vps. If a user wants to login in to use a webmail roundcube they have to go to mail.mydomain.com/mail. If a user goes to mail.mydomain.com they are not directed to the webmail roundcube. My question is that how can i make it that if a user goes to mail.mydomain.com they can see the roundcube login page enen if they don't enter the prefix /mail.
I am sure this must be in nginx but i don't know where to chnage.
Thank you


text:
Q: unable to convert timestamp to formated date I'm building a chat app so when a user sends message, a time stamp is also sent in database. I followed this answer for this implementation.
database()
        .ref('/')
        .child(`chats/${merged_uid}/${+new Date()}`)
        .set({
          message: msgInput,
          number: current_user.phoneNumber,
          uid: current_user.id,
          time: +new Date(),
        });

and i'm rendering this time stamp in my app in a flatlist in following way
<Text style={styles.timeStamp}>
                {new Date(item.time * 1000).getHours() +
                  ':' +
                  new Date(item.time * 1000).getMinutes()}
              </Text>

but my timestamp is not rendering correctly. These are the problems i'm facing with timestamp.

*

*It's not correct. i.e my current time of message is 4:44pm so it shows 16:50, here hours is correct but mins aren't. and sometimes it just doesn't give time correct. in next following 6 message time was 13:31, 14:35, 16:13, 19:1, 17:44, 20:44 respectively while current time was 4:44pm.

*Time is not formatted. i.e How can i convert it to 12hrs time format

A: The issue there is that you are multiplying by 1000, changing the correct value given by +new Date().
Your code on the browser console for 14:25:
(new Date(+new Date() * 1000)).getMinutes()
6
(new Date(+new Date() * 1000)).getMinutes()
35
(new Date(+new Date() * 1000)).getMinutes()
49
(new Date(+new Date() * 1000)).getMinutes()
0

The code without the multiplyer for 14:27:
(new Date(+new Date())).getMinutes()
27
(new Date(+new Date())).getMinutes()
27
(new Date(+new Date())).getMinutes()
27

A: Below is the JS function to get 12 hr formatted timestamp from JS Date. It is actually unsure from provided details, what kind of data is in item.time.

function getTimeStamp(date) {
    var mn = "AM",
        h = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds(),
        ms = date.getMilliseconds();
    if (h >= 12) {
        mn = "PM";
        if (h > 12) {
            h -= 12;
        }
    }
    if (h == 0) {
        h = 12;
    }
    return `${String(h).padStart(2, 0)}:${String(m).padStart(2, 0)}:${String(s).padStart(2, 0)}.${String(ms).padStart(3, 0)} ${mn}`;
}

// Check
var hour = 0;
while (hour < 25) {
    var d = new Date();
    d.setHours(hour);
    console.log(getTimeStamp(d));
    hour++;
}


text:
Q: Behavior of JS unary plus operator applied on a string representing a negative hex according to MDN, when using the unary plus operator:

Integers in both decimal and hexadecimal ("0x"-prefixed) formats are
  supported. Negative numbers are supported (though not for hex). If it
  cannot parse a particular value, it will evaluate to NaN.

But when I run this Jasmine test (the toBe() matcher applies a === operator):
   it("should return NaN when trying to convert a string representing a NEGATIVE HEX to the corresponding number", function() {
    var a = '-0xFF';
    expect(typeof +a).toBe('number');
    expect(isNaN(+a)).toBeTruthy(); //Fails on Chrome and Opera...
  });

It fails on Chrome and Opera (and passes in IE, Safari and Firefox).
Is it a flaw in Chrome and Opera's engines or am I missing something?

A: It may - or may not be seen as a flaw, depending on how one's attached to specifications. )
I've found an interesting discussion regarding this behavior. Looks like Firefox was for once in the 'better-than-spec' camp, but then fixed it according to spec.

A: According to the EcmaScript specification, the unary + operator applies the [String-]to-Number-conversion on the value (here a string), which accepts hex numbers - but not negative hex numbers.


text:
Q: sql oracle todate differences Can someone please explain to me why the output for Query 4 is different to the others when query 1 returns the replaced values used in query 2 which should equate to running the same as query 4?
I suspect it's something to do with the nls_date_format however I'm not sure.
Query 1
SELECT TO_DATE(SYSDATE, 'DD/MON/YYYY')FROM DUAL;
TO_DATE(SYSDATE,'DD/MON/YYYY')
------------------------------
02-SEP-15

Query 2
SELECT TO_DATE('02-SEP-15') - TO_DATE('01/JAN/07') FROM DUAL;
TO_DATE('02-SEP-15')-TO_DATE('01/JAN/07')
-----------------------------------------
                                     3166

SELECT TO_DATE(SYSDATE, 'DD/MON/YY') - TO_DATE('01/JAN/2007') FROM DUAL;

Query 3
TO_DATE(SYSDATE,'DD/MON/YY')-TO_DATE('01/JAN/2007')
---------------------------------------------------
                                               3166

Query 4
SELECT TO_DATE(SYSDATE, 'DD/MON/YYYY') - TO_DATE('01/JAN/2007') FROM DUAL;

TO_DATE(SYSDATE,'DD/MON/YYYY')-TO_DATE('01/JAN/2007')
-----------------------------------------------------
                                              -72732

A: Never call to_date on a date.
Assuming your nls_date_format is set to "DD-MON-RR", which is what it appears to be based on your first query, when you run TO_DATE(SYSDATE, 'DD/MON/YYYY') the following happens.

*

*to_date doesn't accept a date as a parameter, it only takes a varchar2.  So Oracle has to do an implicit cast from date to varchar2 using your session's nls_date_format.

*That transforms the call to to_date( '02-SEP-15', 'DD/MON/YYYY' )

*Since your string input parameter has a 2 digit year but your format mask specifies a 4 digit year, you get a very unexpected result.  Rather than being interpreted as 2015, it is interpreted as the year 15 (2000 years ago when the Roman Empire was a thing).

*Now you subtract a 2007 year from a 0015 year and you get a difference of just over 1,991 years (727,321 days to be exact).

The moral of the story-- never call to_date on a date.  It's already a date.  Converting it to a date makes no sense.  If you just want to set the time portion of a date to midnight, use trunc.  Don't cast a date to a varchar2 back to a date.


text:
Q: Ionic2 and SqlStorage, sql with more than 1 line I have a service to manage the database and at the constructor I create all my database or part if not exist.
I haven´t have problem while I was working with an unique line at create database.
sql=" CREATE TABLE cliente (id INTEGER PRIMARY KEY AUTOINCREMENT,nombre TEXT, telefono TEXT);";
this.storage.query(sql);

The problem has arrived when I have tried a sql with more than one line
sql=`DROP TABLE IF EXISTS cliente;
CREATE TABLE cliente (id INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT, telefono TEXT);
DROP TABLE IF EXISTS parte;
CREATE TABLE parte (id INTEGER PRIMARY KEY AUTOINCREMENT, clienteid INTEGER CONSTRAINT fk_clienteid REFERENCES cliente (id) ON DELETE CASCADE ON UPDATE SET DEFAULT, fecha DATE NOT NULL, horaini TIME NOT NULL, horafin TIME NOT NULL, trabajorealizado TEXT, personafirma TEXT);`;

this.storage.query(sql);

I receive this error "could not prepare statement (1 not an error)".
I test with only two sql lines (first two) and I get the error. If a execute one by one  all work fine....
I´d like to know if this is the way (one by one) or whether a best way to do this.
thanks.


text: Q: How to avoid access db compaction? My access db pulls data through odbc every few mins and deletes data in local tables and writes new data. After a while db size exceeds 2gb and it has to be compacted. How can I avoid this compaction step? Linking with odbc is not an option.