text:
Q: Execute php object method without reloading using ajax Context
i'm currently working on a school project to create feed aggregator.
I'm currently working on rssfeed object and therefor it's display.
I wanted to create a function to display the head of the feed with a button which call a method to display all rss posts related to this feed
You can see our current version at: http://aaron.tixp.eu/vues/vue_testRSS.php
I already have RssFeed class which contains info about it and an array of RssPost object.
Problem

*

*The problem is that i don't know how to make the button to call the function to display all the posts.

*Moreover i need this button (or a new button which can replace this one) to reverse the last operation.

*I've already read many solutions but no one for the entire problem and since i have nearly no knowledge on javascrpit, jQuery or Ajax I don't know how to resolve this.
It would be great if someone can help me.
Solved!
I updated the code
here's some code:
the file vue_testrss.php where i put my tests for rss:
<?php
/**
 * Created by PhpStorm.
 * User: Thomas MEDARD
 * Date: 11/12/15
 * Time: 16:12
 */
require_once '../vues/vue_page-builder.php';
require_once '../controleurs/objetphp/controleur_rssfeed.php';

$scripts = array("http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", "javascript/scroll_to_back_to_top.js");
head('Test', 'salut les coco', 'projet, test, php, yolol', '', $scripts);

if (isset($_GET['rssfeed']) && $_GET['rssfeed'] !== '')
    $url = $_GET['rssfeed'];
else
    $url = 'http://www.legorafi.fr/feed/';
try {
    $flux = new RssFeed($url);
    $flux1 = new RssFeed('http://www.jeuxvideo.com/rss/rss-news.xml');
    $fluxArray = array($flux, $flux1);
    announcement($fluxArray);
}
catch (Exception $e){
    //echo 'Exception : ' . $e->getMessage() . "
\n";
    echo 'RSS invalide' . '
' . "\n";
}
echo '
Test RSS

' . "\n";
?>

        <form id="formulaire-connexion" action="vue_testRSS.php" method="get">

                    rss
                    <input id="rssfeed" type="text" name="rssfeed" value=""/>

        </form>

accueil

<?php
if (isset($fluxArray)) {
    foreach ($fluxArray as $value) {
        echo $value->displayHead() . '

';
    }
}
foot();

Here is the code to display the RssFeed objects:
public function displayHead () {
    $imageLink = isset($this->image) ? $this->image->getUrl() : '';
    $strToReturn = '
' . "\n"
        . '
' . "\n"
        . ((isset($this->favicon) || $this->favicon !== '') ?
            '                favicon . '" alt="">' . "\n" : '')
        . '                link) ? $this->link : '') . '">'
            . (isset($this->title) ? $this->title : '') . '' . '
' . "\n"
        . (isset($this->pubDate) ? '                publication date : ' . $this->pubDate . '
' . "\n" : '')
        . (isset($this->lastBuildDate) ? '                last update : ' . $this->lastBuildDate
            . '
' . "\n" : '')
        . (isset($this->image) ? '                image) ? $imageLink : '') . '" alt="'
            . $this->image->getTitle() . '">
' . "\n" : '')
        . (isset($this->summary) ? '                ' . $this->summary . '
'  . "\n": '')
            . '            url . '"><button type="button" value="expand"
            . name="expand" onclick="'
        . 'expand_rss(\'' . $this->url . '\')">Expand</button>' . "\n"
        . '
' . "\n"
        . '
url . '">
' . "\n"
        . '
';
    return $strToReturn;

the second one is function which should be called inside the

:
public function displayPosts () {
    $strToReturn = '';
    foreach ($this->rssPosts as $valeur) {
        $strToReturn .= $valeur . "\n"
            . '

' . "\n\n";
    }
    return $strToReturn;
}

For now i'm using the script inside vue_testrss.php to write inside the

.
and the file vue_expandajax.php:
 <?php
require_once '../controleurs/objetphp/controleur_rssfeed.php';
/**
 * Created by PhpStorm.
 * User: Thomas
 * Date: 21/12/2015
 * Time: 12:35
 */
if (isset($_POST['action']) && isset($_POST['url'])) {
    switch ($_POST['action']) {
        case 'expand':
            expand($_POST['url']);
            break;
    }
}

function expand($url) {
    $feed = new RssFeed($url);
    echo $feed->displayPosts();
    exit;
}

I don't know if it can help but here is a link to the git repositery of the project: https://github.com/Tixp/aaron.git

A: Having looked at the link and then the source code from the relevant page I knocked this up to help guide you a little. Without seeing the contents of the backend php script we can do no more, but something along these lines might help.

        <title>Test</title>

           Le Gorafi.fr Gorafi News Network

           last update : Fri, 18 Dec 2015 13:00:47 +0000

           <button onclick="get_rss()" name="expand" value="expand" type="button">Expand</button>

As an example for the vue_expander.php script I tested using the following code. It differs from your code but it was just to test really that it all worked - hopefully you might find it useful.
<?php
    /* vue_expander.php */
    $html=array();
    $datasrc='http://www.legorafi.fr/feed/';
    $xml=file_get_contents( $datasrc );

    /* shorthand method to retrieve value from a child node */
    function nodevalue( $node=false, $parent=false ){
        global $xpath;
        return $node && $parent && !empty( $xpath->query( $node, $parent )->item(0)->nodeValue ) ? $xpath->query( $node, $parent )->item(0)->nodeValue : false;
    }

    /* Create DOM Objects */
    $dom=new DOMDocument('1.0','utf-8');
    $dom->loadXML( $xml );
    $xpath=new DOMXPath( $dom );

    /* Get rudimentary title & description for the RSS feed */
    $root  = $dom->getElementsByTagName('channel')->item(0);
    $title = nodevalue('title',$root);
    $descr = nodevalue('description',$root);

    /* Begin preparing output */
    $html[]="

{$title}

{$descr}
";

    /* Get all items in rss feed */
    $col = $dom->getElementsByTagName('item');
    foreach( $col as $item ){
        /* grab values from childnodes */
        $title = nodevalue('title',$item);
        $comments = nodevalue('comments',$item);
        $link = nodevalue('link',$item);

        /* Other child nodes not calculated but done in same way etc */
        $content = nodevalue('content:encoded',$item);

        $html[]="

{$title}

{$comments}

            more..

";
    }
    /* send response back to ajax callback function */
    echo implode( PHP_EOL, $html );
?>


text:
Q: JQuery Autocomplete asp.net action not firing on select Somehow action is not completed when I choose an item from the menu. Everything else works fine, except again - nothing happens when I select an item.
Here is the code:
<script type="text/javascript">

$(document).ready(function() {
    $("#<%=txtSearchTerm.ClientID%>").autocomplete("Acc.ashx", {
        formatItem: function(item) { return item.toString().split("#")[0]; },
        formatResult: function(item) { return item.toString().split("#")[0]; },
        select: function(event, ui) { alert('something'); }
    });

    });

</script>

A: I ended up with this working solution
<script type="text/javascript">

$(document).ready(function() {
    $("#<%=txtSearchTerm.ClientID%>").autocomplete("Acc.ashx", {
        formatItem: function(item) { return item.toString().split("#")[0]; },
        formatResult: function(item) { return item.toString().split("#")[0]; }
    });

    $("#<%=txtSearchTerm.ClientID %>").result( function findValueCallback(event, data, formatted)
    {
        if(data)
        {
            $('#<%=hidOID.ClientID %>').val(data[0].toString().split('#')[1]);
        }
    });

    });

</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSV remove a row of data when column has value 0 using PHP I'm writing a cron php script to clean up a csv file before importing into a website db. Each row has a Quantity_Available field. My intention is to not write the rows with Quantity_Available == "0" to reduce the size of the file (14,000 records).
I'm comfortable with opening the existing file and writing it to a new file. Just not sure of the code for checking that field and skipping that line if it has that value.
Start Array:
Item, Quantity_Available, Color
Car,3,Blue
Horse,0,Brown
Motorcycle,2,Black
Expected result:
Car,3,Blue
Motorcycle,2,Black
I've don a good deal of searching here and haven't found this specific instance.

A: If the only thing you need to do is remove lines that have a quantity of zero and you have command line access, I suggest using grep -v ',0,' file.csv instead of writing PHP


text:
Q: prove $\int_{0}^{2\pi}(1-\cos x)^n\cos nx dx=(-1)^n\frac{\pi}{2^{n-1}} $ prove $$\int_{0}^{2\pi}(1-\cos x)^n\cos nx dx=(-1)^n\frac{\pi}{2^{n-1}} $$
I tried with $2\cos x =z+\frac1z$ then use residue theorem but I faced some troubles
my try is :
$2\cos x =z+\frac1z$
$$I=\int_{\left | z \right |=1}\frac{(-1)^n}{2^{n+1}}\frac{(z^2-2z+1)^n}{z^{2n+1}}dz$$
$$I=Res_{z=0}\frac{(z^2-2z+1)^n}{z^{2n+1}} $$
but I can't find closed form for the derivative
if any one can explain more how I can continue
if any one can solve it  using real or complex analysis

A: By periodicity, shift the interval of integration to $[-\pi,\pi]$. Then by parity
$$\int_{-\pi}^\pi (1-\cos x)^n \cos nx\,dx = \int_{-\pi}^\pi (1-\cos x)^n e^{inx}\,dx.$$
Now substitute $z = e^{ix}$, $dx = \frac{dz}{iz}$ and $\cos x = \frac{1}{2}(z + z^{-1})$ to get
$$\begin{align}
\int_{-\pi}^\pi (1-\cos x)^n \cos nx\,dx &= \frac{1}{i} \int_{\lvert z\rvert = 1} \left(1 - \frac{z+z^{-1}}{2}\right)^n z^n \,\frac{dz}{z}\\
&= \frac{1}{i} \int_{\lvert z\rvert = 1} \left(z - \frac{z^2}{2} - \frac{1}{2}\right)^n\, \frac{dz}{z}.
\end{align}$$
When expanding the power, all integrals vanish except the one for the $\left(-\frac{1}{2}\right)^n$ term.


text:
Q: how to strand executorservice My program flow is like this:
I need to sequential processing per user's request
In C++ I will use boost asio and one strand per user but I had to code in java
So I intend to create one SingleThreadExecutor per user and post user's task into it's executor
But if user num get big I think this approach will slow because of the big number of thread
So I looking for alternative solution, the other approach in my head is one queue per user and some how tosh that queue to a fixed thread pool, need advise here, thanks.

A: Found solution just 5 minute after I post question T_T
It's here, CallbackTask  approach look promising.


text:
Q: Why/how does this compile? C++ in MS Visual Studio 2008. Warning level 4 plus a load of extra warnings enabled as well. I'd expect this to give a warning at least, but more likely a compiler error?
Function declaration is as follows:
int printfLikeFunction(
   const int               bufferLength,
   char * const            buffer,
   const char * const      format,
   ... );

Code usage - there's a typo: although the ARRAY_SIZE of outputBuffer is passed in, outputBuffer itself isn't - surely this should not compile:
printfLikeFunction( ARRAY_SIZE( outputBuffer ), "Format: %s, %s", arg1, arg2 );

Clearly this is wrong and a mistake has been made. However the compiler should have caught it! The buffer parameter should be a char-pointer, and it's being passed a string literal which is a const char-pointer. This must be an error. (arg1 and arg2 are (possibly const) char pointers as well, so coincidentally the declaration is matched even without outputBuffer being in the correct place).
At run time, this code crashes as it attempts to write into the string literal. No surprise there, I just don't understand how it was allowed to compile.
(Though, incidentally, this is presumably why sprintf_s has the buffer and size parameters in a different order to this function - it makes such errors unequivocally fail).

A: C++ has a special loophole for string literals for compatibility with pre-const C-style code. Although string literals are arrays of const char, they can be converted to a pointer to non-const char.
Paraphrasing 4.2/2 [conv.array]: a 'narrow' string literal can be converted to an rvalue of type pointer to non-const char. The conversion is only considered when there is an explicit target type (e.g. a function parameter) and not when a general lvalue to rvalue conversion is required.
This conversion is deprecated, but still available. Note that while the conversion allows the literal to be converted to a pointer to non-const char type, it would still invoke undefined behaviour to try to modify any of the characters in the string literal through this pointer.

A: I seem to recall that the compiler has an option that controls how string literals are treated. By default they are treated as char * in order to not break a whole lot of existing non-const-safe code, but you can change it to treat them as const char *. This may help trigger the error you are looking for.
(later) I don't have a Microsoft compiler handy at the moment, but looking throught the reference on MSDN I can't seem to find such an option. I may be thinking of GCC, which does have such an option.

A: int printfLikeFunction(
   const int               bufferLength,
   char * const            buffer,
   const char * const      format,
   ... );
the buffer parameter  is specified as char* const, so it only protects the buffer address to be modified, not the buffer content.
to avoid buffer to be written into, you need to declare it as const char* const like the format.
the compiler allows writing into buffer since you declare it as char* .
the const postfix modifier only prevents to reassign buffer value in your function.
see http://jriddell.org/const-in-cpp.html to view const modifier impact on variables

A: String literals in C are const char pointers ( char*const ), not const pointers to const chars ( const char* const ).
C++ originally followed C usage, but then the ANSI C++ standard was amended at some point ( I'm not sure when ) to make them const char* const. Microsoft products traditionally have tended to value backwards compatibility with previous versions over compliance - there may be a compiler option to force the "new" behaviour, but since the examples of string literals on MSDN are all non-const, I doubt that there is.


text:
Q: How to reduce/specify number of connections in celery flower? I am running an app on a limited service host, where my Redis server has a maximum of 50 connections. I have configured my web app to be using a consistent 20 Redis connections. However, if I launch Flower to inspect the Redis, my connections jump up to 45. How can I reduce how many connections Flower is launching?
I thought I found a way by making my flower start command:
celery -A myapp flower --redis_max_connections=2 --concurrency=4 -l info

But this didn't seem to change anything... What am I missing?


text:
Q: Adding strong emphasis to an img tag. Semantics I'm actually coding a website and a doubt came to me. I have a list of images (it's an artist portfolio, so it should be images), some of which have a "Featured" badge. Is it semantically correct to wrap the img into a strong tag instead of using a class="featured"? Will it add strong emphasis to the image?
Reading the W3C spec., it refers strong and em as text-level semantics, but I'm not sure what happens with media like img.
Thank you so much.

A: I think that's fine. You may already be doing this, but you need to make sure that the ALT text describes why the images has been emphasized. Eg alt="man with dog - featured"

A: I think that it would be perfectly acceptable to do this and preferable.

A: First of all, I think the HTML 4 spec allows it. Question is, can you rely on what browser will do with it. I would not take my chances with that.
But at least, in many browsers you can attach formatting to
strong img {
    /* mark up for the featured image */
}

And this should then work for all browser that support it.

A: I wouldn't use the strong tag on images, I am not sure why it would be preferable since it refers to 'emphasized' text only: an aural user agent may use different voices for emphasis, it would be pointless for images.
Why don't you just use a class?


text:
Q: Select IF EXISTS THEN ELSE on Mysql I have tried to solve this issue a lot, checked a lot of sites, tried more examples, but did not get what I want yet.
My sql logic on my php Page like at below:
IF (EXISTS (SELECT * FROM suborders WHERE subId = 1))
THEN SELECT * FROM suborders WHERE subId = 1     //if exists just do this sql again
ELSE SELECT id FROM orders WHERE id = 1 LIMIT 1;

Mysql Gives an error on syntax at the first query. So, I also tried to use another way at below:
delimiter //
create procedure test()
begin
IF EXISTS (SELECT * FROM suborders WHERE subId = 1) THEN
SELECT * FROM suborders WHERE subId = 1;
ELSE
SELECT id FROM orders WHERE id = 1 LIMIT 1;
END IF;
end //
delimiter ;

call test();

Using 2nd query mysql returns empty result, without error. Actually, there should be something to fetch...

A: IF EXISTS (SELECT * FROM suborders WHERE subId = 1 )
BEGIN
   SELECT * FROM suborders WHERE subId = 1
END
ELSE
BEGIN
    SELECT id FROM orders WHERE id = 1 LIMIT 1
END

Full stored Procedure:
DELIMITER //
 CREATE PROCEDURE sp_select_suborders(IN `p_subId`)
    IF EXISTS (SELECT * FROM suborders WHERE subId = p_subId )
    BEGIN
       SELECT * FROM suborders WHERE subId = p_subId
    END
    ELSE
    BEGIN
        SELECT id FROM orders WHERE id = p_subId LIMIT 1
    END //
 DELIMITER ;

Usage:
$stmt = $db->prepare('CALL sp_select_suborders(?)');

A: Why don't you simple handle the case of no results in php?
$yourDBUsage->query("SELECT * FROM suborders WHERE subId = 1");

if ($yourDBUsage->count == 0){
   $yourDBUsage->query("SELECT id FROM orders WHERE id = 1 LIMIT 1;");
}

A: Since suborders.subId is a foreign key referencing orders.id, you can approach your query logic with a single LEFT JOIN query.  I would prefer this solution because it means you do not have to maintain a stored procedure separately. All the query logic is bundled with your application code.
By doing a LEFT JOIN from orders against suborders, columns from suborders may return NULL.  In your application code, you may then test if they are null, and if they are, use the id from orders instead.  This method essentially transfers the flow logic to your PHP code, while stuffing all the database actions into one query, which will either return one row, or many rows (or none, if the requested id doesn't exist in orders)
SELECT
  orders.id AS orders_id,
  suborders.*
FROM
  orders
  LEFT JOIN suborders ON orders.id = suborders.subId
WHERE orders.id = ?

In the PHP logic, execute that query with an appropriate value in place of ?. When fetching, you will be able to discern immediately if suborders has no return, as all the suborders columns will be NULL.
// Assume fetched into $orders
foreach ($orders as $order) {
  if ($order['subId'] === null) {
    // Use orders.id...
    // If it is a unique id, this will be the only row
    // and the loop will terminate here
    echo $order['orders_id'];
  }
  else {
    // subId has a value, so you can use the other suborders cols
    echo $order['subId'];
    echo $order['other_suborder_column'];
  }

This way, if suborders does match and populate columns, you would be able to loop over the entire returned rowset, equivalent to SELECT * FROM suborders.  Otherwise, you can break the loop right away (or if orders.id is unique as I suspect it is, it will only ever return one row anyway with an orders_id and null suborders).


text:
Q: How to order posts by parents? I wanted to order my post type archive by its parents (like page list in wp-admin).
This is what i have tried, but no luck so far.
add_action( 'pre_get_posts', 'budget_archive_data' );

function budget_archive_data($query){
    $main_budget = array(3,4);

    if ( (is_post_type_archive('account') || is_post_type_archive('budget')) && $query->is_main_query() ) {

        $query->set( 'orderby', 'parent' );
        $query->set( 'order', 'DESC' );
        $query->set( 'posts_per_page', -1 );
        $query->set( 'post__not_in', $main_budget );

    }
}

The result was:

*

*Post 2 whose post_parent is 0

*Post 3 whose post_parent is 0

*Post 6 whose parent is 0

*Post 4  whose parent is 2

*Post 5 whose parent is 3

Anyone can help? Thanks before.


text:
Q: UPDATE query methods must either return void or int (the number of updated rows) while trying to return Flow Koltin version : 1.6.21.
Room dependencies :
implementation "androidx.room:room-runtime:2.4.2"
implementation "androidx.room:room-ktx:2.4.2"
kapt "androidx.room:room-compiler:2.4.2"
implementation "androidx.room:room-rxjava2:2.4.2"
testImplementation "androidx.room:room-testing:2.4.2"

Here is the query method :
@Query("UPDATE releve SET accuracy_indicator = :isEnabled WHERE id_local = :releveId")
    fun updateAccuracyIndicator(releveId: Long, isEnabled: Boolean): Flow<Int>

I don't know how to handle this issue ?

A: An update operation is a one-shot so it should return a single Int rather than a flow of Ints. You can make the return type Int, and you can optionally mark the function suspend so it won't block the caller.


text:
Q: ASP.NET Core MVC : this localhost page can't be found Created a user controller with action methods. Right clicked on "Upsert" action method and added a view page.
Problem is when I go to browser with this URL
https://localhost:44318/Admin/User/Upsert

userId fetching but it shows an error

This localhost page can't be found

Meanwhile my other action method properly working same controller like UserLock, User delete etc.
public class UserController : Controller
{
    private readonly ApplicationDbContext _db;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly UserManager<IdentityUser> _userManager;

    public UserController(ApplicationDbContext db)
    {
        _db = db;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Upsert(string userId)
    {
        ........
        return View(objFromDb);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Upsert(ApplicationUser user)
    {
        .......
        return View(user);
    }
}

A: StartUp.cs
using BornoMala.DataAccess.Data;
using BornoMala.DataAccess.Repository;
using BornoMala.DataAccess.Repository.IRepository;
using BornoMala.Utility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BornoMala
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddIdentity<IdentityUser, IdentityRole>().AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddSingleton<IEmailSender, EmailSender>();
            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddScoped<IUnitOfWork, UnitOfWork>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}

A:
This localhost page can't be found

Please check if you organize your controllers and views in correct folder structure, like below.

And check if you associate the controller with an Area
[Area("Admin")]
public class UserController : Controller
{
    //...

For more information about working with Areas in ASP.NET Core, you can check this doc:
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-5.0#areas-for-controllers-with-views


text:
Q: Bash execute string as command without expanding escaped spaces I have an external executable that I need to pass arguments to. With a bash script, I have code that determines these arguments. Some arguments may have escaped spaces.
I need to then execute that string, without expanding each of the arguments.
# ... some code that determines argument string
# the following is an example of the string

ARGSTR='./executable test\ file.txt arg2=true'
exec ${ARGSTR}

I must have the $ARGSTR be expanded so that I can pass arguments to ./executable, but each of the arguments should not be expanded. I have tried quoting "test file.txt", but this still does not pass it as one argument to ./executable.
Is there a way to do something like this?

A: Us an array instead of a string:
#!/usr/bin/env bash

ARGSTR=('./executable' 'test file.txt' 'arg2=true')
exec "${ARGSTR[@]}"

See:
BashFAQ-50 - I'm trying to put a command in a variable, but the complex cases always fail.
https://stackoverflow.com/a/44055875/7939871

A: This may achieve what you wanted :
ARGSTR='./executable test\ file.txt arg2=true'
exec bash -c "exec ${ARGSTR}"


text:
Q: Swift Decodable nestedContainer and backwards compatibility I just stumbled upon something but I can't find the behavior documented anywhere so I wanted to check if it is correct.
Scenario:
I make a Swift app that downloads and parses a JSON file. Please note that the actual implementation is more complex, so a custom implementation is needed for decoding (which is not the case in the below example, but it exhibits the same behaviour as the one I want to show)
The objects look like this:
enum ScreenName: String, Decodable, CaseIterable {
    case screen1 = "screen1"
    case screen2 = "screen2"
}

struct ScreenContents: Decodable {
 ...
}

struct Screens {
    let screens: [ScreenName: ScreenContents]

    enum CodingKeys: String, CodingKey {
        case screens
    }
}

The data:
{
  "screens":{
    "screen1":{..},
    "screen2":{..}
  }
}

The implementation to load the Screens:
extension Screens: Decodable {

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let screensContainer = try container.nestedContainer(keyedBy: ScreenName.self, forKey: .screens)

        for enumKey in screensContainer.allKeys {
               ....
        }
}

This works fine. The data downloaded from a URL is parsed an all is well.
Now I want to release a new version of my app, where I introduce case screen3 = "screen3". For the new version of the app there is no isse, the item is added to the enum, the JSON on the server is updated and all works fine.
However I was worried about backwards compatibility. Since the current version of the app in production does not know about screen3 and therefore Swift cannot cast the incoming string to an enum, what will happen? Will an exception be thrown in init(from: decoder) ?
So I tried loading a more recent file, containing screen3, with the above code. To my amazement it worked without throwing any errors.
What actually happens is that
let screensContainer = try container.nestedContainer(keyedBy: ScreenName.self, forKey: .screens)
ignored the screen3 entry and only returned screen1 and screen2.
This is obviously good news as my backwards compatibility problem is solved, however I would like to see this backed by some kind of documentation, so I am not relying on a bug or another quirk before going live with this, and I didn't find any.
Can anyone help?
Thanks

A: The whole point of CodingKey is that it lists the keys that you're interested in. A keyed container is a view over data, and may not include all the data (in your case it doesn't include screen3). The documentation for allKeys touches on this (emphasis added):

Different keyed containers from the same decoder may return different keys here, because it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.

The type you've requested is ScreenName, which is an enum and supports two specific strings. So those are the only things you're going to get. But CodingKey does not have to be an enum. For example, I could build a struct CodingKey (and I do this all the time, and wish it would be added to stdlib).
struct StringKey: CodingKey, Hashable, CustomStringConvertible {
    var description: String {
        return stringValue
    }

    let stringValue: String
    init(_ string: String) { self.stringValue = string }
    init?(stringValue: String) { self.init(stringValue) }
    var intValue: Int? { return nil }
    init?(intValue: Int) { return nil }
}

This is a CodingKey that can accept any string at all (I use this to decode arbitrary JSON where the keys may not be known in advance). I could build another one that only accepted strings that began with some prefix and returned nil for everything else. CodingKeys can do all kinds of things.
But the final rule is that the keyed container only contains entries for keys that could be converted to the requested CodingKey.
So yes, this is officially backward compatible as written. You're not just lucky. This is how it works.


text:
Q: Closure and Sequence.
I dug this example out of Chen's free online source notes.
I am very puzzled by the last comment
but the limit $\mathbf{a}$ does not belong to $\ell_0$.Hence the linear subspace $\ell_0$ is not closed in $\ell^\infty$
I don't understand the idea. To show a subset $\ell_0$ isn't closed in $\ell^\infty$, should you find a sequence in $\ell_0$ that doesn't converge in $\ell^\infty$? Not the other way around? Or generally speaking isn't this true for any metric space?

A: The following result is used here:

Let $(X,d)$ be a metric space, and $F$ be a subset of $X$. If $F$ is closed, and $\{x_n\}$ is a sequence of elements of $F$ which converges to some $x\in X$, then $x\in F$.

(so by closed it means that "we can't escape by limit")


text:
Q: how to make an MovieClip transparent? I have this situation:
there is some generic movieclip with some color in background (can be green, red, etc), and I load one image and attach in this movieclip as a child, using the same dimensions of the movieclip.
But if this image has some transparency I can see the background ( green, red, etc).
I try this:
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event){
var tempImage:Bitmap = new Bitmap(e.target.content.bitmapData);
image.bitmapData = tempImage.bitmapData;

obj.graphics.beginFill(0xFFFFFF, 0);
obj.graphics.drawRect(0,0,obj.width, obj.height);
obj.graphics.endFill();

obj.addChild(image);
});

But it is not working. And I cant change the obj.alpha because I cant see the image in this case. There is another way?
Thanks

A: Have you tried Bitmapfill instead?
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event){

    obj.graphics.beginBitmapFill(e.target.content.bitmapData);
    obj.graphics.endFill();
});


text:
Q: Facebook API – how to get Page-Scoped User ID (ids_for_pages is empty)? My goal is to identify authors of posts published on my Facebook Page, by matching them with user ID-s from my database, which ID-s are App-Scoped User ID-s (ASID).
I've generated User Access Tokens (through app) and extended it to long-lived access tokens. Then I've generated Page Access Tokens for all pages managed by users – listed via GET user/accounts.
At first, I check the author of the post ({PID} is Facebook Post ID):
curl -X GET 'https://graph.facebook.com/v6.0/{PID}?fields=admin_creator&access_token={ACCESS_TOKEN}'

That gives my ID of user, which I believe is Page-Scoped User ID (PSID).
In order to make matching, I am trying to establish PSID-s for all pages managed by all users from my database:
curl -X GET 'https://graph.facebook.com/v6.0/{UID}/ids_for_pages?access_token={ACCESS_TOKEN}&appsecret_proof={APPSECRET_PROOF}'

Where {UID} is user ASID, {ACCESS_TOKEN} is Page Acccess Token and APPSECRET_PROOF is hash generated from Page Access Token and App Secret. The app and the pages are owned by the same business (which is obligatory to use ids_for_pages endpoint).
Unfortunately, the response is:
{"data":[]}

I've read the documentation – https://developers.facebook.com/docs/facebook-login/connecting-accounts (which recommends using App Access Token for ids_for_pages) and similar StackOverflow question – Getting ids_for_pages from Graph returns empty (which recommends using Page Access Token for ids_for_pages).
Therefore, instead of Page Access Token as {ACCESS_TOKEN} I've also tried using (with corresponding APPSECRET_PROOF):

*

*App access token (generated from App Secret)

*User access token (long-lived)

But without effect. I always get empty list as response.
I've even tried to change {UID} (App-Scoped User ID) to:

*

*Standard Facebook Profile ID

*Page-Scoped User ID (which is what i want to get in response!), obtained from admin_creator field of fetched pages' posts

Nothing. Response is empty. I'm completely stuck.

As @04FS suggested, the reason could be something described in Facebook API documentation of ids_for_pages (linked above):

Your initial call to the API may trigger an app review that can take approximately 48 hours to complete.

However, over 48 hours have passed since the question was asked and over 72 hours since my initial call to the API, but the response is still empty.


text:
Q: localhost keeps redirecting to 0.0.0.0 when navigating to 127.0.0.1:8000 to access laravel I always used Laravel valet for developing Laravel projects, but i was curios and wanted to try docker for the first time. After a lot of struggle i decided to ga back to Laravel valet, only to find out that the url i used with valet redirects to 0.0.0.0:8080.
0.0.0.0:8080 was the url docker exposed outside the container.
I removed docker completely from my mac. Stil got the same problem.
I've tried to run php artisan serve, but 127.0.0.1:8000 also redirects to 0.0.0.0:8080.
I've tried access other Laravel applications with valet, no problem.
With my host file is nothing wrong, and so is my network settings.
Here is my host file
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost


text:
Q: Command-shift-D equivalent for Xcode 4? I'm trying out the Xcode 4 beta, and I'm really missing ⌘-Shift-D, which lets you search for symbols or files and open them quickly. Does anyone know how to invoke it in Xcode 4?

A: ⌘-Shift-O

A: Command-Shift-O is the new "open quickly" keyboard shortcut in XCode 4.  "O" for open I guess...

A: In Xcode 3 you can command-doubleclick a symbol to jump to its definition. A future version of Xcode which is under NDA may provide very similar functionality.


text:
Q: Send an array of complex objects using ksoap2 to .NET web service I am facing a problem in sending an array of complex object from a J2ME Client using KSOAP to .net web service (Soap services).
my TestSoap.java file has a setArr() method which takes an array of PropHeaderMapBin object and sends it to the web service which returns an integer (count of PropHeaderMapBin objects)
TestSoap.java

package org.tempuri;

    import com.n9ciphers.test.Constants;
    import java.util.Vector;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransport;
    import org.tempuri.PropHeaderMapBin;

    public final class TestSoap {

        public int setArr(PropHeaderMapBin[] inArr) throws Exception {

            SoapObject _client = new SoapObject("http://tempuri.org/", "SetArr");
            SoapObject[] _propHeaderMapBinSO = new SoapObject[inArr.length];

            PropHeaderMapBin[] prop = inArr;
            //PropHeaderMapBin[] prop = new PropHeaderMapBin[inArr.length];
            Vector _propVector = new Vector(inArr.length);
            if (inArr != null) {

                //System.out.println("_len  " + inArr.length );

                for (int i = 0; i < inArr.length; i++) {
                    _propHeaderMapBinSO[i] = new SoapObject("http://tempuri.org/", "PropHeaderMapBin");
                    _propHeaderMapBinSO[i].addProperty("PropertyName", prop[i].getPropertyName());
                    _propHeaderMapBinSO[i].addProperty("value", prop[i].getValue());
                    _propHeaderMapBinSO[i].addProperty("HeaderText", prop[i].getHeaderText());
                    _propHeaderMapBinSO[i].addProperty("label", prop[i].getLabel());

                    _propVector.addElement(_propHeaderMapBinSO[i]);
                }
            }

            _client.addProperty(pi, _propVector);

            SoapSerializationEnvelope _envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            _envelope.addMapping("http://www.tempuri.org/", "PropHeaderMapBin", new PropHeaderMapBin().getClass());
            //_envelope.addTemplate (_client);
            _envelope.bodyOut = _client;
            _envelope.dotNet = true;

            HttpTransport _ht = new HttpTransport(Constants.endPoint + "Test.asmx");
            _ht.debug = true;
            _ht.call("http://tempuri.org/SetArr", _envelope);

            //System.out.println("response: " + result.toString());

            System.out.println("Request Dump:" + _ht.requestDump);
            //Dialog.show("Request Dump", _ht.requestDump, Dialog.TYPE_INFO, null, "OK", null);
            System.out.println("Response Dump:" + _ht.responseDump);
            //Dialog.show("Response Dump", _ht.responseDump, Dialog.TYPE_INFO, null, "OK", null);

            return Integer.parseInt(_envelope.getResponse().toString());
            //return 0;
        }
    }

Output of setArr() method call. the server does not recognize the datatype of the objects in array and it sets the arraytype to anytype[3] and returns a 0 instead of 3.
Request Dump:
<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>
        <SetArr xmlns="http://tempuri.org/" id="o0" c:root="1">
            <inArr i:type="c:Array" c:arrayType="d:anyType[3]">
                <item i:type="n0:PropHeaderMapBin" xmlns:n0="http://tempuri.org/">
                    <PropertyName i:type="d:string">1</PropertyName>
                    <value i:type="d:string">1</value>
                    <HeaderText i:type="d:string">Pradhan</HeaderText>
                    Pradhan
                </item>
                <item i:type="n1:PropHeaderMapBin" xmlns:n1="http://tempuri.org/">
                    <PropertyName i:type="d:string">2</PropertyName>
                    <value i:type="d:string">2</value>
                    <HeaderText i:type="d:string">Kavya</HeaderText>
                    Kavya
                </item>
                <item i:type="n2:PropHeaderMapBin" xmlns:n2="http://tempuri.org/">
                    <PropertyName i:type="d:string">3</PropertyName>
                    <value i:type="d:string">3</value>
                    <HeaderText i:type="d:string">Puchi</HeaderText>
                    Puchi
                </item>
            </inArr>
        </SetArr>
    </v:Body>
</v:Envelope>

Response Dump:<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <SetArrResponse xmlns="http://tempuri.org/">
            <SetArrResult>0</SetArrResult>
        </SetArrResponse>
    </soap:Body>
</soap:Envelope>
response = 0

my wsdl file for reference
<wsdl:definitions targetNamespace="http://tempuri.org/">
    <wsdl:types>
        <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
            <s:element name="GetArr">
                <s:complexType/>
            </s:element>
            <s:element name="GetArrResponse">
                <s:complexType>
                    <s:sequence>
                        <s:element minOccurs="0" maxOccurs="1" name="GetArrResult" type="tns:ArrayOfPropHeaderMapBin"/>
                    </s:sequence>
                </s:complexType>
            </s:element>
            <s:complexType name="ArrayOfPropHeaderMapBin">
                <s:sequence>
                    <s:element minOccurs="0" maxOccurs="unbounded" name="PropHeaderMapBin" nillable="true" type="tns:PropHeaderMapBin"/>
                </s:sequence>
            </s:complexType>
            <s:complexType name="PropHeaderMapBin">
                <s:sequence>
                    <s:element minOccurs="0" maxOccurs="1" name="PropertyName" type="s:string"/>
                    <s:element minOccurs="0" maxOccurs="1" name="value" type="s:string"/>
                    <s:element minOccurs="0" maxOccurs="1" name="HeaderText" type="s:string"/>
                    <s:element minOccurs="0" maxOccurs="1" name="label" type="s:string"/>
                </s:sequence>
            </s:complexType>
            <s:element name="SetArr">
                <s:complexType>
                    <s:sequence>
                        <s:element minOccurs="0" maxOccurs="1" name="inArr" type="tns:ArrayOfPropHeaderMapBin"/>
                    </s:sequence>
                </s:complexType>
            </s:element>
            <s:element name="SetArrResponse">
                <s:complexType>
                    <s:sequence>
                        <s:element minOccurs="1" maxOccurs="1" name="SetArrResult" type="s:int"/>
                    </s:sequence>
                </s:complexType>
            </s:element>
        </s:schema>
    </wsdl:types>
    <wsdl:message name="GetArrSoapIn">
        <wsdl:part name="parameters" element="tns:GetArr"/>
    </wsdl:message>
    <wsdl:message name="GetArrSoapOut">
        <wsdl:part name="parameters" element="tns:GetArrResponse"/>
    </wsdl:message>
    <wsdl:message name="SetArrSoapIn">
        <wsdl:part name="parameters" element="tns:SetArr"/>
    </wsdl:message>
    <wsdl:message name="SetArrSoapOut">
        <wsdl:part name="parameters" element="tns:SetArrResponse"/>
    </wsdl:message>
    <wsdl:portType name="TestSoap">
        <wsdl:operation name="GetArr">
            <wsdl:input message="tns:GetArrSoapIn"/>
            <wsdl:output message="tns:GetArrSoapOut"/>
        </wsdl:operation>
        <wsdl:operation name="SetArr">
            <wsdl:input message="tns:SetArrSoapIn"/>
            <wsdl:output message="tns:SetArrSoapOut"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="TestSoap" type="tns:TestSoap">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="HelloWorld">
            <soap:operation soapAction="http://tempuri.org/HelloWorld" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
        <wsdl:operation name="GetArr">
            <soap:operation soapAction="http://tempuri.org/GetArr" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
        <wsdl:operation name="SetArr">
            <soap:operation soapAction="http://tempuri.org/SetArr" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:binding name="TestSoap12" type="tns:TestSoap">
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="GetArr">
            <soap12:operation soapAction="http://tempuri.org/GetArr" style="document"/>
            <wsdl:input>
                <soap12:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
        <wsdl:operation name="SetArr">
            <soap12:operation soapAction="http://tempuri.org/SetArr" style="document"/>
            <wsdl:input>
                <soap12:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="Test">
        <wsdl:port name="TestSoap" binding="tns:TestSoap">
            <soap:address location="http://xxx.xxx.xxx.xxx/Services/Test.asmx"/>
        </wsdl:port>
        <wsdl:port name="TestSoap12" binding="tns:TestSoap12">
            <soap12:address location="http://xxx.xxx.xxx.xxx/Services/Test.asmx"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

I wud appreciate any help if some one has already faced this kind of issue and resolved it successfully.

A: I can give you hint to solve a problem.
using soapUI tool create web service project with same WSDL (it is very easy and fast).
Compare your request dump with soap body generated by soapUI. You will find out the difference and
hence solution.

A: @Rajnikant had it spot on. if you have wcf web services that are not working, use SOAPui to import the wsdl endpoints. this will create a test harness for the methods that you can then use to call your wcf methods and see the request dump. Compare this with the request dump from the mobile (using androidHttpTransport.requestDump).....note the parameters being passed and their namespaces....this is very important


text:
Q: Return value size or type of a system call in Linux I understand, from looking at kernel code, the linux system call return type is long int and the size is effectively 32-bit.
Is it possible to have a linux system call return a 64-bit value (of type, say, long long int)?
I understand that changing the size makes no sense but I am interested in learning the limitations if there are any or if this is just a matter of preference.

A: On x86, the return value is put in the eax register, so it cannot be bigger than 32 bit; similarly, on x86-64 it is stored on rax (the 64-bit extension of eax).
In general, the trend seems to be to always use a register for the return value (which seems reasonable for system calls), so you are limited to the size of the "native integer" of the current platform. If you needed to return bigger stuff, you'd have to resort to passing the location for the output via a pointer.

A: I am limiting my discussion to x86_64 and i386 in this answer:
System calls are declared as long.
A 64-bit kernel will return a 64-bit int value back to user-space for system calls.
A 32-bit kernel will return a 32-bit int value.
However, lets say that on the 32-bit kernel you change the return type of the system calls to long long; then they would be returned in %eax and %edx together with LSB in %eax and MSB in %edx
So your call gate (stuff in entry.S) will just have to ensure that it's not clobbering %eax and %edx on iret / ret instructions.
Your corresponding user-space wrapper functions that make the system call via int80 or via _syscall() macros on old systems or reimplementing the syscall(2) library call in the newer system to be a long long return type.


text:
Q: Create R dataframe from single string containing elements and whitespace I have string that looks like this
string <- "\n\t\t\t1,2\n\t\t\t3,4\n\t\t"

And I need to create following data frame
1 2
3 4

One way is to use strsplit function, but it feels that there must be much better way of doing it.
Any help will be appreciated.

A: You can convert a character string to a thing that behaves a bit like a file with textConnection and then feed it to read.csv:
> read.csv(textConnection(string),head=FALSE)
  V1 V2
1  1  2
2  3  4
3 NA NA

the stray tabs after the last newline produce that last line of NA values, you'd need to take care of those some way.


text:
Q: C upper case to lower case I am having issue with lower casing my words that are being used as inputs. So my program takes in words and sorts them alphabetically and removes duplicates. But I'd like to change words upper case and lower them to equal to lower case words.
example: Apple changes to apple
my input:
./a.out Orange apple banana Apple banana
my output:
Apple
Orange
apple
banana

Here is what I am trying to achieve
output:
apple
banana
orange

Here is my code
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
  int i, j, k, size;
  size = argc -1;
  char *key;
  char* a[argc-1];

  for (i = 2; i < argc; i++) {
    key = argv[i];

    j = i-1;
    while (j >= 1 && strcmp(argv[j], key) > 0) {
      argv[j+1] = argv[j];
      j--;
    }

    argv[j+1] = key;
  }

  if (argc > 1){
      for (i = 1; i < argc;){
        puts(argv[i]);

        while (argv[++i] != NULL && strcmp(argv[i - 1], argv[i] ) == 0)
          continue;
      }
  }

  return 0;
}

A: You have a list of words and you want to output them sorted, and only the unique ones. And you want to do it in a case insensitive fashion.

*

*Get all the strings to the same case.

*Sort the list of strings.

*Don't output repeats.

C has no built in function to lower case a string, but it does have ones to lower case characters: tolower. So we write a function to lower case a whole string by iterating through it and lower casing each character.
void str_lower(char *str) {
    for( ; str[0] != NULL; str++ ) {
        str[0] = (char)to_lower(str[0]);
    }
}

Then we need to sort. That's handled by the built in qsort function. To use it, you need to write a function that compares two strings and returns just like strcmp. In fact, your comparison function will just be a wrapper around strcmp to make qsort happy.
int compare_strings( const void *_a, const void *_b ) {
    /* The arguments come in as void pointers to the strings
       and must be cast. Best to do it early. */
    const char **a = (const char **)_a;
    const char **b = (const char **)_b;

    /* Then because they're pointers to strings, they must
       be dereferenced before being used as strings. */
    return strcmp(*a, *b);
}

In order to handle any data type, the comparison function takes void pointers. They need to be cast back into char pointers. And it's not passed the string (char *) it's passed a pointer to the string (char **), again so it can handle any data type. So a and b need to be dereferenced. That's why strcmp(*a, *b).
Calling qsort means telling it the array you want to sort, the number of items, how big each element is, and the comparison function.
qsort( strings, (size_t)num_strings, sizeof(char*), compare_strings );

Get used to this sort of thing, you'll be using it a lot. It's how you work with generic lists in C.

The final piece is to output only unique strings. Since you have them sorted, you can simply check if the previous string is the same as the current string. The previous string is strings[i-1] BUT be sure not to try to check strings[-1]. There's two ways to handle that. First is to only do the comparison if i < 1.
for( int i = 0; i < num_strings; i++ ) {
    if( i < 1 || strcmp( strings[i], strings[i-1] ) != 0 ) {
        puts(strings[i]);
    }
}

Another way is to always output the first string and then start the loop from the second.
puts( strings[0] );
for( int i = 1; i < num_strings; i++ ) {
    if( strcmp( strings[i], strings[i-1] ) != 0 ) {
        puts(strings[i]);
    }
}

This means some repeated code, but it simplifies the loop logic. This trade-off is worth it, complicated loops mean bugs. I botched the check on the first loop myself by writing if( i > 0 && strcmp ... )`.

You'll notice I'm not working with argv... except I am. strings and num_strings are just a bit of bookkeeping so I didn't always have to remember to start with argv[1] or use argv+1 if I wanted to pass around the array of strings.
char **strings = argv + 1;
int num_strings = argc-1;

This avoids a whole host of off-by-one errors and reduces complexity.

I think you can put the pieces together from there.

A: There are a set of standard functions for checking and changing the type of characters in ctype.h. The one you are interested in is tolower(). You can #include<ctype.h> and then add a snippet like the following to pre-process your argv before doing the sorting:
for(i = 1; i < argc; i++) {
    argv[i][0] = tolower(argv[i][0]);
}

That will only operate on the first character of each word. If you need to normalize the entire word:
for(i = 1; i < argc; i++) {
    for(j = 0; argv[i][j]; j++) {
        argv[i][j] = tolower(argv[i][j]);
    }
}

A: Silly me, I was able to figure it out after looking at my code realizing that i can do key[0] = tolower(key[0]); which i did before having a pointer point at it.
for (i = 2; i < argc; i++) {
    key = argv[i];
    key[0] = tolower(key[0]);
    j = i-1;
    while (j >= 1 && strcmp(argv[j], key) > 0) {
      argv[j+1] = argv[j];
      j--;
    }

    argv[j+1] = key;
  }

Which lower cases the first letter. And if i wanted to lower case all the letters, i would've have used a for loop. Thank you everyone for your contribution. :)


text:
Q: HttpContext.Current is null when adding delegate handler In one of my project I had added delegate handler to log incoming and outgoing requests. For Logging I am using Nlog. I was generating a unique Id, per request to relate logs with this specific Id.
This worked fine for me. Now recently I modified my code in handler, and set HttpContext.Currnet.Item value to this unique id. Now I am supposed to get this id, and pass it to external Apis.
Issue I faced is inside controller HttpContext.Current is null.
I know what is the main root cause. This is because of handler.SendAsync, which will make the thread SynchronizationContext as null.
I want to pass HttpContext.Current to my ongoing threads.
What I did:
I set ConfigureAwait(false)
I set appsettings -> aspnet:UseTraskFriendlySynchronizationContext to true
but these are not working.
I am using .net framework 4.7.1

A: Thanks @Alexander,
After your comments I reviewed my code again and found this problem is not caused by await base.SendAsync(). In fact I was calling internal methods with async, which ruined HttpContext.Current.
For reference below is my DelegatingHandler implementation. Before this I defined two methods i.e. IncomingMessageAsync(), OutgoingMessageAsync as async. Now I had changed it to simple methods. Because I don't want Task in these methods.
public  class MessageHandler : DelegatingHandler
{
    private static NLog.Logger logger;
    HttpContext context;

    public MessageHandler()
    {
        logger = NLog.LogManager.GetCurrentClassLogger();
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var correlationID = $"{DateTime.Now.Ticks}{Thread.CurrentThread.ManagedThreadId}";
        context = HttpContext.Current;
        context.Items["correlationID"] = correlationID;     //used in Nlog aspnet-item:variable=correlationID
        IncomingMessageAsync(request);
        var response = await base.SendAsync(request, cancellationToken);
        context.Items["responseTime"] = DateTime.Now;
        HttpContext.Current = context;
        OutgoingMessageAsync(response);
        return response;
    }

    protected void IncomingMessageAsync(HttpRequestMessage request)
    {
        logger.Info("Request received from {URL}", request.Method + " " + request.RequestUri);
    }

    protected void OutgoingMessageAsync(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            logger.Info("Response returned with status {Status}", response.StatusCode);
        }
        else
        {
            logger.Warn("Response returned with status {Status}", response.StatusCode);
        }
    }
}


text:
Q: New badge notifications targets wrong post for "Nice Answer" I like the new feature when I get a badge telling me which answer it was. However recently the links for the "Nice Answer" badge seems to be giving links to the previous post that got (or should have gotten) this badge rather than the most recent. This has happened every time for a while now.

*

*I know that badges are awarded after a delay but I don't think that's happening here - there's a strong correlation between a post getting 10 or more votes and a badge being awarded a few minutes later (but not for that post).

*I know that deleted answers cause you to lose a badge, but I don't see how that fully explains the behaviour. I think I should have caught up again by now.

Here's a couple of screenshots that I hope clarify things:

As you can see about 1 hour ago I got 10 upvotes for How do I create a join which says a field is not equal to X? and also a "Nice Answer" badge for Why can I not "see" this enum extension method.
About 15 hours ago I got 15 upvotes for Why can I not "see" this enum extension method and a "Nice Answer" badge for Gotchas when making use of Nullable<T> in C# 4.
This pattern continues, with the upvotes and the badge being awarded at about the same time but for different questions. I couldn't find a similar issue here but I'm wondering has anyone else reported this issue? And can it be fixed so that it behaves as I'd expect?
It doesn't bother me much but it is a bit confusing and I guess I'm not the only one.

A: Sounds like we need to resync your badge reasons.
As it stands we never clear out reasons from the reason table. I'm betting there is an invalid reason in there which is causing this to happen. Since its in there, it means the valid reason is not finding its way in.
It's a very tricky thing though cause over time reasons may become not relevant and if we clear them out we may never be able to discover them again. Eg. Think tumbleweed.
I think the simplest fix here is to assign reasons in reverse order so it "feels" more correct.
EDIT
Fixed


text:
Q: Cordova Setup : Getting error message "Please run android emulator" in net-beans
I am facing issue while setting up Cordova in NetBeans.
     Following options are already set up in my system :

Java SDK,
Cordova,
Andriod NetBeans plugin
Andriod studio SDK

After creating sample Cordova project in Netbeans, I am not able to run in Emulator.
Below is error message I am getting.
Error Message: Image
Or Suggest any other IDE for Cordova.

A: Go to Andriod studio > Tools > ADV manager > select and add virtual device. In default doen't have any device.


text:
Q: Extract KeyValue pair and convert it into JSON (Column and rows) using jquery I am working on Asp.net MVC. I want to import Excel data into one of my grids.  I read Excel file using ExpandoObject (dynamic)  and then converting it into key/value pairs. I would like to know how to extract KeyValue pair and generate a header and data row from that key/value pair in JSON format.
Data will look like this:

I want to convert this KeyValue into Header and row like:
[
    {"CustomerName" : "Messi", "City":"Buenos Aires", "Country" :"Argentina"},
    {"CustomerName" : "Ronaldo", "City":"Lisbon", "Country" :"Portugal"},
    {"CustomerName" : "Persie", "City":"Amsterdam", "Country" :"Netherlands"},
    {"CustomerName" : "Ronnie", "City":"London", "Country" :"England"}
]

I have used the following jQuery snippet but it doesn't work:
var arr = [];

$.each(dataReceivedFromServer, function (i, data) {
  var d = data.Key;
  arr.push({
         d: data.Value,
         });
  });

If I do above, it shows me [{"d":"Messi"},{"d":"Buenos Aires"},{"d":"Argentina"} and so on...
In short, I want to bind data from Excel file to KendoUI grid (all columns would be dynamic as user can select any file).
Does anyone know how to do this?
Update # 1:
@webkit - Please see below image as the output of Console.log

A: I would highly recommend to transform the data before you receive it, as it would be more reliable. However, if this is not possible and you can guarantee that there is some grouping rules on your data set, you could apply the following:
var customer = {
    //this transform asserts the key value collection will be in a groupable order
    transform: function(coll, groupBeginKey){
        var result = [];
        var currentObject = {};
        var size = coll.length;
        $.each(coll,function(idx,data){
            //check if we are beginning
           var defined = (typeof(currentObject[data.Key]) !== 'undefined');

            if(!defined &&
               data.Key === groupBeginKey){
                currentObject = {};
            }else if((defined &&
               data.Key === groupBeginKey)){

                result.push(currentObject);
                currentObject = {};
            }
            //set the property on the object
            currentObject[data.Key] = data.Value;
            //handle last
            if(idx >= size-1){
                result.push(currentObject);
            }
        });

        return result;
    }
};

For the following data set (I have simplified it for simplicity):
var data = []

data.push({ "Key": "CustomerName", "Value": "Paul"});
data.push({ "Key": "City", "Value": "Las Vegas"});
data.push({ "Key": "CustomerName", "Value": "George"});
data.push({ "Key": "Zip", "Value": "1234567"});
data.push({ "Key": "City", "Value": "New York"});
data.push({ "Key": "CustomerName", "Value": "Joe"});
data.push({ "Key": "City", "Value": "Omaha"});

Asserting that the customer can be grouped from CustomerName to City, you use it as follows (it will include the customer that has a zipcode):
var results = customer.transform(data,"CustomerName");

Please see it in action at the following jsfiddle (look in the debug console for output):
http://jsfiddle.net/pHQze/


text:
Q: Redux Saga - yield spawn takeEvery call no overload I use redux-saga version 1.1.3  and have this here:
import {
  spawn,
  race,
  take,
  call,
  put,
  takeEvery,
  delay,
} from "redux-saga/effects";
import {
  MessageCenterActionTypes
} from "../types";

function remove(notification) {
  return {
    type: MessageCenterActionTypes.MESSAGECENTER_REMOVE,
    notification,
  };
}

export function* saga() {
  yield spawn(
    takeEvery,
    MessageCenterActionTypes.MESSAGECENTER_ENQUEUE,
    removeNotificationAfterElapsedTime,
    4000,
  );
}

export function* removeNotificationAfterElapsedTime(waitFor, {
  notification
}) {
  const {
    shouldBeRemoved
  } = yield race({
    shouldBeRemoved: call(delay, waitFor),
    _: take(
      (action) =>
      action.type === MessageCenterActionTypes.MESSAGECENTER_REMOVE &&
      action.notification.id === notification.id,
    ),
  });

  if (shouldBeRemoved) {
    yield put(remove(notification));
  }
}

export default saga;

But in yield spawn(takeEvery, MessageCenterActionTypes.MESSAGECENTER_ENQUEUE, removeNotificationAfterElapsedTime, 4000,);

it says:
No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ <P extends ActionPattern<Action<any>>>(pattern: P, worker: (action: ActionMatchingPattern<P>) => any): ForkEffect<never>; <P extends ActionPattern<...>, Fn extends (...args: any[]) => any>(pattern: P, worker: Fn, ...args: HelperWorkerParameters<...>): ForkEffect<...>; <A extends Action<...>>(pattern: ActionPattern...' is not assignable to parameter of type '{ context: unknown; fn: (this: unknown, ...args: any[]) => any; }'.
      Type '{ <P extends ActionPattern<Action<any>>>(pattern: P, worker: (action: ActionMatchingPattern<P>) => any): ForkEffect<never>; <P extends ActionPattern<...>, Fn extends (...args: any[]) => any>(pattern: P, worker: Fn, ...args: HelperWorkerParameters<...>): ForkEffect<...>; <A extends Action<...>>(pattern: ActionPattern...' is missing the following properties from type '{ context: unknown; fn: (this: unknown, ...args: any[]) => any; }': context, fn

How should the call look like ?

A: spawn function can accept single generator function and inside of this generator function you can define your takeEvery logic.
The rest of your code doesn't require any changes.
export function* saga() {
  yield spawn(function*() {
    yield takeEvery(
      MessageCenterActionTypes.MESSAGECENTER_ENQUEUE,
      removeNotificationAfterElapsedTime,
      4000,
    );
  });
}


text:
Q: Hibernate: OR in ORDER BY clause Consider this situation: I have a table of lessons, every lesson has a day of week (0-6; not a date) and a lesson hour when the lesson holds (not the time, but rather sequence number of the lesson in a day, ie. 1 to 10). And I need to find the first lesson after specific day and hour.
Given these lessons (day-hour): monday-5, wednesday-2, friday-1, friday-3.
For a lesson after wednesday-2 I would receive friday-1, friday-3 after friday-2, monday-5 after friday-5, and so on. So it "overflows" over the end of the week.
In one project where I used Hibernate HQL I solved it with this query:
SELECT l FROM Lesson l
ORDER BY (l.day > :day OR (l.day = :day AND l.hour >= :hour)),
l.day DESC, l.hour DESC LIMIT 1

Surprisingly, this really worked, although I really don't remember how I came up with it. It's a real magic.
But now I need to do it in another project (this time Java EE web-based) where I use JPA, and Hibernate too. Thinking it'll work the same (using Hibernate and HQL again), it throws exception:
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: OR near line 1, column 101

which points to that OR in ORDER BY clause.
I know that OR inside ORDER BY is really awkward but it did work, so I thought it is OK. But now I don't know what to do with it. Could it be because of different Hibernate version or because of the use of JPA? (I'm not sure about version, both are Hibernate 3). Both databases were MySQL.
Thanks for any help (or providing another query which will work as specified).

A: Disclaimer, I really don't know that much about Hibernate so I'm going to assume that l.day > :day in your order by "returns" a boolean.
I'm a little surprised that this worked at all; I would use a case statement in this situation so that it's abundantly clear what's going on:
SELECT <columns>
  FROM Lesson l
 ORDER BY case when (l.day > :day OR (l.day = :day AND l.hour >= :hour)) then 1
               else 0 end DESC
        , l.day DESC
        , l.hour DESC
 LIMIT 1


text:
Q: Add score to saved score when I restart the app and start tapping on the button the saved score is set to 0 and counts up from there how can I change it that it counts up the saved score?
import UIKit
import iAd

class ViewController: UIViewController, ADBannerViewDelegate {

    @IBOutlet var TapLabel: UILabel!
    @IBOutlet var Banner: ADBannerView!

    var taps = 0

        override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

            TapLabel.text = String(NSUserDefaults.standardUserDefaults().integerForKey("key"))

            Banner.hidden = true
            Banner.delegate = self
            self.canDisplayBannerAds = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
        return true
    }

    func bannerViewDidLoadAd(banner: ADBannerView!) {
        Banner.hidden = false
    }

    @IBAction func Button(sender: UIButton){

        taps += 1
        TapLabel.text = "Taps: \(taps)"
        NSUserDefaults.standardUserDefaults().setInteger(taps, forKey: "key")

    }

}

A: You need to set taps to what is stored in NSUserDefaults. Currently you only set this to the label.
So in your viewDidLoad method, add this:
taps = NSUserDefaults.standardUserDefaults().integerForKey("key")

Then below that add the following to update the display:
TapLabel.text = "Taps: \(taps)"

Another way to do this is so make your taps property set and get the user defaults directly. Here is an example:
import UIKit
import iAd

class ViewController: UIViewController, ADBannerViewDelegate {

    @IBOutlet var TapLabel: UILabel!
    @IBOutlet var Banner: ADBannerView!

    var taps: Int {
        get {
            return NSUserDefaults.standardUserDefaults().integerForKey("key")
        }
        set {
            NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "key")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        TapLabel.text = "Taps: \(taps)"

        Banner.hidden = true
        Banner.delegate = self
        self.canDisplayBannerAds = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
        return true
    }

    func bannerViewDidLoadAd(banner: ADBannerView!) {
        Banner.hidden = false
    }

    @IBAction func Button(sender: UIButton){

        taps += 1
        TapLabel.text = "Taps: \(taps)"
    }
}

A: You change this my giving Taps an initial number and then setting it to the previously stored value Below is the code
@IBOutlet var TapLabel: UILabel!
@IBOutlet var Banner: ADBannerView!

var taps: Int = 0

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
        let previousTaps = String(NSUserDefaults.standardUserDefaults().integerForKey("key"))
        TapLabel.text = previousTaps
        taps = Int(previousTaps)
        Banner.hidden = true
        Banner.delegate = self
        self.canDisplayBannerAds = true

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

}

func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
    return true
}

func bannerViewDidLoadAd(banner: ADBannerView!) {
    Banner.hidden = false
}

@IBAction func Button(sender: UIButton){

    taps += 1
    TapLabel.text = "Taps: \(taps)"
    NSUserDefaults.standardUserDefaults().setInteger(taps, forKey: "key")

}


text:
Q: C++ random srand code-if else does not give correct result I am not receiving correct response to my code. It should give 'Excellent' when I type in correct number; however, it always outputs 'Incorrect' - Please suggest.
#include <iostream>
#include <ctime>
using namespace std;

int guess()
{
    int x = 0;
    x = 1 + rand() % 1000;
    return x;
}

int main()
{
    int input = 0;
    srand( time( 0 ) );
    cout << guess() << endl;
    cout << "I have a number between 1 and 1000. " << endl;
    cout << "Can you guess my number? " << endl;
    cout << "Please type your first guess. " << endl;
    cin >> input;

    if (guess() == input)
        cout << "Excellent! You guessed the number! " << endl;
    else
        cout << "Incorrect! " << endl;

    system ("pause");
    return 0;
}

A: You are calling twice the function guess(), so it will give you probably different values at each run. You must store the value and then compare it with the original one.


text:
Q: new in Xcode 6.3/iOS 8.3: using self alloc for convenience constructor causes build error This code did not change between Xcode 6.2 and 6.3, but the line containing [self alloc] now causes the error:
Multiple methods named 'initWithType:' found with mismatched result, parameter type or attributes
@implementation AGNetworkDataRequest

+ (instancetype)networkDataRequestWithType:(AGNetworkDataRequestType)type
{
    AGNetworkDataRequest *r = [[self alloc] initWithType:type];//error here
    return r;
}

- (id)initWithType:(AGNetworkDataRequestType)type
{
    //typical init code
}

//...

If I Cmd+click on the initWithType: call, I am shown the conflict in CAEmitterBehavior, an object not referenced in our project at all, but I'm guessing must be new in iOS 8.3.
If I change the [self alloc] to [AGNetworkRequest alloc], the subclasses inheriting this method will just return the parent object, which acts in opposition to how we designed this class.
Any way to eliminate the conflict without changing the method name (which requires changing all method calls throughout the app)?

A: cast your alloc return.
[(AGNetworkDataRequest*)[self alloc] initWithType:type];

This will give the compiler enough information to make the call.  If the compiler doesn't know the length of your parameter there is a chance the call will fail at runtime (and potentially be very difficult to debug).
returning instancetype rather than id is supposed to fix this (allocWithZone will automatically return instancetype...) but it's possible because you're using 'self' there is not enough static information.


text:
Q: Java -- For an animation, how should a logic class notify a loosely coupled view to repaint For an application that repaints frequently, how should the 'model' notify the 'views' that they need to repeatedly repaint one of their components. This:

class AppLogic extends Observable {
  void runAnimation() {
    while (isAnimationRunning) {
      modifyDataStructures();
      setChanged();
      notifyObservers();
      Thread.sleep(25);
    }
  }
}

class View extends JComponent implements Observer {
  void update(Observable o) {
    o.getData();
    innerPanel.repaint();
  }
}

seems like a terrible way to go about animating a panel, especially if the animation is being repainted most of the time that the program is running. Any suggestions? Thanks.
*Ignore the obvious errors in threading and such

A: Assuming that you are building a kind of "Dashboard" application that updates the information periodically, do what this answer says. If you want something more advanced (like animations for a game) you need more work. Check this article for some interesting tidbits about game programming and animation in Java.

A: Rather than "running" the business logic, you could use a Swing Timer in the View component and just ask the business model to paint itself, e.g passing the current time as a parameter.


text:
Q: @ngrx/store subscription to part of a store and avoid detecting changes to other parts Background
One of the reducers in my store deals with things that are selected within the app. The interface for this store (let's called it app) could look like this:
interface IApp {
    selectedProject: IProject;
    selectedPart: IPart;
}

So I want to have a subscription that performs an action only when a different 'project' is selected. I wrote something like this:
this.store.select('app')
    .map((store: IApp) => store.selectedProject)
    .subscribe((project: IProject) => {
        // Stuff happens here
    });

This function does it stuff when selectedProject changes. However, it also does it stuff when selectedPart changes. Clearly, it listens to the whole of the app store, regardless of the map. That makes sense.
Question
I don't want this to happen. I only want my function to execute when selectedProject changes.
I know I can split selectedProject and selectedPart into different stores to solve this. However, I could quickly end up with many, many stores. Maybe this the way it is meant to be?
Is there another way though? Can I keep the store with this interface and have a subscription that only detects changes to the selectedProject part of the store?

A: I believe you are looking for distinctKeyUntilChanged.
this.store.select('app')
  //Only emit when selectedProject has changed
  .distinctUntilKeyChanged(
    //Key to filter on
    'selectedProject',
    //Optional comparison function if you have a specific way of comparing keys
    (x, y) => x.projectName === y.projectName)
  .pluck('selectedProject')
  .subscribe((project: IProject) => {});


text:
Q: register_sidebar / dynamic_sidebar with sidebar id I am trying to get rid of the following error in debug:
Notice: register_sidebar was called incorrectly.
No id was set in the arguments array for the "Header" sidebar.

So when I register that sidebar I added the id parameter like so:
register_sidebar(array(
    'id' => 'header-sidebar',
    'name' => 'Header',
    'before_widget' => '
',
    'after_widget' => '
',
    'before_title' => '
',
    'after_title' => '
',
));

Now no matter if I use the name field or the id field dynamic_sidebar always returns false.
I've tried:
dynamic_sidebar( 'Header' );

and
dynamic_sidebar( 'header-sidebar' );

My understand is both of the above should work.  Note if I comment out the id parameter in the register_sidebar call and use dynamic_sidebar( 'Header' ); everything works fine.  What am I missing?
This is WP 4.2.2.
So per these directions: List all sidebar names? I was able to list all the sidebar names and when I set the id parameter with register_sidebar the id in the list of names changes.  The specific sidebar I'm playing with now is 'sidebar-5' before setting an id and 'sidebar-jsp' after.  Once the id field is set I can not use dynamic_sidebar with the name 'Sidebar', the original id 'sidebar-5' or the new id 'sidebar-jsp'.
Per s_ha_dum's suggestion I wrapped a single sidebar inside a function so that I could make it happen after 'widgets_init'.  This did not work.
function register_header_sidebar_jsp() {
    register_sidebar(array(
        'name' => 'Sidebar',
        'id' => 'sidebar-jsp',
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
',
    ));
}
add_action( 'widgets_init', 'register_header_sidebar_jsp' );

I'm calling it right now with:
<?php var_dump(dynamic_sidebar('sidebar-jsp')); ?>

I'm not sure what's going on but I don't have all day to mess with this.  Thanks for your suggestions everyone.

A: Your code works when I test it. I can only assume that the registration code is being hooked into the system too early or too late. register_sidebar() should be hooked on widgets_init per the Codex. Therefore:
function register_header_sidebar_wpse_190618() {
  register_sidebar(
    array(
      'id' => 'header-sidebar',
      'name' => 'Header',
      'before_widget' => '
',
      'after_widget' => '
',
      'before_title' => '
',
      'after_title' => '
',
    )
  );
}
add_action( 'widgets_init', 'register_header_sidebar_wpse_190618' );

A: <?php dynamic_sidebar( 'new-header-sidebar' ); ?>

register_sidebar( array(
    'name' => __( 'Header', 'theme-slug' ),
    'id' => 'new-header-sidebar',
) );

You may have a I.D conflict so try changing the I.D

A: Try starting the id field value with 'sidebar'.
If that doesn't work, the order shouldn't matter, but try following the codex example:
register_sidebar( array(
    'name' => __( 'Main Sidebar', 'theme-slug' ),
    'id' => 'sidebar-1',
    'description' => __( 'show on all posts and pages', 'theme-slug' ),
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
',
) );

Also try not using the word 'header' in the id field.


text:
Q: 433 MHz RF noise problems I know this is kind of a noob question. I am trying to establish a wireless communication between two 8051 microcontrollers using a 433 MHz RF module. But since 433 MHz is a quite noisy frequency, the receiver immediately starts collecting the garbage around. In this case, would implementing a software filter do the job to eliminate the garbage data or is my data getting completely disturbed on the way? Thanks in advance.

A: Are you using such type of modules?

If yes, then don't expect them to work without proper software noise filtering algorithms. This module will give out data at Rx output even if there is no other transmitter operating at 433MHz. This is because this device works on OOK(On-Off Keying) and AGC (automatic gain control). Thus if Rx does not detect any signal for some time it will automatically reduce the threshold, and once the threshold gets close to the noise level, then the noise will get interpreted as the bitstream of \$ 1\$'s and \$0\$'s.
To properly identify your packets, add 3-4 identification bytes to each of the frames you transmit. Adding more number of identification bytes will reduce the probability that the noise will get interpreted as your packet.
Usually, 3-4 bytes are sufficient.
Also, it takes some time (few bit durations) to get the threshold adjusted with the transmitting signal level, so if you are not transmitting continuously then it is better to send 1 or 2 junk bytes before transmitting any frame (as initial bits have some chance of getting corrupted due to improper initial threshold level).
Hardware solution: A common chipset used in such receiver module is PT4317. If you check the datasheet then you can see that the data slicer inputs are available off-chip. Thus the slicing threshold can be manually adjusted by properly assigning threshold voltage to DSN pin. But this will compromise the sensitivity of the receiver and thus the longest range it can operate with. You will have to experiment with different values of this pin's voltage and the range it produces.

A: It does not have to be the environment that's noisy, it is also the receiver itself which produces noise. How that's solved in most 433 MHz devices is by using coding of the data. So the data packets consist of the data itself plus extra code so that the micro can recognize the data packets and distinguish them from the noise.
There are libraries for Arduino for data transfer over 433 (or 315) MHz. One example is the Virtualwire library. I suggest you look into those to see how it is done.
Just don't expect a "clear" channel when you're not sending data. 433 MHz communications do not work like that. They are designed with extremely simple (and cheap) receiver and transmitter using OOK modulation (also simple), the "clever" bit is then done in software by correlation, pattern recognition etc. Since it is for low data rates this can be done even in a simple micro controller.

A: There is nothing about the 433MHz band that makes it especially noisy, though there may be occasional interference from other users of the band, that's probably not what you're seeing.
Simple receivers can crank up the gain in the absence of a signal until their own internal noise is decoded as spurious signals, and that's probably what you are seeing : software filtering is unlikely to be a fix.
Check the datasheet for your receiver : there might be an RSSI output - (Received Signal Strength Indicator) - usually an analog voltage, representing the incoming signal strength (and not very precisely).
One approach is to read this in an analog (ADC) channel, and ignore the receiver output if the RSSI is below a certain level. If you're not attempting maximum range, you can set this level fairly high so that you only decode a strong signal with few errors.
Otherwise you may need to combine with some other error mitigation scheme - re-transmitting faulty messages or error correcting codes for example - details are far too wide for a simple Q&A but how to meet a specific service goal might be a better question.

A: Thought experiment: remove the receiver antenna, replace with short circuit from antenna connection on pcb to ground on pcb. Place receiver in a perfect faraday cage and only when you cool it down to significantly close to absolute zero will the automatic gain control in the receiver not be sensitive enough to pick up noise and amplify it.


text:
Q: SQL Server 2005, Caches and all that jazz Background to question: I'm looking to implement a caching system for my website. Currently we're exploring memcache as a means of doing this. However, I am looking to see if something similar exists for SQL Server. I understand that MySQL has query cache which although is not distributed works as a sort of 'stop gap' measure. Is MySQL query cache equivalent to the buffer cache in SQL Server?
So here are my questions:

*

*Is there a way to know is currently stored in the buffer cache?

*Follow up to this, is there a way to force certain tables or result sets into the cache

*How much control do I have over what goes on in the buffer and procedure cache? I understand there used to be a DBCC PINTABLE command but that has since been discontinued.

*Slightly off topic: Should the caching even exists on the database layer? Or it is more prudent to manage caches using Velocity/Memcache? Is so, why? It seems like cache invalidation is something of a pain when handling many objects with overlapping triggers.

Thanks!

A: SQL Server implements a buffer pool same way every database product under the sun does (more or less) since System R showed the way. The gory details are explain in Transaction Processing: Concepts and Techniques. I addition it has a caching framework used by the procedure cache, permission token cache and many many other caching classes. This framework is best described in Clock Hands - what are they for.
But this is not the kind of caching applications  are usually interested in. The internal database cache is perfect for scale-up scenarios where a more powerfull back end database is able to respond faster to more queries by using these caches, but the modern application stack tends to scale out the web servers and the real problem is caching the results of query interogations in a cache used by the web farm. Ideally, this cache should be shared and distributed. Memcached and Velocity are examples of such application caching infrastructure. Memcache has a long history by now, its uses and shortcommings are understood, there is significant know-how around how to use it, deploy it, manage it and monitor it.
The biggest problem with caching in the application layer, and specially with distributed caching, is cache invalidation. How to detect the changes that occur in the back end data and mark cached entries invalid so that new requests don't use stale data.
The simplest (for some definition of simple...) alternative is proactive invalidation from the application. The code knows when it changes an entity in the database, and after the change occurs it takes the extra step to mark the cached entries invalid. This has several short commings:

*

*Is difficult to know exactly which cached entries are to be invalidated. Dependencies can be quite complex, things are always more that just a simple table/entry, there are aggregate queries, joins, partitioned data etc etc.

*Code discipline is required to ensure all paths that modify data also invalidate the cache.

*Changes to the data that occur outside the application scope are not detected. In practice, there are always changes that occur outside the application scope: other applications using the same data, import/export and ETL jobs, manual intervention etc etc.

A more complicated alternative is a cache that is notified by the database itself when changes occur. Not many technologies are around to support this though, it cannot work without an active support from the database. SQL Server has Query Notifications for such scenarios, you can read more about it at The Mysterious Notification. Implementing QN based caching in a standalone application is fairly complicated (and often done badly) but it works fine when implemented correctly. Doing so in a shared scaled out cache like Memcached is quite a feats of strength, but is doable.

A: Nai,

Answers to your questions follow:

*

*From Wiki - Always correct... ? :-).  For a more Microsoft answer, here is their description on Buffer Cache.

Buffer management
SQL Server buffers pages in RAM to
  minimize disc I/O. Any 8 KB page can
  be buffered in-memory, and the set of
  all pages currently buffered is called
  the buffer cache. The amount of memory
  available to SQL Server decides how
  many pages will be cached in memory.
  The buffer cache is managed by the
  Buffer Manager. Either reading from or
  writing to any page copies it to the
  buffer cache. Subsequent reads or
  writes are redirected to the in-memory
  copy, rather than the on-disc version.
  The page is updated on the disc by the
  Buffer Manager only if the in-memory
  cache has not been referenced for some
  time. While writing pages back to
  disc, asynchronous I/O is used whereby
  the I/O operation is done in a
  background thread so that other
  operations do not have to wait for the
  I/O operation to complete. Each page
  is written along with its checksum
  when it is written. When reading the
  page back, its checksum is computed
  again and matched with the stored
  version to ensure the page has not
  been damaged or tampered with in the
  meantime.

*For this answer, please refer to the above answer:

Either reading from or writing to any page copies it to the buffer cache. Subsequent reads or writes are redirected to the in-memory copy, rather than the on-disc version.

*You can query the bpool_commit_target and bpool_committed columns in the sys.dm_os_sys_info catalog view to return the number of pages reserved as the memory target and the number of pages currently committed in the buffer cache, respectively.

*I feel like Microsoft has had time to figure out caching for their product and should be trusted.
I hope this information was helpful,
Thanks!

A: Caching can take many different meaning for an ASP.Net application spread from the browser all the way to your hardware with the IIS, Application, Database thrown in the middle.
The caching you are talking about is Database level caching, this is mostly transparent to your application. This level of caching will include buffer pools, statement caches etc. Make sure your DB server has plenty of RAM. In theory a DB server should be able to load the entire DB store in memory. There is not much you can do at this level unless you pre-fetch some anticipated data when you start the application and ensure that it is in DB cache.
On the other hand is in-memory distributed caching system. Apart from memcache and velocity, you can look at some commercial solutions like NCache or Oracle Coherence. I have no experience in either of them to recommend. This level of caching promises scalability at a cheaper cost. It is expensive to scale the DB tier compared to this. You may have to consider aspects like network bandwidth though. This type of caching, specially with invalidation and expiry can be complicated
You can cache at Web Service tier using output caching at IIS level (in IIS 7) and ASP.Net level.
At the application level you can use ASP.Net cache. This is the one that you can control most and gives you good benefits.
Then there is caching going on at client web proxy tier that can be controlled by cache-control HTTP header.
Finally you have browser level caching, view state and cookies for small data.
And don't forget that hardware like SAN caches at physical disk access level too.
In summary caching can occur at many levels and it for you to analyse and implement the best solution for your scenario. You have find out stability and volatility of your data, expected load etc. I believe  caching at ASP.Net level (specially for objects) gives you most flexibility and control.

A: Your specific technical questions about SQL Server's buffer cache are going down the wrong path when it comes to "implement a caching system for my website".
Sure, SQL Server is going to cache data so it can improve its performance (and it does so rather well), but the point of implementing a caching layer on your web front-ends is to avoid from having to talk to the database at all - because there is still overhead and resource contention even when your query is fulfilled entirely from SQL Server's cache.
You want to be looking into is: memcached, Velocity, ASP.NET Cache, P&P Caching Application Block, etc.


text:
Q: How to share common quiz data generated by one player to all other in real time matches using GameKit and avoid staring by all the players? I am developing a quiz with real time matches using GameKit. How do I know who initiated the match as matching happening real time at both players' side.The problem is that if one of the players generates some random question and same question will be shared among all the players. I want to avoid sharing of questions from all the players. Any solution?

A: Try making a class system. At the beginning of a match, have each player generate a random number. The highest random number will be classified as the "Sender". Rarely there will be a tie - In this case, simply resend the random number. Then, you can check if the device playing is marked "Sender" and then send the random quiz question.