text:
Q: Associative arrays in javascript I have this object:
function formBuddy()
{
    var fields = new Array();
    var labels = new Array();
    var rules = new Array();
    var count=0;

    this.addField = function(field, label, rule)
    {
        fields[count] = field;
        labels[field] = label;
        rules[field] = rule;
        count = ++count;
    }
}

Its used in this way:
var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");

The problem is, in the addField() function the fields array is being set correct (perhaps because a numerical index is being used to refer to it) but the other 2 arrays (labels and rules) aren't being touched at all. Doing a console.log shows them as empty in firebug.
What do I need to change to make them work? I'd still like to refer to the rules and labels by the string index of the field.

A: Use objects instead:
function formBuddy()
{
    var fields = {};
    var labels = {};
    var rules = {};
    var count = 0;

    this.addField = function(field, label, rule)
    {
        fields[count] = field;
        labels[field] = label;
        rules[field] = rule;
        count++;
    }
}

But as Christoph already mentioned, I would store this information in a single data structure too. For example:
function formBuddy() {
    var fields = {};
    this.addField = function(name, label, rule) {
        fields[name] = {
            name: name,
            label: label,
            rule: rule
        };
    };
    this.getField = function(name) {
        return fields[name];
    };
}

var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
alert(cForm.getField("c_last_name").label);

A: fields should be an array, whereas labels and rules should be objects as you want to use strings as keys. Also, addField() is the same for each instance of FormBuddy() (names of constructor functions should be capitalized) and should reside in the prototype, ie
function FormBuddy() {
    this.fields = []; // this is the same as `new Array()`
    this.labels = {}; // this is the same as `new Object()`
    this.rules = {};
}

FormBuddy.prototype.addField = function(field, label, rule) {
    this.fields.push(field);
    this.labels[field] = label;
    this.rules[field] = rule;
};

You can access the labels/rules via
var buddy = new FormBuddy();
buddy.addField('foo', 'bar', 'baz');
alert(buddy.labels['foo']);
alert(buddy.rules.foo);

Just to further enrage Luca ;), here's another version which also dosn't encapsulate anything:
function FormBuddy() {
    this.fields = [];
}

FormBuddy.prototype.addField = function(id, label, rule) {
    var field = {
        id : id,
        label : label,
        rule : rule
    };

    this.fields.push(field);
    this['field ' + id] = field;
};

FormBuddy.prototype.getField = function(id) {
    return this['field ' + id];
};

var buddy = new FormBuddy();
buddy.addField('foo', 'label for foo', 'rule for foo');

It's similar to Gumbo's second version, but his fields object is merged into the FormBuddy instance. An array called fields is added instead to allow for fast iteration.
To access a field's label, rule, or id, use
buddy.getField('foo').label

To iterate over the fields, use
// list rules:
for(var i = 0, len = buddy.fields.length; i < len; ++i)
    document.writeln(buddy.fields[i].rule);

A: Arrays are treated as Objects in Javascript, therefore your piece of code works, it's just that firebug's console.log isn't showing you the "Objects" inside the array, rather just the array values ...
Use the for(var i in obj) to see what objects values the Array contains:
function formBuddy() {
    var fields = new Array();
    var labels = new Array();
    var rules = new Array();
    var count=0;

    this.addField = function(field, label, rule)
    {
        fields[count] = field;
        labels[field] = label;
        rules[field] = rule;
        count = ++count;

        for(var i in labels) {
            console.log(labels[i]);
        }
        for(var i in rules) {
            console.log(rules[i]);
        }

        console.log(labels.c_last_name);
        // or
        console.log(labels["c_last_name"]);
    }
}

var cForm = new formBuddy();
cForm.addField("c_last_name","Last Name","required");

A: Is this an alternative to what you are seeking ?
Try it.
<script type="text/javascript">"use strict";
  function formBuddy() {
      this.fields = new Array();
      this.labels = new Array();
      this.rules = new Array();
      this.count=0;

      this.addField = function(field, label, rule)
      {
          this.fields[this.count] = field;
          this.labels[field] = label;
          this.rules[field] = rule;
          this.count++;
      }
  }

  var cForm = new formBuddy();

  // FILLING IN THE DATABASE
  cForm.addField("c_first_name","Diasoluka","duplicated");
  cForm.addField("c_Middle_name","Nz","inspect");
  cForm.addField("c_last_name","Luyalu","mandatory");
  cForm.addField("c_first_name","Diasoluka","duplicated");

  console.log(`ACCESSING EACH PROPERTY INDIVIDUALLY\n,${'.'.repeat(31)}`);

  let el=Object.entries(cForm.fields); // DESTRUCTURING
      console.log(Object.is(el,Object.entries(cForm.fields)));
      // false

  const [f1,f2,f3] = el; // DESTRUCTURING=DÉCOMPOSITION
  console.log("FIELDS:\n",f1," | ",f2," | ",f3,"\n\n");
  // FIELDS:
    // Array [ "0", "c_first_name" ]
    // Array [ "1", "c_Middle_name" ]
    // Array [ "2", "c_last_name" ]

  let labels = Object.entries(cForm.labels); // DESTRUCTURING
  const [l1,l2,l3] = labels; // DESTRUCTURING
  console.log("LABELS:\n",l1," | ",l2," | ",l3,"\n\n");
  // LABELS:
    // Array [ "c_first_name", "Diasoluka" ]
    // Array [ "c_Middle_name", "Nz" ]
    // Array [ "c_last_name", "Luyalu" ]

  let rules = Object.entries(cForm.rules); // DESTRUCTURING
  const [r1,r2,r3] = rules; // DESTRUCTURING
  console.log("RULES:\n",r1," | ",r2," | ",r3,"\n\n");
  // RULES:
    // Array [ "c_first_name", "duplicated" ]
    // Array [ "c_Middle_name", "inspect" ]
    // Array [ "c_last_name", "mandatory" ]

  console.log(`PAESING THE DATABASE =\nACCESSING ALL THE FIELDS AT ONCE\n,${'.'.repeat(31)}`);

  for(let key in cForm.fields){
    let el=cForm.fields[key]; // ASSIGNMENT=AFFECTATION
        console.log(Object.is(el,cForm.fields[key]));
        // true true true true

    console.log(`${el} // ${cForm.labels[el]} // ${cForm.rules[el]}\n`);
  }
  // c_first_name // Diasoluka // duplicated
  // c_Middle_name // Nz // inspect
  // c_last_name // Luyalu // mandatory
  // c_first_name // Diasoluka // duplicated

  console.log("\n");

  console.log(`THE INNER STRUCTURE OF OUR cForm OBJECT\n,${'.'.repeat(31)}`);
  console.log(Object.entries(cForm)); // DESTRUCTURING
  // (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
    // 0: (2) ['fields', Array(4)]
    // 1: (2) ['labels', Array(0)]
    // 2: (2) ['rules', Array(0)]
    // 3: (2) ['count', 4]
    // 4: (2) ['addField', ƒ]
    // length: 5
    // [[Prototype]]: Array(0)
</script>


text:
Q: Identifying forward looking sentences in text I am looking to identify sentences in a text, that talk about future.
It could be future tense, sentences starting with "I expect ... grows" and such.
Can anyone recommend any ready to use solutions for that (preferably, in python)?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Compose setupWithNavController I am looking for a Compose variant of setupWithNavController(Toolbar, NavController) to automatically update the up button in an AppBar whenever the Navigation destination changes.
So far I haven't found anything useful.
Is it considered a bad design in Compose? Or is there some simple way how to achieve the same thing that I am not seeing?

A: I've hacked up a solution, but I am not satisfied.

androidx.navigation:navigation-compose:1.0.0-alpha08 provides an extension function to observe the current back stack entry.
@Composable
fun NavController.currentBackStackEntryAsState(): State<NavBackStackEntry?>

I've created a similar extension to observe the previous back stack entry
/**
 * Gets the previous navigation back stack entry as a [MutableState]. When the given navController
 * changes the back stack due to a [NavController.navigate] or [NavController.popBackStack] this
 * will trigger a recompose and return the second top entry on the back stack.
 *
 * @return a mutable state of the previous back stack entry
 */
@Composable
fun NavController.previousBackStackEntryAsState(): State<NavBackStackEntry?> {
    val previousNavBackStackEntry = remember { mutableStateOf(previousBackStackEntry) }
    // setup the onDestinationChangedListener responsible for detecting when the
    // previous back stack entry changes
    DisposableEffect(this) {
        val callback = NavController.OnDestinationChangedListener { controller, _, _ ->
            previousNavBackStackEntry.value = controller.previousBackStackEntry
        }
        addOnDestinationChangedListener(callback)
        // remove the navController on dispose (i.e. when the composable is destroyed)
        onDispose {
            removeOnDestinationChangedListener(callback)
        }
    }
    return previousNavBackStackEntry
}

and a composable for the back button
@Composable
fun NavigationIcon(navController: NavController): @Composable (() -> Unit)? {
    val previousBackStackEntry: NavBackStackEntry? by navController.previousBackStackEntryAsState()
    return previousBackStackEntry?.let {
        {
            IconButton(onClick = {
                navController.popBackStack()
            }) {
                Icon(Icons.Default.ArrowBack, contentDescription = "Up button")
            }
        }
    }
}

I had to return a @Composable (() -> Unit)? (instead of no return value common to composable functions) because the TopAppBar uses the nullability to check whether to offset the title by 16dp (without icon) or by 72dp (with icon).
Finally, the content looks something like this
@Composable
fun MainContent() {
    val navController: NavHostController = rememberNavController()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Weather") },
                navigationIcon = NavigationIcon(navController)
            )
        },
    ) {
        NavHost(
            navController,
            startDestination = "list"
        ) {
            composable("list") {
                ...
            }
            composable("detail") {
                ...
            }
        }
    }
}

List:

Detail:

It might be cleaner to create a custom NavigationTopAppBar composable and hoist the NavController out of NavigationIcon but the idea stays the same. I didn't bother tinkering further.

I've also attempted to automatically update the title according to the current NavGraph destination. Unfortunately, there is not a reliable way to set a label to destinations without extracting quite a big chunk of internal implementation out of androidx.navigation:navigation-compose library.


text:
Q: memory leak in C++ class I've defined two classes CA and CB.
I would like to prevent memory leak and I don't know how to properly destroy the class CB (assuming that the memory leak is coming from it).
mpz_t is a GMP datatype.
Here's my code
class CA {
public:
void SetFoo (unsigned long int);
CA  ();
CA  (unsigned long int);
~CA ();
private:
mpz_t foo;
};

where
CA::CA () {
mpz_init (foo);
}

CA::CA (unsigned long int in) {
mpz_init   (foo);
mpz_set_ui (foo, in);
}

CA::~CA () {
mpz_clear (foo);
}

void CA::SetFoo (unsigned long int in) {
mpz_set_ui (foo, in);
}

and
class CB {
public:
CB  ();
~CB ();
private:
list <pair<uint16_t, CA*>> mylist;
};

where
CB::CB () {
pair<uint16_t, CA*> mypair;
CA* C = new CA [2];
C [0].SetFoo (100);
C [1].SetFoo (200);
mypair.first  = 0;
mypair.second = &C[0];
mylist.push_front (mypair);
mypair.first  = 1;
mypair.second = &C[1];
mylist.push_front (mypair);
}

CB::~CB () {
???
}

A: You can use std::unique_ptr instead of a regular pointer. This will automatically deallocate the memory on the destruction of each element.
typedef std::unique_ptr<Ca[]> CA_array;
list <pair <uint16_t, CA_array> > mylist;

Alternatively, you could iterate through the elements and deallocate memory using delete [].
CB::~CB () {
    for (auto &item : mylist)
        delete [] item.second;
}


text:
Q: UIPasteboard: image saving issue I'v thought that dealing with UIPasteboard is easy but it turned out to be a time-consuming issue...
I want to store an UIImage in UIPasteboard and then paste this image in iMessage, WhatsApp, Gmail... and others.
That's my method where I use UIPasteboard
- (void) postClipboard
{
    if ([[modelView currentView] isImage])
    {
        UIImage *image = [self readyImageLandscape:orientationLandscape];
        [[UIPasteboard generalPasteboard] setImage:image];
    }
}

It works on iPhone 3GS 5.1. I've tested it on Gmail and WhatsApp
Then I modified the method to
- (void) postClipboard
{
    if ([[modelView currentView] isImage])
    {
        UIImage *image = [self readyImageLandscape:orientationLandscape];
        [[UIPasteboard generalPasteboard] setImage:image];
        [[UIPasteboard generalPasteboard] setPersistent:YES];
    }
}

Still works on iPhone 3GS 5.1.
But my employer says that it doesn't work on iPhone 4S 6.0 neither in WhatsApp nor in any other application.
Am I doing all wrong or there should be another approach to make it work on iPhone 4S 6.0?

A: See this answer: https://stackoverflow.com/a/12613632/830946
Looks like that code will work with a single image, but not with multiple.


text:
Q: Object with another's object's property as a key I have an object like this:
var myObj = {action1:0, action2:1, action3:2};
Test function gets values from this list as parameters and to simplify unit-testing I want to get human readable labels inside of the function
function myFunc(someaction, anotheraction, blablabla)
{
    console.log("Action: " + arguments[0] + " then action: " + arguments[1]);
    //some code here
}

So inside of the function I can see only values like 0 1 2
Trying to workaround I tried to create new object like this
var dictObj = {myObj.action1:"action1", myObj.action2:"action2", myObj.action3:"action3"}

and then resolve values to names inside of the function:
console.log("Action: " + dictObj[arguments[0]] + " then action: " + dictObj[arguments[1]]);

But it didn't work because of
'Uncaught SyntaxError: Unexpected token .'

How I can rework this code to get readable description?

A: In ES5 and earlier, you have to create that object with a series of statements:
var dictObj = {};
dictObj[myObj.action1] = "action1";
dictObj[myObj.action2] = "action2";
dictObj[myObj.action3] = "action3";

As of ES2015 (aka "ES6"), you can do it with computed property names in the object initializer instead:
let dictObj = {
    [myObj.action1]: "action1",
    [myObj.action2]: "action2",
    [myObj.action3]: "action3"
};

You can use any expression within the [] to create the property name; in this case it's just a simple property lookup.
In both cases, note that there's no live relationship; if you change myObj.action1 to 42 later, after doing the above, it doesn't have any effect on the property name in dictObj.


text:
Q: Magento 2 product share in instagram and twitter and get the response after share I would like to get the response after the product share in instagram and twitter in magento2 product page.
I am getting the response for Facebook like below code:
require([
"jquery"
], function($){
    $(document).ready(function() {
var product_url = $('#product_url').val();
var product_id = $('#product_id').val();
var product_name = $('#product_name').val();
 window.fbAsyncInit = function() {
      // init the FB JS SDK
      FB.init({

            appId      : '',                        // App ID from the app dashboard
            channelUrl : product_url, // Channel file for x-domain comms
            status     : true,                                 // Check Facebook Login status
            xfbml      : true                                  // Look for social plugins on the page
          });

          // Additional initialization code such as adding Event Listeners goes here
        };

        // Load the SDK asynchronously
        (function(d, s, id){
           var js, fjs = d.getElementsByTagName(s)[0];
           if (d.getElementById(id)) {return;}
           js = d.createElement(s); js.id = id;
           js.src = "//connect.facebook.net/en_US/all.js";
           fjs.parentNode.insertBefore(js, fjs);
         }(document, 'script', 'facebook-jssdk'));

    function fb_share() {
        FB.ui( {
            method: 'feed',
            name: "Facebook API: Tracking Shares using the JavaScript SDK",
            link: product_url,
            picture: "https://stackexchange.com/users/flair/557969.png",
            caption: "Tracking Facebook Shares on your website or application is a useful way of seeing how popular your articles are with your readers. In order to tracking Shares, you must used the Facebook JavaScript SDK."
        }, function( response ) {
            if (jQuery.type(response) != 'undefined') {
               $.ajax({
                showLoader: true,
                //url: '',
                data: { product_id: product_id, product_name: product_name},
                type: "POST",
                dataType: 'json'
              }).done(function (data) {
              });
                //$("#fb_successresult").append(" Appended text");
            }else{
                //$("#fb_failresult").append("Not Appended text");
            }
        } );

    }

    $(document).ready(function(){
      $('button.share-btn').on( 'click', fb_share );
    });
        });
    });

Thank you.


text:
Q: convert a time to unix time in CPP This is very old question and there are similar topics to this here and here and so on. I have:

*

*year like 2014,

*month like 10,

*...

*seconds like 23.

Using these integers I want to get the unix time (the seconds since 1970. 01. 01.). But finally I want only an integer again. How can I do that?
I can use only STL and QT (not Boost). I know there is QDateTime which can solve this, but I still don't know how.
EDIT1:
I tried this one, but it seems something went wrong:
const WCCIL::QDate dd(/*fill it*/);
const WCCIL::QTime tt(/*fill it*/);
WCCIL::QDateTime ddtt( dd, tt); // error, no constructor
ddtt.toUTC();

A: The first link you posted (C++ How can I convert a date in year-month-day format to a unix epoch format?) contains the answer you want. You need to use a tm struct with mktime(). See the mktime() man page for more information.


text:
Q: Как проверить есть ли фраза в строк php Проблема следующая. С помощью php мне надо определить, есть ли в строке фраза "собрать минимальный пакет".
Строки которые выводятся в цикле могут содержать другой текст.
Различного рода функции strpos и тд работают почему то только для символа, но не работают для слова или фразы.
Можно попробовать регулярное выражение, но мне нужно что бы:
$bigString = "Собрать минимальный пакет документов и передать его любым удобным Вам способом";

$needle = "Собрать минимальный пакет";

if(если $needle есть в строке $bigString)
сделать что-то

Обновление
Обьясните ПОЧЕМУ?

A: Смотрите в сторону функции stristr
<?php
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
    echo '"earth" не найдена в строке';
 }
 // выводит: "earth" не найдена в строке

A: Вариант 1:
Стоит почитать про регулярные выражения. Там всё просто, если почитать)
$text = "В этом тексте есть нужное слово";

Ищем "слово"
preg_match("/слово/", $text, $match);
var_dump($match);

Вариант 2:
Можно воспользоваться функцией strpos
if (strpos($text, 'слово') !== false) // именно через жесткое сравнение
{
    echo 'Найдено';
} else {
    echo 'Не найдено';
}


text:
Q: How to stop receiving repeated OnKeyPress events on a TForm? I have a main Form and when I select an item and press Enter a second modal Form is shown. This has some TEdit controls to change the item parameters. When the user has finished, he can press Esc to cancel or Enter to update the item, and close the edit Form.
The problem is that if the user presses and holds Enter, a loop is occurs. The Form is closed and opened again and then closed... and so on.
I changed the WndProc of the modal Form and cancel if the previous key state was pressed. But this works only if I don't have any controls on the Form. If I drop a TEdit (which is needed), the Form re-enters the loop. The modal Form has KeyPreview set to true, because I want to be able to validate the data from anywhere.
This is the minimal code to reproduce the problem:
After you test this, you can drop a TEdit on Form2 and you will notice that a loop occurs.
Form1:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    procedure FormKeyPress(Sender: TObject; var Key: Char);
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if Key = #13 then Form2.ShowModal;
end;

end.

Form2:
unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm2 = class(TForm)
    Edit1: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
  protected
    procedure WndProc(var Msg: TMessage); override;
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
 KeyPreview:= True;
end;

procedure TForm2.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if Key = #13 then begin Key:= #0; ModalResult:= mrOK; end;
end;

procedure TForm2.WndProc(var Msg: TMessage);
begin
 if (Msg.Msg = WM_CHAR) and ((Msg.LParam and $40000000) <> 0) then Exit;
 inherited;
end;

end.

A: Because it's impossible to hook TWinControl.DoKeyPress to solve this issue as it should, I came up with this workaround:
Form1:
procedure TForm1.FormCreate(Sender: TObject);
begin
 Application.OnActivate:= AppActivate;
end;

procedure TForm1.AppActivate(Sender: TObject);
begin
 EnterReleased:= (GetAsyncKeyState(VK_RETURN) and $8000) = 0;
end;

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if Key = #13 then begin
  Key:= #0;
  if EnterReleased then begin
   EnterReleased:= False;
   Form2.ShowModal;
  end;
 end;
end;

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
 if Key = VK_RETURN then EnterReleased:= True;
end;

Form2:
procedure TForm2.FormCreate(Sender: TObject);
begin
 KeyPreview:= True;
end;

procedure TForm2.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if Key = #13 then begin
  Key:= #0;
  if EnterReleased then begin
   EnterReleased:= False;
   ModalResult:= mrOK;
  end;
 end;
end;

procedure TForm2.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
 if Key = VK_RETURN then EnterReleased:= True;
end;


text:
Q: linker error with classes in c++
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

I have created this code
  class Game{
    static SDL_Surface* screen;
public:
    //Initiate Game(SDL_Graphics, folder for output.....)
    static void initialize();
    static void initializeScreen();

};

void Game::initializeScreen()
{

    Game::screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 32,  SDL_DOUBLEBUF |SDL_HWSURFACE |SDL_SWSURFACE);
    SDL_Init(SDL_INIT_VIDEO);
    Game::screen == NULL ? printf("SDL_Init failed: %s\n", SDL_GetError()):printf("SDL_Init initialized\n");
    SDL_WM_SetCaption("SDL Animation", "SDL Animation");
}

It compiles but I get e linker error, how can I fix this?
1>game.obj : error LNK2001: unresolved external symbol "private: static struct SDL_Surface * Game::screen" (?screen@Game@@0PAUSDL_Surface@@A)

Edit: This is how I fixed it, in game.cpp
added this
SDL_Surface* Game::screen;

outside of any function*

A: You need to add the following definition in your cpp file SDL_Surface* Game::screen = NULL.

Here is an example code where you can have a static variable without defining it in the cpp file using a function.
#include <iostream>

struct Lazy {
    static int& GetValue() {
        static int a = 0;
        return a;
    }
};

int main() {
    std::cout << Lazy::GetValue() << std::endl;
    int& a = Lazy::GetValue();
    a = 1;
    std::cout << Lazy::GetValue() << std::endl;
}

A: You have to define static (variable) members (not functions) in seperate source files(*.cpp) and link against them.
for example:
//MyClass.h
class MyClass {
    static int x;
};

//MyClass.cpp
#include "MyClass.h"
int MyClass::x;


text:
Q: Why is Gallery So Slow / Accessing GoogleLoginService? I'm working on an app which allows users to view images, so I'm sending an intent to let the Gallery display the image. For some reason, it takes several seconds to display the image. LogCat shows it trying to connect to "GoogleLoginService"? Why does gallery connect to the internet? Can this be turned off on the phone or in code?
I/CacheService(19326): Preparing DiskCache for all thumbnails.
I/CacheService(19326): DiskCache ready for all thumbnails.
I/ActivityManager( 1433): Starting activity: Intent { act=android.intent.action.VIEW     dat=file:///mnt/sdcard/x/attachments/68efeba8-7f0c-47bf-b7d7-d714f29f99c7.jpg typ=image/* cmp=com.cooliris.media/.Gallery }
I/Gallery (19326): onCreate
D/GoogleLoginService( 1601): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService }
I/RenderView(19326): First Draw
D/GoogleLoginService( 1601): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService }
I/ActivityManager( 1433): Displayed activity com.cooliris.media/.Gallery: 477 ms (total 477 ms)
D/GoogleLoginService( 1601): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService }
I/GridLayer(19326): Slot changing from -1 to -1

A: The device is using the Gallery3D application which integrates with Picasa - login to Picasa is handled by the Google account authenticator. Most of the account fiddling happens on a separate thread however (if I remember that app correctly) - and doesn't really impact the startup.
It's almost always the gallery thumbnails fetch that's the culprit.


text:
Q: Replacing empty values with zeros I know this question has been asked many times before, but having followed previous solutions I still can't resolve the issue:
I have a SSRS (2008R2) report, that displays data in a matrix. There is a horizontal column group containing values that may or may not exist: when the value doesn't exist, I'd like to replace the empty cell with a 0. Currently the report renders like:

and I'd like those empty cells to have 0's in them instead.
The cell expression was set to:
 =Sum(Fields!number.Value)

so I tried
 =iif (IsNothing(Sum(Fields!number.Value)),0,Sum(Fields!number.Value))

and
=iif (IsNothing(Fields!number.Value),0,Sum(Fields!number.Value))

and
=iif (Sum(Fields!number.Value)>0,Sum(Fields!number.Value),0)

... but the "empty" cells persist. I'm sure I'm doing something daft... but what?
EDIT: To illustrate my situation better, my query produces output (in SSMS) similar to:
File | outcomeID     | number
A    |    Outcome1   |   2
A    |    Outcome2   |   1
B    |    Outcome2   |   2
C    |    Outcome1   |   1
D    |    Outcome3   |   2

... which would produce the outcome in SSRS of:
File | Outcome1 | Outcome2  | Outcome3
 A   |    2     |     1     |
 B   |    2     |           |
 C   |    1     |           |
 D   |          |           |    2

using a Column Group:

Even if I change the expression to be simply:
=999
I end up with
File | Outcome1 | Outcome2  | Outcome3
 A   |    999   |     999   |
 B   |    999   |           |
 C   |    999   |           |
 D   |          |           |    999

... i.e. lots of blank spaces.
EDIT2: I've uploaded a very small example .rdl file [REMOVED], using the example data above - it reproduces the issue

A: my first thought was a change to the stored procedure but since i had a similar report to test something on quickly i had an idea.
try this instead
=0+Sum(Fields!number.Value)

A: I tend to use the following (on SSRS 2005, however): =CInt(Fields!number.Value). It's possible to use other conversions, like CDbl, as well.
Alternatively, but a tiny bit longer, try =IIf(Fields!number.Value Is Nothing, 0, Fields!number.Value).


text:
Q: Duplicate rows in SQl query to estimate the db growth I am trying to estimate the database size and its compress backup. I am running below query to check the size and be able to get the rough idea of how much database would be growing in few weeks or so. However, when I run below query I am getting duplicate results for some reason and I can not figure out. Any help would be appreciated.
SELECT
 CONVERT(VARCHAR(10),backup_start_date, 111) AS BackupDate,
 FLOOR( backup_size/1024000000) AS DBSize_GB,
 FLOOR(compressed_backup_size/1024000000) AS BackupSize_GB, Database_Name
FROM msdb.dbo.backupset as b
WHERE database_name = @dbname
 AND type = 'd'
 AND DATEPART(mm,backup_start_date) = @mon --comment this line for all the     months
ORDER BY
backup_start_date DESC

Results:
Attached here


text:
Q: Access modal view controller with ios UI Automation Is there a way to access the elements of an modal view controller with UI Automation. I can't find the view or any elements when printing the tree of the local target. Only the view "behind" is shown in the screenshot.

A: Problem solved: Modal view controllers are not added instantly to the view hierachy. Adding:
UIATarget.localTarget().delay(1);

before printing the tree solved the problem.


text:
Q: Print only first matching line of regex and ignore other matches I am trying to print only the first match of the regex(foo.*bar.*zoo) along with rest of the content of the file/variable. Need to ignore all occurrence of this regex, except first.
Here is one scaled down input and some of my attempts to generate the desired results.
input:
 echo "$x"
foo bar zoo
1 2   3
2,4,5
foo bar           zoo
1 9 8

Attempts:
echo "$x"|sort -u |uniq
1 2   3
1 9 8
2,4,5
foo bar zoo
foo bar           zoo

echo "$x"|awk '/foo.*bar.*zoo/{if(f==0)print $0;f++}1'
foo bar zoo
foo bar zoo
1 2   3
2,4,5
foo bar           zoo
1 9 8

echo "$x"|grep  -m1 foo
foo bar zoo

Expected result:
foo bar zoo
1 2   3
2,4,5
1 9 8

A: With awk
$ awk '/foo.*bar.*zoo/{if(!c++) print; next} 1' ip.txt
foo bar zoo
1 2   3
2,4,5
1 9 8

*

*/foo.*bar.*zoo/ if this matches

*

*if(!c++) print print if c is falsey (which is the default for uninitialized variables), next time c will be positive number and thus fail this condition

*next skip rest of the commands

*1 idiomatic way to print contents of $0 (input record)

Just for fun, some other variations:
awk '{if(/foo.*bar.*zoo/) {if(!c++) print} else print}'
awk '!/foo.*bar.*zoo/ || !c++' # RHS will be executed only if LHS fails

A: This might work for you (GNU sed):
sed '0,/foo.*bar.*zoo/b;//d' file

From the beginning of the file to a regexp that matches your criteria, print as normal.
Thereafter, delete any line that matches the criteria.
Alternative:
sed -n '/foo.*bar.*zoo/{p;:a;n;//!p;ba}' file

Or:
sed '/foo.*bar.*zoo/{x;/./d;g}' file

A: A dirty, quick way to achieve that result is running this:
grep -m1 foo filename && grep -v foo filename

A: $ awk '/foo.*bar.*zoo/ && c++{next} 1' file
foo bar zoo
1 2   3
2,4,5
1 9 8


text:
Q: Dynamically creating HTML elements based on mySQL data Hi so currently I have a set of codes which dynamically creates HTML elements through AJAX using an external JSON data. When I created this, I wanted to store my data in an external file rather than in a database.
However, I now need to store them in mySQL so I was wondering how I can still dynamically create the HTML elements like this but now the data will be from mySQL instead of retrieving it from an external JSON file. I'm still quite new to this so I am really confused as to how to tackle this situation.
This is what my current code looks like:

JSON Data:
 [
        {
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        },
        {
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        },
        {
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        }
]

When I tried pulling my data using PHP and encoding it to JSON, it gave me this result and it did not create any of the HTML elements needed.

A: You can create a MySQL table like this,
CREATE TABLE `record` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `team` TEXT NULL,
  `title` TEXT NULL,
  `filePath` TEXT NULL,
  `imagePath` TEXT NULL,
  `desc` TEXT NULL,
  PRIMARY KEY (`id`));

Then you can use this query to insert your data,
INSERT INTO `record` (`team`, `title`, `filePath`, `imagePath`, `desc`) VALUES ('Team Name', 'Title', '#', 'image path', 'Data Description');

After that, you can create a PHP file to pull your data and print it in JSON format,
You can give the PHP file a filename like,
CR_QuickLookData.php

With PHP code,
<?php

$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT team,title,filePath,imagePath,`desc`  FROM record";
$result=mysqli_query($con,$sql);

$list = array();
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
    $list[] = array (
        'team' => $row['team'],
        'title' => $row['title'],
        'filePath' => $row['filePath'],
        'imagePath' => $row['imagePath'],
        'desc' => $row['desc']
    );
}

mysqli_free_result($result);
mysqli_close($con);

echo json_encode($list);

Then in index.html,
<!DOCTYPE html>


text:
Q: Mac OS X server keeps prompting for passwords on all devices I'm running an Mac OS X Server (10.6.7) with iCal, Address Book and Mail enabled.
My issue is that the clients (iCal and Calendar in iOS) keeps asking for passwords on strange intervals, and it usually results in it not accepting the right password until you restart the client.
It can run smoothly for days and some times it just goes completely bananas.
It makes no difference if its a regular user or a Open Directory user.
This happens to all the services mentioned above but iCal is the worst.

A: This is a known issue. In my own testing, it appears to be fixed in Mac OS X Server v10.6.8. The release notes for the update mention:

Calendar Service
  - Improves authentication support for iOS devices.

If this does not resolve your problem, then the workaround used until now was to edit /private/etc/caldavd/caldavd.plist to enable Basic authentication and disable Digest. Note that this is a bad idea if users communicate with the server over an untrusted network without SSL or VPN.
The same configuration changes can be applied to the Address Book service by editing /private/etc/carddavd/carddavd.plist. Look for Authentication / Basic / Enabled and change it to true, and Authentication / Digest / Enabled to false.
Again, do not use this workaround if the traffic is unencrypted. Without SSL or VPN the passwords are clearly visible to anyone monitoring the network.


text:
Q: How to integrate odoo with azure blob storage? I am trying to integrate my odoo with azure blob storage, how can I do that?

A: you should checkout the capabilities of odoo on their documentation page: https://docs.bitnami.com/azure/faq/
There is a section of the supported capabilities in Azure as bellow:

The Bitnami Launchpad for Microsoft Azure creates the following resources in your Microsoft Azure account:
  A storage account for each region in which the user launches an instance.
  Application images are added to that storage account when the user launches instances.
  Machine disks are created in that storage account when the user launches instances.
  A resource group with the rest of the resources needed by the instance.
  A resource group for the various storage accounts.

Source: https://docs.bitnami.com/azure/faq/


text:
Q: Different definitions of closed differential form I have recently read, out of curiosity, Tao's very motivating introduction to Differential forms and integration. At pages 5 and 8 he seems to define a closed $k-$form (on some manifold) to be a $k-$form whose integral along any closed $k-$submanifold (i.e., one with zero boundary) vanishes. I am used, instead, to the definition that a form is closed iff its differential is zero. I think that in general Tao's definition is strictly stronger than mine. Here are my thoughts. In the following, we only consider oriented (and, if necessary, compact) manifolds. I believe that the following conditions should all be equivalent for a $k-$form $\omega$:

*

*$d\omega=0$ (my definition of being closed)

*$\int_S d\omega = 0$ for all $(k+1)-$submanifolds $S$

*$\int_{\partial S} \omega=0$ for all $(k+1)-$submanifolds $S$, i.e., $\omega$ vanishes on all exact submanifolds

The equivalence of 2. and 3. is given by Stokes' theorem. 1. clearly implies 2. and I think that 2. implies 1. because the integration pairing is non-degenerate.
In particular, if the above holds, I think that Tao's condition is equivalent to mine iff the $k-$th singular homology of the ambient manifold vanishes $(*)$.
I thought maybe de Rham's theorem could solve the problem, but if I interpret it right, it only implies that $\omega$ is exact if and only if its integration along every closed $k-$submanifold gives $0$ $(!)$. Which is kind of dual to 1. $\Leftrightarrow$ 3. above.
Now, it seems very strange to me that Tao should use a definition that is not equivalent to the usual one, so I think I must be missing something. Please help me to answer the following:

*

*A) Are my three conditions above equivalent and is $(!)$ correct?

*B) Is $(*)$ right? In particular, when considering singular homology of manifolds, can we restrict to smooth submanifolds (with boundary) instead of arbitrary continuous images of simplices?

*C) Did I get Tao's definition of closed form right? If so, is it really different from mine? Why?

A: I will post this as an answer, since there are at least 4 people interested to know how this ends: I have informed professor Tao of the possible error and he has immediately acknowledged it and told me that he has corrected it. The link to the notes does not seem to be working at present, but I think it is probably just a temporary disruption.


text:
Q: How to get error.h in visual studio or equivalent? I have large C++ project that I inherited and am trying to transfer it from Linux to Visual Studio on Windows. Managed to link required libraries, but one build error just baffles me.
In Linux, someone was including a header <error.h> everywhere, and I can't even find a documentation page to see what it is. First I thought is part of standard library, but I am now beginning to see it's a specific header for Linux OS.
So, how do I include it in Visual studio? I can't even find what it is and am tempted to just rearrange code to use stdexcept header, as the only thing these codes do is abort compilation and printout error messages by using some error(...) function from error.h.

A: error.h is a header from the GNU C Library. It is not specific to Linux, it is specific to glibc.
It is documented right here (search on the page for error.h).
The functions declared in error.h should not be used in portable code, so getting rid of code that uses them is not a bad idea. Alternatively, it is not difficult to implement them.


text:
Q: highcharts & rails Hi I'm trying to use highcharts on my app...for that I'm following the highcharts episode the script works but when I want to put the real data I got this :

I've followed all the steps however here is my model:
class TankingLog < ActiveRecord::Base
belongs_to :gas_station
belongs_to :car
attr_accessible :car_id, :cost, :date, :gallon, :gas_station_id, :km
validates_presence_of :cost, :date,:gallon,:km
validates_numericality_of :cost, :gallon
validates_numericality_of :km #:only_integer
def self.total_on(date)
    where("date(date) = ?",date).sum(:cost)
end
end

and here is my html.erb:
<!DOCTYPE html>

Listing Tankings

  <% if @tankinglog.count<1 %>

    There are no tankings for this car. Do you want to <%= link_to 'create a new tanking', new_user_car_tanking_log_path(@user, @car)%>

  <% else %>

        Cost
        Gallon
        Km
        Date
        Gas Station's id

      <% for tankinglog in @tankinglog  %>

          <%= number_to_currency (tankinglog.cost) %>
          <%= tankinglog.gallon %>
          <%= tankinglog.km %>
          <%= tankinglog.date %>
          <%= tankinglog.gas_station_id %>

      <% end %>

    <%= link_to 'New tanking', new_user_car_tanking_log_path(@user, @car), :class => "btn btn-primary" %>
  <% end %>

  <%= link_to 'back', user_cars_path(current_user), :class => "btn btn-primary" %>

thanks for your help
also here is that my script shows:

A: Do you have the foo_chart div that it is trying to render to? Have you included jQuery's js before including highcharts' js? What are the contents of the "Console" of the browser? Does the console have any js errors? Can you share the generated html, as text not image?
How to get errors from console (Chrome)

Clicking on the line number will take you to the exact place where js broke

A: was my fault, I had a syntax error, it was:
series: [{
        pointInterval: <%= 1.day * 1000 %>,
        pointStart: <%= 0.weeks.ago.at_midnight.to_i * 1000 %>,
        data: <%= (0.weeks.ago.to_date..Date.today).map { |date| TankingLog.total_on(date).to_f}.inspect %>
      }]

isntead
series: [{
    pointInterval: <%= 1.day * 1000 %>,
    pointStart: <%= 0.weeks.ago.at_midnight.to_i * 1000 %>,
    data: [data: <%= (1.weeks.ago.to_date..Date.today).map { |date| TankingLog.total_on(date).to_f}.inspect %>]
  }]

thanks for help


text:
Q: Count number of distinct string with PIG I am new in PIG and try to count the number of distinct countries in the following dataset (you can download it from this link):
Athlete Country Year    Sport   Gold    Silver  Bronze  Total
Yang Yilin  China   2008    Gymnastics  1   0   2   3
Leisel Jones    Australia   2000    Swimming    0   2   0   2
Go Gi-Hyeon South Korea 2002    Short-Track Speed Skating   1   1   0   2
Chen Ruolin China   2008    Diving  2   0   0   2
Katie Ledecky   United States   2012    Swimming    1   0   0   1
Ruta Meilutyte  Lithuania   2012    Swimming    1   0   0   1

What I tried so far:
athletes = LOAD '/data/OlympicAthletes.csv' USING org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'YES_MULTILINE', 'NOCHANGE', 'SKIP_INPUT_HEADER') AS (athlete:chararray, country:chararray, year:int, sport:chararray, gold:int, silver:int, bronze:int, total:int);
distinct_countries= distinct (foreach athletes generate country);
country_count_try1 = COUNT(distinct_countries);
country_count_try2 = FOREACH distinct_countries GENERATE COUNT(country);
country_count_try3 = FOREACH (GROUP athletes country) GENERATE count(athletes.country) as total_country;

A: You need to group the whole dataset to count.
distinct_countries= distinct (foreach athletes generate country);
country_count_try4 = foreach (group distinct_countries all) generate COUNT(distinct_countries) as cnt;


text:
Q: LED power management I am creating a led grid with 176 cells. Details:

*

*The size of each cell is 30cm x 30cm.

*Each cell contains two WS2812 LEDs that work under 5 volts.

*The power supply unit has to be placed 10~20 meters away from the led grid.

*To minimize the current value and voltage drop, I decided to use a 350W, 24V power supply unit.

Power management proposal:

*

*Each led @ full brightness consumes about 0.5W, one row has 16 cells, each row consumes about 0.5w x 2leds/cell x 16 cells = 16W

*At the location of the PSU, split the power into 12 channels: 11 channels to 11 rows and 1 channel to MCU. Each channel is protected by a 2A PTC resettable fuse.

*Each row consumes 16W which is going to be about 16w/24v = 0.66A. Considering the power consumption through the wire. I assume each row uses 24V/1A~0A (Sometimes one row can be all off and another row is on full brightness)

*Each channel feeds the power to one row.

*24V channels are stepped down to 5V by a buck converter. This is to ensure every LED has the same brightness without voltage drop.

Questions:

*

*How can I ensure that each signal shares the same ground reference? How should I connect the grounds properly?

*How can I improve the design?

A: a) NO buck converter is 100% efficient, 85% is more realistic.
0.66A/85% = 0.77A
c)Worst case scenario: Assume star ground connections with star point on the side of the grid.
Assuming 5m per row and 0.5mm2 wire we get 171 mOhms per row. Current will be dropping with every cell, thus voltage drop will be well below 100mV. If we take into account fact that each WS2812 is acting as amplifier you can ignore ground wire voltage drop.
d) Run one thick(2.5-4mm2) cable from PSU to the grid, then spit it into 11 rows.


text:
Q: Xamarin Forms sending mail from app directly In Xamarin forms I want to sent email directly from app without opening email client. I want user to type in text and just send it with predefined subject to predefined email address. I need implementation for IOS and Android. Is it possible to do within share project in Xamarin forms?

A: I think you should ask yourself if that really is the best approach, I think it would be better to have some call to your back-end and have that send it for you.
But I'm not the one to judge your requirements, so if I'm just looking for a solution why not setup a SendGrid account (free up til a whole bunch of mails in Azure) and use the SendGrid API (easily accessible through a NuGet package) to send your mail. There are probably some more alternatives like this out there.


text:
Q: IOException while writing to text file despite locking the block I know the answer must be out there somewhere, I applied suggestions both from many other questions and from MSDN itself but I'm probably overlooking something here.
This is my method, I use it to dump output to file. lock object declaration attached for clarity.
private static Object fileLock = new Object();
private static void WriteToFile(string msg, bool WriteLine)
{
    lock (fileLock)
    {
        msg = DateTime.Now.ToShortTimeString() + " - " + msg;

        FileInfo F = new FileInfo("dump.txt");
        using (StreamWriter writer = F.Exists ? F.AppendText() : F.CreateText()) //<--THIS LINE THROWS
        {
            if (WriteLine)
                writer.WriteLine(msg);
            else
                writer.Write(msg);
        }
    }
}

Question is: Why does the using line above throws an IOException complaining another process is using the file the 2nd time I call the method ?
I'm calling it like this around my code:
Console.WriteLine(something)
#if(DEBUG)
    Extensions.WriteToFile(something,true);
#endif

Again, I'm sure this is a trivial issue and someone else asked something like this getting the right answer, but I'm unable to dig it up.
UPDATE
Refactoring out the FileInfo object and switching to File.XXX methods made the code work fine. I still wonder what the issue was, anyway the issue looks like solved.

A: @Guffa: declaration has to be private static object fileLock = new object();
@alex: Your code works just fine on my machine although it's a bit too complicated for the task imo.
static void Write(string text, string file)
    {
        using (StreamWriter sw = File.AppendText(file))// Creates or opens and appends
        {
            sw.WriteLine(text);
        }
    }

Maybe some antivirus or indexer locks your dump file.


text:
Q: git apply a patch as much as possible when failing I am moving from one repository to another and need to port some of the changes. The directory structure is mostly the same but the files not all identical.
I am using 'git format-patch' and 'git am' or 'git apply' to port those changes. When it works, life is good, but when it fails because of some minor change or files missing, nothing gets applied.
I can filter files out using --exclude, but what I really would like is that it applies as much as it can and just tell me where there are conflicts / failure.
I am also open to other option for applying the patches or things like that.

A: You could also try git apply --3way.

A: The --reject option is probably what you're looking for. With that, you'll get classic .rej files for failing chunks, while all the good chunks will be applied.


text:
Q: Why while(true) loop in java repeat two times? And why the condition at the end doesn't work? this is my java program that should ask you what you want to do with the array 'drugs' which contain some strings. But when I run it the while loop repeats 2 times before ask me to digit 'q' to exit... end when I press q key the condition ignore this. I'm new in java and I'm begin crazy with that, thanks for support.
public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    System.out.println("This program will show the array \'drugs\' in different way, using functions\n\n");

    printMenu();
    System.out.print(">>");
    int ans = input.nextInt();

    String[] drugs = {"LSD", "cocaine", "weed", "eroine(white)", "eroine(brown)", "hashish", "extasi"};

    String ans2 = "";
    while(true){
      switch(ans){
        case 1:
          printArray(drugs);
          break;
        case 2:
          printArrayReverse(drugs);
          break;
        case 3:
          shiftOnLeft(drugs);
          break;
        case 4:
          break;
        default:
          System.out.println("Insert a valid number\n");
          break;
      }
      System.out.print("\n\n[Press q to quit or enter key to repeat the loop again]");
      ans2 = input.nextLine();

      if(ans2 == "q"){
        break;
      }
    }
  }


text:
Q: Call ICommand outside item source I have an ICommand in my PageViewModel and want it to be call in my CheckedChanged of RadioButton. However, this RadioButton is inside:
<views:RoundedPage>
<Carousel ItemSource="...">
    <DataTemplate DataType="...">
       <CollectionView ItemSource="...">
         <DataTemplate DataType="...">
           <RadioButton CheckedChanged="" />
         </DataTemplate>
       </CollectionView>
    </DataTemplate>
</Carousel>
</views:RoundedPage>

So how am I gonna call this command outside those sources.
Thank you

A: At first, I don't recommend you to deal with the UI event in your view model. The view model is used to resolve the logic behavior behand the view.
So you can set the CheckedChanged event by the following method:
1.create a void method in the page.cs, such as
private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {
         //do something
    }

2.binding in the xaml
  <RadioButton CheckedChanged="RadioButton_CheckedChanged"/>

If you still want to deal with the event in the viewmodel, you need to use the behavior to covert the event to a command.
There is a simple in the official document and you can check it:
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/behaviors-eventtocommandbehavior/


text:
Q: How to Integrate $ \int \sin^2x\cos\ x \ dx $ without substitution How can I calculate the following integral without using substitution?
$$
\int \sin^2x\,\cos\ x \, dx
$$
I have been stuck on this problem for about a day and cannot seem to come to a conclusion.

A: Using the equality $\cos  x=D_x(\sin\, x)$ we can see that the integral $\int \sin^2x\cdot\cos  x \, dx$ is equal to integral $\int \sin^2x \cdot D_x(\sin\, x) \, dx$. That is
$$
\int \sin^2x\cdot\cos  x \, dx
=
\int \sin^2x \cdot D_x(\sin\, x) \, dx
$$
Now we can apply the formula of 'integration by parts'
$$
\int \sin^2x\cdot\cos  x \, dx
=
\int \sin^2x \cdot D_x(\sin\, x) \, dx
=
\sin^2x \cdot\sin\, x-\int D_x(\sin^2x)\cdot\sin\, x \, dx
$$
By $D_x(\sin^2x)= 2\cdot \sin x\cdot D_x(\sin x)=2\cdot\sin x\cos x$ we have
$$
\int \sin^2x\cdot\cos  x \, dx
=
\sin^2x \cdot\sin\, x-\int D_x(\sin^2x)\cdot\sin\, x \, dx
=
\sin^3x-\int 2\cdot\sin x\cdot\cos x \cdot\sin\, x \, dx
$$
and
$$
\int \sin^2x\cdot\cos  x \, dx
=
\sin^3x-2\int \sin^2\, x \cdot\cos x \, dx
$$
Then we have
$$
\int \sin^2\, x \cdot\cos x \, dx = \frac{1}{3}\sin^3 x
$$

A: If you prefer making it complicated, the other way consists in linearising the integrand:
\begin{align}
\sin^2x\cos x&=\frac12(1-\cos 2x)\cos x=\frac12(\cos x-\cos 2x\cos x)\\
&=\frac12\Bigl(\cos x -\frac12\bigl(\cos(2x+x)+\cos(2x-x)\bigl)\Bigr)\\
&=\frac14(\cos x-\cos 3x).
\end{align}

A: Identify the integral as one of the form
$$\int f'f^n\,dx=\frac{f^{n+1}}{n+1}+C$$
This is an-almost immediate integral.

A: Use $2\sin(x)\cos(x)=\sin(2x)$:
$$I=\int\sin^2(x)\cos(x)\,dx=\frac{1}{2}\int\sin(x)\big(\frac{1}{2}(2\sin(x)\cos(x))\big)\,dx=\frac{1}{2}\int\sin(x)\sin(2x)\,dx$$
Two iterations of IBP yields:
$$I=-\frac{1}{2}\sin(x)\cos(2x)+\frac{1}{2}\bigg[\frac{1}{2}\cos(x)\sin(2x)+\frac{1}{2}I\bigg]$$
Which becomes:
$$I=\frac{4}{3}\Big(\frac{1}{4}\cos(x)\sin(2x)-\frac{1}{2}\sin(x)\cos(2x)\Big)+C$$

A: $$\int \sin^2x\,\cos\ x \, dx =\int \frac13(\sin^3x)'\,\cos\ x \, dx =\frac13\sin^3x+c$$


text:
Q: Is it possible to detect if a matplotlib artist is a mappable suitable for use with colorbar? Some matplotlib functions (e.g., contourf and imshow) return artist objects that can be used to produce colorbars when passed as the mappable argument to colorbars. Other objects (e.g., plot) return artists that are not mappable.
Is it is possible to detect if an artist is such a suitable object? I'd like to write an API that uses arbitrary pyplot functions, and lets me add a colorbar after the fact based on the last function that returned a mappable.

A: This is a hack I used in the past:
hasattr(cs, 'autoscale_None')

Not sure if this holds for all Artists though.  It is usually OK telling lines and points apart from colorbar-material mappables (countour(f), pcolor, scatter, etc).


text:
Q: TinyMCE only returning changed content after click, why? I want to extract content from TinyMCE seamlessly whenever a change is made. BUT it seems with TinyMCE 4.3 that the only way to keep getContent() returning the most recent changes, you need to trigger a click.
Please check out my fiddle: http://jsfiddle.net/xxfm68ue/1/
tinyMCE.init({
    // General options
    mode : "exact",
    elements : "thisID",

    // Skin options
    skin : "o2k7",
    skin_variant : "silver",

    setup: function(editor) {
      editor.on('change', function(e) {
        alert(e.target.getContent());
        console.log(e.target.getContent());
      });
    }
});

Is there another way to extract the content automatically?

A: change event triggers when new value is different than old value. So unless user has stopped typing (i.e. blur event is triggered), change event will not be triggered.
To track changes, while user is typing, you need to catch keypress events
The following code attaches event handler to keyup event. So now, every single key press (unwanted key press are checked by isCharacterKeyPress()) trigger the contentChanged event as well.
setup: function(editor) {

     // helper function for keyup event
    function isCharacterKeyPress(evt) {
        if (typeof evt.which == "undefined") {
            // This is IE, which only fires keypress events for printable keys
            return true;
        } else if (typeof evt.which == "number" && evt.which > 0) {
            // In other browsers except old versions of WebKit, evt.which is
            // only greater than zero if the keypress is a printable key.
            // We need to filter out backspace and ctrl/alt/meta key combinations
            return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
        }
        return false;
    };

    //function which will act on "change" event
    var contentChanged = function(e) {

      if(e.type == "keyup" && ! isCharacterKeyPress(e) )
      {
        return;
      }
      alert(e.target.innerHTML);
      console.log(e.target.innerHTML);
    };

//adding eventhandlers
    editor.on('keyup', contentChanged );
    editor.on('change', contentChanged );

}


text:
Q: Unable to retrieve updated textbox value php // RESOLVED
I found out what was causing this problem - the textboxes were inside a div with display:none .
// -------------------------------------
I have some echoed default values from my db in the textboxes .
I updated the values and pressed the Submit button, but it did not capture the updated value; it still got the default values.
// EDIT
Eg. values I have gotten from the db are "email@email.com" for $_email and "91231231" for $_contact.
I changed the email textbox value to "email2@email.com" and clicked the button, but the var_dump($_POST) still shows the original value "email@email.com" instead of the updated one.
//
The form (account_console.php)
    <form action="../lib/update_details.php" method="post">

         ...
    E-mail
    <input type="text" class="form-control" name="tbEmail2" value="<?  php echo $_email; ?>"  />

    Contact No.
    <input type="text" class="form-control" name="tbContactNo2"  value="<?php echo $_contact; ?>" />

    <input type="submit" name="btnUpdateProfile" class="btn btn-primary" value="Update" />

    ...
    </form>

Retrieval (../lib/update_details.php)
    ...
    else if (isset($_POST["btnUpdateProfile"])) {
    var_dump($_POST);
    $email = $_POST["tbEmail2"];
    $contact_no = $_POST["tbContactNo2"];

    ....

var_dump($_POST) returns
    array(6) { ["tbEmail2"]=> string(17) "email@email.com" ["tbContactNo2"]=> string(8) "91231231" ["btnUpdateProfile"]=> string(6) "Update" ["tbNewPw2"]=> string(0) "" ["tbRepPw2"]=> string(0) "" ["iFrom"]=> string(30) "../student/account_console.php" }

Please help. Thank you!

A: I would ensure the updated value is actually being sent using a HTTP proxy inspector like Fiddler or the browser developer tools network inspector.
Or just change the form method="get" and you can see the value in the query-string.

A: Try:
$_POST['tbEmail2'];
instead of:
$_POST["tbEmail2"];


text:
Q: Why is Python list.remove() not working properly? I have some lists of strings and I'm trying to find the most repeated value for each one of them. For doing so, I recreated a function whose input is the desired list; however, many of those lists contain the following element '\\N'. (two backlash and a capital N)
I don't want to take into account that element when the function search for the most repeated value, so I thought about filtering out said element from the list first and then run the function.
I tried using
NewList=List.remove('\\N')

to no avail. In fact, it deletes the whole list as I get nothing in return, using len(NewList) prints an error saying that it has no length. I thought that the element may be at fault, but I tried removing another string from the List and the same thing happened.
What's going on? is there a better way to filter out that element from the list?
Thank You

A: Each time you call list.remove, it removes one matching item from the list, and returns None.
>>> my_list = ['foo', '\\N', 'bar', '\\N', 'ola']
>>> my_list.remove('\\N')
>>> my_list
['foo', 'bar', '\\N', 'ola']
>>> my_list.remove('\\N')
>>> my_list
['foo', 'bar', 'ola']

If you want to create a new list rather than modifying the existing list, consider using a list comprehension:
>>> my_list = ['foo', '\\N', 'bar', '\\N', 'ola']
>>> new_list = [i for i in my_list if i != '\\N']
>>> new_list
['foo', 'bar', 'ola']


text:
Q: Is the Common Name attribute (CN) in X.509 certificate supposed to be unique? I am implementing PKI authentication for my application, and everything I've read online says that you extract the CN attribute from the certificate subject and use the CN to look up the user in the LDAP server, for example.
However, when I browse my company's LDAP directory, every user's CN attribute is just first and last name. This does not uniquely identify a user across an Organizational Unit or the company. Does this mean that the CN is not set up correctly here? Examples of CN values I've seen online are usually a concatenation of first, last names and email address. Is this usual format the CN attribute takes on?

A: The subject of a certificate is an X.500 Distinguished Name (DN) as per RFC 5280 (see section 4.1.2.6 on https://www.rfc-editor.org/rfc/rfc5280#page-23). Yes, the DN must be unique for each subject. Instead of a first name/last name concatenation, you could pick something unique like an E-mail address, employee ID or user account.
Also note that the DN may have multiple elements rather than a single CN (Common Name) entry but I think that's beyond the scope of the question.


text:
Q: How to use info on substring position from one file to extract substring from another file (loop, bash) I'm trying quite hard to write a script that "loopingly" extracts substrings from one file, while getting the information on where to cut from another file. I'm working in bash on MobaXterm. I have the file cut_positions.txt, which is tab delimited and shows name, start point, end point, length, comment:
k141_20066  103484  104617  1133    phnW
k141_20841  13200   14324   1124    phnW
k141_23852  69  452 383 phnW
k141_32328  1   180 179 phnW

and the string_file.txt with the name (it would be no problem to remove/add the ">" in one of the files) and the string (the original strings are way longer, up to 1.000.000 characters):
>k141_10671 CCTTCCCCCACACGCCGCTCTTCCGCTCTTGCTGGCC
>k141_10707 AGGCGGTATCAGACCTTGCCGCAACACTAAGCCCAGTAACGCTGTCGCCCTTATATCTGA
>k141_11190 CTTTTGTGACAGTGCAGGGCAATGGTGGATTTATCAGTATCGGGCAGAA
>k141_1479  AGCCGACAGCAGCGCCGAGGGCACATAATCCGATGACACGATGTCCAAAAGATCCGCCTCGGC

Now I want to use the input from the cut_positions.txt. I want to use the first column to match the right line, then the second column as start point of the substring and the fourth column as length of the substring. This should be done with all lines in cut_positions.txt and written to a new out.txt. To get closer I tried (with my original data):
➤ grep ">k141_28027\b" test_out_one_line.txt | awk '{print substr($2,57251,69)}'
TCACTTGAGCGCAATTATTCGCTCTCCGGCGGCGTCAGCATCAGCCTGATCATGCGTCACCAAAAGTGT

which worked well as handmade way. I figured out as well how to access the different elements in cut_positions.txt (here the first row in the second column):
awk -F '\t' 'NR==1{print $2}' cut_positions.txt

but I can't figure out how to turn this into a loop, as I don't know how to connect the different redirections, piping steps and so on that I used for the small steps. Any help is very much appreciated (and tell me, if you need more sample data)
thanks
crazysantaclaus

A: The following script should work for you:
cut.awk
# We are reading two files: pos.txt and strings.txt
# NR is equal to FNR as long as we are reading the
# first file.
NR==FNR{
    pos[">"$1]=$2 # Store the startpoint in an array pos (indexed by $1)
    len[">"$1]=$4 # Store the length in an array len (indexed by $1)
    next # skip the block below for pos.txt
}

# This runs on every line of strings.txt
$1 in pos {
    # Extract a substring of $2 based on the position and length
    # stored above
    key=$1
    mod=substr($2,pos[key],len[key])
    $2=mod
    print # Print the modified line
}

Call it like this:
awk -f cut.awk pos.txt strings.txt

One important thing to mention. substr() assumes strings to start at index 1 - in opposite to most programming languages where strings start at index 0. If the positions in pos.txt are 0 based, the substr() must become:
mod=substr($2,pos[key]+1,len[key])

I recommend to test it with simplified, meaningful versions of:
pos.txt
foo  2  5  3    phnW
bar  4  5  1    phnW
test 1  5  4    phnW

and strings.txt
>foo 123456
>bar 123456
>non 123456

Output:
>foo 234
>bar 4


text:
Q: get the form processing data immediately after form submitting in Javascript, before page refresh I have used Django to develop a web app.
After form submit, I want to get the form processing result( msg here in my case)  immediately in view function, before page refresh.
url.py:
path('index/', views.form_process, name='index'),

view.py
 def form_process(request):
     if request.method == 'POST':
                Form_instance = Form(data=request.POST)
                if Form_instance.is_valid():
                        msg="success"
                else:
                        msg="fail"

                return render(request, 'index.html', context={'msg': msg})

index.html
<form id="myform">
...

 </form>
  <button class="button" onclick="myFunction()" id="submit">submit</button>

<script>
function myFunction() {
...
$("#myform").submit();

    if ('{{msg}}'.includes('success'))
    {alert("success");
     }

}
</script>

Now the msg always send to the js after page refresh. My boss want to make it pop up immediately after form submitting,  before page refresh.
How could  get the msg generated in view function immediately after form submitting in Javascript, before page refresh.
I have tried ajax but failed to capture the msg, no alert form ajax popped up:
$('#myForm').ajaxForm({
        url : '/index/',    //I also tried 127.0.0.1:8000/index, also no pop up
        type: 'get',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

How could I get the form processing data immediately after form submitting in Javascript, before page refresh?

A: The type in ajaxForm should be POST not get


text:
Q: Disconnect Bridge From Lever How can I disconnect a bridge from a lever? I've decided I'd rather have my two bridges operating independently of each other.

A: It is necessary to deconstruct one of the devices in the set. Generally you would then rebuild it.
When you deconstruct either a bridge or a lever in a pair that are connected, the connection is broken. The connecting mechanism stays in the remaining device (and is wasted unless you deconstruct it also), but you get all the mechanisms back that were in the deconstructed device.
In the situation you describe you have one lever with three mechanisms in it (one to make the lever and one for each device it is attached to), and two bridges, each with one mechanism. Your options are:

*

*Deconstruct the lever and build two new levers. Then attach both new levers to bridges.

*Deconstruct one of the bridges and build a new lever to attach the bridge to after you rebuild it.
The advantage of the former is that you don't have to deal with having one of the bridges be gone for a while. The advantage of the later is that you end up using one fewer mechanism.
There is a third option, however which may be even better: Just build two new levers and attach one bridge to each. Then if you need to close both at once, you can hit the current lever, and if you want to close just one you can use the appropriate new lever.
This is doable because not only may one lever be attached to many devices, but one device may be attached to many levers.
The downside of this third approach is that you have to keep track of the lever states. If you have closed the bridge using the lever attached to both, and then you hit the lever attached to one, it could be in a state to tell it to close again, rather than opening. Or say that you had closed the bridges with the lever attached to both, then opened them individually with the levers attached to just one. Then an invasion arrives. You would need to hit the lever attached to both twice before the bridges would close and keep away the invaders.
The third option gives more flexibility, but requires more awareness of machine state. For your purposes, demolishing and rebuilding a bridge to break the connection is probably the simplest answer.


text:
Q: Asynchronous call in a Grails controller Is there a way to implement this?
redirect(url: "${myDomain1RootUrl}/j_spring_security_logout") // make this asynchronous call
redirect(url: "${myDomain2RootUrl}/j_spring_security_logout") // make this asynchronous call
redirect(uri: "/j_spring_security_logout")

Basically, this code is going to logout the session for several internal domains and then finally, it logs out of the current site. Is this possible?
Thanks.

A: No, you can't have multiple redirects. But Spring Security supports a 'logoutSuccessUrl' parameter which you can use to chain the requests. Go to url1 which logs out and redirects to url2, which logs out and redirects back to this app and logs out:
String url1 = "${myDomain1RootUrl}/j_spring_security_logout"
String url2 = "${myDomain2RootUrl}/j_spring_security_logout"
String url3 = createLink(uri: "/j_spring_security_logout", absolute: true)

String twoPlusThree = url2 + '?logoutSuccessUrl=' + URLEncoder.encode(url3)
String all = url1 + '?logoutSuccessUrl=' + URLEncoder.encode(twoPlusThree)
redirect url: all


text:
Q: Web Scraping - ResultSet object has no attribute 'findAll' Having an issue with bs4 when reading second value in array within a for loop. Below I will paste the code.
However, when I use line #19, I receive no errors. When I swap it out for the entire array (line #18), It errors out when it attempts to gather the second value. Note that the second value in the array is the same value as line #19.
import requests
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

SmartLiving_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=Smart%20Living&selectedFacets=Brand%7CSmart%20Living&sortBy="
IEL_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=IEL&selectedFacets=Brand%7CIts%20Exciting%20Lighting&sortBy="
TD_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=two%20dogs&selectedFacets=Brand%7CTwo%20Dogs%20Designs&sortBy="

Headers = "Description, URL, Price \n"

text_file = open("HayneedlePrices.csv", "w")
text_file.write(Headers)
text_file.close()

URL_Array = [SmartLiving_IDS, IEL_IDS, TD_IDS]
#URL_Array = [IEL_IDS]
for URL in URL_Array:
  print("\n" + "Loading New URL:" "\n" + URL + "\n" + "\n")

  uClient = uReq(URL)
  page_html = uClient.read()
  uClient.close()
  soup = soup(page_html, "html.parser")

  Containers = soup.findAll("div", {"product-card__container___1U2Sb"})
  for Container in Containers:

    Title             = Container.div.img["alt"]
    Product_URL       = Container.a["href"]

    Price_Container   = Container.findAll("div", {"class":"product-card__productInfo___30YSc body no-underline txt-black"})[0].findAll("span", {"style":"font-size:20px"})

    Price_Dollars     = Price_Container[0].get_text()
    Price_Cents       = Price_Container[1].get_text()

    print("\n" + "#####################################################################################################################################################################################################" + "\n")
    # print("   Container: " + "\n" + str(Container))
    # print("\n" + "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + "\n")
    print(" Description: " + str(Title))
    print(" Product URL: " + str(Product_URL))
    print("       Price: " + str(Price_Dollars) + str(Price_Cents))
    print("\n" + "#####################################################################################################################################################################################################" + "\n")

    text_file = open("HayneedlePrices.csv", "a")
    text_file.write(str(Title) +  ", " + str(Product_URL) + ", " + str(Price_Dollars) + str(Price_Cents) + "\n")
    text_file.close()

  print("Information gathered and Saved from URL Successfully.")
  print("Looking for Next URL..")
print("No Additional URLs to Gather. Process Completed.")

A: The problem is that you import BeautifulSoup as soup and also define a variable soup = soup(page_html, "html.parser") with the same name!
I refactored your code a bit, let me know if it works as expected!
import csv

import requests
from bs4 import BeautifulSoup

smart_living_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=Smart%20Living&selectedFacets=Brand%7CSmart%20Living&sortBy="
IEL_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=IEL&selectedFacets=Brand%7CIts%20Exciting%20Lighting&sortBy="
TD_IDS = "https://www.hayneedle.com/search/index.cfm?categoryID=&page=1&searchQuery=two%20dogs&selectedFacets=Brand%7CTwo%20Dogs%20Designs&sortBy="

site_URLs = [smart_living_IDS, IEL_IDS, TD_IDS]

sess = requests.Session()

prod_data = []

for curr_URL in site_URLs:
    req = sess.get(url=curr_URL)
    soup = BeautifulSoup(req.content, "lxml")

    containers = soup.find_all("div", {"product-card__container___1U2Sb"})
    for curr_container in containers:
        prod_title = curr_container.div.img["alt"]
        prod_URL = curr_container.a["href"]

        price_container = curr_container.find(
            "div",
            {"class": "product-card__productInfo___30YSc body no-underline txt-black"},
        )

        dollars_elem = price_container.find("span", {"class": "main-price-dollars"})
        cents_elem = dollars_elem.find_next("span")

        prod_price = dollars_elem.get_text() + cents_elem.get_text()
        prod_price = float(prod_price[1:])

        prod_data.append((prod_title, prod_URL, prod_price))

CSV_headers = ("title", "URL", "price")

with open("../out/hayneedle_prices.csv", "w", newline="") as file_out:
    writer = csv.writer(file_out)
    writer.writerow(CSV_headers)
    writer.writerows(prod_data)

I tested it by repeating the current URL list 10 times, it took longer than I was anticipating. There are certainly improvements to be made, I might rewrite it to use lxml in the next few days, and multiprocessing might also be a good option. It all depends on how you're using this, of course :)


text:
Q: Manage single screen for two targets iOS I have an app with two targets. Both targets are sharing some resources and some resources are different.
Everything is fine until, I have a screen where I ask user for some info i.e. his date of birth, but it is not required in other target.
So how I can manage it that if user is using app with target1, he will not see date of birth text field but when user is using with target2, app will ask for date of birth.
I am using preprocessors in my .pch to determine which target is used.

A: You can set flag value and using this you can hide your view in coding part.
if(target2)
    {
        [self.textField setHidden:YES];
    }else{
        //DO what ever you want
    }

A: You can do this by detecting the bundleIdentifier because every target has its own:
if([[[NSBundle mainBundle] bundleIdentifier]
                            isEqualToString:@"my.app.identifier"]){
    [self doSomething];
} else {
    [self doSomethingElse];
}


text:
Q: How to databind into html control asp.net mvc razor by using knockout.js? Hi; i try to learn knockout.js using asp.net mvc razor. i have been written some codes below but http://localhost:56238/Contact/SendMessage  is empty. i see only html control. How to bind ViewModel to UI by using knockout.js

@{
    ViewBag.Title = "SendMessage";
}

SendMessage

First name:

Last name:

First name: <input data-bind="value: firstName" />

Last name: <input data-bind="value: lastName" />

Full name:

<button data-bind="click: capitalizeLastName">Go caps</button>

A: ko.applyBindings never executed in your code, you must put it somewhere outside the ViewModel. "this" in computed not gonna work because it does not point to the view model.
It should be something like this:

One more thing, I see you're using jquery without including jquery lib.


text:
Q: Calculating time of a packet through a network cable I am preparing for an exam in networking.
In one of the previous exams this question was given:
Assume you're sending a packet of length 4000 bit
through a cable of length 1000 km.
The signal in the cable is moving at 200000 km/s.
The signal bandwidth is 10 Mbit/s.
Calculate how much time it would take for the packet to arrive.

If I would have done this with a car, considering road length and car speed,
it would probably take 200 seconds. Though I am not sure how to apply the mbit/s and bits in the calculation.
Is this a correct way of doing it?
(10 mbit/s / 4000 bit) * (200000 km/s / 1000 km) = seconds packet needs to arrive

A: The transfer time equals to SEND_TIME + EXPANSION_TIME
(I use Mbit as 10^6 bit for simplicity instead of 2^20, the principle remains the same)
SEND_TIME = #bits / #bits_per_sec = 4000 / 10*10^6 = 4*10^-4
EXPANSION_TIME = length / expansion_speed = 1000 / 200000 = 5 * 10^-3

total is then 0.0054 seconds

Bonus:
A good practice is to look at the units and make sure you get to the correct units at the end, so the above is actually:
SEND_TIME = #bits / #bits_per_sec = 4000[bit] / 10*10^6[bit/sec] = 4*10^-4 [bit/bit * sec] = 0.0004 [sec]
EXPANSION_TIME = length / speed = 1000 [km] / 200000 [km/sec] = 5 * 10^-3 [km / km * sec] = 0.005 [sec]


text:
Q: How to make middle element stretch horizontally over all available space I have a basic form

    Label
    <input/>
    <button>Search!</button>

that I want to display inline with these basic declarations:
.outer{
    width: 100%;
}

.outer, label, button {
    display: inline-block;
}

The problem is - how to pull the Search button to the right and make the input element stretch horizontally over the available space?
Here is a JSBin where I attempted this effect but didn't know how to stretch the input. I don't know the total width, so can't control the width of the input.

A: You can use floating:
HTML:

    Label
    <button>Search!</button>

<input/>

CSS:
.outer{
  border: solid thin;
  overflow: hidden; /* Clear float */
}
.outer > label {
  float: left; /* Push left */
}
.outer > button {
  float: right; /* Push right */
}
.outer > div {
  overflow: hidden; /* Make it take remaining space */
}
.outer > div > input {
  width: 100%;  /* Make it fill its parent */
  box-sizing: border-box; /* Avoid extra width because of borders */
}

Demo

A: You can use CSS tables:
HTML:

  Label

<input/>

  <button>Search!</button>

CSS:
.outer {
  display: table;
  width: 100%;
}
.outer > * {
  display: table-cell;
}
.outer > div  {
  width: 100%; /* Make it take as much space as possible */
}
.outer > div > input {
  width: 100%; /* Make it fill its parent */
  box-sizing: border-box; /* Avoid extra width because of borders */
}

Demo

A: You can use flexible boxes:
HTML:

  Label
  <input/>
  <button>Search!</button>

CSS:
.outer {
  display: flex;
}
.outer > input {
  flex-grow: 1;
}

Demo

A: Change your css a title bit, try this
.outer label, .outer button {
  display: inline-block;
  width:10%
}
input {
  width:75%
}


text:
Q: Running a PySpark code in python vs spark-submit I have a PySpark code/application. What is the best way to run it (utilize the maximum power of PySpark), using the python interpreter or using spark-submit?
The SO answer here was almost similar but did not explain it in great details. Would love to know, why?
Any help is appreciated. Thanks in advance.

A: I am assuming when you say python interpreter you are referring to pyspark shell.
You can run your spark code both ways using pySpark interpreter, using Spark-submit or even with multiple available notebooks (Jupyter/Zeppelin).

*

*When to use PySpark Interpreter.

Generally when we are learning or doing some very basic operations for an understanding or exploration purpose we use pySpark interpreter.

*Spark Submit.

This is usually used when you have written your entire application in pySpark and packaged into py files, so that you can submit your entire code to Spark cluster for execution.
A little analogy may help here. Let's take an example of Unix shell commands. We can execute the shell commands directly on the command prompt or we can create shell script (.sh) to execute the bunch instruction at once. Similarly, you can think of pyspark interpreter and spark-submit utility, where in pySpark interpreter you can execute individual command. However, you can package your spark application into py files and execute using spark-submit utility.
Hope this helps.
Regards,
Neeraj

A: Running your job on pyspark shell will always be in client mode. Where as using spark-submit you can execute it in either modes. I.e. client or cluster


text:
Q: Export Files from OpenVZ root.hdd I have a little problem, and I have had a backup from my hoster, this consists of the following files, now the question arises how do I get the files out of it, I don't want to start servers but those Get files from it

I hope I am right here with my problem

A: That appears to be a ploop image.
You tagged your question Debian, I believe ploop is available and apt install ploop should work.  Then you should be able to mount/unmount the image using the ploop tools:
ploop mount -m /mnt /path/to/DiskDescriptor.xml
ploop umount /path/to/DiskDescriptor.xml


text:
Q: DataTables GET parameters missing I'm using the following init:
$('#PlaceHolder').dataTable(
    {
        "dom": 'T<"clear">lfrtip',
        "processing": true,
        "serverSide": true,
        "bDestroy"  : true,
        "iDisplayLength":10,
        "ajax": "../scripts/myDataTables_server_processing.php",
        "order": [[ 0, "desc" ]],
        "aoColumns":
            [
                {"bSortable": false},
                null,null,null,null,null,null,null,null,null,null,null,null,
                {"bSortable": false},
                {"bSortable": false},
                {"bSortable": false}
            ],
        "tableTools":
        {
            "sSwfPath": "../resources/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
            "sRowSelect": "multi",
            "aButtons":
                [

                    {
                        "sExtends":    "copy",
                        "bSelectedOnly": "true"
                    },
                    // "print",
                    {
                        "sExtends":    "collection",
                        "sButtonText": "Save",
                        "aButtons":
                            [
                                {
                                    "sExtends":    "csv",
                                    "bSelectedOnly": "true"
                                },
                                {
                                    "sExtends":    "xls",
                                    "bSelectedOnly": "true"
                                },
                                {
                                    "sExtends":    "pdf",
                                    "bSelectedOnly": "true",
                                    "sPdfOrientation": "landscape",
                                    "sTitle": "Raport zgrzewania"
                                }
                            ]
                    }
                ]
        }

    }

).fnClearTable();

when ajax GET myDataTables_server_processing.php is called for data the header looks ok:
Query String Parametersview sourceview URL encoded
draw:13
columns[0][data]:0
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:false
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:1
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:2
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
columns[3][data]:3
columns[3][name]:
columns[3][searchable]:true
columns[3][orderable]:true
columns[3][search][value]:
columns[3][search][regex]:false
columns[4][data]:4
columns[4][name]:
columns[4][searchable]:true
columns[4][orderable]:true
columns[4][search][value]:
columns[4][search][regex]:false
columns[5][data]:5
columns[5][name]:
columns[5][searchable]:true
columns[5][orderable]:true
columns[5][search][value]:
columns[5][search][regex]:false
columns[6][data]:6
columns[6][name]:
columns[6][searchable]:true
columns[6][orderable]:true
columns[6][search][value]:
columns[6][search][regex]:false
columns[7][data]:7
columns[7][name]:
columns[7][searchable]:true
columns[7][orderable]:true
columns[7][search][value]:
columns[7][search][regex]:false
columns[8][data]:8
columns[8][name]:
columns[8][searchable]:true
columns[8][orderable]:true
columns[8][search][value]:
columns[8][search][regex]:false
columns[9][data]:9
columns[9][name]:
columns[9][searchable]:true
columns[9][orderable]:true
columns[9][search][value]:
columns[9][search][regex]:false
columns[10][data]:10
columns[10][name]:
columns[10][searchable]:true
columns[10][orderable]:true
columns[10][search][value]:
columns[10][search][regex]:false
columns[11][data]:11
columns[11][name]:
columns[11][searchable]:true
columns[11][orderable]:true
columns[11][search][value]:
columns[11][search][regex]:false
columns[12][data]:12
columns[12][name]:
columns[12][searchable]:true
columns[12][orderable]:true
columns[12][search][value]:
columns[12][search][regex]:false
columns[13][data]:13
columns[13][name]:
columns[13][searchable]:true
columns[13][orderable]:false
columns[13][search][value]:
columns[13][search][regex]:false
columns[14][data]:14
columns[14][name]:
columns[14][searchable]:true
columns[14][orderable]:false
columns[14][search][value]:
columns[14][search][regex]:false
columns[15][data]:15
columns[15][name]:
columns[15][searchable]:true
columns[15][orderable]:false
columns[15][search][value]:
columns[15][search][regex]:false
order[0][column]:0
order[0][dir]:desc
start:10
length:10
search[value]:
search[regex]:false
_:1414344724424
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Type:text/html
Date:Sun, 26 Oct 2014 17:32:22 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=95
Pragma:no-cache
Server:Apache/2.2.21 (FreeBSD) mod_ssl/2.2.21 OpenSSL/0.9.8q mod_fcgid/2.3.6
Transfer-Encoding:chunked

but when I output $GET in " myDataTables_server_processing.php" the last parameter that is available is "start" and no "length", nor "search" are available ("variable is not set") as if the GET url data was truncated.
What can be the reason for this?
Thanks
Tom


text:
Q: How to upload images synchronously on Flickr in iOS? I am working with an application in which i have to upload images on flickr . When i select 15-20 images at once and call uploading methods , it starts uploading and there is no issue with that , but the problem is the when select more than 40 images and starts uploading at once, its memory increases over 300mb and application crashes. I don't know is this  the architecture issue of iOS operating system or    Flickr api, which starts uploading all the images at once. Is there any way by which i send one image at a time and after uploading it i send second image, so only one image uploaded at once and there will no issue of memory.
Some of my Upload method  for flickr :
-(void)startupuploader:(NSString *)filePath{

        image=YES;

        NSLog(@"filepath in flicke : %@",filePath);

        JPEGData = [[NSData alloc]initWithContentsOfFile:filePath];

        // NSLog(@"JPEGData in flicke : %@",JPEGData);

        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];

        NSLog(@"data in flicke : %@",data);

        [self.flickrRequest uploadImageStream:[NSInputStream inputStreamWithData:JPEGData] suggestedFilename:@"Flickr"

                                     MIMEType:@"image/jpeg" arguments:[NSDictionary dictionaryWithObjectsAndKeys:@"0", @"is_public", nil]];
  [UIApplication sharedApplication].idleTimerDisabled = YES;

  }

When i call this method for uploading it take all path at once and start uploading all the images at once , which results in crashing my application.
 Please help me out .
        Thanks in advance.

A: A couple of thoughts:

*

*Rather than doing it sequentially, (for which you'll pay a serious performance penalty) I might suggest still doing this concurrently, but controlling the degree of concurrency. For example, I might suggest wrapping upload in NSOperation and add these operations to operation queue with a maxConcurrentOperationCount of 4 or 5. This way you enjoy some concurrency (and the performance gain that will yield), but it constrains it so you don't exhaust limited network connections or use up too much memory at once.
It's hard for me to get much more specific than that, as I'm unfamiliar with this uploadImageStream method, though. Is that your own method (in which case you should update your question showing us that method) or is that a Flickr-provided method? Usually if methods run asynchronously they provide either a completion block or delegate method to indication completion. You'd need some completion pattern in order to be able to enjoy a controlled degree of concurrency via NSOperationQueue.

*Rather than load the file into a NSData and then creating a stream from that, why don't you create a [NSInputStream inputStreamWithFileAtPath:filePath], and bypass the NSData entirely. That should seriously constrain the memory usage, all by itself. Your current pattern will try to load all of these images completely into memory at the same time. By using streams, it will curtail the amount of memory used at any given time.


text:
Q: Adding jar with Ant My Eclipse project has the following structure:
-- | My project
  |-src

  |-build

  |-doc

  |-lib

In lib are placed my jar files. These files have been added to the Build path with "Add to Buildpath command". The project successfully compiles.
I want to build the project with Ant, to this aim I wrote the following xml file
<project name="ABTestConnector" basedir=".">
<property name="src.dir"     value="src"/>
<property name="build.dir"   value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir"     value="${build.dir}/jar"/>
<property name="main-class"  value="test.Prova"/>
<property name="lib.dir"     value="/lib"/>
<property name="doc.dir"     value="/doc"/>

<fileset dir="${lib.dir}">
       <include name="*.jar"/>
 </fileset>
<target name="clean">
    <delete dir="${build.dir}"/>
</target>

<path id="class-path">
  <fileset dir="${lib.dir}">
    <include name="*.jar" />
  </fileset>
</path>

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac includeantruntime="false" srcdir="${src.dir}" destdir="${classes.dir}">
        <classpath refid="class-path"/>
    </javac>
</target>

<target name="jar" depends="compile">
    <mkdir dir="${jar.dir}"/>
    <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
        <manifest>
            <attribute name="Main-Class" value="${main-class}"/>
            <fileset dir="${classes.dir}" includes="**/*.class" />
            <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
        </manifest>
    </jar>
</target>

<target name="run" depends="jar">
    <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>

</target>
<target name="clean-build" depends="clean,jar"/>
<target name="main" depends="clean,run"/>
<target name="doc" depends="clean-build" description="generate javadoc">
       <javadoc sourcepath="${src.dir}" destdir="${doc.dir}"/>
</target>

I have also tried in the fileset: include name="**/*.jar"/>
But I still get the errors
[javac] /home/bruno/Documenti/TestingEnvironment/EclipseWorkspace/SeleniumABTestConnector_0.0.1/src/driversTod/TodSelenium.java:10: package org.openqa.selenium does not exist
[javac] import org.openqa.selenium.By;

Thank you in advance.


text:
Q: Cocycle conditions of fibre bundles In a classical approach of fibre bundle one always need the cocycle condition is satisfied, namely:
$$g_{12} g_{23} g_{31}\equiv 1$$
in $U_1\cap U_2\cap U_3$. However, I do not see why this cocycle condition cannot be succinctly stated as $g_{12} g_{21}=1$. It seems to me that I can still reassemble the original bundle without any problem arises. What is the significance of bringing in the intersection of three sets? I guess maybe I have omitted some important details but I do not see where it is.
My thanks in advance.

A: It depends whether you're talking about the cocycle condition for $0$-cochains or for $1$-cochains. Review the construction of transition functions and Čech cochains and coboundaries.


text:
Q: Can not connect to DB, after deleting old DB and all migrations I replaced all URLFields in the models with Cloudinary fields, and decided to drop the DB and make new, because issues appeared. So every migration file, accept init files was deleted, I dropped the DB, even deleted all containers and volumes(I use docker for PostgreSQL). I have made new images and containers in docker. New database. But still can't connect to database nad migrate.
This is the error:
 django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more det ails.
This is my DB Settings:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'fishbook_db', 'USER': '*******', 'PASSWORD': '********', 'HOST': 'localhost', 'PORT': '5432', }, }
I have tried to fix the problem, by searching for this error in the web. I see a lot of people have the same problem, but I wasn't able to find solution so far.


text:
Q: How to return a Promise of an array in typescript I'm trying to return an array in a form of promise. I first unzipped a file, then parsed the file with csv-parse. I'm saving all returned objects in an array, then return this array
I tried to return without a promise the transpiler didn't complain. But I want to scale it
/**
 * Wraps writeFile in a promise.
 * @param content The Base64 content of the file to read.
 * @returns A buffer containing the contents of the file.
 */
protected writeFileAsync(path: string, content: Buffer): Promise<IProblem[]> {
    new Promise<Buffer>((resolve, reject) => {
        fs.writeFile(path, content,  "base64", (err) => {
            if (err) {
                reject(err);
            }

            resolve(content);
        });
    })
    .then(result => {
        fs.readFile(result, (err, data) => {
            if (err) {
                Log.error("Error while reading the zip file");
                this.listOfProblems = [];
                return this.listOfProblems;
            }
            let zip: JSZip = new JSZip();
            zip.loadAsync(data)
            .then(contents => {
                Object.keys(contents.files).forEach(filename => {
                    zip.file(filename).async('nodebuffer')
                    .then(content => {
                        let parser: csvParse.Parser = csvParse((data, err) => {
                            if (err) {
                                Log.error("Error while reading the zip file");
                                this.listOfProblems = [];
                                return this.listOfProblems;
                            }
                            let problem: IProblem;

                        }) as csvParse.Parser;
                        fs.createReadStream(content).pipe(parser);
                    })
                })
            })
        })
    })
    .catch(() => {
        Log.error("Error while reading the zip file");
        this.listOfProblems = [];
        return this.listOfProblems;
    });
    return this.listOfProblems;
}

It's showing error in the last line

A: You have to return your promise and not the list.
return new Promise<Buffer>((resolve, reject) => {


text:
Q: Getting highest value from a dictionary and replacing that value with a new letter Hi so Im trying to do frequency analysis to solve a key. I have a dictionary with all values. I am trying to change the value that occurs the most in the dictionary to 'e' as it occurs the most in the english langugae.
I have searched online and everything i try it does not work so lets say d = {a:54, b: 73, d: 98}
i want to change that d to the letter e.
how do i go about this in my text file? like how do i call the dictionary to implement such a change?
thank you!

A: Here is my solution assuming you want to do this for all letters (not just 'e'):
Obviously, d and frequencies can be extended as needed.
d = {'a':54, 'b': 73, 'd': 98}

# letters in decreasing order of frequency
frequencies = ['E','T','A','O','I','N','S','R','H','D','L','U','C','M','F','Y','W','G','P','B','V','K','X','Q','J','Z']

# get a list of values (the numbers) from the dictionary
values = list(d.values())

# sort the numbers in decreasing order
values.sort(reverse = True)

# build a new dictionary with the sorted letters as keys and sorted values as values.
d = {frequencies[i] : values[i] for i in range(min(len(values), len(frequencies)))}

print(d)

The resulting value of d will be
{'E': 98, 'T': 73, 'A': 54}

A: I found this helpful tip from another post (Getting key with maximum value in dictionary?):
import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max_key = max(stats.iteritems(), key=operator.itemgetter(1))[0]

You can use this to access the key with the highest value, and then do
d['e'] = d[max_key]
d.pop(max_key)

to rename the element.