text:
Q: wpf listbox with colorized items I am making an apllication which colorizes black and white Pictures.
I have a Listbox which I use to display my current Color Palette.
Hex code is hardly readable for Humans (at least me) which is why I want to colorize the Items in my ListBox.
My Listbox looks like this right now:

As an example of what I mean, I have a simple TextBox which is beeing colorized:

System.Drawing.Color? color = cl.ColorFromHexString(Basecolor.Text);
if (color != null)
{
    System.Drawing.Color col = (System.Drawing.Color)color;
    this.Basecolor.Foreground = new SolidColorBrush(cl.ToMediaColor(col));
}

So my Goal is to have different colors for each entry:

The Listbox Items are assigned by using the following code (probably not best practice):
List<String> ColorStringPalette = new List<string>();
private void AddColorButton_Click(object sender, RoutedEventArgs e)
{
    System.Drawing.Color? color = cl.ColorFromHexString(ColorHexCode.Text);
    if (color != null)
    {
        if (!ColorStringPalette.Contains(ColorHexCode.Text))
        {
            ColorStringPalette.Add(ColorHexCode.Text);
        }
        ColorList.ItemsSource = ColorStringPalette;
    }
}

What would be the apropriate way to set foreground colors for the individual items of the Listbox?

A: you can change ItemTemplate and bind Foreground (it requires brush but will do converion from string):
<ListBox.ItemTemplate>
    <DataTemplate>
         <TextBlock Text="{Binding}" Foreground="{Binding}"/>
    </DataTemplate>
</ListBox.ItemTemplate>


text:
Q: ASP.NET 2.0 FormsAuthentication Application AuthenticateRequest should ignore WebResource.axd I noticed that in my ASP.NET application the Application_AuthenticateRequest event handler is being called several times for the WebResource.axd file.
I have code inside the AuthenticateRequest event handler to generate a modified GenericPrinicpal, that even though it is simple, doesn't need to be executed for the .axd resource.
I'm seeing this behavior while debugging using IIS Express, with the application running in Integrated Pipeline mode.
What is the proper way to handle this?

A: Application_AuthenticateRequest happens for all requests that are handled by .net.
You could test for the extension and bypass if it's .axd.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Text inside table over image which hovers? I have created a table, and inside every cell, there is an image which has a "hover" effect. The image contains graphics + text (hardprinted).
Everything works good till the promoter of my site, told me to put "real" text over the JPG, and remove the printed text from image.
I have tried several things, but I couldn't find something. Maybe I messed "position".
Here is the code:
HTML

And CSS
#button {
display: block;
width: 135px;
height: 34px;
background: url('images/navibutton.jpg') 50% bottom;
background-repeat:no-repeat;
text-indent: -99999px;
position: static;
}
#button:hover {
background-position: 0 0;
}
#tablestyle {
margin: auto;
width: 900px;
}

I have tried to put text before a, after a, but whatever I try does not work. Or the cell totally loses position, or the text is hidden (or something else).
For the hover "effect" I use a 135x68 image. It's working.


text:
Q: While loop in JSP to execute javascript not working? Please don't hesitate to edit the question or ask more details if I  missed anything.
I know it's bad to use Scriptlets in JSP.
But I am assigned to maintain the existing JAVA project which is build only with only JSP and servlets(No framework).
My task is to implement the load balancing for my applicaiton using Apache HTTP Server.
The application works fine with out load balancing. When I implement the load balancing using the Apache HTTP Server, I am facing the problem with JSP.
I will give a scenario. My JSP has one while loop and it runs the javascript to update the content .
My  JSP has,
<%
    String jsPreAppend = "<script language=JavaScript >push('";
    String jsPostAppend = "')</script> ";
    String s=null;
    int i = 0;

       try {
        while (true) {
            System.out.println("count :"+i);
            out.print(jsPreAppend + i + jsPostAppend);
            out.flush();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                out.print(jsPreAppend + "InterruptedException: " + e + jsPostAppend);
            }

            i++;

          }
       } catch (Exception e) {
             out.print(jsPreAppend + "Exception: " + e + jsPostAppend);
       }
%>

My JavaScript has,
 function push(content) {
         document.getElementById('update').innerHTML = content;
 }

The console output will be,
count :1
count :2
count :3
.
.
.
count : n
count :n+1

But the content will not updated in JSP. I thing the javascript fails in while loop.
But the SysOut() works because the updated content will be printed for every sec in the console .
But the same applicaiton  work's fine with out load balancing(only one tomcat).
Hope our stack users will help me.

A: When your HTML gets rendered, JSP would have already got executed. So what you are trying to do cannot be achieved by that code.
You need to write a Java script method which does some update once in sometime. Check this thread to write the same logic using Javascript

A: Take into account that the while(true) loop will be executed server side. At that point, the response document (the HTML) is being built, and it can't be yet interpreted by the client. This loop is only writing javascript calls to a kind of buffer where the response is stored before it is sent to the client.
As an example, what that loop is doing is writing ad-infinitum to the response:
<script language=JavaScript >push('1')')</script>
...
<script language=JavaScript >push('n')')</script>

The fact that every line is being written at every second is irrelevant. You see the traces in the standard output at the correct times because that's what is being executed on the server.
This will make the request get stuck in that infinite loop unless there's an exception of some kind. Even if the loop ended at some point, and the request finished processing, when these statements would get executed by a client, they would be executed sequentially without any delay.
You should move those calls to client side, and schedule its execution with a client-side mechanism such as setTimeout(), like @sanbhat suggested in his answer.


text:
Q: VLOOKUP troubles in Excel I have a list of contacts. There are people, and companies, both in the same spreadsheet.
I need to copy a company's address (from column F) in to a person's address (also column F), based on a match. That is, E2 is my source cell, and the E column is what I need to match. When a match is made, the formula should copy F3 in to F2.
In plain English, I need to company company address values in to person address values. I've fiddled with VLOOKUP but can't get it to cooperate.
See this example: http://versastudio.com/misc/excel_vlookup.png

A: You can get the company address against person, by using Match and Index Formula in Array Formula.

Select Cell Range G2:G5 and Then in First Cell (G2) Place formula
=IF(A2:A5="Person", INDEX(F2:F5,MATCH(E2:E5,C2:C5,0),1),F2:F5)
and press Ctrl + Shift + Enter.
Might be, It help you.


text:
Q: Implementing custom IComparer<> (with example) Ive just written the following code, which will order strings by their native string.Compare() but allow a collection of exceptions (in this case customPriority) that will place priority over the default string.Compare() function.
It all seems a bit long winded, I was wondering if there was something built into .NET to allow this?
    var unorderered = new[] { "a", "b", "c", "x", "y", "z" };
    var ordered = unorderered.OrderBy(a => a, new CustomStringComparer());
    //expected order y,x,a,b,c,z

class CustomStringComparer : IComparer<string>
{
    int IComparer<string>.Compare(string x, string y)
    {
        if (x == y)
            return 0;
        else
        {
            //----------------------------
            //beginning of custom ordering
            var customPriority = new[] { "y", "x" };
            if (customPriority.Any(a => a == x) && customPriority.Any(a => a == y)) //both in custom ordered array
            {
                if (Array.IndexOf(customPriority, x) < Array.IndexOf(customPriority, y))
                    return -1;
                return 1;
            }
            else if (customPriority.Any(a => a == x)) //only one item in custom ordered array (and its x)
                return -1;
            else if (customPriority.Any(a => a == y)) //only one item in custom ordered array (and its y)
                return 1;
            //---------------------------
            //degrade to default ordering
            else
                return string.Compare(x, y);

        }
    }
}

A: First, I think it's useful to restate the problem: You want to sort by:

*

*the index in the given array; if the item is not in the array, the index is infinity

*the string itself

That means you can achieve your sort order by using OrderBy() for the first condition followed by ThenBy() for the second one:
private static uint NegativeToMaxValue(int i)
{
    if (i < 0)
        return uint.MaxValue;
    return (uint)i;
}

…

var ordered = unorderered
    .OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
    .ThenBy(a => a);

NegativeToMaxValue() is necessary, because items not in the array should be last, but they would be first normally, because the index is -1. (A hackish and unreadable way to do the same would be to directly cast the result of IndexOf() to uint.)
If you wanted to reuse this sorting by creating an IComparer, I believe there is nothing in .Net to help you with that. But you could use ComparerExtensions instead:
IComparer<string> comparer = KeyComparer<string>
    .OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
    .ThenBy(a => a);

A: There is no built-in comparison method to do what you want, but I'm guessing that isn't the "long-winded" part that you are talking about.
What's annoying is that you have to create a custom comparer class just to pass what should be a simple comparison function.
Well, there is a way to mitigate that. You can write a couple of helper classes that allow you to use OrderBy() just by passing the name of a method. If you write these classes, they will work for ALL your OrderBy() statements.
Here's some sample code. The helper classes are called EnumerableExt and ComparisonDelegator. They work together to allow you to pass a method to OrderBy().
The code below is clearly much longer than your code, but remember that the EnumerableExt and ComparisonDelegator classes would be in a separate common assembly, so you shouldn't count those.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            var unorderered = new[] { "a", "b", "c", "x", "y", "z" };

            var ordered = unorderered.OrderBy(compare); // Just need to specify the compare method!
        }

        // Each custom compare method must be written specially, as before:

        private static int compare(string x, string y)
        {
            if (x == y)
                return 0;
            else
            {
                //----------------------------
                //beginning of custom ordering
                var customPriority = new[] { "y", "x" };
                if (customPriority.Any(a => a == x) && customPriority.Any(a => a == y)) //both in custom ordered array
                {
                    if (Array.IndexOf(customPriority, x) < Array.IndexOf(customPriority, y))
                        return -1;
                    return 1;
                }
                else if (customPriority.Any(a => a == x)) //only one item in custom ordered array (and its x)
                    return -1;
                else if (customPriority.Any(a => a == y)) //only one item in custom ordered array (and its y)
                    return 1;
                //---------------------------
                //degrade to default ordering
                else
                    return string.Compare(x, y);

            }
        }
    }

    // The following classes only need to be written once:

    public static class EnumerableExt
    {
        ///
        /// Convenience method on IEnumerable{T} to allow passing of a
        /// Comparison{T} delegate to the OrderBy method.
        ///

        public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
        {
            Contract.Requires(list != null, "list can't be null.");
            Contract.Requires(comparison != null, "comparer can't be null.");

            return list.OrderBy(t => t, new ComparisonDelegator<T>(comparison));
        }
    }

    ///
    /// Provides a mechanism for easily converting a Comparison<> delegate (or lambda) to an IComparer<>.
    /// This can be used for List.BinarySearch(), for example.
    ///
    /// <typeparam name="T">The type of items to be compared.</typeparam>

    public sealed class ComparisonDelegator<T>: IComparer<T>, IComparer
    {
        /// Create from a Comparison<> delegate.
        /// <param name="comparison">A Comparison<> delegate.</param>

        public ComparisonDelegator(Comparison<T> comparison)
        {
            Contract.Requires(comparison != null);

            this._comparison = comparison;
        }

        /// Implements the IComparer.Compare() method.

        public int Compare(T x, T y)
        {
            return _comparison(x, y);
        }

        /// Implements the IComparer.Compare() method.

        public int Compare(object x, object y)
        {
            return _comparison((T)x, (T)y);
        }

        /// Used to store the Comparison delegate.

        private readonly Comparison<T> _comparison;
    }
}

You could also then write the compare method inline as follows (but I wouldn't recommend that for such a complex compare method; this is just for the purposes of illustration):
    private static void Main(string[] args)
    {
        var unorderered = new[] { "a", "b", "c", "x", "y", "z" };

        var ordered = unorderered.OrderBy((x, y) =>
        {
            if (x == y)
                return 0;
            else
            {
                var customPriority = new[] { "y", "x" };
                if (customPriority.Any(a => a == x) && customPriority.Any(a => a == y)) //both in custom ordered array
                {
                    if (Array.IndexOf(customPriority, x) < Array.IndexOf(customPriority, y))
                        return -1;
                    return 1;
                }
                else if (customPriority.Any(a => a == x)) //only one item in custom ordered array (and its x)
                    return -1;
                else if (customPriority.Any(a => a == y)) //only one item in custom ordered array (and its y)
                    return 1;
                else
                    return string.Compare(x, y);
            }
        });
    }

A: I am 99.99% sure that, Nothing such exist by default in the .Net Framework.

Your sorting is very much customized, and is not a general way of sorting, hence thing like that do not exist in the .NET Framework by default.


text:
Q: Is this excercise doable without a computer? Triangular Number with n divisors
The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five
  divisors.
What is the value of the first triangle number to have over five
  hundred divisors?

from https://projecteuler.net/problem=12
$n$th triangular number=$\frac{n(n+1)}{2}$
(little Gauss)
Algorithm to find number of divisors:
from https://www.geeksforgeeks.org/total-number-divisors-given-number/
# Python3 program for finding
# number of divisor

# program for finding
# no. of divisors
def divCount(n):

    # sieve method for
    # prime calculation
    hh = [1] * (n + 1);

    p=2;
    while((p * p) < n):
        if (hh[p] == 1):
            for i in range((p * 2),n,p):
                hh[i] = 0;
        p+=1;

    # Traversing through
    # all prime numbers
    total = 1;
    for p in range(2,n+1):
        if (hh[p] == 1):

            # calculate number of divisor
            # with formula total div =
            # (p1+1) * (p2+1) *.....* (pn+1)
            # where n = (a1^p1)*(a2^p2)....
            # *(an^pn) ai being prime divisor
            # for n and pi are their respective
            # power in factorization
            count = 0;
            if (n % p == 0):
                while (n % p == 0):
                    n = int(n / p);
                    count+=1;
                total *=(count + 1);

    return total;

# Driver Code
n = 24;
print(divCount(n));

# This code is contributed by mits

Is the task doable without a computer, in reasonable time?
If so, what's the "magic" trick?

A: I believe this problem can be solved without computers.
If $T(n)$ is the n-th triangular number, then we know that
$$T(n)=1+2+3+...+n=\sum^n_{i=1}=\frac{n(n+1)}{2}$$
Let's assume that we know the prime factorizations of both $n$ and $n+1$, and we'll write
$$n=p_1^{e_1}p_2^{e_2}p_3^{e_3}...p_s^{e_s}\text{  and  }n+1=q_1^{f_1}q_2^{f_2}q_3^{f_3}...q_t^{f_t}$$
Notice that $n$ and $n+1$ cannot share any prime factors (as they are consecutive numbers), and so we know that all the $p_i$ and $q_i$ are distinct primes. Also, one and only one of $n$ and $n+1$ are divisible by $2$. The exponents $e_i$ and $f_i$ are therefore the only things we really need to consider in order to determine the number of divisors of $T(n)$. The fact that $T(n)=\frac{n(n+1)}{2}$ means that we'll need to neglect a single power of two in the factorization of $n$ or $n+1$ (remember, only one is even). Let's assume, without loss of generality, that $n$ is even and that $p_1=2$. Then, some quick combinatorics tell us that the total number of factors of $T(n)$ will be
$$(e_1+1)(e_2+1)...(e_s+1)(f_1+1)(f_2+1)...(f_t+1)=e_1\Pi^s_{i=2}(e_i+1)\Pi^t_{i=1}(f_i+1)$$
Even better, as we're increasing our triangular numbers looking for the first one to satisfy the property in question, we only need to calculate the factorization of $n+1$ (as we already know that factorization of $n$, as it was previously $n+1$). This should decrease the run time substantially.


text:
Q: Perform search operation and save some data from the text following it, in ruby if possible There is a text document containing this text.
---random data---
==String_1==
{{item_1
    | name= name_1 | url=url_1 | email= email_1 | address= |
}}
---random data---

Now, I want that whenever String_1 is encountered, all the fields (name, url, email and address) as strings in a Hash named item_1.
Ruby code is preferred.

A: With this pattern you can extract all the values you need that are inside named captures:
/(?: ==String_1== \s+ {{ (?<name> \S+ ) | (?!\A)\G )  # entry point
 \s* \| \s*
 (?<key>   [^\s=]+ ) \s* = \s*
 (?<value> [^|}]+? ) (?=\s*[|}]) # the lookahead is used to enforce the lazy
                                 # quantifier to take all the value until an
                                 # optional trailing space before a pipe or a
                                 # closing curly bracket
/x

It's a little a general pattern that isn't probably the most appropriate to your specific case, but you are free to adapt it or to use ideas from it to build your own.

A: This should do it, though I don't quite understand what you mean by wanting to save the results in a hash named item1. I have saved the results in an array of hashes.  I presume you can adjust this to your requirements.  (My apologies for the horizontal scrolling--I try to avoid the need for that.)
Code
KEYS = %w{ name url email address }
def pull_vals(fname)
    enum = File.readlines(fname).to_enum
    arr = []
    r = /\s*\|\s*name=\s*(\S*)\s*\|\s*url=\s*(\S*)\s*\|\s*email=\s*(\S*)\s*\|\s*address=\s*(\S*)\s*\|/
    loop do
      next unless enum.next =~ /==String_1==/
      enum.next
      arr << KEYS.zip(enum.next.scan(r).flatten(1)).to_h
    end
    arr
end

Example
text =<<_
---random data---
==String_1==
{{item_1
    | name= name_1 | url=url_1 | email= email_1 | address= |
}}
---random data---
==String_1==
{{item_2
    | name= name_2 | url=url_2 | email= email_2 | address= home |
}}
_

FNAME = "my_file"
File.write(FNAME, text)

pull_vals(FNAME)
  #=> [{"name"=>"name_1", "url"=>"url_1", "email"=>"email_1", "address"=>""},
  #    {"name"=>"name_2", "url"=>"url_2", "email"=>"email_2", "address"=>"home"}]

When, as in this case, the regex pattern is repetitious, it may be easiest to get it working for one part of the string, then use a bit of code to form the regex:
Regexp.new (KEYS.map {|str| "\\s*\\|\\s*#{str}=\\s*(\\S*)"} << "\\s*\\|").join


text:
Q: Adding message to IMAP folder using ZF3 I am trying to add a new message to IMAP folder using Zend Framework 3.
The code I use is the following:
...
$draftMessage = new \Zend\Mail\Storage\Message([
  'headers' => [
    'subject' => 'voyteck0@gmail.com',
  ],
  'content' => 'ala ma kota',
]);
[valid-imap-connection]->appendMessage($draftMessage, 'Drafts', [\Zend\Mail\Storage::FLAG_DRAFT]);
...

However I always get an exception thrown:
Zend\Mail\Storage\Exception\RuntimeException:'cannot create message, please check if the folder exists and your flags' thrown in /.../zendframework/zend-mail/src/Storage/Imap.php(480)
I have also used in here a pseudo-element [valid-imap-connection] not to blur the problem - but the connection is working fine (retrieves messages, sends them, moves between folders etc.)
The folder exists - I have done some debuging even within ZF already and found out that in that line 480 the command returns NULL on the above code. If I change the folder into non-existing one - it returns false.
The Exception itself is thrown once (! result) - so null is also true for this condition.
However even if I am removing the code that throws exception (And the code completes execution with that NULL value) - still the message is not appearing in the folder (checking directly on the disk). There's nothing interesting in Dovecot logs (apart from the fact the connection is successfully established).
Any ideas highly welcome :)

A: I think the problem was with 2 things:

*

*I should have used \Zend\Mail\Message class (not the ...\Storage... one)

*The draftMessage should be a string version (actually dunno why - since appendMessage already uses toString() function)

So the code that works is following:
...
$draftMessage = new \Zend\Mail\Message();
$draftMessage->setSubject('voyteck0@gmail.com');
$draftMessage->setBody('ala ma kota');
[valid-imap-connection]->appendMessage($draftMessage->toString(), 'Drafts', [\Zend\Mail\Storage::FLAG_DRAFT]);
...


text:
Q: Load another HTML file inside dialog I have a index.html and have another html file with a lot of text.
Now I don't want to paste this bunch of codes into my index.html.
I don't want to make it larger, the other file is not always called only if the button is clicked.
How do I get the div area from another_file.html ?
$("#buttonClick").on("click",function(evt) {
    $("#load-another-file").dialog({});

A: I believe you are looking for jQuery's $.ajax, which is a way of loading data without refreshing the page:
$("#buttonClick").on("click",function(evt) {
    $.ajax({
        url: 'another_file.html',
        success: function(data){ // You received the data
            $("#load-another-file").html(data).dialog("open");
        }
    });
});

Note: for this to work, you might have to put your files on a server (even a local one), because some browsers don't allow Ajax requests on local files for security reasons (e.g. Google Chrome).

A: Maybe you're looking for jquery.load(), load perform a server call and fetchs the HTML returned in your element.
$("#buttonClick").on("click",function(evt) {
    $("#load-another-file").dialog().load("another_file.html");
});


text:
Q: cannot convert from 'System.Web.HttpPostedFileBase' to 'string' var file = Request.Files[0];
                    //HttpPostedFileBase hpf = Request.Files[0];

                    if (file != null && file.ContentLength > 0)
                    {
                        //var fileName = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        var allowedExtensions = new[] { ".bmp", ".png", ".jpg", "jpeg", ".gif" };
                        if (allowedExtensions.Contains(fileExtension))
                        {
                            //Delete files
                            var pathD = Server.MapPath("~/Avatar/1");
                            var images = Directory.GetFiles(pathD, CustomerID + ".*");
                            for (int i = 0; i < images.Length; i++)
                                System.IO.File.Delete(Server.MapPath(("~/Avatar/1/") + Path.GetFileName(images[i])));

                            //Up files
                            var fileName = CustomerID + fileExtension;
                            var path = Path.Combine(Server.MapPath("~/Avatar/1/"), fileName);

everything works fine but getting a problem with one line
                            System.Drawing.Image imageToBeResized = System.Drawing.Image.FromFile(file);
                            int imageHeight = imageToBeResized.Height;
                            int imageWidth = imageToBeResized.Width;
                            int maxHeight = 400;
                            int maxWidth = 400;
                            imageHeight = (imageHeight * maxWidth) / imageWidth;
                            imageWidth = maxWidth;

                            if (imageHeight > maxHeight)
                            {
                                imageWidth = (imageWidth * maxHeight) / imageHeight;
                                imageHeight = maxHeight;
                            }

                            Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                            System.IO.MemoryStream stream = new MemoryStream();
                            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            stream.Position = 0;
                            byte[] imasave = new byte[stream.Length + 1];
                            stream.Read(imasave, 0, imasave.Length);

                            var newImage = System.Drawing.Image.FromStream(stream);
                            newImage.Save(path);

below line gaves me error when i pass file
               System.Drawing.Image imageToBeResized = System.Drawing.Image.FromFile(file);

A: System.Drawing.Image.FromFile takes a string argument. instead of of giving it he file variable give the path you have obtained of the file and it will work.
 System.Drawing.Image.FromFile(Path.GetFileName(file.Filename));
                                  or
   System.Drawing.Image.FromFile(Server.MapPath(Path.GetFileName(file.Filename)));


text:
Q: C - Find number of times each word appears in an input My assignment is to create a function that

Prints a table indicating the number of occurrences of each different words in the text in the same order in which they appear

I'm using gets() to read in the string, a function to tokenize each word in the string and store it in a 2-dimensional array, and need help figuring out how to make one that analyzes the array for duplicates.
Here's the tokenizer function:
void tokeniz(char *array)
{
    char words[arraySize][arraySize] = { NULL };

    const char s[2] = " ";
    char *token;
    int i = 0;

    token = strtok(array, s);

    while (token != NULL)
      {
        strcpy(words[i], token);
        token = strtok(NULL, s);
        i++;
      }
    wotable(words);
}

Earlier in the program, I have a function to count the number of times each character appears in the string (pre-tokenization). Would I be able to repurpose some of that code?
    void   alpha(char *array)
{
    char character = 'a';
    int numberOf = 0, tcc = 0;

    for (character = 'a'; character <= 'z'; character++)
    {
        tcc = (tcc + numberOf);
        numberOf = 0;
        for (int i = 0; i < arraySize; i++)
            if (*(array + i) == character)
                numberOf++;
        if (numberOf != 0)
            printf("\nNumber of %c's:\t\t%d\n", character, numberOf);
    }
    printf("\nTotal character count:\t%d\n\n- - - - - - - - - - - - - -", tcc);
}

A: No, you will not be able to repurpose some of that code.

A: the following code:

*

*cleanly compiles

*needs a few lines of code added in a couple of places

*is a bit wasteful as each new word results in a call to realloc()

*properly checks for errors

*may want to replace the call to fgets() with a call to readline() (be sure to read/understand the man page for readline() )

*could separate the freeing of the memory as part of a cleanup function, so that code only needs to be written once.

and now the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUF_LEN (1024)

struct wordsAndCount
{
    char *pWord;
    size_t  count;
};

// note: following assumes words are not continued across multiple lines
int main( int argc, char *argv[] )
{
    if( 2 != argc)
    {
        fprintf( stderr, "USAGE: %s <inputFileName>\n", argv[0]);
        exit( EXIT_FAILURE );
    }

    // implied else, correct number of command line arguments

    FILE *fp = NULL;
    if( NULL != (fp = fopen( argv[1], "r") ) )
    { // fopen failed
        perror( "fopen for input file failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    struct wordsAndCount **table = NULL;
    size_t   countWords = 0;

    char buffer[ MAX_BUF_LEN ];
    char *token = NULL;
    char *delimeters = ",.;: '\"\n";

    while( fgets( buffer, sizeof buffer, fp ) )
    {
        token = strtok( buffer, delimeters );
        while( NULL != token )
        {
            struct wordsAndCount ** temp = realloc( table, (countWords+1)*sizeof (struct wordsAndCount *) );
            if( !temp )
            { // then realloc failed
                perror( "realloc failed" );
                fclose( fp );

                for( ; countWords; countWords-- )
                {
                    free( (*table[countWords]).pWord );
                }
                free( table );
                exit( EXIT_FAILURE );
            }

            // implied else, realloc successful

            table = temp;

            int foundIndex = 0;
            // if word already in table[] <-- need to add code for this
                (*table[foundIndex]).count++;
            //else
            {
                (*table[countWords]).pWord = strdup( token );
                if( !(*table[countWords]).pWord )
                { // then strdup failed
                    perror( "strdup failed" );
                    fclose( fp );

                    for( ; countWords; countWords-- )
                    {
                        free( (*table[countWords]).pWord );
                    }
                    free( table );
                    exit( EXIT_FAILURE );
                }

                // implied else, strdup successful

                (*table[countWords]).count = 1;
                countWords++;
            }

            token = strtok( NULL, delimeters );
        } // end while tokens
    } // end while more lines in input file

    // print words and counts <-- need to add code for this
} // end function: main


text:
Q: fsck -cc /dev/sdb1 gives this result. Is everything okay? root@host [/]# fsck -cc /dev/sdb1
fsck from util-linux-ng 2.17.2
e2fsck 1.41.12 (17-May-2010)
Checking for bad blocks (non-destructive read-write test)
Testing with random pattern: done
/dev/sdb1: Updating bad block inode.
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information

/dev/sdb1: ***** FILE SYSTEM WAS MODIFIED *****
/dev/sdb1: 11/18317312 files (0.0% non-contiguous), 1198478/73258400 blocks

It said File System Was Modified. So what? I just format it. Anything wrong?

A: It looks like it found nothing.  And then updated the bad block inode with its results, which was nothing.
FILE SYSTEM WAS MODIFIED gets spit out by fsck any time it makes a write to the filesystem.  Changing that one bad block inode qualifies.
Especially whereas you didn't specify to just fix any problems without asking you (-y) if it came up with problems on the disk in need of correction, it would have said something.

A: I'd run it again. The -cc found badblocks and called the program badblocks to repair them. You might want to just run it as:
$ fsck /dev/sdb1

excerpt from fsck.ext3 man page

-c
  This option causes e2fsck to run the badblocks(8) program to find any blocks which are bad on the filesystem, and then marks them as bad by adding them to the bad block inode. If this option is specified twice, then the bad block scan will be done using a non-destructive read-write test.

UPDATE #1: Follow-up Question

Does the fsck found bad block? What is non destructive read write test?

fsck is a front end tool which does a variety of checks as to the overall well being of a filesystem. The -cc switch tells fsck to call badblocks too so that a more thorough check is performed.
A non-destructive read/write entails the contents of the location being backed up first, a pattern is then used to test the location, and the original content is returned.
References

*

*ArchLinux Wiki - badblocks

A: Don't worry, this message  appear when you have a bad file, for example a file with bad name or unicode name, or occurpted file, It's not reated to your filesystem.

A: Apparently you can run dumpe2fs -b to see the list of bad blocks, eg. dumpe2fs -b /dev/sdb1. I guess if the output is empty, there are no bad blocks (but I don't have a drive with bad blocks available right now, so can't test it).


text:
Q: Python exception not caught I am currently playing with sockets and JSON in Python where I have the following code:
class RCHandler(SocketServer.BaseRequestHandler):
    def setup(self):
        pass

    def handle(self):
        raw = self.request.recv(1024)
        recv = raw.strip()

        if not recv:
            return

        # do some logging
        logging.debug("RECV: (%s)" % recv)

        try:
            data = json.loads(recv)
        except:
            logging.exception('JSON parse error: %s' % recv)
            return

        if recv == 'quit':
            return

The problem is that when I send a faulty JSON string, e.g. '{"method": "test"', the exception seems to be caught, but I still get the following traceback:
DEBUG: 20/09/2015 12:33:57 - RECV: ({"method": "test")
ERROR: 20/09/2015 12:33:57 - JSON parse error: {"method": "test"
Traceback (most recent call last):
  File "./remoteControl.py", line 68, in handle
    data = json.loads(recv)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 17 (char 16)

What am I missing here? I am not supposed to get a traceback if I catch the exception right? My server class extends ThreadingTCPServer if that has anything to do with it.
When I ran another python script:
#!/usr/bin/python

import json
import socket

d = '{"method": "test"'

try:
    data = json.loads(d)
except:
    print "fail"

It only prints "fail" and no traceback.

A: You did catch the exception, but you are telling logging to include the exception information (which includes the traceback), by using the Logger.exception method here:
except:
    logging.exception('JSON parse error: %s' % recv)

From the method documentation:

Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(), except that any passed exc_info is not inspected. Exception info is always added to the logging message. This function should only be called from an exception handler.

Emphasis mine.
Also see the Formatter.formatException() documentation; it is this method that does the exception formatting here:

Formats the specified exception information (a standard exception tuple as returned by sys.exc_info()) as a string. This default implementation just uses traceback.print_exception(). The resulting string is returned.

and traceback.print_exception() does this:

Print exception information and up to limit stack trace entries from traceback to file.

If you did not want the exception to be included, use logging.error() instead:
except:
    logging.error('JSON parse error: %s' % recv)

or provide a custom Formatter subclass that formats the exception information without the traceback.


text:
Q: Get child pages of current page as well as current page link I intend to create a sidebar to retrieve a list of the current page's children as well as the current page itself. Here is the code that I have been using which retrieves the current pages children even when on the child pages, however when I try to include the $parent as $post->post_parent it displays all pages
    <?php
   if ($post->post_parent)  {
        $ancestors=get_post_ancestors($post->ID);
        $root=count($ancestors)-1;
        $parent = $ancestors[$root];
    } else {
        $parent = $post->ID;
    }
    $children = wp_list_pages("title_li=&child_of=". $parent ."&echo=0");
    $parent = wp_list_pages("title_li=&child_of=". $post->post_parent ."&echo=0");
    if ($children) { ?>

        <?php echo  $parent ?>
        <?php echo $children; ?>

<?php } ?>

A: /*-------------------------------------------------------------------
    Return parent page ID or child as else. Add this to functions.php
---------------------------------------------------------------------*/

function get_top_parent_page_id() {
    global $post;

    if ($post->ancestors) {
        return end($post->ancestors);
    } else {
        return $post->ID;
    }
}

//Use this in the template
<?php while ( have_posts() ) : the_post();

    //Add parent page slug into arguments
    $query = new WP_Query('pagename=page_slug');
    if ($query->have_posts() ){ while ($query->have_posts() ) { $query->the_post(); } }

    //Get children by calling function in functions.php for the top parent id
    $current_page_id = get_top_parent_page_id();
    $args = array( 'post_type' => 'safaris', 'post_parent' => $current_page_id, 'orderby' => 'title', 'order' => 'ASC' );
    $child_query = new WP_Query($args);

    $i = 0;
    if ($child_query->have_posts() ){ while ($child_query->have_posts() ){ $child_query->the_post();
    $i++; if( 1 == $i ) { ?>

<?php the_title(); ?>

    <?php } else { ?>

<?php the_title(); ?>

    <?php } } } wp_reset_postdata();  endwhile; ?>

A: Here is the code that worked.
<?php if ( !is_page()) { ?>

Recent posts

        <?php
        $args = array( 'numberposts' => 4, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
        $postslist = get_posts( $args );
        foreach ($postslist as $post) :  setup_postdata($post);
        $image_id = get_post_thumbnail_id();
        $image_url = wp_get_attachment_image_src($image_id,'thumbnail', true);
        ?>
            <a class="recentposts" href="<?php the_permalink(); ?>" title="<?php the_title();?>">
                <?php
                if ( has_post_thumbnail() ) {
                echo '
';
                the_post_thumbnail( 'sidebarThumb' );
                echo '
';
                }
                ?>

<?php the_title(); ?>

                        <?php echo get_the_date('F y'); ?>

                        <?php
                                global $post;
                            $fname = get_the_author_meta('first_name');
                            $lname = get_the_author_meta('last_name');
                            $full_name = '';

                            if( empty($fname)){
                                $full_name = $lname;
                            } elseif( empty( $lname )){
                                $full_name = $fname;
                            } else {
                                //both first name and last name are present
                                $full_name = "{$fname} {$lname}";
                            }

                            echo 'By '.$full_name;
                            ?>

            <div class="feature-image" style="background-image: url(<?php echo $image_url[0];  ?> );">

        <?php endforeach;
        wp_reset_postdata();
        ?>

<?php } ?>


text:
Q: Induce Mac graphical login from SSH How do I induce the Mac graphical login from SSH? Is there a way to make the loginwindow process start a user session by running a command when remotely logged in via SSH as an admin on Mac OS X?
When the machine is at the login window (no user is currently logged in), I want it to open up a user's session as if I had clicked on the username and entered a password.
Solutions that don't involve scripting the GUI are highly preferred, but this Apple KB page may be of interest for those who go that route.

A: Not knowing the password makes things complicated, but maybe the solution is: is it possible to temporarily blank out a user's password? (And afterwards reset it to whatever it was before.)
As a start:
First, get the login window to display. Just log out the current user, use fast user switching, or use SSH:
cd "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/"
sudo ./CGSession -suspend

Or, to switch to a specific user right away, which will probably show the login window (this suddenly no longer works on my 10.5 Leopard):
sudo ./CGSession -switchToUserID 501
What's shown now depends a bit on the System Preferences, but let's assume it's the users' icons and their names. To activate a name we'd have to type the first letters. Then, after Return, the password prompt shows. Alternatively one can select any name (like by pressing Arrow Down) and then press Option-Return to be prompted for both any username and its password. I don't know how one can tell which screen is shown, but let's save that for later...
So, to select the first (random) user name and press Option-Return, type a specific user name, hit Return, and type the password:
sudo osascript -e 'tell app "System Events"
  key code 125
  keystroke return using option down
  keystroke "the username"
  delay 1.0
  keystroke return
  delay 1.0
  keystroke "the password"
  delay 1.0
  keystroke return
end tell'
The above shows some error, which as far as I can tell does not limit the usage:
osascript[285] : 3891612: (connectAndCheck) Untrusted apps are not
    allowed to connect to or launch Window Server before login.
_RegisterApplication(), FAILED TO establish the default connection to
    the WindowServer, _CGSDefaultConnection() is NULL.
Alternatively, use the language specific script from "Script the Login window through Apple Remote Desktop" (maybe one day the comments at that site will show a better solution):
tell process "SecurityAgent"
  set value of text field 1 of group 1 of window 1 to "the username"
  set value of text field 2 of group 1 of window 1 to "the password"
end tell
click button "Log In" of window 1 of application process "SecurityAgent"
But the main problem is: this still needs the password. However: obviously no password is needed when a user has a blank password. In fact, for blank passwords just clicking a user's icon is all that's needed. So, if sending keystrokes using AppleScript is acceptable, then maybe "all" that's left to figure out:

*

*Is it possible to temporarily blank out a user's password, to allow for starting (or resuming) the session without knowing that password...?

*Can one make the AppleScript error-proof? Like:

*

*How to tell if the login window is visible? (maybe stat -f%Su /dev/console can help, as that yields root while the login window is displayed)

*How to tell which login window is shown? (Like: one showing icons and login names, or a dropdown list, or maybe only a password prompt if someone selected to switch to some specific user?)

*Get rid of the delays.

*What about that error message?

(A note for testing: when using Screen Sharing it seems that setting the preference When controlling computers: Encrypt passwords and keystrokes only also retains the connection when the login window is shown, or after a user has successfully logged in. When using Encrypt all network data then my Mac needs to re-establish the Screen Sharing connection each time a login is shown or a user is switched.)

A: I've been investigating this recently.
Put this in your app's PAM stack, or test with sshd:
session    required       pam_launchd.so launchd_session_type=Aqua

That goes a long way towards getting you a graphical session which is pretty close to a switched-out user session. In particular, it's in the right bootstrap namespace and has the correct bootstrap ports (I think). You can check the source for what pam_launchd does; it's using some reasonable-looking private library (vproc_priv.h functions in libvprop) to call the Mach routines for setting up the ports and namespace. It matches with all the (limited) docs Apple provides for the Mach-derived syscalls.
Next, you need to set your audit user-id to the that of the user with the BSM API, or the loginwindow won't talk to you on Lion.
The session looks very close to a switched-out session now if you check "launchctl blist", and some processes and services come to life nicely (like the pasteboard, and so on). In fact, everything except Finder and loginwindow is running. Until loginwindow runs though, you can't launch a graphical application, and the per-session loginwindow process is always spawned as a direct child of the global one. How does one poke the loginwindow process to launch a new loginwindow in the fresh session? I can't find a way to get the last piece in place!
Any help completing this answer gratefully received.

A: running the command with sudo allows you to set the script to unreadable by standard users.  It's not perfect, but if your admin user is already compromised, the game is over anyway!
chmod u-r scriptname
my script looks like this, it works remotely when one user is already running, to switch to a second user via SSH (tested on Snow Leopard 10.6.3):
#!/bin/bash
#go to login window
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -switchToUserID 503

osascript -e 'tell app "System Events"
keystroke "password"
  delay 1.0
  keystroke return
end tell'

exit

A: I needed to log the same user into 25 different workstations, in order to do a software update.  I was not able to run the 'osascript -e ...' command reliably from SSH sessions, even with sudo privileges.  I was, however, able to run it via Apple Remote Desktop.  If you have ARD:

*

*select your machines

*wake them up and log them out of other users, if needed

*choose "Send UNIX Command..." from the "Manage" menu

*paste Arjan's script (omitting the word 'sudo') into the command dialog box

*select and enter "Run command as: User: root"

I was delighted to find all 25 Mac Minis running Finder as the user, within less than a minute.  Just to reiterate, with ARD you don't have to type in the sudo password on every machine.  The lines you need to paste into the command dialog are (substituting a valid user name and password):
osascript -e 'tell app "System Events"
  key code 125
  keystroke return using option down
  keystroke "the username"
  delay 1.0
  keystroke return
  delay 1.0
  keystroke "the password"
  delay 1.0
  keystroke return
end tell'

A: You can setup autologin via defaults command in mac depending on your security requirements. https://apple.stackexchange.com/questions/264068/can-autologin-be-set-up-from-the-command-line-how


text:
Q: Geometric probabilistic problem on a plane Let $T$ be a triangle with vertices belonging to a given Cartesian plane $P$ and with side lengths $a$, $b$ and $c$, where $a\ge b\ge c\ge 0$. Let $L_T$ be a straight line selected uniformly at random from the set of all straight lines on $P$ intersecting $T$, which we define as follows:
$L_T$ is selecting uniformly at random from the set of all straight lines intersecting $T$ and making an angle $\theta$ with a given axis of $P$, where $\theta$ is selected uniformly at random from $[0,\pi)$.

Question: What are the probabilities $\Pr(a)$, $\Pr(b)$ and $\Pr(c)$ that each side of $T$, with length $a$, $b$ and $c$ respectively, is not intersected by $L_T$?

A: The answer I propose is:
$$Pr(a)=\dfrac{b+c-a}{a+b+c}, \ \ \ \ Pr(b)=\dfrac{c+a-b}{a+b+c}, \ \ \ \  Pr(c)=\dfrac{a+b-c}{a+b+c} \tag{0}$$
Why that ? This question deserves to be formulated at first in terms of "measure theory",  probabilities being considered in a second step, in the framework of the domain called "Integral Geometry" or "Geometric Probability" (see Historical note below).
As all plane lines can be given a unique standardized form:
$x \cos \theta+y \sin \theta=p, \tag{1}$
Therefore, $(p,\theta)\in \mathbb{R^+} \times [0,2\pi)$ is a parameterization of the set of plane lines.
With this parametrization, a natural measure (invariant for the group of direct isometries) is
$$\mu(S)=\int_S dpd\theta$$
(see first reference at the bottom of this text).
For example the measure of the set of straight lines intersecting the disk centered in $0$ with radius $R$ is:
$$  \int_{(p,\theta)\in [0,R] \times [0,2\pi)}dpd\theta=\int_{p=0}^R\int_{\theta=0}^{2 \pi}dpd\theta=2 \pi R$$
(i.e., its perimeter).
Let $S_{A|B,C}$ be the set of lines that separate vertex $A$ from vertices $B,C$, otherwise said, that intersect $AB$ (length $c$) and $AC$ (length $b$) but not $BC$ (length $a$).
One can compute the measure of set $S_{A|B,C}$ to be:
$$ \mu(S_{A|B,C}) \ = \ \int_{S_{A|B,C}} dpd\theta \ = \ b+c-a \tag{2}$$
and similar formulas for the other cases.
It is remarkable that the positivity of measure (2) is equivalent to triangle inequality...
One has to work with conditional probabilities, i.e., by assuming that we limit our attention to lines $(L)$ intersecting triangle $ABC$.
Due to the fact that a line that intersects a triangle intersects two and only two of its sides (setting apart lines passing through one of the vertices, which have measure $0$, therefore are neglectable from the point of view of measure theory):
$$(L) \in S_{A|B,C}, \ \ (L) \in S_{B|C,A}, \ \ (L) \in S_{C|A,B}$$
are disjoint and their union is the whole set of lines (complete set of events in probabilistic terms). Therefore, we have a total measure:
$$(b+c-a) \ + \ (c+a-b) \ + \ (a+b-c) \ = \ a+b+c$$
i.e, the perimeter of the triangle (as was found for the disk above) !
As a consequence, the (conditional) probabilities you are looking for can "logicaly" been taken as given by (0).
Historical corner: "Integral Geometry" (aka "Geometric probability") was initiated by Buffon in the mid-18th century, then by Crofton in the $1880$s, followed by Poincaré (cinematic formulas, see reference below) around 1900, but especially developed by Blaschke and his students circa $1930-1950$ (see Santalo's book "Integral Geometry and Geometric Probability" for a rather clear exposition).
Remark: A cousin domain of Integral Geometry is "Stereology"
A nice presentation of Integral Geometry can be found here.
A rather accessible reference here.
For a generalisation of the perimeter result, see Cauchy-Crofton formula
For cinematic formulas see this (more difficult!) reference.
Another (very theoretical) reference.

Edit: For 3D, use Crofton formula (one of the many formulas of stereology dealing with a number of intercepts $N(...)$ of a variable plane $P$ with a fixed triangle $T$):
$$\int N(P \cap T) d\mu  \ = \ \pi L(T)$$
where $L(T)$ is the length (= perimeter) of triangle $T$.
($N=0,2$ in the case of a triangle, $N=1$ being a case with measure $0$).
Of course, practically speaking, the integral in the LHS will be approximated using a mean value...


text: Q: How do I get access to the bounds of a view present in ViewController class from another class? I have a map drawing app and I need to access the view's bounds from other classes so that I can determine the drawing levels on the map. How would I access the bounds of one the views present in ViewController from another class?


text:
Q: how to print the div contents using jquery I am trying to print my contents, but the body does not contain the entire print contents which i am inserting. Seems to some sort of height issue.
var printcontent=$("#printDiv").html();
var printdiv=document.createElement('div');
$(printdiv).html(printcontent);
$('body').before(printdiv);
$('body').css('visibility', 'hidden');
window.print();
$('body').css('visibility', 'visible');

A: if you want to print certain data I recommend set media using css like this
@media print {
    p {
        font-family: georgia, serif;
        font-size: 14px;
        color: blue;
    }
}

this will give you p content when you go for print. same you can do for your div element

A: CSS media query (print) is the right way to do it. You could also do something like the following in jQuery. Bear in mind that you'd end up having an extra div around your body contents, but that may not be a problem I guess.
var printcontent = $("#printDiv").html();
var printdiv = $('
', { 'id': "print-layout"}).html(printcontent);

$('body').wrapInner("

");
$('#body-content').before(printdiv);
$('#body-content').css('visibility', 'hidden');

window.print();
setTimeout(function() {
    $('#print-layout').remove();
    $('#body-content').css('visibility', 'visible');
}, 0);

*

*Here is a working demo for the above

*Why setTimeout(fn, 0) is useful


text:
Q: case expressions must be constant expressions error when using map types in optionMenu In every case it gives me the error case expressions must be constant expressions.I am working on application on Google Maps API V2 and I have added the map types to the Option Menu (onOptionItemSelected)
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.mapTypeNormal:
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case R.id.mapTypeTerrain:
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case R.id.mapTypeSatellite:
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.mapTypeHybrid:
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case R.id.gotoCurrentLocation:
                gotoCurrentLocation();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }

tried converting switch into if-else..But the same error appears
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.mapTypeNormal) {
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        } else if (itemId == R.id.mapTypeTerrain) {
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        } else if (itemId == R.id.mapTypeSatellite) {
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        } else if (itemId == R.id.mapTypeHybrid) {
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        } else if (itemId == R.id.gotoCurrentLocation) {
            gotoCurrentLocation();
        } else {
            return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);

    }

A: The issue is that all of your R.id values are not actually final as they should be. In your R file, you'd find that they are something like public static int sample=0x7f035054;.
The solution to that issue is using if statements. The code you have provided the second time SHOULD work. You can't possibly be getting an "case expressions must be constant expressions" if you had removed the switch statement and used those if statements instead.
Try restarting your IDE and rebuilding the project, with the switch statement definitely replaced by the if statements.


text:
Q: How to reduce padding-top of content area on the Stack Overflow website I want to reduce the size of padding-top for the content area of the Stack Overflow website - using some custom CSS code applied using Tampermonkey.
The element I'm talking about is called div#content and currently padding-top is set to 24px. I want to reduce just this padding, but keeping the others the same.
Here is a minimal template using Tampermonkey:
// ==UserScript==
// @name        stackoverflow_reducepaddingtop
// @match       *://stackoverflow.com/*
// @grant       GM_addStyle
// @run-at      document-start
// ==/UserScript==

GM_addStyle ( ` ` );

A: Refer to:

*

*How to change a class CSS with a Greasemonkey/Tampermonkey script?
and

*Understanding Style Precedence in CSS:
Your script was complete except for the actual CSS.  So finished it is:
// ==UserScript==
// @name        stackoverflow_reducepaddingtop
// @match       *://stackoverflow.com/*
// @grant       GM_addStyle
// @run-at      document-start
// ==/UserScript==

GM_addStyle ( `#content {padding-top: 0px !important;}` );

Note that the !important; flag may not be needed for that exact selector (right now), but other CSS you could use does require it in a Stylus or GM_addStyle scenario. (Especially when using document-start.)


text:
Q: How do I Open the Red-Locked Doors? If you climb to the very top of Dustforce's hub world, you find a row of locked doors, and a scientist with the following message:

I wouldn't go in there if I were you.

How do I open these doors?  I don't want to know what's behind them, so please don't post it in your answer.

A: You need to get a SS on a gold door level to get a red key.
An SS on a silver door gets you a gold key.
Spoiler withheld by request, but iirc there are 16 red door locks here ;)


text:
Q: Find the values for n0 and the constant factor c such that f(n) = n log n is Ω(n) I was recently introduced to big O and big Omega, as well as big theta. I know that big O is the worse case scenario in terms of runtime, big Omega is the best case scenario, and big theta is in between. However, I'm still confused on how I would use it mathematically to prove that n log n = Ω(n). Also, I get that n0 is the lowest possible number for the equation to work, but where does the constant factor c come in? Any advice and help is greatly appreciated, thanks!

A: If you understand the definition of big-O, but struggle with the definition of big-Ω, you can use Knuth's definition of big-Ω to turn it around for you:
f(n) = Ω(n) <=> n = O(f(n))
Thus, if you can prove that n = O(n logn), you have proven your original problem.
If you are looking to understand the c and n0 defnition of big-Ω, I'm sure there are examples online. As already noted, see cs.stackexchange.com and math.stackexchange.com.

A: As mentioned in the definition of big-Ω,
we can say if the function f(n) is having growth rate faster than that of g(n) , f(n) = Ω(g(n))
Here n log n always grows faster than n
Hence, n log n = Ω(n).


text:
Q: Android - status bar prevents full screen My app correctly runs in full screen when it's started. However after minimizing and then returning to the app, the status bar pops up and pushes my views down a little. How can I keep the status bar from moving my views?
Here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.example.draw"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
    <com.example.draw.DrawView
        android:id="@+id/draw"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:fitsSystemWindows="false"
    />
<com.admob.android.ads.AdView
       android:id="@+id/ad"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       myapp:backgroundColor="#000000"
       myapp:primaryTextColor="#FFFFFF"
       myapp:secondaryTextColor="#CCCCCC"
       android:layout_gravity="bottom"
/>

Here is part of my activity's onCreate:
requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);

I also have the fullscreen theme in the manifest:
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Thanks

A: There are known bugs with the status bar / notification bar.
See:
http://code.google.com/p/android/issues/detail?id=3674
http://code.google.com/p/android/issues/detail?id=8052
http://code.google.com/p/android/issues/detail?id=5906

A: You can fix this issue with:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

(do that in onCreate).... note that this will break the soft keyboard (IME) - as edittext can no longer slide into view above the keyboard. That flag prevents the window from moving at all....
If you need an edit text to also work while fixing the status bug you can do
someEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            } else {
                hideKeyboard();
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }
    });

A: Just android:theme="@android:style/Theme.NoTitleBar.Fullscreen" attribute on your activity on the manifest is enough. Hope its works

A: I had the same issue. I changed the activity for the interstitial and deleted:
android:theme="@android:style/Theme.Translucent"


text:
Q: InvalidArgumentError: Graph execution error: TensorFlow pose estimation using OpenCV I am trying to build pose detection using cv2, tensorflow in google colab
I am encountering with the following error..
Code:
import tensorflow as tf
import tensorflow_hub as hub
import cv2
from matplotlib import pyplot as plt
import numpy as np
from google.colab.patches import cv2_imshow

model = hub.load('https://tfhub.dev/google/movenet/multipose/lightning/1')
movenet = model.signatures['serving_default']

img_original = cv2.imread('/content/brandon-atchison-eexdeq3NleQ-unsplash.jpeg',1)
img_copy = img_original.copy()
input_img = tf.cast(img_original,dtype=tf.int32)
img_copy.shape

tensor = tf.convert_to_tensor(img_original,dtype=tf.int32)
tensor

results = movenet(tensor)

I have created the variable img_copy cuz I need to perform some operations on the image and want the  original image as it is. Not sure what is the error I am facing while trying to get results from the movenet model.

edit:

A: Try:
results = movenet(tensor[None, ...])

since you are missing the batch dimension, which is needed to feed data to your model. You could also use tf.expand_dims:
tensor = tf.expand_dims(tensor, axis=0)
# resize
tensor = tf.image.resize(tensor, [32 * 186, 32 * 125])

Here is a working example:
import tensorflow_hub as hub

model = hub.load('https://tfhub.dev/google/movenet/multipose/lightning/1')
movenet = model.signatures['serving_default']

tensor = tf.random.uniform((1, 160, 256, 3), minval=0, maxval=255, dtype=tf.int32)
movenet(tensor)

Check the model description and make sure you have the correct shape:

A frame of video or an image, represented as an int32 tensor of dynamic shape: 1xHxWx3, where H and W need to be a multiple of 32 and the larger dimension is recommended to be 256. To prepare the input image tensor, one should resize (and pad if needed) the image such that the above conditions are hold. Please see the Usage section for more detailed explanation. Note that the size of the input image controls the tradeoff between speed vs. accuracy so choose the value that best suits your application. The channel order is RGB with values in [0, 255].


text:
Q: Android FragmentStatePagerAdapter for custom View because I don't like the default implementation of Android's Bottom Navigation Bar, I have made my own and connected it with a FragmentStatePagerAdapter. I just want to know how I can get already created Fragments with their saved instance state from my adapter just like viewpager does?
It would be nice if anyone could help me solve this.

A: I solved it on my own. I totally had forgotten to care about the Saved Instance State of my view. I got it from the ViewPager source code and modified it slightly because some  Methods were marked as deprecated. Here the implementation.
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    SaveState ss = new SaveState(superState);
    ss.position = lastSelectedPosition;
    ss.itemId = lastSelectedItemId;
    if (mAdapter != null) {
        ss.adapterState = mAdapter.saveState();
    }
    return ss;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (!(state instanceof SaveState)) {
        super.onRestoreInstanceState(state);
        return;
    }
    SaveState ss = (SaveState) state;
    super.onRestoreInstanceState(ss.getSuperState());
    if (mAdapter != null) {
        mAdapter.restoreState(ss.adapterState, ss.loader);
        setSelectedItem(ss.position, ss.itemId);
        lastSelectedItemId = ss.itemId;
        lastSelectedPosition = ss.position;
    }
}

public static class SaveState extends BaseSavedState {
    int position;
    int itemId;
    Parcelable adapterState;
    ClassLoader loader;

    SaveState(Parcelable superState) {
        super(superState);
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(position);
        out.writeInt(itemId);
        out.writeParcelable(adapterState, flags);
    }

    public static final Parcelable.ClassLoaderCreator<SaveState> CREATOR = new
    Class later dater<SaveState>() {
        @Override
        public SaveState createFromParcel(Parcel source) {
            return new SaveState(source, null);
        }

        @Override
        public SaveState[] newArray(int size) {
            return new SaveState[size];
        }

        @Override
        public SaveState createFromParcel(Parcel source, ClassLoader loader) {
            return new SaveState(source, loader);
        }
    };

    SaveState(Parcel in, ClassLoader loader) {
        super(in);
        if (loader == null) {
            loader = getClass().getClassLoader();
        }
        position = in.readInt();
        itemId = in.readInt();
        adapterState = in.readParcelable(loader);
        this.loader = loader;
    }

}


text:
Q: When does a wordpress subscriber become a woocommerce customer? Ok so I'm trying to find out what determines a wordpress user becomes a subscriber or a customer. So my site has over 5000 subscribers but 1000 customers. Lately I have been getting hit by bots that will register 300 - 400 accounts in a day. So I'm trying to determine if its' the registration form itself that determines who becomes what role. Like if it's original wordpress form they become a subsriber but a woocommerce registration form they become a customer. As the bots are using a very specific link to automatically register and it's the default wordpress registration link. So I'm trying to figure out the best way to avoid this from happening while also being able to determine fake subscriber from real subsribers, as checking some of the subsribers have actually logged in. I figured then all customers should have logged in, assuming customers were created once they purchased something from the store but in fact thats not the case. So any real input on this would be very nice and helpful.

A: So talking to Wordpress and Woocommerce it is when the user uses the Woocommerce Registration Form is when a user is assigned the Customer Role over Subscriber Role.
I want to add to this now also, I'm unsure what update this occured but in Wordpress Settings->General Tab there is a box that asks for New User Default Role. So now you can make sure every user is a customer or a subscriber or whatever role you decide to choose.


text:
Q: try-with-resource without declaring variable I want to use try-with-resource to switch context but it seem try() can't use a resource without declaring a variable which makes the code less elegant. e.g.
class SwitchContext implements Closeable {
   public SwitchContext(String newContext) {
     //Set new context to local thread
   }

   public void close() {
     //Restore old context to local thread
   }

and the usage:
String func() {
  try (new SwitchContext(newContext)) {
     //Do something
     return "dummy";
  }

void func2() {
  try (new SwitchContext(newContext)) {
     //Do something
  }

But I get Syntext error on the try(). Only if I write it like this:
try (SwitchContext c = new SwitchContext(newContext)) {
It passes compilation.
What is the most elegant way to do it?
Update
Since in some of the answers people didn't understand what I'm trying to do I'll try to explain better. I'm trying to do the following logic in a more elegant way:
void func() {
   Context old = ContextUtil.getCurrentContext();
   try() {
       ContextUtil.setContext(A)
       //Do something or call other methods
       //Any method than need the context use ContextUtil.getCurrentContext()
   } finally () {
      ContextUtil.setContext(old)
   }
}

A: Do not discard the new object's reference
The new command returns a reference to the newly instantiated object. Your code attempt would discard that reference. So none of your code to follow could access that instantiated resource object. It makes no sense to create a resource object that cannot be used.
The solution is to create a reference variable into which we can capture the newly created resource object's reference.
String func() {
    try (
        SwitchContext context = new SwitchContext( newContext ) ;
    ) {
    // Do something with that resource.
    String result = context.calculate() ;
    return result ;
}
// At this point, `SwitchContext#close` has been called and executed, closing our resource object.

You commented, « It is not a truly new resource ». If you mean the object you want to utilize and automatically close has already been instantiated, use a different form of try-with-resources.
In later versions of Java, your try-with-resources can access, and automatically close, a resource that was instantiated earlier.
SwitchContext context = new SwitchContext( newContext ) ;
… more code …
String func() {
    try (
       context
    ) {
    // Do something with that resource.
    String result = context.calculate() ;
    return result ;
}
// At this point, `SwitchContext#close` has been called and executed, closing our resource object.

Try-with-resources is all about calling close
Keep in mind that the entire point to using try-with-resources is to have the JVM automatically call the resources' close method. If calling close is not your intention, use a different flow-of-control structure in your code.

A:
The try-with-resources statement is a try statement that declares one or more resources

From the Oracle tutorial.
Long story short: the syntax of a language is what it is. And when the language asks for a declaration, then that is what you have to put in your code.
Or, when you want the formal stuff, check out the JLS:
TryWithResourcesStatement:
try ResourceSpecification Block [Catches] [Finally]

ResourceSpecification:
( ResourceList [;] )

ResourceList:
Resource {; Resource}

Resource:
LocalVariableDeclaration
VariableAccess
VariableAccess:
ExpressionName
FieldAccess


text:
Q: How to use autodetect schema in big query app script to load string type columns as headers in bigquery table? I have a google script that loads the csv table from cloud storage to big query. It works fine with most tables but when all the columns types are string, the auto detection is not able to find header name and it gives the column as string_01, string_02. Here's is the part of the code.
        load.setDestinationTable(tableReference);
        load.setSourceUris([source]);
        load.setSourceFormat('CSV');
        load.setAutodetect(true);
        load.setMaxBadRecords(0);
        load.setWriteDisposition('WRITE_TRUNCATE');

Does anyone know what can I add to the code to have the first line be selected as the header for the table. Any help would be appreciated.

A: You may have to add skip_leading_rows.
load.skipLeadingRows(1)

This will let the API know that 1st row is a header and should not be used as part of the "data" import.


text:
Q: How to create a map on your webserver that has the same name as a permalink without having a 403 error In Wordpress we created some pages like

*

*website.com/page-1/

*

*website.com/page-1/subpage-1/

*website.com/page-1/subpage-2/

*website.com/page-2/

*

*etc. etc.

Now on the FTP we also created a map called 'page-1'. This map only contains another folder called 'app' (so we have website.com/page-1/app).
Now some visits are getting a 403 error on 'website.com/page-1' because the server does not route the traffic to Wordpress but to the -almost empty- folder on the FTP called 'page-1'. Most browsers do fine, SEO checkers and some proxy's do not route to the Wordpress page.
Can I resolve this issue so that visitors are always getting to the Wordpress page when visiting 'website.com/page-1'?
When I delete the folder called 'page-1' the issue is resolved. Too bad I need this folder because an emailing went out with this specific URL.


text:
Q: Finding Azure/AD groups with React-AAD-MSAL I have integrated basic authentication with the React-Aad-MSAL client into a my react-app which allows me to get things like the users name and email successfully. Here in a component I wanted to check the users groups before displaying some data.
import React, { useContext } from 'react'
import { observer } from 'mobx-react-lite'
import { Container, Header } from 'semantic-ui-react';
import {
    AzureAD,
    AuthenticationState,
    IAzureADFunctionProps
  } from "react-aad-msal";
import { authProvider } from '../../../app/auth/authProvider';
import { RootStoreContext } from '../../../app/stores/rootStore';

const PurchasePipelineDashboard: React.FC = () => {
    const rootStore = useContext(RootStoreContext)
    const {
        idTokenClaimsAction } = rootStore.serverCatalogStore;

    return (
        // <Container style={{marginTop:'7em'}}>
        //
        // </Container>
        <AzureAD provider={authProvider} >
        {({
          accountInfo,
          authenticationState,
          error
        }: IAzureADFunctionProps) => {
          return (
            <React.Fragment>
              {authenticationState === AuthenticationState.Unauthenticated && (

Oooo weee!

              )}
            </React.Fragment>
          );

        }}
      </AzureAD>
    )
}

export default observer(PurchasePipelineDashboard);

My question is; how would I go about gathering what groups the user is in? I have checked the accountInfo.account.idTokenClaims, but none of those return tokens. I see other tutorials using Graph, but do I actually need both libraries? Any help would be greatly appreciated!

A: You have two options here, you can either add them to the claims in the token as per here: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims#configuring-groups-optional-claims
but there are limitations, such as it will only return something like 150-200 groups max.
or you can make a separate graph api call to get users groups. Here's an example of how to call graph with react https://github.com/microsoftgraph/msgraph-training-reactspa
You would be looking at the getmembergroups endpoint of graph for this: https://learn.microsoft.com/en-us/graph/api/user-getmembergroups?view=graph-rest-1.0&tabs=http


text:
Q: How to analytically continue the 'two-dimension' zeta function? How to meromorphically continue
$$f(s)=\sum^\infty_{n=1}\sum^\infty_{m=1}\frac1{(an+bm)^s}$$ to $\Re s\le 2$? ($a,b$ are positive constants.)
In the case $a=b$, we have
$$f(s)=a^{-s} \sum^\infty_{n=1}\sum^\infty_{m=1}\frac1{(n+m)^s} =a^{-s}\sum^\infty_{N=1}\frac{N-1}{N^s}=a^{-s}(\zeta(s-1)-\zeta(s))$$ and we can exploit the well-known analytic continuation of $\zeta$ to continue $f$ to a meromorphic function on $\mathbb C$.
How about for arbitrary $a,b$?

A: As usual, for $a >0,b>0,\Re(s) > 2$ $$\Gamma(s)F(a,b,s)=\Gamma(s)\sum_{n,m} (an+bm)^{-s}=\sum_{n,m} \int_0^\infty x^{s-1}e^{-(an+bm)x}dx$$ $$= \int_0^\infty x^{s-1}\sum_{n,m}e^{-(an+bm)x}dx=\int_0^\infty \frac{x^{s-1}}{(e^{ax}-1)(e^{bx}-1)}dx $$
The latter converges and is analytic for $\Re(a)> 0,\Re(b) > 0,\Re(s) > 2$.
With $f_{a,b}(x)=\frac{x^2}{(e^{ax}-1)(e^{bx}-1)}$ we obtain for $\Re(s) > 1-K$
$$\int_0^\infty x^{s-3}(f_{a,b}(x)-1_{x <1}\sum_{k\le K}\frac{f_{a,b}^{(k)}(0)}{k!}x^k)dx = \Gamma(s)F(a,b,s)-\sum_{k\le K}\frac{f_{a,b}^{(k)}(0)}{k!}\frac1{s-2+k}$$
which is the analytic continuation of the RHS to $\Re(s) > 1-K$.
Thus $\Gamma(s)F(a,b,s)$ is meromorphic on the whole complex plane and the integers $\le 2$ are simple poles of residue $\frac{f_{a,b}^{(2-k)}(0)}{(2-k)!}$,

Whence $F(a,b,s)$ is analytic for $\Re(a)>0,\Re(b) > 0,s\in \Bbb{C}-\{ 1,2\}$.


text:
Q: Sending email from php and mysql - avoid duplicate but join in one message I have been working on the code that would ultimately send e-mails to people matched to each other in terms of interests and other parameters.
In general, the database has already been built, the queries also get the effect that satisfies me, i.e. people who match each other in the answer.
Here I will present briefly what the cut base looks like and the query displaying users who are matched to each other:
DB FIDDLE LINK
Then, for preview purposes, it uses a query on my site that looks something like this:
PHP + HTML:
    SEND EMAIL'S!
    <?php
     include_once 'connection.php';
     $result = mysqli_query($conn,"select
     m.id, m.name, m.email,
     f.id, f.name, f.email
     from
     choices c
     join choices s
     on c.chooser = s.choice
     left join users m on m.id = c.chooser
     left join users f on f.id = c.choice
     where s.chooser = c.choice
     and m.gender = 'M'
     and f.gender = 'F'");
    ?>

    <?php
     if (mysqli_num_rows($result) > 0) {
    ?>

      Id
      Name
      Email

      Id
      Name
      Email

    <?php
     $i=0;
     while($row = mysqli_fetch_array($result)) {
    ?>

    <?php echo $row["0"]; ?>
    <?php echo $row["1"]; ?>
    <?php echo $row["2"]; ?>

    <?php echo $row["id"]; ?>
    <?php echo $row["name"]; ?>
    <?php echo $row["email"]; ?>

In response, I get:
| id | name | email | | id | name | email |
| -- | ---- | ----- |-| -- | ---- | ----- |
| 203 | TOM W | tomw@gmail.com || 101 | KATE B | kateb@gmail.com |
| 204 | MARK K | markk@gmail.com || 101 | KATE B | kateb@gmail.com |
| 204 | MARK K | markk@gmail.com || 102 | ALEX S | alexs@gmail.com |

Now for my problem.
Is there anyone able to show an example of how to press the SEND EMAIL'S (send.php) Send an email to all of their matches (both male and female), but if any of these people have more than one match I would like to avoid sending two emails to the same person, just include all their matches in one body
What e-mails do I expect?
First email:
From: MyEmail@gmail.com
To: tomw@gmail.com
Subject: Got a match!
Body:
Congratulations TOM W!, we matched you with:
KATE B (kateb@gmail.com)

And this is not a problem ... But the problem arises when sending an email to KATE B, who already has two matches: TOM W and MARK K.
From: MyEmail@gmail.com
To: kateb@gmail.com
Subject: Got a match!
Body:
Congratulations KATE B, we matched you with:
TOM W (tomW@gmail.com)
MARK K (markk@gmail.com)

And further, the message to MARK K will contain two people in the body because he has two matches, both with Kate B and Alex S (one message with two matched people) and Alex S in the body will have only one person, which is MARK K.
Is anyone able to show such universal code written in php that will send e-mails as described above?


text:
Q: KSOAP namespaces and XML output formatting of request I'm building an Android app that needs to get some data via a SOAP interface. I'm trying to use the KSOAP2 module (using ksoap2-android-2.6.0-jar-with-dependencies.jar).
I'm having trouble with getting KSOAP to give me correct namespace prefixes in child elements.
I want this:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
<n0:GetRequest id="o0" c:root="1" xmlns:n0="http://dummy.com/nbi">
    <n0:Port i:type="d:string">Data</n0:Port>
</n0:GetRequest>
</v:Body></v:Envelope>

but ksoap2 gives me this:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
<n0:GetRequest id="o0" c:root="1" xmlns:n0="http://dummy.com/nbi">
    <Port i:type="d:string">Data</Port>
</n0:GetRequest>
</v:Body></v:Envelope>

The only difference being that the Port element in the 2nd XML request doesn't have the n0 prefix on the tag label.
I've been brushing up on proper namespace xml theory and it seems to me that well formed XML should either have the namespace prefix on all the relevant elements or the parent element should have a default namespace definition. Playing with SoapUI I can manually submit requests to my server and get either of those options to work, but I can't work out how to make ksoap produce either request format. i.e. I can't work out how to produce an element with a default namespace or how to produce an element that has the namespace prefix on every child element.
I've tried every variation of settings I can think of but the only (inelegant) solution I can come up with is to manually add the prefix to the Port label.
Has anyone worked out how to do achieve what I want?
My SOAP server doesn't like the request without the strict XML formatting syntax.
Here's the relevant code snippet:
private static final String namespace = "http://dummy.com/nbi";
private static final String URL = "http://192.168.254.117/soap/nbi";
String SOAP_ACTION = namespace + "/" + methodCall;
SoapObject request = new SoapObject(namespace, methodCall);
    PropertyInfo pi = new PropertyInfo();
pi.setName("myName");
pi.setValue("myString");
pi.setType(String.class);
    request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = false;
envelope.setAddAdornments(false);
envelope.implicitTypes = false;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try
   {
    List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
    headerList.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("nbsam:nbsam".getBytes())));
        androidHttpTransport.call(SOAP_ACTION, envelope, headerList);
        SoapObject response = (SoapObject)envelope.getResponse();
        String result = response.getProperty(0).toString();

    }

A: I worked this out in the meantime.
Quite simple really but I didn't see other examples of this when searching about.
Just need to use the setNamespace method on the PropertyInfo used to construct the request.  Like this:
pi.setNamespace("http://example.com/nbi");

A: If you want to remove the namespace only from the Property you can set an empty string when create the PropertyInfo. Like This:
PropertyInfo pi = new PropertyInfo();
pi.setNamespace("");
pi.setName("myName");
pi.setValue("myString");
pi.setType(String.class);

A: You can get the default namespace effect using the following scheme.
SoapObject request = new SoapObject(NAMESPACE, "GetRequest");
SoapObject data = new SoapObject("", "Port");
request.addSoapObject(data);

This should give you something like:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
<GetRequest id="o0" c:root="1" xmlns:n0="http://dummy.com/nbi">
    <Port i:type="d:string">Data</Port>
</GetRequest>
</v:Body></v:Envelope>

You can also do envelope.setAddAdornments(false) on the Envelope to get an even nicer:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
<GetRequest xmlns:n0="http://dummy.com/nbi">
    <Port i:type="d:string">Data</Port>
</GetRequest>
</v:Body></v:Envelope>


text:
Q: cache.match() returns response but no headers When I'm performing a cache.match(url) I successfully get a response. But the response the cache is giving me has no headers and I can't understand why.
When I'm looking into the developer tools and the cache storage, I can see the headers that are stored with the corresponding request.
Does anyone know, why I cannot get the headers?


text:
Q: A reliable aluminium battery that charges in a minute. What's the catch? This article

Ultra-fast charging aluminum battery offers safe alternative to conventional batteries, phys.org.

reports on the finding by a Stanford group of an aluminium-ion battery that can apparently compete in most respects with lithium-ion ones, lasts for thousands of cycles, and can be recharged in about one minute.

An ultrafast rechargeable aluminium-ion battery. M.-C. Lin et al. Nature (2015) (epub ahead of print).

To read both the paper and the phys.org report, everything is fantastic and this is the solution to all world problems, which makes me a bit suspicious. What's the catch?

A: They write that capacity is still half of that of lithium ion batteries, although this can probably be improved. However, this does look like a real breakthrough.


text:
Q: Combining HTML Form to Datatables ajax request Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin.
I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading).
I want to retrieve data from the following URL:
/api/device_input/?format=datatables&device_id=something
// device_id can be 1, 2, 3 and so on.

The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing):
1) User enters device ID into a form. Form gets submitted.
2) Django view takes the POST request and returns the filtered queryset to the template.
3) The queryset populates the HTML table values and datatables handles the rest (pagination etc)
But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is:
1) User opens page, an empty datatable is displayed, with a prompt to enter device ID.
2) User enters device ID, and the datatable is loaded with records for that device id.
But the datatables ajax request only gets invoked when someone messes with the datatable (such as change page or select page length). I want to invoke the ajax request when someone enters device_id into my form and dynamically tell ajax to create the right URL.
Here's what my javascript looks like:
<!-- Javascript function to initialize the datatable -->
<script>
    var device_id = document.getElementById("id_input").value
    $(document).ready(function() {
        $("#device_inputs_table").DataTable({
            "lengthMenu": [
                [10, 20, 30, -1],
                [10, 20, 30, "All"]
            ],
            fixedHeader: {
                headerOffset: 62
            },
            "order": [
                [0, "desc"]
            ],

            "serverSide": true,
            "ajax": "/api/device_input/?format=datatables&device_id=" + device_id, // need to add a number at the end that user will input
            "columns": [
                // All my table columns
            ]
        });
    });
</script>

I'm sure this is simple to do, but my unfamiliarity with ajax and javascript has me scratching my head, any help is appreciated!
UPDATE: I tried adding a simple variable to get device_id from the form element, but it doesn't get added to my URL... how do I print my URL out on the dom? (I'm only checking through the network tab on chrome dev tools...) Of course my form doesn't even invoke the ajax request so that's another issue.

A: First you need to declare a variable to hold the DataTable and call it from your javascript.
Example:
var deviceInputsTable = $('#device_inputs_table').DataTable({
// Rest of the table declaration goes here.
})

Then, you create a function that triggers to load data in your deviceInputsTable, something like:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID // (get this from the input)
// do the ajax call here and this is the important part:
success: function(data){
    // This is just a rough scratch, but this is how you initially call the first data in the table, consequent calls will now be server-side since your device_id now has a value in the ajax call you showed above.
    deviceInputsTable.clear().rows.add(data).draw()
}
}

I hope this helps.
EDIT, concerning your comment below:
You can use a normal jQuery ajax call. Something like this:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID;
            $.ajax({
                type: 'GET',
                url: `SomeURLhereAppendingthedeviceIDParameter`,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                   // Transform the AJAX's response here and get the data to add to your data table below
                   deviceInputsTable.clear().rows.add(data).draw()
                }
            });
};

To trigger the ajax again on change of the input, you can call the on change function in jQuery.
$('#id_input').on("change",function(){
loadDeviceInputsTableData($('#id_input').val());
});

A: This issue was solved by using datatable's API, my question was about changing the ajax url dynamically upon user input. Here's what I did:
// Get device ID from wherever user inputs it, in my case it was a button with id: id_input
device_id = document.getElementById('id_input').value;

// Dynamically set your datatable's ajax URL to whatever you want. I concatenated the device id
// string with my url string. ajax.url("your URL") is enough to set the URL
// .load() is for getting data from the new URL you've just set.

$('#device_inputs_table').DataTable().ajax.url(
            "/api/device_input/?format=datatables&device_id=" + device_id).load();

Doing this gave me the final URL: "/api/device_input/?format=datatables&device_id=1" (if user inputted 1) fixing my issue.


text:
Q: Table Reorder to be enabled/disabled based on button click I am using Bootstrap table reorder plugin to reorder rows of a table.
In the HTML table if I set the "data-reorderable-rows" to TRUE then I can reorder the rows.
But if I want to disable the reorder based on click of a button, it is not working.
Code can be found here https://live.bootstrap-table.com/code/devanasrikanth/12935
Any suggestions on how I can disable/enable table reorder based on button click.


text:
Q: AngularJS $rootScope.$emit not Firing the Method I want to fire a directive based on demand using a service. Below is the directive code.
var app = angular.module('MyModule').service('DOMService', ['$rootScope', function ($rootScope) {
    this.Manipulate = function () {
        $rootScope.$emit('manipulateDOM');
    };
}]).directive('domDirective', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'EA',
        replace: 'false',
        scope: true,
        link: function (scope, elm, attrs) {
            $rootScope.$on("manipulateDOM", function () {
                alert("Entered......");
                //  element.find('#DirectiveLable').css('background-color', 'red')
                // element.find('#DirectiveLable').css('height', '100')
            });
        },
    };
}]);

My HTML like below

        <dom-directive>
            Click Here
        </dom-directive>

I am calling the service like below inside my Angular Controller
angular.module('MyModule').controller('CitizenRelationAccordionController', ['$scope', '$q', '$attrs', 'DOMService',
    function ($scope, $q, $attrs, DOMService) {
       DOMService.Manipulate();
    }
 ]);

Issue is that eventhough DOMService is firing, it's not invoking the directive method where alert has written

A: I think that you missed the [] in the module declaration: here is a working example from what you wrote.
Hope this could help,
Dario


text:
Q: MySQL Trigger invalidate I have to invalidate a Before inset trigger so that the line will not be inserted in the table
CREATE TRIGGER Trig1
 ON MyTable
 FOR EACH ROW
BEGIN
.
.
.
.
.
END

Can i use an other way that displays the error message rather than
INSERT into Mytable values (NULL)


text:
Q: How can I extension Java class with Kotlin to use like static fun? public class TestA {
     public static void a() {}
}

fun TestA.b(){}

How can I extension Java class with Kotlin to use like static fun ?
just like TestA.b() to use this fun

A: Actually, it is currently not yet supported to statcally extend a Java-Class. See the corresponding issue
https://youtrack.jetbrains.com/issue/KT-11968


text:
Q: Actualizar Fragment desde CardView A ver si alguien me puede ayudar.
Tengo un Fragment en el que tengo varios TextView con datos y un RecycleView. Dentro del CardView del RecycleView tengo un boton para cada elemento de la lista. Quiero que al pulsar ese boton se me actualicen los valores de los TextView que tengo en el Fragment.
Poniendo en ejemplo.. el RecycleView contiene una lista de productos que he vendido. y un TextView contiene el precio total de la venta. Si al pulsar el boton del CardView quito uno de esos productos. Que actualize el valor que hay en el TextView.
public ViewHolder(View itemView ){
            super(itemView);
        contexto=itemView.getContext();
        txtreferencia=(TextView) itemView.findViewById(R.id.txtreferencia);
        txtcantidad=(TextView) itemView.findViewById(R.id.txtcantidad);
        txtdescripcion=(TextView) itemView.findViewById(R.id.txtdescripcion);
        txtdescripcion=(TextView) itemView.findViewById(R.id.txtdescripcion);
        txtid=(TextView) itemView.findViewById(R.id.txtid);
        btneliminar=(Button) itemView.findViewById(R.id.btneliminarpiezapedido);

        card=(CardView)itemView.findViewById(R.id.cardpiezas);
      // btnlocalizar=(Button)itemView.findViewById(R.id.btnlocalizar);
        btneliminar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                borrar_pieza(Integer.parseInt(txtid.getText().toString()));
        AQUI QUIERO ACTULIZAR  LOS VALORES DEL FRAGMENT QUE CONTIENE EL RECYCLERVIEW
            }
        });
    }

Gracias por la ayuda.

A: Al final resolví el problema declarando static las vistas del fragment. Desde el boton el CardView llame aun procedimiento actualizar.
 btneliminar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                borrar_pieza(Integer.parseInt(txtid.getText().toString()));
                actuacion a=new actuacion();
                a.actualizar();
            }
        });
public RecyclerView actualizar(){

    this.listadodepiezas.setLayoutManager(new LinearLayoutManager(getActivity()));
    Clase_lista_piezas_pedido clase_pieza =new Clase_lista_piezas_pedido();
    ArrayList<Clase_lista_piezas_pedido> pieza=clase_pieza.Obtener_piezas_pedido(naviso);
    adaptador=new Recicle_listapiezaspedidas(pieza);
    this.listadodepiezas.setAdapter(adaptador);

    return this.listadodepiezas;
}


text:
Q: Rotation of 90, 180 and 270 using python and tensorflow I want to randomly rotate my images in 90, 180, and 270 degrees, that is, by multiples of 90 degrees.
Currently, I am using the ImageDatagenerator to augment my data:
train_dataGen = ImageDataGenerator(rescale=None,horizontal_flip=True,rotation_range=90,
                                   vertical_flip=True)

If rotation_range variable is equal to 90, like the code above, does it only do rotations of 90 degrees? or does it perform rotations of multiples of 90?

A: def rotate_image(image):
    return np.rot90(image, np.random.choice([-1, 0, 1]))

train_dataGen = ImageDataGenerator(
    preprocessing_function=rotate_image)

This function will rotate by either -90, 0, or 90 degrees.

A: To apply these rotations to images, one can use the function apply_affine_transform() within keras preprocessing. This function is used by ImageDataGenerator to perform transforms.
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

x = np.arange(256).reshape(16, 16)
x = np.tile(x[..., np.newaxis], 3)
# x.shape == (16, 16, 3)
plt.imshow(x)

x_90 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=90)
plt.imshow(x_90)

x_180 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=180)
plt.imshow(x_180)

x_270 = tf.keras.preprocessing.image.apply_affine_transform(x, theta=270)
plt.imshow(x_270)

The rotation_range parameter of ImageDataGenerator specifies a range of possible rotations. A random is taken from the uniform distribution between -rotation_range and rotation_range. Here is the source.
if self.rotation_range:
    theta = np.random.uniform(
        -self.rotation_range,
        self.rotation_range)
else:
    theta = 0