text:
Q: Limit search to site contents in root site My organization built an intranet in the root site of the root site collection. Currently, using the search function in the site pulls all results from our entire SharePoint environment. We'd like to limit search results to only the contents of that site, blocking out results from any sites below the root site collection. I understand why it does this, since all SharePoint items include the root address in their path.
Research has led me to believe query rules are the answer, and have tried this query rule at the site level to exclude results from anything below the root site collection:
-Path:https://[orgname].sharepoint.com/sites*

While the test of the query appears to behave appropriately, live search does not; all results still display. Is there a quirk to query rules at the site, or could this have something to do with the fact that we're running search using the modern/non-classic experience?

A: I would not use Query Rules. You have two options that will effectively remove the additional sites. The first is to simply secure the sites you do not wish people to see in search results with appropriate permissions. If they do not have access to the sites, they will not see the content. That is how "Security Trimming" works. Your second option is to change the default Result Source to include the additional query parameter -Path:https://[orgname].sharepoint.com/sites/* The thing to remember is that your users can still access the sites and information in these sites, they just cannot search for it.
Also, if your users are knowledgable, they can create a search page that does not use your result source and easily find the content you are trying to "hide".
The best option is "security" and it is simple.


text:
Q: window.getSelection() sometime get range is not true

                <div class="placeholder"  v-show="editorContent == ''" :style="placeholderColor?`color:${placeholderColor}`:null">{{placeholder}}

I want to make a text editor, so I use window.getSelection() to get the text that mouse selected.
But sometimes, I get weird results.
For example, if I select the text "hahhahahhahahahahhahahahahahhahahahahhahaha", when I log the current Selection I get

anchorNode: text
anchorOffset: 3
focusNode: text
focusOffset: 43
isCollapsed: false
rangeCount: 1
type: "Range"
baseNode: text
baseOffset: 3
extentNode: text
extentOffset: 43

when the anchorOffset should actually have been 0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerShell get name of folders in a path I try to figure out some names of folders in a path.
For example:
C:\folder1\folder2\folder3\folder4\folder5\folder6

how can i get the name of folder 2 or 3? Just as a String without any Slashes.

A: You can use .Split("\") to the path folder
$pathfolder = "C:\folder1\folder2\folder3\folder4"
$pathfolder.Split("\")

cls
$pathfolder = "C:\folder1\folder2\folder3\folder4"
$A = $pathfolder.Split("\")
$Count = $pathfolder.Split("\").Count

For ($i=1; $i -le $Count+1; $i++) {
    echo $A[$i]
}

$pathfolder = "C:\folder1\folder2\folder3\folder4"
$A = $pathfolder.Split("\")

echo "The folder number 2 with name : " $A[2]
echo "The folder number 3 with name : " $A[3]

A: You should be able to use Get-ChildItem with the Directory and Depth command.
Something like
Get-ChildItem -Directory -Depth 6

This should return all Directory Names that are in the subfolder.
You could then pipe this into Select to grab just the name and parent directory.
Get-ChildItem -Directory -Depth 6 | Select Name, Parent

Edit
If you want to go in the reverse direction because you have a file in folder 6 and want the name of folder 2 you could do something like this.
(get-item FileIn6.txt).directory.parent.parent.parent.parent | select Name

So if FileIn6.txt is a file sitting in folder 6, you get item and then grab the directory property, and the parent of that, parent of next, etc. Hopefully that makes sense.

A: $Path = "C:\f1\f2\"
$pspath = Get-ChildItem $Path
$namef2 = $pspath.Parent.Name
$namef2
$namef2.GetType().Name
$namef1 = $pspath.Parent.Parent.Name
$namef1
$namef1.GetType().Name


text:
Q: How to package scons tools for distribution and installation I'm writing a tool for scons in the form of a python package (a directory with an __init__.py file) which can be used by copying it into one of the many possible site_scons/site_tools directories.
Are there standard tools or methods for packaging such tools for distribution and installation? For instance, an automated installer might ask whether they want to install it site-wide or just for a specific user, or just for a specific project and then find the right place to install it. I suppose it wouldn't be too hard to write this installer myself, but if there's already something out there that is widely used, I'd prefer to stick with that.

A: Tools that outside of the scons distribution are encouraged to be distributed as a python package inside a DVCS. Preferably  It is described on The SCons ToolsIndex They also suggest that you write a bit about the builder in a wiki entry.
This is of course not a package in the normal sense, but it is the simplest way for a developer using scons to be able to find and install. You could of course create an installer that cloned the repo for you and in the correct location, but I guess most users of the scons tools are proficient to clone it in the correct location themselves.


text:
Q: Finding index of kth smallest element in an array efficiently (iterative)? I would like to find the kth smallest element in an array but actually need its index for my partition method.
I found this code on this blog for finding the kth smallest element:
http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
But this only returns the value, not the index.
Do you have any idea how I can find the index of it efficiently?

A: The simplest way is to create an additional indices array of the same length, fill it by numbers from 0 to length-1 and when arr array is changed, perform the same change with the indices array. Finally return the corresponding entry from the indices array. You don't even have to understand the original algorithm to do this. Here's the modified method (my changes are marked with ***):
public static int selectKthIndex(int[] arr, int k) {
    if (arr == null || arr.length <= k)
        throw new IllegalArgumentException();

    int from = 0, to = arr.length - 1;

    // ***ADDED: create and fill indices array
    int[] indices = new int[arr.length];
    for (int i = 0; i < indices.length; i++)
        indices[i] = i;

    // if from == to we reached the kth element
    while (from < to) {
        int r = from, w = to;
        int mid = arr[(r + w) / 2];

        // stop if the reader and writer meets
        while (r < w) {

            if (arr[r] >= mid) { // put the large values at the end
                int tmp = arr[w];
                arr[w] = arr[r];
                arr[r] = tmp;
                // *** ADDED: here's the only place where arr is changed
                // change indices array in the same way
                tmp = indices[w];
                indices[w] = indices[r];
                indices[r] = tmp;
                w--;
            } else { // the value is smaller than the pivot, skip
                r++;
            }
        }

        // if we stepped up (r++) we need to step one down
        if (arr[r] > mid)
            r--;

        // the r pointer is on the end of the first k elements
        if (k <= r) {
            to = r;
        } else {
            from = r + 1;
        }
    }

    // *** CHANGED: return indices[k] instead of arr[k]
    return indices[k];
}

Note that this method modifies the original arr array. If you don't like this, add arr = arr.clone() at the beginning of the method.


text:
Q: How to click a radio button on a webpage with javascript I am trying to automate a bunch of repetitive tasks in a web application from Invisalign (for tooth alignment). Every time I submit a case for alteration, there are 4 clicks (3 buttons and 1 radio) which must be made, followed by a page reload and another two clicks.
I have the clicks worked out alright but I am struggling with the radio button. For the first button I am using the following:
document.querySelector("button[type='button'][data-qa-name='approve-proceed-button']").click();

Once that is clicked a radio button must be selected. I am attempting to change data-qa-checked= from "false" to "true" (see below)
<div class=-"c012081"

        <input class="c01917" type="radio" value="leaveAsIs">

            <svg class="c01920 c0189 c0192" viewBox="0 0 16 16"><path d="M8,1.33333333 C11.68,1.33333333 14.6666667,4.32 14.6666667,8 C14.6666667,11.68 11.68,14.6666667 8,14.6666667 C4.32,14.6666667 1.33333333,11.68 1.33333333,8 C1.33333333,4.32 4.32,1.33333333 8,1.33333333 Z M8,13.3333333 C10.9466667,13.3333333 13.3333333,10.9466667 13.3333333,8 C13.3333333,5.05333333 10.9466667,2.66666667 8,2.66666667 C5.05333333,2.66666667 2.66666667,5.05333333 2.66666667,8 C2.66666667,10.9466667 5.05333333,13.3333333 8,13.3333333 Z M8,11.3333333 C6.15905083,11.3333333 4.66666667,9.84094917 4.66666667,8 C4.66666667,6.15905083 6.15905083,4.66666667 8,4.66666667 C9.84094917,4.66666667 11.3333333,6.15905083 11.3333333,8 C11.3333333,9.84094917 9.84094917,11.3333333 8,11.3333333 Z"></path></svg>

        Leave as is

    <input class="c01917" type="radio" value="fixForMe">
<svg class="c01920 c0189 c0192" viewBox="0 0 16 16"><path d="M8,1.33333333 C4.32,1.33333333 1.33333333,4.32 1.33333333,8 C1.33333333,11.68 4.32,14.6666667 8,14.6666667 C11.68,14.6666667 14.6666667,11.68 14.6666667,8 C14.6666667,4.32 11.68,1.33333333 8,1.33333333 Z M8,13.3333333 C5.05333333,13.3333333 2.66666667,10.9466667 2.66666667,8 C2.66666667,5.05333333 5.05333333,2.66666667 8,2.66666667 C10.9466667,2.66666667 13.3333333,5.05333333 13.3333333,8 C13.3333333,10.9466667 10.9466667,13.3333333 8,13.3333333 Z"></path></svg>
Fix for me

I have been trying something along the lines of:
document.querySelectorAll("button[type='radio']")].find(function (ele) {return ele.innerText === "inspection-panel-warning-leave-as-is"})).click();

or
document.querySelector("radio[type='radio'][data-qa-name='inspection-panel-warning-leave-as-is']").checked = true;

I am sure there is a pretty simple solution but after repeated attempts, I just can't get it to work.
The last part is that I would like to set a delay in seconds, or until the next page loads to click the next button (using the first code sample). If I could get that it would put it all together. I am really hoping someone can help me out with this. This is such an awesome community. Thank you in advance for the assistance. I love trying to put these things together.

A: Using the correct selector
Your radio is an input element, with a type of radio, <input class="c01917" type="radio" value="leaveAsIs">
In your selector, you are trying to find a button element or even some type of radio element.
What you need in your selector is to find the input with a type of radio and optionally the class for greater specificity document.querySelector('input[type="radio"].c01917').

const radio = document.querySelector('input[type="radio"].c01917');
radio.checked = true;
<div class=-"c012081"

        <input class="c01917" type="radio" value="leaveAsIs">

            <svg class="c01920 c0189 c0192" viewBox="0 0 16 16"><path d="M8,1.33333333 C11.68,1.33333333 14.6666667,4.32 14.6666667,8 C14.6666667,11.68 11.68,14.6666667 8,14.6666667 C4.32,14.6666667 1.33333333,11.68 1.33333333,8 C1.33333333,4.32 4.32,1.33333333 8,1.33333333 Z M8,13.3333333 C10.9466667,13.3333333 13.3333333,10.9466667 13.3333333,8 C13.3333333,5.05333333 10.9466667,2.66666667 8,2.66666667 C5.05333333,2.66666667 2.66666667,5.05333333 2.66666667,8 C2.66666667,10.9466667 5.05333333,13.3333333 8,13.3333333 Z M8,11.3333333 C6.15905083,11.3333333 4.66666667,9.84094917 4.66666667,8 C4.66666667,6.15905083 6.15905083,4.66666667 8,4.66666667 C9.84094917,4.66666667 11.3333333,6.15905083 11.3333333,8 C11.3333333,9.84094917 9.84094917,11.3333333 8,11.3333333 Z"></path></svg>

        Leave as is

    <input class="c01917" type="radio" value="fixForMe">
<svg class="c01920 c0189 c0192" viewBox="0 0 16 16"><path d="M8,1.33333333 C4.32,1.33333333 1.33333333,4.32 1.33333333,8 C1.33333333,11.68 4.32,14.6666667 8,14.6666667 C11.68,14.6666667 14.6666667,11.68 14.6666667,8 C14.6666667,4.32 11.68,1.33333333 8,1.33333333 Z M8,13.3333333 C5.05333333,13.3333333 2.66666667,10.9466667 2.66666667,8 C2.66666667,5.05333333 5.05333333,2.66666667 8,2.66666667 C10.9466667,2.66666667 13.3333333,5.05333333 13.3333333,8 C13.3333333,10.9466667 10.9466667,13.3333333 8,13.3333333 Z"></path></svg>
Fix for me


text:
Q: Не выводятся данные из бд Не выводятся данные которые я вносил в бд. При прохождении кода дебагером после строки db.Contacts.Add(Contact1); выхожу в консоль.
И потом выходит ошибка:
Необработанное исключение типа "System.InvalidOperationException" в EntityFramework.dll
Дополнительные сведения: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Модели:
public class Contact
{
    [Key]
    public int Id { get; set; }
    public string SurName { get; set; }
    public string Name { get; set; }
    public string MiddleName { get; set; }
    public string BirthDate { get; set; }
    public string Organization { get; set; }
    public string Position { get; set; }

    //public virtual ICollection<ContactInformation> ContInforms { get; set; }

    /*public Contact()
    {
        ContInforms = new List<ContactInformation>();
    }*/

}
public class ContactInformation
{
    //public int? ContactId { get; set; }
    [Key]
    public int Id { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Skype { get; set; }
    public string Another { get; set; }

    //public virtual Contact Contact { get; set; }
}

Контекст базы данных:
public class ContactContext : DbContext
{
    // Имя будущей базы данных можно указать через
    // вызов конструктора базового класса
    public ContactContext()
        : base("MyBases")
    { }
    // Это свойство ссылается на таблицу в базе данных
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<ContactInformation> ContInform { get; set; }

    //protected override void OnModelCreating(DbModelBuilder modelBuilder)
    //{
    //modelBuilder.Entity<ContactInformation>().HasRequired(p => p.Contact)
    // .WithMany(b => b.ContInforms)
    // .HasForeignKey(p => p.ContactId);
    //modelBuilder.Ignore<ContactInformation>();
    //}
}

Код взаимодействия с контекстом базы данных:
class Program
{

    static void Main(string[] args)
    {

        using (ContactContext db = new ContactContext())
        {
            //db.Contacts.Load();
            Contact Contact1 = new Contact
            {
                Id = 0,
                Name = "Вася1",
                SurName = "Пупкин1",
                MiddleName = "Николаевич1",
                BirthDate = "1.11.1990",
                Organization = "Купол1",
                Position = "programmer1",
            };
            Contact Contact2 = new Contact
            {
                Id = 0,
                Name = "Вася2",
                SurName = "Пупкин2",
                MiddleName = "Николаевич2",
                BirthDate = "1.11.1990",
                Organization = "Купол2",
                Position = "programmer2",

            };

            // добавляем их в бд
            db.Contacts.Add(Contact1);
            db.Contacts.Add(Contact2);
            //Contact contact2 = db.Contacts
            //    .Where(o => o.Id == 1)
            //    .FirstOrDefault();
            //db.Contacts.Remove(contact2);

            //сохраняем изменения
            db.SaveChanges();

            ContactInformation ContactInformation1 = new ContactInformation
            {
                Another = "1",
                Email = "1",
                Id = 0,
                Phone = "1",
                Skype = "1",

            };

            ContactInformation ContactInformation2 = new ContactInformation
            {
                Another = "2",
                Email = "2",
                Id = 0,
                Phone = "2",
                Skype = "2",

            };

            ContactInformation ContactInformation3 = new ContactInformation
            {
                Another = "3",
                Email = "3",
                Id = 0,
                Phone = "3",
                Skype = "3",

            };

            try
            {
                //db.ContInform.AddRange(new List<ContactInformation> { ContactInformation1, ContactInformation2, ContactInformation3 });
                db.SaveChanges();
                Console.WriteLine("Объекты успешно сохранены");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            // получаем объекты из бд и выводим на консоль
            var users = db.Contacts;
            Console.WriteLine("Список объектов:");
            foreach (Contact c in users)
            {
                Console.WriteLine("{0}.{1} - {2} - {3} - {4} - {5} - {6}", c.Id, c.Name, c.SurName, c.MiddleName, c.Organization, c.Position, c.BirthDate /*c.ContInforms*/);
            }

        }
        //Console.ReadKey();
    }
}

Файл конфигурации
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MyBases" connectionString="data source=(localdb)\MSSQLLocalDB;Initial Catalog=userstore.mdf;Integrated Security=True;"
 providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>


text:
Q: Sharepoint 2013 provider hosted app using Profile Service getting an errorwhile checking prerequisites for an app Interestingly I am able to install the app on mysites but not on a different publishing portal site.
When I try to add it I get the following meesage
Sorry, this app is not supported on your server.
The app tries to call UserProfile Service. The appmanifest.xml has the following permissions
AppPermissionRequests AllowAppOnlyPolicy="true"
    AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl"
    AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl"
    AppPermissionRequest Scope="http://sharepoint/social/tenant" Right="FullControl"
    AppPermissionRequest Scope="http://sharepoint/social/core" Right="FullControl"
    AppPermissionRequest Scope="http://sharepoint/social/microfeed" Right="FullControl"
    AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl"
  AppPermissionRequest
Caught a SPException while checking prerequisites for App 'Address' with asset id '': Microsoft.SharePoint.SPException: An error has been encountered while checking prerequisites for an app. ---> System.ArgumentNullException: Value cannot be null.  Parameter name: name
 at Microsoft.SharePoint.Utilities.SPUtility.ThrowArgumentExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String argumentName, String argumentLocalizedMessage, String traceMessage, Type argumentExceptionType)
 at Microsoft.SharePoint.Utilities.SPUtility.ThrowArgumentExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String argumentName, Type argumentExceptionType)
 at Microsoft.SharePoint.Administration.SPCapability..ctor(String name, SPCapabilityStatus capabilityStatus, String message)
 at Microsoft.Office.Server.UserProfiles.SPSocialPermissionProvider.GetMissingCustomDependencies(Uri permissionRequestScope, SPWeb hostWeb)
 at Microsoft.SharePoint.Administration.SPAppPermissionProvider.GetMissingDependencies(Uri permissionRequestScope, SPAppPrerequisitesCheckingContext context, Boolean shouldLog)
 at Microsoft.SharePoint.Marketplace.SPAppPrerequisitesChecker.CheckPermissionScopeDependencies(List`1 permissionScopeList, Boolean shouldLog)     -
 -- End of inner exception stack trace ---
 at Microsoft.SharePoint.Marketplace.SPAppPrerequisitesChecker.CheckPermissionScopeDependencies(List`1 permissionScopeList, Boolean shouldLog)
 at Microsoft.SharePoint.Marketplace.SPAppPrerequisitesChecker.Check(SPAppMetadata appMetadata, List`1& missingCapabilities, Boolean shouldLog)

Caught an exception while on calling SPCapabilityChecker.GetMissingCapabilities(): System.ArgumentNullException: Value cannot be null.  Parameter name: name
 at Microsoft.SharePoint.Utilities.SPUtility.ThrowArgumentExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String argumentName, String argumentLocalizedMessage, String traceMessage, Type argumentExceptionType)
 at Microsoft.SharePoint.Utilities.SPUtility.ThrowArgumentExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String argumentName, Type argumentExceptionType)
 at Microsoft.SharePoint.Administration.SPCapability..ctor(String name, SPCapabilityStatus capabilityStatus, String message)
 at Microsoft.Office.Server.UserProfiles.SPSocialPermissionProvider.GetMissingCustomDependencies(Uri permissionRequestScope, SPWeb hostWeb)
 at Microsoft.SharePoint.Administration.SPAppPermissionProvider.GetMissingDependencies(Uri permissionRequestScope, SPAppPrerequisitesCheckingContext context, Boolean shouldLog)
 at Microsoft.SharePoint.Marketplace.SPAppPrerequisitesChecker.CheckPermissionScopeDependencies(List`1 permissionScopeList, Boolean shouldLog)

A: I changed the permissions to the following and it is working now. It appears that it was not finding some social list in the site ( publishing site)
AppPermissionRequests AllowAppOnlyPolicy="true"
AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl"
AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl"
AppPermissionRequest Scope="http://sharepoint/social/tenant" Right="Read" AppPermissionRequest


text:
Q: Why is the prefix "Trans" shortened to "X"? In technical literature as well as aircraft user interfaces where there is not enough space to write the whole word, the prefix "trans" is shortened to "x".

Transmit -> Xmit
Transfer -> Xfer

I am interested to know what is the origin of this. I am curious because "Ex" and "Trans" do not have a similar sound.

A: X is commonly used to refer to cross because of its shape of two lines crossing.
Trans- means cross/across. Trans- and cross- are interchangeable in many cases.
From Wikipedia (emphasis mine):

In abbreviations, it can represent trans- (e.g. XMIT for 'transmit', XFER for 'transfer'), cross- (e.g. X-ing for 'crossing', XREF for 'cross-reference'), Christ- as shorthand for the labarum (e.g. Xmas for 'Christmas', Xian for 'Christian'), the crys- in 'crystal' (XTAL), or various words starting with ex- (e.g. XL for 'extra large', XOR for 'exclusive-or').

Example: a transatlantic flight is one that crosses the Atlantic, and something that is transdermal crosses through the skin.
The trans- in transmit and transfer is analogous to transatlantic.
Crossing a mit or a fer makes perfect sense.

*

*-Mit is from the Latin mittere which means to send.

*-Fer is from the Latin ferre which means to bear or carry.

'Transmit' often means to send across something or over a specific medium and 'transfer' can be to carry across from one to another.
Therefore trans- is often replaced with X- in certain words.

A: Oddly enough, 'Tx' is used to describe 'a transmitter' or 'to transmit something' and is very much relevant in electronics domain. Similarly, 'Rx' describes 'a receiver' or 'to receive something/reception of signal'. Here is a picture which shows Tx and Rx use in electronics:

Picture source

A: OED:

trans-, prefix

Etymology: The Latin preposition trans, across, to or on the farther side of, beyond, over', also used in combination, (1) with verbs, (2) adjectives (3) the neames of geographical features and names, etc.

e.g. transcribe, transcript, transcription, tranship, transport, transmarine, transmural, transatlantic,
The shape of the letter X is described as a cross: The letter is formed by one line crossing another:

b. The letter considered with regard to its shape: chiefly attributive and in other combinations. Hence identified with a cross. X's and O's: the game of noughts and crosses. X chair, a chair in which the underframe resembles the letter X in shape; so X-frame (usually attributive).

1976   Country Life 27 May (Suppl.) 486/1   Late 18th century wheel-back armchairs with saddle seats and X-frame legs.

d. [the letter or mark 'X'] Used to mark a location on a map or the like; esp. in X marks the spot and variants.

1918   J. M. Barrie Echoes of War 5   In the rough sketch drawn for to-morrow's press, 'Street in which the criminal resided'..you will find Mrs. Dowey's home therein marked with a X.

A: In addition to the other edifying answers and comments: from an information-theory viewpoint, given the rarity of initial "x" in English words, the presence of it (especially if unpronounceable) is a clear signal that there is something at play slightly out of the ordinary, and it will not be easily mistaken for anything else. That is, information-theory-wise, the chance of misunderstanding is low (more technically/precisely, the error-correction properties of this usage are excellent).


text:
Q: Provisoning profile Generate button not working New UI of developer account is not allowing to add new device in my provisioning profile. On top it shows to press Genrate button, but after modification Genrate button is still diable. Has anyone came across this.
I was able to add device successfully, but the problem is with modifying provisioning profile.
I am admin of the account.

A: This is because you are using some special characters while giving name to your provisioning profile. Now apple has restricted to use "_" so if you are using underscore than don't use it.
It will enable generate button.
Hope it helps


text:
Q: Uploading an Image File to API using Laravel I am trying to upload a file using an external API call. However facing some issues when trying to attach the data to the request. I need to attach the file itself and the file name as form data.
I have tried the following:
$response = Http::attach('image', $file->path(), $fileName)->withOptions([
                        "multipart" => [
                            "name" => "image",
                            "contents" => fopen($file->path(), "r"),
                            "filename" => $fileName,
                        ],
                        [
                            "name" => "fileName",
                            "contents" => $fileName
                        ]
                        ])->post("<API-ENDPOINT>");

But I am getting errors with the post() method expecting an array?
I tried sending it this way too
$response = Http::post("<API ENDPOINt>",
                    [
                        "multipart" => [
                            [
                                "name" => "image",
                                "contents" => file_get_contents("storage/app/images/".$fileName),
                                "filename" => $fileName,
                            ],
                            [
                                "name" => "fileName",
                                "contents" => $fileName,
                            ]
                        ]
                    ]);

But this didn't work as expected either, I am getting file_get_contents(storage/app/images/e5b7e91dfa34a94f09d200f9436ea4e3f3c0d46e-action-helicopter.jpg): Failed to open stream: No such file or directory even though the file does exist.
Any help here would be appreciated. Doesn't have to use these methods, just any way to POST the File data along with the filename that can be accessed in the form body of the request. Tried checking docs and other forums but no previous answers helped.

A: I got it sorted by using the below:
$response = Http::attach('image', file_get_contents($file->path()), $fileName)->post("<endpoint>", [
                        "fileName" => $fileName
                    ]);```


text:
Q: After updating to Magento CE 1.9.1 main navigation sub menus don't show I updated from 1.9 to 1.9.1.
Since then if I hover of any category menu, the sub-menus don't show any more.
Does Magento 1.9 main navigation works with jQuery or any other js library?
Could it be a jQuery conflict?

A: First of all there is a 404 error which can be seen in dev tools console, error says:
http://happygemslondon.co.uk/skin/frontend/base/default/js/lib/jquery-1.10.2.min.js Failed to load resource: the server responded with a status of 404 (Not Found)

which means that the jquery file provided by the latest version was not found on your server. You should check if you haven't forgot about any files during the upgrade, eventually you should upload missing file to the base/default (or your custom) namespace.


text:
Q: Parse file names in directory to output to csv with timestamp? I have several hundred documents inside of a few directories.  All have a common naming structure but the values differ:
10_03022014_229_14_12-9663 5930 4454.pdf

10_03022014_230_19_4-574 1564 1452 177.pdf

What I am attempting to do is create a CSV based upon this data, strip some whitespace, and remove the PDF filename extension in PowerShell.  The end result would look something like this:
10,03022014,229,14,12,966359304454

10,03022014,230,19,4,57415641452177

All of these values are alpha-numeric except for the final one which is barcode data.
To further complicate things for myself I need to have the output file have a similar naming structure based upon the first two "values" followed by a date and time stamp.
Example would be 10_03022014_datestamp_timestamp.csv if the files in the directory start with 10_02022014.
Any recommendations would be greatly appreciated!

A: An alternative solution:
#Get pdf-files
Get-ChildItem -Filter "*.pdf" |
#Group files that belong to the same csv-file
Group-Object -Property @{e={$_.BaseName.Split("_")[0,1] -join ("_")}} |
#Foreach csv-group
ForEach-Object {
    #Generate csv-filename
    $path = "$($_.Name)_$((Get-Date).ToString("MMddyyyy_HHmm")).csv"
    #Format content and save
    $_.Group | % { $_.BaseName -replace " " -replace '[-_]',"," } | Set-Content -Path $path
}

A: The file name processing seems straightforward enough. I believe you're just replacing underscores, hyphens with a comma and removing spaces from the file's base name.  The following should get you the reformatted strings, at least per your two provided values:
Get-ChildItem -Filter '*.pdf' |
    ForEach-Object { $_.BaseName -Replace '[-_]', ',' -Replace ' ', '' }

I'm still not exactly clear on what you mean about the csv file name.  Once you clarify that, I'd be happy to help with that as well.

I think this is closer to what you're looking to do:
# Generate '_date_time.csv' string.
$fileSuffix = "_" + (Get-Date -Format yyyyMMdd) + "_" + (Get-Date -Format HHmm) + ".csv"

Get-ChildItem -Filter '*.pdf' |
    ForEach-Object {
        # Get the first two tokens, underscore delimited, of PDF file name.
        $filePrefix = $_.Name.Split('_')[0,1] -Join('_')
        # Preform requisite replacements on PDF file name
        $string = $_.BaseName -Replace '[-_]', ',' -Replace ' ', ''
        # Write string out to CSV file, concat prefix/suffix to generate name.
        $string | Out-File -Append -FilePath $($filePrefix + $fileSuffix)
    }


text:
Q: CouchDB view query with multiple key values I am currently trying to create a view and query to fit this SQL query:
SELECT * FROM articles
WHERE articles.location="NY" OR articles.location="CA"
ORDER BY articles.release_date DESC

I tried to create a view with a complex key:
function(doc) {
  if(doc.type == "Article") {
    emit([doc.location, doc.release_date], doc)
  }
}

And then using startkey and endkey to retrieve one location and ordering the result on the release date.
.../_view/articles?startkey=["NY", {}]&endkey=["NY"]&limit=5&descending=true

This works fine.
However, how can I send multiple startkeys and endkeys to my view in order to mimic
WHERE articles.location="NY" OR articles.location="CA" ?

A: My arch nemesis, Dominic, is right.
Furthermore, it is never possible to query by criteria A and then sort by criteria B in CouchDB. In exchange for that inconvenience, CouchDB guarantees scalable, dependable, logarithmic query times. You have a choice.

*

*Store the view output in its own database, and make a new view to sort by criteria B

*or, sort the rows afterward, which can be either

*

*Sort client-side, once you receive the rows

*Sort server-side, in a _list function. The is great, but remember it's not ultimately scalable. If you have millions of rows, the _list function will probably crash.

A: The short answer is, you currently cannot use multiple startkey/endkey combinations.
You'll either have to make 2 separate queries, or you could always add on the lucene search engine to get much more robust searching capabilities.
It is possible to use multiple key parameters in a query. See the Couchbase CouchDB documentation on multi-document fetching.


text:
Q: DevForce 2010 Formatting Dates for EntityQuery I've run into a situation where I need to query by Date and Time.  I'm trying to write an EntityQuery where the date and time are in the same format.  The query below returns no rows.  However if I remove the two date clauses, rows are returned and then I can check the dates looping through the results.  I would prefer to use the dates in the query.
the variable ap in the query is a C# object

var query = from log in Manager.Logs
            where log.StartDttm == ap.StartDttm
                  && log.EndDttm == ap.EndDttm
                  && log.TypeId == 1
            select log;

I came up with this workaround to query between midnight and 11:59:59pm for each date.  I don't like this either, but this does at least reduce the number of rows returned by the query.
var query = from log in Manager.Logs
            where && log.StartDttm >= ap.StartDttmQueryBegin
                  && log.StartDttm <= ap.StartDttmQueryEnd
                  && log.EndDttm >= ap.EndDttmQueryBegin
                  && log.EndDttm <= ap.EndDttmQueryEnd
                  && log.TypeId == 1
            select log;

A: DevForce doesn't expect any specific date/time formats or modify them when the query is built and executed, but it's not the date format per se but the precision of the data stored in the database vs. the precision of the DateTime fields in the "ap" object which is causing the issue.
In EF you can use the EntityFunctions and/or SQLFunctions APIs to perform date/time truncating/formatting, but these are difficult to use in DevForce due to the client/server serialization and EntityQuery to ObjectQuery conversion that DevForce performs.  These APIs can be made to work on the "server side" of DevForce via an RPC call.
Your workaround, although it may feel cumbersome, is probably your best option.  You could also try calling a stored procedure or using an ESQL passthru query, both of which will give you a little more control over the resulting SQL query.


text:
Q: Pandas dataframe to check an empty string I would like to differentiate an empty string with certain lengths    and a regular string such as G1234567. The length of the empty string right now in my dataset is 8 but I would not guarantee all future empty string will still have length of 8.
This is what the column looks like when I print it out:
0
1
2
3
4

9461    G6000000
9462    G6000001
9463    G6000002
9464    G6000003
9465    G6000004
Name: Sub_ID, Length: 9466, dtype: object

If I apply pd.isnull() on the entire column, I will have a mask populated with all False. I would like to ask if there is anyway for me to differentiate between an empty string with certain lengths and a string that is actually populated with something.
Thank you so much for your help!

A: The following creates a mask for all the cells in your DataFrame (df) that are just empty strings (strings that only contain whitespaces):
df.applymap(lambda column: column.isspace())


text:
Q: How to merge first part of a list value prior to a character, based on the values after the character in python I have a scenario where I need to combine the element values of a list in python. This is based on the values coming after a specific character in the element. For example:
I have a below input list value
[('245|CALENDAR_DATE-DATE'), ('129|AREA-VARCHAR'),('450|DIVISION-VARCHAR'),('678|CALENDAR_DATE-DATE'),('298|DIVISION-VARCHAR')]

I have to get the output list as below
[('245,678|CALENDAR_DATE-DATE'), ('129|AREA-VARCHAR'),('450,298|DIVISION-VARCHAR')]

So in the list, if the values of two elements after the pipe(|) is same, I have to club the values before pipe(|) as comma separated values.
The clubbing should occur into the element which is placed first out of the two.
Thanks in advance.

A: Try groupby:
from itertools import groupby
l = [('245|CALENDAR_DATE-DATE'), ('129|AREA-VARCHAR'),('450|DIVISION-VARCHAR'),('678|CALENDAR_DATE-DATE'),('298|DIVISION-VARCHAR')]
print([','.join([x.split('|')[0] for x in v]) + '|' + i for i, v in groupby(sorted(l, key=lambda x: x.split('|')[1]), lambda x: x.split('|')[1])])

Output:
['129|AREA-VARCHAR', '245,678|CALENDAR_DATE-DATE', '450,298|DIVISION-VARCHAR']

A: First you may keep the numbers related to a string together, use a dict for this : key is the string, value a list if the ints
occurences = {}
for value in values:
    content = value.split("|")
    occurences[content[1]] = occurences.get(content[1], []) + [content[0]]

print(occurences)  # {'CALENDAR_DATE-DATE': ['245', '678'], 'AREA-VARCHAR': ['129'],
                   #  'DIVISION-VARCHAR': ['450', '298']}

Then just concat each pairs using your formatting
result = [','.join(v) + '|' + k for k, v in occurences.items()]

print(result) # ['245,678|CALENDAR_DATE-DATE','129|AREA-VARCHAR','450,298|DIVISION-VARCHAR']


text:
Q: Consul Through SSH VPN I'm attempting to connect an existing cluster to a remote AWS EC2 instance. I'm using OpenSSH (ssh -w) to create tunnel device something like this:
https://help.ubuntu.com/community/SSH_VPN
I'm trying to connect one of my consul servers running linux to the AWS instance also running linux (ubuntu 14.04).
I can get the tunnel setup and ping each machine however thats where I start to get fuzzy on what to do next.
I have a private IP address on eth0 of 10.x and a 192.x on tun0.
Which one should I bind consul to?
How can I make it so the other Consul Servers know how to connect to AWS through this connection?
I would like vault running on each of the 3 local servers to be available from AWS
I'm using Ubuntu 14.04 with OpenSSH. Consul 0.5.2
Thanks in advance for the help.


text:
Q: I want to get value of first column row on eack href click in HTML table I want to get the first column row value on each row href click EDIT . for eg if i click on first row href then i should get alert with its first column row value .
$(document).ready(function () {
        var jsonData = [{
            id: 'A01',
            name: 'Fadhly'
        }, {
            id: 'A02',
            name: 'Permata'
        }, {
            id: 'A03',
            name: 'Haura'
        }, {
            id: 'A04',
            name: 'Aira'
        }];

        $.each(jsonData, function (key, val) {
            var tr = '
';
            tr += '' + (key + 1) + '	';
            tr += '' + val.id + '	';
            tr += '' + val.name + '	';
            tr += 'Edit</a	';
            tr += '
';
            $('tbody').append(tr);
        });

My HTML Code

  #
  Id
  Name
  Action

A: Given a generated HTML structure as follows with n rows being dynamically added to
:

      #
      Id
      Name
      Action

      1
      2
      3

        Edit

You could use the following jQuery to execute alert() of the text within the first column of the respective row using click handler with a context provided:
$(document).ready(function(){
    $('tbody').on('click', 'a', function(){
        var value = $(this).closest('tr').find('td').first().text();
        alert(value);
    });
});

Here is a jsfiddle demonstrating the functionality. It demonstrates the value of the first column being alerted as well as shows dynamic/added rows via click event executing the event on  click. This is because the  elements aren't directly targeted, they are supplied as context to permanent DOM element such as  which won't be added or removed.
Update
If you need to grab other columns you could structure the jQuery query using eq() to grab a zero (0) based index. For example if you need the second column you could:
// first column
var value = $(this).closest('tr').find('td').eq(0).text();

// second column
var value = $(this).closest('tr').find('td').eq(1).text();

// third column
var value = $(this).closest('tr').find('td').eq(2).text();

Hopefully that helps!

A:     $.each(jsonData, function (key, val) {
        var tr = '
';
        tr += '' + (key + 1) + '	';
        tr += '' + val.id + '	';
        tr += '' + val.name + '	';
        tr += '<button class="delete" data-key="' + (key + 1) + '" onclick="alert('+(key+1)+')">Edit</button>	';
        tr += '
';
        $('tbody').append(tr);
    });

Simply add it to the onclick attribute...

A: check this out.
this works perfectly
$(document).ready(function () {
        var jsonData = [{
            id: 'A01',
            name: 'Fadhly'
        }, {
            id: 'A02',
            name: 'Permata'
        }, {
            id: 'A03',
            name: 'Haura'
        }, {
            id: 'A04',
            name: 'Aira'
        }];

        $.each(jsonData, function (key, val) {
            var tr = '
';
            tr += '' + (key + 1) + '	';
            tr += '' + val.id + '	';
            tr += '' + val.name + '	';
            tr += '<button class="delete" data-key="' + (key + 1) + '">Edit</button>	';
            tr += '
';
            $('tbody').append(tr);
        });

         $('tbody .delete a').click(function(){
             alert($(this).closest('tr').find('td:first-child').text());
         });
});

here is the updated jsfiddle link. check it out.
https://jsfiddle.net/86n7qkpe/


text:
Q: Persistent Bar is Crashing with bootstrap I want to make a navbar in footer of my codeigniter web project. I found a problem.
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

That stylesheet is crashing with the sliding menu. It make my searching input messed up too.

When i choose the account it will display something like this. The filling inside the sliding menu put above the toolbar. And the slider didn't work anymore.

But when i'm reload the account page it will display the better page although the searching still messed up.

I don't know what to do. It would be great if u can help me. Thank you . .
View Home
<!DOCTYPE html>

        <title>home</title>
        <link href="<?php echo base_url();?>css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />

        <link href="<?php echo base_url();?>css/style.css" rel="stylesheet" type="text/css" media="all" />

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="keywords" content="Food shop Responsive web template, Bootstrap Web Templates, Flat Web Templates, Andriod Compatible web template,
        Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyErricsson, Motorola web design" />

        <link href='http://fonts.googleapis.com/css?family=Rokkitt:400,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Lobster+Two:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

        <link href="<?php echo base_url();?>css/index.css" rel="stylesheet" type="text/css" media="all" />
        <link rel="stylesheet" href="<?php echo base_url();?>css/imgslider.css" type="text/css" media="screen" />

        <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Menu

                <?php if($tipeUser=="user"){?>

Welcome <?php echo $nama;?>

<a href="<?php echo base_url();?>home_controller/" style="color:white">Home

<a href="<?php echo base_url();?>home_controller/my_voucher/0" style="color:white">My Voucher

<a href="<?php echo base_url();?>home_controller/my_profile" style="color:white">Profile

<a href="<?php echo base_url();?>home_controller/logout" style="color:white">Logout

                    <?php } else if($tipeUser=="restoran"){ ?>

Welcome <?php echo $nama;?>

<a href="<?php echo base_url();?>home_controller/" style="color:white">Home

<a href="<?php echo base_url();?>home_controller/dashboard" style="color:white">Dashboard

<a href="<?php echo base_url();?>home_controller/voucher_management" style="color:white">Voucher Management

<a href="<?php echo base_url();?>home_controller/logout" style="color:white">Logout

                    <?php } else if($tipeUser==""){  ?>

<a href="<?php echo base_url();?>home_controller/" style="color:white">Home

<a href="<?php echo base_url();?>home_controller/login" style="color:white">Login / Register

<a href="<?php echo base_url();?>home_controller/list_voucher" style="color:white">Voucher

<a href="<?php echo base_url();?>home_controller/list_restoran" style="color:white">Restaurants

                        <?php
                        if($data_kategori->num_rows()>0)
                        {
                            foreach ($data_kategori->result() as $rows)
                            { ?>

<a href="<?php echo base_url();?>home_controller/Type/<?php echo $rows->id_jenis_makanan; ?>"><img src="<?php echo $url_image;?>category/<?php echo $rows->id_jenis_makanan; ?>/<?php echo $rows->img_jenis_makanan; ?>" width="100%" class="img-responsive" alt="">

                        <?php } } ?>

<a href="<?php echo base_url();?>home_controller/faq" style="color:white">Faq

<a href="<?php echo base_url();?>home_controller/blog" style="color:white">Blog

                <?php } ?>

                                <button class="toggle-button"></button>

                                <?php echo form_open('home_controller/search_bar');?>

                                    <form>
                                        <input type="text" id= "input-keyword" name="input-keyword" placeholder="Search ..." value="<?php echo set_value('input-keyword')?>" >
                                        <input type="submit" value="">
                                    </form><?php echo form_close(); ?>

                    <?php
                        if($dataSliderVoucher->num_rows()>0)
                        { ?>

                            <?php
                                $i = 1;
                                foreach ($dataSliderVoucher->result() as $rowsSliderVoucher)
                                {
                                    if($i==1)
                                    {
                                    ?>

                                        <a href="<?php echo base_url();?>home_controller/Details/<?php echo $rowsSliderVoucher->id_restoran?>"><img src="<?php echo $url_image;?>restaurant/<?php echo $rowsSliderVoucher->id_restoran?>/deals/<?php echo $rowsSliderVoucher->gambar_voucher?>" height="200em" class="img-responsive" alt="">

<?php echo $rowsSliderVoucher->nama_voucher?>

                                    <?php }
                                    else
                                    { ?>

                                        <a href="<?php echo base_url();?>home_controller/Details/<?php echo $rowsSliderVoucher->id_restoran?>"><img src="<?php echo $url_image;?>restaurant/<?php echo $rowsSliderVoucher->id_restoran?>/deals/<?php echo $rowsSliderVoucher->gambar_voucher?>" height="200em" class="img-responsive" alt="">

<?php echo $rowsSliderVoucher->nama_voucher?>

                                    <?php }
                                $i++;} ?>

                            Previous

                            Next

                <?php } ?>

Latest Deals

                            <?php if($dataLastDeals->num_rows()>0)
                                {
                                    foreach ($dataLastDeals->result() as $rowsLastDeals)
                                    { ?>

                                            <?php if($tipeUser=="user" || $tipeUser==""){ ?>

                                                    <?php
                                                        if($rowsLastDeals->sisa_voucher > 0) {
                                                        ?>

                                                        <a href="<?php echo base_url();?>home_controller/GetVoucher/<?php echo $rowsLastDeals->id_voucher;?>">
                                                            <img src="<?php echo base_url();?>.././img/restaurant/<?php echo $rowsLastDeals->id_restoran;?>/deals/<?php echo $rowsLastDeals->gambar_voucher;?>" class="img-responsive-search" alt="" style="object-fit: fill;height: 90px; margin-bottom:10px;">

                                                        <?php
                                                        }
                                                        else{ ?>
                                                        <img src="<?php echo base_url();?>.././img/restaurant/<?php echo $rowsLastDeals->id_restoran;?>/deals/<?php echo $rowsLastDeals->gambar_voucher;?>" class="img-responsive-search" alt="" style="object-fit: fill;height: 90px; margin-bottom:10px;">

                                                        <?php }
                                                    ?>

                                            <?php } ?>

                                <?php }} ?>

<a href="<?php echo base_url();?>home_controller/" data-transition="pop">Home

<a href="<?php echo base_url();?>home_controller/login" data-transition="pop">Account

<a href="<?php echo base_url();?>home_controller/list_voucher">Voucher

<a href="<?php echo base_url();?>home_controller/faq">Faq

<a href="<?php echo base_url();?>home_controller/blog">Blog

    <?php if($this->session->flashdata('message')) :
    echo "";
    endif; ?>


text:
Q: Flutter AutoComplete not showing all suggestions im using intellij idea for flutter,
before when i want to use colors or any kind of style in flutter i used to only type any word and a suggestion would pop up with correct suggestions , check the image below plz,
i used to type - white - or any color and auto complete suggestion pop up with Colors.white or when i want to change font size i only type (si) and a suggestion window pop up with fontSize,
just recently since 2 days, its not working any more, when i type white, it wont show quick suggestions anymore
white
strange thing is it's working on other places like when i type (cen) it shows correct suggestions (check image below plz) :
center
i have the latest version of intellij idea


text:
Q: SQL: Select statement to return ratio of 2 column values I have a table of electronic testing data containing pass/fail results for pairs of components at given voltages. It looks like this:
Component_A|Component_B|Voltage|Result
1           2           1.0     Pass
1           2           1.0     Pass
1           2           1.0     Fail
1           2           1.0     Fail
1           2           2.0     Pass
1           2           2.0     Pass
1           2           2.0     Pass
1           2           2.0     Pass
3           4           1.0     Pass
3           4           1.0     Pass
3           4           1.0     Pass
3           4           1.0     Pass
3           4           2.0     Pass
3           4           2.0     Pass
3           4           2.0     Pass
3           4           2.0     Pass

For each Component_A, Component_B, Voltage, I'd like to show the failure ratio for the given Component_A/Component_B/Voltage combination as well as the failure ratio for that combination of Component_A/Component_B. The expected output would be as follows:
Component_A|Component_B|Voltage|Voltage_Fail_Ratio|Component_Fail_Ratio
1           2           1.0     2/4(0.5)            2/8(0.25)
1           2           2.0     0/4(0)              0/8(0)
3           4           1.0     4/4(0)              0/8(0)
3           4           2.0     0/4(0)              0/8(0)

It would be great to have some options (using unions or subqueries... the more options the better). I've tried a writing a subquery to at least get the voltage_fail_ratio, but it doesn't report component/voltage combos with no failures and I am not sure how to get the component_fail ratio:
SELECT f.component_a,f.component_b,f.voltage,f.failcount,p.passcount, f.failcount/(f.failcount+p.passcount) FROM
 ((SELECT component_a,component_b,voltage, count(*) as failcount from `tests` where
  result='FAIL'
 GROUP BY component_a,component_b,voltage) f INNER JOIN
 (SELECT component_a,component_b,voltage, count(*) as passcount from `tests` where
  result='PASS'
 GROUP BY component_a,component_b,voltage) p on p.component_a=f.component_a and p.component_b=f.component_b and
 p.voltage=f.voltage);

http://sqlfiddle.com/#!9/623ae/1

A: I think this is what you want - it computes the Voltage_Fail_Ratio and Component_Fail_Ratio in two separate subqueries that are then joined on matching component_a and component_b values:
SELECT t1.component_a, t1.component_b, t1.Voltage, t1.Voltage_Fail_Ratio, Component_Fail_Ratio
FROM (
  SELECT component_a, component_b, Voltage,
         SUM(result = 'FAIL') / COUNT(*) AS Voltage_Fail_Ratio
  FROM tests
  GROUP BY component_a, component_b, Voltage
  ) t1
JOIN (
  SELECT component_a, component_b,
         SUM(result = 'FAIL') / COUNT(*) AS Component_Fail_Ratio
  FROM tests
  GROUP BY component_a, component_b
  ) t2 ON t2.component_a = t1.component_a AND t2.component_b = t1.component_b
;

Output:
component_a     component_b     Voltage     Voltage_Fail_Ratio  Component_Fail_Ratio
1               2               1           0.5                 0.25
1               2               2           0                   0.25
3               4               1           0                   0
3               4               2           0                   0

Demo on SQLFiddle

A: This is somehow similar with @Nick's but using views with WITH.
Just to give you more option.
WITH for_volt_fail_ratio AS(
  SELECT com_a, com_b, volt, SUM(result = 'FAIL') / COUNT(*) AS Voltage_Fail_Ratio
  FROM tests
  GROUP BY com_a, com_b, volt),
 for_com_fail_ratio AS(
  SELECT com_a, com_b,SUM(result = 'FAIL') / COUNT(*) AS Component_Fail_Ratio
  FROM tests
  GROUP BY com_a, com_b),
 sh AS(
   SELECT tb1.com_a,tb1.com_b,tb1.volt,tb1.Voltage_Fail_Ratio,tb2.Component_Fail_Ratio
   FROM for_volt_fail_ratio tb1 INNER JOIN for_com_fail_ratio tb2 ON (tb1.com_a=tb2.com_a AND tb1.com_b=tb2.com_b)
  )
 SELECT * FROM sh

Demo

A: The simplest approach is conditional aggregation:
select component_a, component_b, voltage,
        sum(case when result = 'PASS' then 1 else 0 end) as num_pass,
        sum(case when result = 'FAIL' then 1 else 0 end) as num_fail,
        avg(case when result = 'FAIL' then 1.0 else 0 end) as fail_rate
from tests
group by component_a, component_b, voltage;

If you are indeed using MySQL (as the SQL Fiddle suggests), you can simplify this to:
select component_a, component_b, voltage,
        sum(result = 'PASS') as num_pass,
        sum(result = 'FAIL') as num_fail,
        avg(result = 'FAIL') as fail_rate
from tests
group by component_a, component_b, voltage


text:
Q: read Data URL with File API polyfill I am trying to use the File API library (https://github.com/mailru/FileAPI) as a fallback for browsers which do not support the File API, in order to read a file as a Data URL and pass that on to another function.
I have this code:
function handleFileSelect(event) {
    // If supported, use native File API.
    if(window.FileReader != null) {
        console.log('Using native File API.'); // !
        var files = event.target.files;
        for(var i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onload = function(event) {
                insertImage(event.target.result);
            };
            reader.readAsDataURL(f);
         }
    }
// Otherwise, use fallback polyfill for browsers not supporting native API.
else {
    console.log('Using polyfill for File API.'); // !
    var file = FileAPI.getFiles(event.target);
    FileAPI.readAsDataURL(file, function(evt) {
        console.log(evt);
    });
  }
}

However, console.log(evt) returns an Object which reports error: "filreader_not_support_DataURL".
Have I done something wrong with File API polyfill or is there a shim or other polyfill I have to use to get data URLs to work?
Thanks.
-- Sam.

A: Feature is implemented yet via flash - thanks to the author of FileAPI plugin.
// bind to your upload container
var el = document.getElementById('uploadElementId');
FileAPI.event.on(el, 'change', function (evt/**Event*/) {
    var files = FileAPI.getFiles(evt);
    // get Data URL for the first file
    FileAPI.readAsDataURL(files[0], function (dataUrlObject) {
        if (dataUrlObject.type == 'load') {
            // Success
            var dataUrl = dataUrlObject.result;
        }
    });
});

Whole thread here: https://github.com/mailru/FileAPI/issues/153

A: I think the error message is clear. You want to use this polyfill to read file as Data URL and it tell you that it dont support Data URL. So I assume there is no other way to do this.


text:
Q: Best way to iterate to a part of an array based on value? I have an php-array like this:
$students = array(
  array(1, 'James', 'Brown', 10, 50),
  array(2, 'John', 'Doe', 10, 40),
  array(3, 'Adam', 'Works', 10, 40));

Where the columns represent id, first name, last name, category, and level. As example I use three rows... in practice I use many more.
Now I need to group print the results based on column (category or level) and a specific value. For example, I want to print (echo) all students in category 10. I can loop through each record and check the category; if 10 then print. The same applies for level 40. Loop through the whole set again and check the level; if 40 then print.
With an eye on performance, is there a smarter way to achive this? For example, first sort or filter?
I could choose to query the database many times but I doubt if this is the best way. I guess manipulating the array is better.
Thanks for your support!

A: The most straightforward way to do this is with the array_filter() function. But if these values come from a database, you're probably better off writing better queries.
$ cat array-filter.php
<?php
$students = array(
  array(1, 'James', 'Brown', 10, 50),
  array(2, 'John', 'Doe', 10, 40),
  array(3, 'Adam', 'Works', 10, 40));

$level_40 = array_filter($students, function($a) {return $a[4]==40 ? true : false;});
print_r($level_40);
?>

$ php array-filter.php
Array
(
    [1] => Array
        (
            [0] => 2
            [1] => John
            [2] => Doe
            [3] => 10
            [4] => 40
        )

    [2] => Array
        (
            [0] => 3
            [1] => Adam
            [2] => Works
            [3] => 10
            [4] => 40
        )

)

The callback function just compares the fifth column to the integer literal 40. The fifth column has index 4, not 5, hence the expression $a[4]==40 ?.
If you're getting this data from a database, you're probably better off writing better SQL. To get all the students whose level is 40, you'd write something like
select *
from students
where level = 40
order by student_id;

The result set will contain exactly the right rows, so you don't need to filter them. And they'll be in exactly the right order, so you don't need to sort them.


text:
Q: Add a MenuItem to Menu at specific position or group programmatically I have a
<android.support.design.widget.NavigationView
  app:menu="@menu/drawer"
/>

with the following menu items:
<item
    android:id="@+id/main_item"
    android:icon="@drawable/ic_menu_main"
    android:title="@string/app_name"/>

<group
    android:id="@+id/some_group"
    android:checkableBehavior="single"/>

<item
    android:id="@+id/teams_item"
    android:icon="@drawable/ic_menu_teams"
    android:title="@string/teams"/>

Now I want to add an item either to the some_group or just below it.
I tried:
MenuItem mi = menu.add( R.id.soume_group, someId, NONE, "some name" );

or
MenuItem mi = menu.add( R.id.soume_group, someId, 2, "some name" );

but the items are added at the bottom of the menu.
How to fix my problem?
TIA

A: You can use the orderInCategory to define the order
    <item
        android:id="@+id/main_item"
        android:icon="@drawable/ic_menu_main"
        android:orderInCategory="100"
        android:title="@string/app_name"/>

    <item
        android:id="@+id/teams_item"
        android:icon="@drawable/ic_menu_teams"
        android:orderInCategory="1000"
        android:title="@string/teams"/>

if you want to insert between main_item and teams_item you can use orderInCategory that is between
// 500 is between main_item(100) and teams_item(1000)
MenuItem mi = menu.add( NONE, someId, 500, "some name" );


text:
Q: Show the code (i.e "&entity_name;"), not the corresponding character If I write   in a HTML file the browser automatically translates it to its corresponding character, in this case a space.
How can I escape from this phase? I mean, if I would like to print just the code (i.e.  ) how can I prevent the browser from doing that?

A: You can't stop the browser from treating HTML as HTML.
If you want to include a & as data instead of as the start of a character reference, then use the character reference for it:

A: For this you will need JQuery.
Try .text() method. http://api.jquery.com/text/
Get the body content an then replace it with text.
Means: $('body').text($('body').html());.
This will give you an output of your html in plain Text. Actually you can do this with other Elements as well. Replace the Word body with the element, class or id you need.


text:
Q: Django form help_text best practices we've got into an argument during a code review. Where is the best place to keep long form help text in a django project?
Situation: We need to add relatively long (about 320 characters) help texts to a field. For form rendering we are using ModelForm. For form rendering we are using bootstrap library.
Opinion A: Add it directly into an HTML template.
# template.html

     {{ form.field.label }}
    {{ form.field }}

        Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text.

Pros:

*

*It is better to keep long help_text inside html file, not .py

*In the future we might want to add HTML tags, and it would be better to have it inside HTML file too.

Option B: Add it to the ModelForm's Meta.
# forms.py
help_texts = {
    'field': 'Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text Help text.'
}
# template.html
{% bootstrap_field form.field %}

Pros:

*

*Field is autogenerated and not hardcoded.

*In the future we can have HTML inside it too with mark_safe().

What do you think about the options? Could you please share your opinion about the best way to handle help_text?

A: IMHO this whole idea of "field auto-generation" is horrible. OK, some field properties come from the model, but most of them should be in the HTML itself.
The project django-silhouette solves this problem very well and that's what I'm moving to on current projects.
As for the question itself, I'd put the help text inside the HTML, as a temporary solution until you fix the problem of repeating yourself in the HTML (which can be with the help django-silhouette or just shared HTML partials).


text:
Q: How to color label a stack of 65 2D images? I segment a 2D particles images and concatenate them in a stack of (64,1000,1000). When I visualize a binary volume I can visualize all the frames but once I labeled the stack using label2rgb I just visualize one frame. Please can you help me to visualize all the frames by keeping for each particle the same color label along all the frames.
blob = measure.label(im_3d, background=0)
color_label = skimage.color.label2rgb(blob , bg_label=0)
skimage.io.imsave(f'Detected_particles_im_3d.tif', im_3d)


text:
Q: Mage 1.9.2.4 1: 1 website, 1 catalog, multiprice, multicurrency I read many many answers. Many have similar questions, but at the end the solution seems to me to build many websites.
My need: Magento 1.9.2.4 to implement 1 website (eg brand.com) with 1 catalog of few products (products are all the same) with different currencies and different prices per country + transactions in the currency of the country NOT the base currency.
Requirement: brand.com/US in USD, brand.com/UK in GBP, brand.com/FR in EUR, brand.com/CH in CHF etc Of course the different folders /US /UK /FR etc will have different languages.
Requirement: Product1 costs 56 USD in US, 57 CHF in Swiss, 62 EUR in EU, etc Product2 same behaviour, etc
Requirement: transactions in US all in USD, in Europe all in EURO, etc
The currency used in transactions must be the one selected by the customer and not the default global one (eg brand.com/US in USD, brand.com/UK in GBP).
OK to consider Magento 2.xx and extensions (either for Mage 1.9 or 2.xx)
OK to create many stores (but don't want to have many catalogues as the products are the same)
PS Customers don't mix the carts with products from different stores, as once changing the store, the cart resets.

A: I see that you can do it by these 2 extensions:

*

*Magento 1: https://bsscommerce.com/magento-multistore-pricing.html

*Magento 2: https://bsscommerce.com/magento-multiple-store-view-pricing-for-magento-2.html
In your case, this module solve your issues by:
+ set base currency for each country, not use the only base currency of the whole website as default Magento. It means brand.com/US in USD, brand.com/UK in GBP,... as you said and of course, transaction is made with base currency of each country.

*

*Set up different prices for the same products per country as you want. Default Magento doesn't allow you to do this one


text:
Q: Handling Posix signals in a library Is it possible to somehow handle Posix signals twice? I need to perform some actions when the process terminates in a library I'm writing. I do it simply like this:
signal(SIGSEGV, sig_handler);
signal(SIGABRT, sig_handler);
signal(SIGFPE, sig_handler);
signal(SIGINT, sig_handler);

This works but is not entirely acceptable as the user of my library may want to handle the signals himself for other reasons. I suppose I would therefore interfere by doing it.
Would it be possible to somehow handle the signal in my sig_handler and then to "rethrow" it so that it is available transparently for anyone else needing it? By "transparently" I also mean that I don't want to ask the user to provide some "custom callbacks", as my library has a defined interface already, no real header. I need some callback in any case the process terminates, install transparently for the user and handle transparently for the user. Is there anything like this? It is sufficient this solution works on Linux. Thanks!

A: The best option is probably to use sigaction to get the current callback and place yours in the middle. This SO answer explains it. However if the application sets it after you do you won't see any call at all.
To get the current one:
struct sigaction sa;
sigaction(SIGINT, NULL, &sa);
...

To set yours:
struct sigaction sa;
...
sigaction(SIGINT, &sa, NULL);

In your callback you call the first one.


text:
Q: How to create a table of contents to Jekyll blog post? If I have a page/post in Jekyll with headers, is it possible to auto-generate a table-of-contents/outline for navigation? Something akin to the top matter of a Wikipedia article.

A: That is the markup parser's task.
In case of Markdown one of the syntax extensions defines Automatic generation of the table of contents:
* This will become a table of contents (this text will be scrapped).
{:toc}

This works in Maruku and kramdown.

A: I have TOC for Jekyll blog which looks similar to Wikipedia TOC

So all my Jekyll posts have a Table of Contents section. It can be done just using kramdown.
Use this code inside your post where you want the TOC to appear
* Do not remove this line (it will not be displayed)
{:toc}

And use this CSS to style it like Wikipedia TOC
// Adding 'Contents' headline to the TOC
#markdown-toc::before {
    content: "Contents";
    font-weight: bold;
}

// Using numbers instead of bullets for listing
#markdown-toc ul {
    list-style: decimal;
}

#markdown-toc {
    border: 1px solid #aaa;
    padding: 1.5em;
    list-style: decimal;
    display: inline-block;
}

Use appropriate colors that suit your blog.
That is it!
TOC can also be done with the help of jekyll-table-of-contents, if in any case the above method doesn't work. This one uses Jquery and a js file.
Here is the detailed guide on how I did it: Jekyll TOC

A: I'm assuming you mean a list of all H1, H2 elements etc in the content itself?  I don't think Jekyll has anything built-in to handle that.  I suspect the easiest way is to let Javascript generate it for you once the page has rendered, using something like this jQuery plugin, or one of the many other plugins/snippets available.

A: you can use this code before your contents.
<link rel="stylesheet" href="http://yandex.st/highlightjs/6.2/styles/googlecode.min.css">

A: https://github.com/allejo/jekyll-toc provides very easy way to add TOC to your jekyll page.

*

*Download the latest toc.html file (caution! should be raw file)

*copy this file to _includes folder.

*add this line before {{content}}: {% include toc.html html=content %}

A: All these methods specified didn't work for me for the GitHub pages blog, also I wanted to simply use the liquid for the purpose.
Here is the detailed description.
How to add toc in Jekyll blog
Here is how it looks.


text:
Q: Ubuntu 11.10 resource hog? Ever since I updated to Ubuntu 11.10 my computer has been getting hot and seems like the resources have been more hogged causing my computer to constantly sound like its doing something intense.
I've disabled Unity and am using Gnome session fallback.
Is there anyone else with this issue?

*

*Best way to explain this is that I feel as if 11.10 is using a LOT more resources than 11.04 did - and I would like to know of a way to make it run smoother and less of a hog

A: Yes, there are issues with 11.10. You can solve some of them by paying close attention to your system, whereas others are very hard to fix. Fortunately, most of these issues are gone Precise Pangolin (to become 12.04 in April) so we have good times ahead. If it's a big problem for you, then I would recommend that you install 10.04 if that's possible, since that will be upgradeable to 12.04 when it's released. Or, if you're a bit more adventurous, you can upgrade/install 12.04 now. It is under development, so you'll have to watch out a little bit when you install upgrades, but there have been rather few issues with it. On both my desktop and laptop, 12.04 is much better than 11.10. Battery time on my laptop has gone from 3.5-4 hours to more than 5 hours.
If it's not too big a problem, and you don't feel too adventurous, then I would recommend just waiting a little while and upgrade to 12.04.


text:
Q: How to achieve parallelism and waiting for response that is used in subsequent steps in reactive programing I am trying to replicate a scenario that we face in the production, which contains a mix of parallelism and waiting until some part is completed, dependent on the response.
Below is a replica of the code.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static java.lang.Integer.sum;

public class Traditional {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Traditional traditional = new Traditional();
        Instant start = Instant.now();
//        traditional.executeMethod();
        Instant end = Instant.now();
        System.out.println("TimeTaken to execute sync :: " + Duration.between(start, end));
        start = Instant.now();
        traditional.executeMethodAsync();
        end = Instant.now();
        System.out.println("TimeTaken to execute async :: " + Duration.between(start, end));
        start = Instant.now();
        traditional.executeMethodReactive();
        end = Instant.now();
        System.out.println("TimeTaken to execute Reactively:: " + Duration.between(start, end));
    }

    private Integer executeMethodReactive() {
        Scheduler scheduler = Schedulers.parallel();
        Mono<Integer> a = Mono.just(firstMethod());
        Mono<Integer> b = Mono.just(secondMethod());
        Mono<Integer> c = Mono.just(thirdMethod());

        Mono<Integer> externalMono = Mono.zip(a, b, c).subscribeOn(scheduler).flatMap(data -> {
            Integer total = sum(data.getT1(), data.getT2());
            Integer diff = diff(data.getT3(), data.getT1());

            return Mono.zip(Mono.just(divide(total, diff)).subscribeOn(scheduler), Mono.just(multiply(total, diff)).subscribeOn(scheduler))
                    .flatMap(innerzip -> Mono.just(innerzip.getT1() + innerzip.getT2()));
        });

        Integer value = externalMono.block(Duration.ofMinutes(1));
        System.out.println(value);
        return value;

    }

    private int executeMethod() {
        int a = firstMethod();
        int b = secondMethod();
        Integer c = thirdMethod();

        Integer total = sum(a, b);

        Integer diff = diff(c, a);

        Integer d = divide(total, diff);

        Integer multi = multiply(total, diff);

        int value = d + multi;
        System.out.println(value);
        return value;
    }

    private Integer executeMethodAsync() throws ExecutionException, InterruptedException {

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(this::firstMethod);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(this::secondMethod);
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(this::thirdMethod);
        CompletableFuture.allOf(future1, future2, future3).join();

        Integer total = sum(future1.get(), future2.get());

        Integer diff = diff(future3.get(), future1.get());

        CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> divide(total, diff));
        CompletableFuture<Integer> future5 = CompletableFuture.supplyAsync(() -> multiply(total, diff));

        Function<Void, Integer> function = (voidValue) -> {
            try {
                return future4.get() + future5.get();
            } catch (InterruptedException | ExecutionException e) {
                return null;
            }
        };
        CompletableFuture<Integer> finalTotal = CompletableFuture.allOf(future4, future5).thenApplyAsync(function);
        System.out.println("Final Total :: " + finalTotal.get());
        return finalTotal.get();
    }

    private int divide(Integer total, Integer diff) {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("divide");
        return total / diff;
    }

    private int multiply(Integer total, Integer diff) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("multiply");
        return total * diff;
    }

    private Integer diff(Integer a, Integer b) {
        return a - b;
    }

    private int firstMethod() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("1");
        return 1;
    }

    private int secondMethod() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("2");
        return 2;
    }

    private int thirdMethod() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("3");
        return 3;
    }
  }

sequential execution of the program is taking 18sec and Async execution is taking 11 sec, I am trying to achieve the same in reactive programming. How to achieve this?
Update
Based on the clue provided by martin, rewrote the method as below and it is working
private Integer executeMethodReactive() {

        Scheduler scheduler = Schedulers.parallel();

        Mono<Integer> externalMono = Mono.zip(Mono.fromCallable(this::firstMethod).log("first").subscribeOn(scheduler),
                Mono.fromCallable(this::secondMethod).log("second").subscribeOn(scheduler),
                Mono.fromCallable(this::thirdMethod).log("third").subscribeOn(scheduler)).flatMap(data -> {
            Integer total = sum(data.getT1(), data.getT2());
            Integer diff = diff(data.getT3(), data.getT1());

            return Mono.zip(Mono.fromCallable(() -> divide(total, diff)).log("divide").subscribeOn(scheduler),
                    Mono.fromCallable(() -> multiply(total, diff)).log("multiply").subscribeOn(scheduler))
                    .flatMap(inner -> Mono.just(inner.getT1() + inner.getT2()));
        });

        return externalMono.block();
    }


text:
Q: Large files split when uploaded to cloud (B2 Backblaze) I'm uploading some ISO files which I made from DVDs to B2 Backblaze cloud. But I see they split there:

There are also some 0 bytes size files, which seems strange.
How can this be explained?
I'm curious if the same happens in other cloud storage services.


text:
Q: Positive definite - Inverse of sparse symmetric matrix Consider a matrix $P\in \mathbb{R}^{n\times n}$ such that at most $m<n$ elements of each column are non zero and $P$ is symmetric. I would like to find the  sufficient condition(s) such that $P^{-1}$ is positive definite. Given the positions of non zero elements in $P$ what are their values such that $P$ is positive definite.

A: If $P$ is an invertible real symmetric matrix, $P^{-1}$ is positive definite iff $P$ is positive definite.  There are many equivalent conditions to positive definiteness.


text:
Q: LIBGDX - how to make dynamic polygons? I am making 2D game, where I can move bones of hero. I don't want to use spritesheets.
Hero's legs and arms are made by polygons, because I want to easily change it's colour.
But I have problem with "dynamic parts of body" i mean knee, ankle and others joints - I must remake polygons for this parts every frame, because for example I change knee angle - so I must create new polygon for knee joint.
This makes game laggy on mobile devices :/
Maybe I'm doing it wrong. How to make dynamic polygons in LIBGDX?

A: If you want to rotate a part of your character you can use the Polygon class
http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Polygon.html
And use the rotate function.
Spritesheets are not that bad anyways, I would rather use them.


text:
Q: Detail in construction on Ramanujan graph by LPS Consider this paper written by Lubotzky, Phillips and Sarnak (1986) on expander graphs.
Below definition 2.2, they let $p,q$ be primes both congruent to $1\mod{4}$. Then they claim that there are $p+1$ vectors $a=(a_0,a_1,a_2,a_3)$ where $a_0\in\mathbb{N}$, $a_j\in\mathbb{Z}$, $a_0$ is odd and $a_j$ even for $j=1,2,3$, and $a_0^2+a_1^2+a_2^2+a_3^2=p$.
Regretfully I have learned little about number theory and I can't figure out why there exists (maybe exactly?) $p+1$ such vectors.
Hope I have clearly expressed my question and thanks for your help!

A: Jacobi's four square theorem says that the number of vectors $(w,x,y,z)$ for which $w^2+x^2+y^2+z^2=p$ is exactly $8(p+1)$, where there are no restrictions on $w,x,y,z$. When $p$ is 1 modulo 4, exactly one of the entries is odd, and since it is nonzero, is either positive or negative; say it is $x$, so that $(w,x,y,z)$ and $(w,-x,y,z)$ are both valid vectors. There are four positions in which to place the odd entry, and there are two possibilities for the sign of that entry, so if we want our vector to have the same shape as LPS requires (positive odd first followed by even) the Jacobi guarantee overcounts by a factor of 8.


text:
Q: Define a set $I$ such that $\cup_{i\in I}{i} = \cup_{a\in A} (\cap_{\alpha\in a}{\alpha})$ (Garling vol. 1, ex. 1.2.5) Exercise 1.2.5 from DJH Garling's "A Course in Mathematical Analysis, vol. 1":
Define a set $I$ such that
$\cup_{i\in I}{i} = \cup_{a\in A}
(\cap_{\alpha\in a}{\alpha})$
We came up with the following solution. Will you please verify it.
$$ B = \cup_{a \in A} a $$
$$ C = \cup_{\alpha \in B} \alpha $$
$$I = \{ c \in \mathcal P(C) : \\
\exists a \in A:
\forall \alpha \in a: c \subseteq \alpha
\} $$
So that the set $B$ contains members of members of $A$, and $C$ contains members of members of members of $A$.
We filter (by the Axiom of Separation) into $I$ only the sets with elements belonging to all the elements of a particular member of the $A$ set.
Note:
As far as I understand, Garling introduced the union axiom in a very concise form:
there exists $\cup_ { a \in A } a$, i.e. we can construct a union of all the members of a particular set.
Then he hints onto the not-so-strict, but convient forms of it, i.e.
$\cup_{a\in A}
(\cap_{\alpha\in a}{\alpha})$ which denotes a union of intersections of all members of all memebers of $A$.


text:
Q: Paging Not Working in ext.js grid, Binded with Ajax Call I am able to bind the grid with the ajax call but, i am not able to figure out how to make paging work.
I have also set the page size of the store still..
This is what i have tried
<script type="text/javascript">
    //Attach to onDOMReady event
    Ext.onReady(onReady);

    function onReady() {

        //Define the model for Ext User Grid.
        Ext.define('ExtUserGridModel', {
            extend: 'Ext.data.Model',
            id: 'UserId',
            fields: [{ name: 'UserId', type: 'int' }, { name: 'UserName', type: 'string' },
    { name: 'EmailId', type: 'string' }, { name: 'IsAdmin', type: 'bool' },
    { name: 'UserFName', type: 'string' }, { name: 'UserLname', type: 'string' },
    { name: 'PhoneNo', type: 'string' }, { name: 'DateOfBirth', type: 'string'}]
        });

        //data geting method for Ext User Grid
        var ExtUserStore = Ext.create('Ext.data.Store', {
            autoLoad: true,
            pageSize: 5,
            remoteSort: true,
            model: 'ExtUserGridModel',
            proxy: {
                type: 'ajax',
                url: 'ExtUsersGrid.aspx/GetExtUsers',
                headers: { 'Content-type': 'application/json' },
                reader: {
                    type: 'json',
                    //totalProperty: 'd.totalCount',
                    root: 'd.userData'
                },
                // sends single sort as multi parameter
                simpleSortMode: true
            }
        });

        // Create Ext User Grid to display data from store
        var grid = new Ext.grid.GridPanel({
            store: ExtUserStore, // Our store
            defaults: {
                flex: 1
            },
            disableSelection: true,
            loadMask: true,
            title: 'Ext Users Grid',
            columns: [ // Grid columns
                {dataIndex: 'UserName', header: 'User Name' },
                { dataIndex: 'EmailId', header: 'EmailId', width: 250 },
                { dataIndex: 'IsAdmin', header: 'IsAdmin' },
                { dataIndex: 'UserFName', header: 'First Name' },
                { dataIndex: 'UserLname', header: 'Last Name' },
                { dataIndex: 'PhoneNo', header: 'User PhoneNo' },
                { dataIndex: 'DateOfBirth', header: 'Birth Date', flex: 1}],
            renderTo: Ext.get('content'),
            // paging bar on the bottom
            bbar: Ext.create('Ext.PagingToolbar', {
                store: ExtUserStore,
                displayInfo: true,
                displayMsg: 'Displaying Records {0} - {1} of {2}',
                emptyMsg: "No Records to display"
            })
        });

Server Side Code
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
    public static Object GetExtUsers(String page, String limit)
    {
        //String page, String limit
        var extUserData = SampleDataManager.GetExtUsers();
        var result = new DataSet
        {
            userData = extUserData.Select(x => new ExtUserData
        {
            UserName = x.UserName,
            IsAdmin = ((Boolean)x.IsAdmin),
            EmailId = x.EmailId,
            UserFName = x.UserFName,
            UserLname = x.UserLname,
            PhoneNo = x.PhoneNo,
            DateOfBirth = x.DateOfBirth
        }),
            totalCount = extUserData.Count()
        };

        return result;
    }
  }
}

class DataSet
{
    public IQueryable<ExtUserData> userData { get; set; }
    public Int32 totalCount { get; set; }
}

class ExtUserData
{
    public Int32 UserId { get; set; }
    public String UserName { get; set; }
    public String EmailId { get; set; }
    public Boolean IsAdmin { get; set; }
    public String UserFName { get; set; }
    public String UserLname { get; set; }
    public String PhoneNo { get; set; }
    public String DateOfBirth { get; set; }
}

The jSON response i Get is
{"d":{"userData":[{"UserId":0,"UserName":"Rex","EmailId":"Vinaypratap.bhadauria@intsof.com","IsAdmin":true,"UserFName":"Vinay Pratap","UserLname":"Singh","PhoneNo":"8557989106","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Ramit","EmailId":"Ramit.gulati@intsof.com","IsAdmin":false,"UserFName":"Ramit","UserLname":"Gulati","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Haider","EmailId":"Haider.hussain@intsof.com","IsAdmin":false,"UserFName":"Haider","UserLname":"Hussain","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"BHupendra","EmailId":"Bhupendra.shukla@intsof.com","IsAdmin":false,"UserFName":"Bhupendra","UserLname":"Shukla","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Anirudh","EmailId":"anirudh.agarwal@intsof.com","IsAdmin":false,"UserFName":"Anirudh","UserLname":"Agarwal","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Sachin","EmailId":"Sachin.Singh@intsof.com","IsAdmin":false,"UserFName":"Sachin","UserLname":"Singh","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Akash","EmailId":"Akash.malhotr@intsof.com","IsAdmin":false,"UserFName":"Akash","UserLname":"malhotr","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"},{"UserId":0,"UserName":"Gautam","EmailId":"Gautam.bharadwaj@intsof.com","IsAdmin":false,"UserFName":"Gautam","UserLname":"Bharadwaj","PhoneNo":"1234567894","DateOfBirth":"03/29/1991"}],"totalCount":8}}

The grid Shows all the records and the pages tells it has showing given no of records Ie:5

A: I solved it like this
change the reader like this
        var ExtUserStore = new Ext.data.JsonStore({
            autoLoad: true,
            //autoLoad: { params: { start: 0, limit: 5} },
            pageSize: 5,
            model: 'ExtUserGridModel',
            proxy: {
                enablePaging: true, // replaces PagingMemoryProxy functionality
                type: 'ajax',
                url: 'ExtUsersGrid.aspx/GetExtUsers',
                headers: { 'Content-type': 'application/json' },
                reader: {
                    type: 'json',
                    totalProperty: 'd.totalCount',
                    root: 'd.userData',
                    model: 'ExtUserGridModel',
                    id: 'd.userData.UserId'
                }
            }
        });

And server Side code like this
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
    public static Object GetExtUsers(Int32 page, Int32 limit)
    {
        //String page, String limit
        Int32 skipRows = (page - 1) * limit < 0 ? 0 : (page - 1) * limit;
        var extUserData = SampleDataManager.GetExtUsers();
        var RequiredData = extUserData.OrderBy(x => x.UserId).Skip(skipRows).Take(limit);
        var result = new DataSet
        {
            userData = RequiredData.Select(x => new ExtUserData
        {
            UserName = x.UserName,
            IsAdmin = ((Boolean)x.IsAdmin),
            EmailId = x.EmailId,
            UserFName = x.UserFName,
            UserLname = x.UserLname,
            PhoneNo = x.PhoneNo,
            DateOfBirth = x.DateOfBirth
        }),
            totalCount = extUserData.Count()
        };
        return result;
    }
    }
}

class DataSet
{
    public Int32 totalCount { get; set; }
    public IQueryable<ExtUserData> userData { get; set; }
}

class ExtUserData
{
    public Int32 UserId { get; set; }
    public String UserName { get; set; }
    public String EmailId { get; set; }
    public Boolean IsAdmin { get; set; }
    public String UserFName { get; set; }
    public String UserLname { get; set; }
    public String PhoneNo { get; set; }
    public String DateOfBirth { get; set; }
}

A: Just some hints (some are micro some are best practice):

*

*you don't need 'd' and I recommend you to turn your selection-result into a list by calling toList(). Dunno where your wrapper object d is coming from, I use Json.Net in all of my projects.

*a reader does not have a model cfg property. If you define one on your store, the store will apply it to the proxy for you. In short, you only need the model at storelevel

*enablePaging is only valid for a Ext.data.Proxy.Memory

*id on the reader should be named idProperty API-link

*I guess you should rename page to start and use this instead of skipRows see the comment below

Where did you submit the arguments Int32 page and Int32 limit and why do you calculate skip rows? For me it looks like you are using ordinary paging with take & skip. This is already provided by the paging toolbar. You should need to do nothing at all. Ok, you need to apply the toolbar and configure the pagesize on the store. From that on the pagingtoolbar will apply a start and limit property to each store request (as long as you don't bypass the pagingtoolbar).


text:
Q: Use tcpdump to capture TCP transmitted data withouth the protocol's details (similar to tcpflow) I use tcpflow a lot to capture data transmitted as part of TCP connections. It allows you to see the transmitted data without any of the TCP protocol details.
Is there a way to accomplish the same thing using tcpdump?
I mean, I was able to see the transmitted  data using tcpdump as well, but including all the contents of the packets which I'm not interested in. I just want the plain data without any of the protocol's details.
This is what I mean:
For instance, sending a "hello world" like this:
echo "hello world" | nc localhost 8098

Using tcpflow, I can accomplish this output:
sudo tcpflow -C -i any port 8098
tcpflow: listening on any
hello world

Using tcpdump, I can get something like:
sudo tcpdump -A -i any port 8098
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
15:14:36.699939 IP localhost.52524 > localhost.8098: Flags [S], seq 4067768558, win 43690, options [mss 65495,sackOK,TS val 4205840266 ecr 0,nop,wscale 7], length 0
E..<..@.@.y..........,...u8..........0.........
............
15:14:36.699959 IP localhost.8098 > localhost.52524: Flags [S.], seq 2708887582, ack 4067768559, win 43690, options [mss 65495,sackOK,TS val 4205840266 ecr 4205840266,nop,wscale 7], length 0
E..<..@.@.<............,.vX..u8......0.........
............
15:14:36.699967 IP localhost.52524 > localhost.8098: Flags [.], ack 1, win 342, options [nop,nop,TS val 4205840266 ecr 4205840266], length 0
E..4..@.@.y..........,...u8..vX....V.(.....
........
15:14:36.700000 IP localhost.52524 > localhost.8098: Flags [P.], seq 1:13, ack 1, win 342, options [nop,nop,TS val 4205840266 ecr 4205840266], length 12
E..@..@.@.y..........,...u8..vX....V.4.....
........hello world

When all I was interested in was the "hello world" part.


text:
Q: Better Way To Show Running Applications in OS X Lion I'm looking to either find a better method (visually) to show running applications on my Macbook Pro. The easiest method would be to increase the size (or make more prominent) of the running program indicator(s) that are present on OS X dock:

Alternatively I would be open to some other method that provides the same "at a glance" feedback as to what is running without having to manually launch a process.
I have looked at a lot of Apple related blogs and Google'd around to no avail. I could obviously increase my stock resolution of 1920 x 1200 to something larger but overall I am very happy with this resolution so I would prefer an alternate method. I also really have no desire to hook up to a larger monitor.

A: The easiest way to do this (in my mind) is to not have any applications permanently stored in your Dock.  In other words, the only applications down there are running ones. (This is what I do, and it works great; I can at-a-glance see what's running without having to use cmd-tab).
That being said, OS X is moving in the direction of "you shouldn't have to care".  Things like Sudden Termination and User Interface preservation are aiming to make it so that a process can disappear silently in the background, but quickly come back when you need it.

A: The easiest method for foreground applications is to press ⌘-TAB. It requires interaction, but it is visual and it doesn't take reworking Apple's interface.
Another approach is to simply enlarge the size of the dock.

System Preferences -> Dock -> Size

A: TinkerTool (free)
You can use TinkerTool to disable the 3D Dock effekt while the Dock is at the bottom (just like when the dock is on the left/right side).

CandyBar (free trial)
You can also use Candybar to customize the look of the dock.

A: DragThing
I use a commercial program called DragThing, which has been around since the early days of Mac OS X and is still in development. Among its many other features, it includes a floating palette in the upper corner of your screen that shows just the programs that are currently running and also lets you click on an icon to bring that program to the forefront. This is in fact an emulation of a feature in the user interface from Apple's Mac OS 9, if you go back far enough to remember that.

A: Are you familiar with things like command-tab or Mission Control (F3/gesture/dock icon), which has been designed with exactly what you want in mind?
Alternatively, what you could do is simply "unpin"/remove all of your Applications' icons from the Dock. Then an icon will only appear there for currently running applications.