text:
Q: Link to prefill status on facebook Twitter offers a dead simple method for prepoulating someones status for posting. Specifically, its as easy as http://twitter.com/?status=message .
I am looking for a similar method to use for facebook. Unfortunately, all I can find are like buttons and similar, which don't fit my need (the content we want posted does not have its own page). Is there any method on facebook to easily set someones status?

A: It sounds like you just want a simple way to share content onto Facebook.  Facebook is deprecating the Share Button, but still seems to support direct URL calls to the Share page:
http://www.facebook.com/sharer/sharer.php?u=cnn.com&t=great+news+site

So, create a link that opens your URL in a new window, like in this Javascript:
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(myUrl)+'&t='+encodeURIComponent(myTitle),'sharer','toolbar=0,status=0,width=626,height=436');

You mention prefilling it with default text.  I believe Facebook explicitly forbids this now.  They say this in the Feed Dialog page, which should pretty much cover their policy for the Sharer page too:

This field will be ignored on July 12, 2011 The message to prefill the text field that the user will type in. To be compliant with Facebook Platform Policies, your application may only set this field if the user manually generated the content earlier in the workflow. Most applications should not set this.

A: This used to work at https://www.facebook.com/connect/prompt_feed.php?message=woot
But nolonger does.

A: In Facebook, to post to a certain user's profile you need the following:

*

*The user to authenticate/authorize your application

*You ask for an extended permission to be able to post to his wall (publish_stream in this case)

*Capture the user id and use it to post whatever you want

Now doing the is easy and can be done in different ways, let's take the PHP-SDK example page and modify it:
<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '191149314281714',
  'secret' => '73b67bf1c825fa47efae70a46c18906b',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(
    'scope' => 'publish_stream'
  );
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');

?>
<!doctype html>

    <title>php-sdk</title>

php-sdk

    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout
    <?php else: ?>

        Login using OAuth 2.0 handled by the PHP SDK:
        <a href="<?php echo $loginUrl; ?>">Login with Facebook

    <?php endif ?>

PHP Session

<?php print_r($_SESSION); ?>

    <?php if ($user): ?>

You

      <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

Your User Object (/me)

<?php print_r($user_profile); ?>

    <?php else: ?>
      You are not Connected.
    <?php endif ?>

Public profile of Naitik

    <?php echo $naitik['name']; ?>

Now I changed the following from the original example:
$loginUrl = $facebook->getLoginUrl(array(
  "scope" => "publish_stream"
));

Now that the user granted your application the right permission you can post to his wall, refer to this answer to get you started.


text:
Q: Allow user zoom in android textview Is it possible to allow users to zoom contents of a textview in android application.
Right now I have created an application where users not able to zoom in or zoom out

A: no. Text is static. If you want to zoom it you have to use a GestureListener and programmatically change the text size.

A: You can use sp instead of dp as your font size units so that the text scales depending on the device settings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: proportion formula google sheets im am still doing my google sheets test and need help finding the answer to the question: what proportion of products are discontinued. i have to express my answer in a formula on google sheets
you can find the link to the data stack here:
products list:
https://docs.google.com/spreadsheets/d/1m67VmLZispyTwFTmPdppsdJNtbvnZsZK2LBCSchUWmU/edit?usp=sharing
my idea was to count the 0 in the column J(discontinued) with the formula: =Countif(J2:J78,"0"). in the next step i would have to show a proportionality and i have no clue how i am supposed to do that. could anyone tell me if the first step is correct and how i should go about the proportionality?
thank you!!

A: You do not need any formula, just build a pivot table

A: You can also use the formula PERCENTIF:

Returns the percentage of a range that meets a condition.
PERCENTIF(range, criterion)

In this case if you want to know the percentage of 0 this would be:
=PERCENTIF(J2:J78;"0")


text:
Q: How can I show the touch swipe trails? I have created a simple html page using Jquery Mobile. the user can navigate between the pages by swiping the screen to the sides.
I want to show a finger trail whenever the user uses the swipe gesture (if you have played Fruit Ninja, you'll know what I mean.)
Any ideas how can I can implement it?

A: JqueryMobile allows you to get touch event coordinates..(may be start and end for swipe)
and you can either use canvas, or simple solution-a grid of div elements to show the swipe gesture trail


text:
Q: Database view in IntelliJ IDEA does not show all databases of connection I have added connection to localhost MySQL/MariaDB database in IntelliJ IDEA 14.1.5.
However the Database view tab is showing only one of my databases. How do I get IntelliJ to show the other databases as well?

A: Right-click on connection -> Properties -> Schemas and Tables tab -> select all the checkboxes in available databases tab -> click OK

A: In order to show all databases of the connection:

*

*Click on the number near the connection name (localhost in this example).

*In the popup, select All schemas.

*You should have all the table visible now.


text:
Q: How do I convert text entered in form to Title Case Using PHP before submitting to MySQL? I am using the PHP below to submit data from an html form to MySQL and to an email address.  I would like all of the data entered in all fields apart from the email field to be converted to Title (Proper) Case.  I am wondering if there is a simple method of doing this.  In searching this site I found this code:
function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

but I am not sure if it is what I need and if it is what I need, how to hook it up to the existing code.  Could someone help with this?
Thanks,
Nick
<?php

$emailFrom = "****";
$emailTo = "****";
$subject = "****";

$body = "****" . "\n\n" . "Waged/Organisation Rate:" . "\n\n";
$row_count = count($_POST['name']);
$row_count2 = count($_POST['name2']);

$values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name'][$i]));
     $email = trim(stripslashes($_POST['email'][$i]));
     $organisation = trim(stripslashes($_POST['organisation'][$i]));
     $position = trim(stripslashes($_POST['position'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks.
     $body .= "Name: " . $name . "    Email: " . $email . "  Organisation: " . $organisation . "   Position: " . $position . "\n\n";

     //prepare the values for MySQL
     $values[] = '(\'' . $name . '\',\'' . $email . '\',\'' . $organisation . '\',\'' . $position . '\')';

}

mysql_select_db($database, $connection);

$query1 = "INSERT INTO conference (Name, Email, Organisation, Position) VALUES "  . implode(',', $values);

$result1 = mysql_query($query1);
if (!$result1) {
  die('Invalid query: ' . mysql_error());
}

 $body .= "Unwaged Rate:" . "\n\n";

 $values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name2'][$i]));
     $email = trim(stripslashes($_POST['email2'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks.
     $body .= "Name: " . $name . "    Email: " . $email . "\n\n";

     //prepare the values for MySQL
     $values2[] = '(\'' . $name . '\',\'' . $email . '\')';
}
$query2 = "INSERT INTO conference (Name, Email) VALUES " . implode(',', $values2);

$result2 = mysql_query($query2);
if (!$result2) {
  die('Invalid query: ' . mysql_error());
}

// send email
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
?>

A: Use the ucwords() function.

A: Use PHP's ucwords function.
http://php.net/manual/en/function.ucwords.php
Example:
$subject = "this is a subject";
$subject = ucwords($subject); //$subject is now "This Is A Subject"


text:
Q: Setting a max record limit in access I have a table that holds several hundred records but I with a special property. I only want the user to be able to select that property 50 times though. How can I set a limit and return an error when the limit is reached?

A: To add to @Kevin Ross, the mechanism "at the DB level" to enforce the rule is a CHECK constraint e.g.
ALTER TABLE tblFoo ADD
   CONSTRAINT tblFoo_bar__50_limit
      CHECK (NOT EXISTS (
                         SELECT T1.Bar
                           FROM tblFoo AS T1
                          WHERE T1.Bar = 'Thing_you_only_want_50_of'
                          GROUP
                             BY T1.Bar
                         HAVING COUNT(*) > 50
                        ));

CHECK constraints have existed in Jet from version 4.0 (circa Access 2000) and still exists in ACE (e.g. Access 2010).
You need to create the CHECK constraint using SQL DDL while in ANSI-92 Query Mode. No, you can't create CHECK constraints using DAO or the Access UI but that doesn't mean they don't exist ;)
If for some reason you have philosophical objection to SQL DDL, you could do similar things with an additional 'sequence' column, row-level Validation Rules and a compound UNIQUE constraint, all of which can be created using DAO or the Access UI and have been available in Jet for more years than I can remember.
Here's a rough sketch of what that alternative approach could look like:
ALTER TABLE tblFoo ADD
   Bar__sequence INTEGER;

ALTER TABLE tblFoo ADD
   CONSTRAINT tblFoo_bar_sequence__values
      CHECK (
             (
              Bar <> 'Thing_you_only_want_50_of'
              AND Bar__sequence IS NULL
             )
             OR (
                 Bar = 'Thing_you_only_want_50_of'
                 AND Bar__sequence BETWEEN 1 AND 50
                )
            );

ALTER TABLE tblFoo ADD
   CONSTRAINT tblFoo_bar__50_limit
      UNIQUE (Bar__sequence);

In this case, the results of the above three SQL DDL statements can be achieved using the Table Designer in the Access UI i.e. add the column, amend the Table Validation Rule and add a unique index.

A: select top 50 * from ...

A: I believe what renick was trying to say was before your save operation you could do something like
SELECT Count(*)
FROM tblFoo
WHERE Bar='Thing_you_only_want_50_of'

You would then check to see if this figure is greater than equal to or greater than 50, if it is then return an error and not then let the user save.
As far as I know there is no way to restrict that at the DB level however access 2010 does have more controls such as triggers etc. Not sure what version you are using but if you are on 2010 it might be worth checking out

A: The question is very unclear. It's not clear if "select" means "display limited to 50 items" or "allow user to create data records that are limited to 50 items". I won't address the first interpretation, since it doesn't seem to me to be relevant.
Assuming certain other things, such as a Jet/ACE back end (the only way the question makes sense to me), how you accomplish this depends on your version of Access.

*

*up to and including Access 2007: you'll have to apply the limitation in the user interface of your application. EDIT: As @onedaywhen has pointed out in his answer, it's possible to use DDL in SQL 92 mode to add a CHECK CONSTRAINT that operates on the current record based on groups of other records. I did not know this was possible when I posted.

*in Access 2010, you can avail yourself of the new table-level data macros (which work like triggers) and limit the user to the 50 selections.
I'm not providing details for either of these, as there's simply not enough information provided to do so.


text:
Q: How do I write a ruby web crawler which uses chrome? I have a ruby web crawler that is currently coded to run in firefox.  How do I switch it over to Chrome instead?
def open_browser()
  tweaked_profile = Selenium::WebDriver::Firefox::Profile.new
  tweaked_profile['nglayout.initialpaint.delay'] = 0
  tweaked_profile.assume_untrusted_certificate_issuer=false
  tweaked_profile['permissions.default.image'] = 2
  tweaked_profile['network.proxy.type'] = 1
  tweaked_profile['network.proxy.http'] = 'ec2proxy.csnzoo.com'
  tweaked_profile['network.proxy.http_port'] = 8080
  driver = Selenium::WebDriver.for :firefox, :profile => tweaked_profile
  $browser = Watir::Browser.new(driver)
end

Should I just ditch watir and go with chromedriver or will watir work for this?

A: Check out http://watirwebdriver.com/chrome/, which has this example:
profile = Selenium::WebDriver::Chrome::Profile.new
...
b = Watir::Browser.new :chrome, :profile => profile

Also, these SO questions provide alternatives for crawling sites: Web crawler in ruby and What are some good Ruby-based web crawlers?


text:
Q: Could not cast value of type __NSCFString to NSDictionary I'm trying to get 'fname' from my Json , this is my code:
let httpResponse = response as? HTTPURLResponse
            print(httpResponse!)
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                DispatchQueue.main.async {
                    let Results = (json as! NSDictionary)
                    if (Results.value(forKey: "error") == nil) {
                        print(Results)
                            let x = Results.value(forKey: "user") as! NSDictionary
                            let fname= x.value(forKey: "fname")
                            print(fname!)
                      //  self.userpass = ["username": self.usernametf.text!,"pass":self.passwordtf.text!]
                       // UserDefaults.standard.set(self.userpass, forKey: "userpass1")
                    }else{
                        print("wrong pass")
                    }
                }
            } catch {
                print("error serializing JSON: \(error)")
            }

and this is my Json:
{
status = 1;
user = "{\"id\":\"1\",\"fname\":\"\\u0645\\u0633\\u0639\\u0648\\u062f\",\"lname\":\"\\u0627\\u0645\\u0627\\u0645\\u06cc\\u0627\\u0646\",\"email\":\"smemamian@yahoo.com\",\"phone\":\"093666023695\",\"pass\":\"c4ca4238a0b923820dcc509a6f75849b\",\"bd\":\"1991-12-20\",\"byear\":\"1991\",\"bmonth\":\"12\",\"bday\":\"20\",\"img\":\"1480141509_1.png\",\"isdelete\":\"1\",\"current_date\":\"2016-11-09 10:04:36\"}";}

but I'm getting error "Could not cast value of type '__NSCFString' (0x1012ec4a0) to 'NSDictionary' (0x1012ed288)."


text:
Q: insert chapters into document I am having trouble inserting chapters into my document. When I use:
\chapter{My Chapter}

the pdf simply displays 'My Chapter' in normal font, with no "Chapter 1" etc etc.
My document is set out as :
\documentclass[12pt]{article}
\usepackage{booktabs}
\usepackage{setspace}
\onehalfspacing
\usepackage[english]{babel}
\usepackage{grffile}
\usepackage{fancyhdr}
\usepackage{hyperref}
\usepackage[demo]{graphicx}
\usepackage{floatrow}
\usepackage[font=small,labelfont=bf]{caption}
\usepackage[options]{algorithm2e}
\usepackage{filecontents}% http://ctan.org/pkg/filecontents
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{hyperref}
\pagenumbering{arabic}
\newcounter{qcounter}
\let\centering\relax
\usepackage{color, colortbl}
\definecolor{name}{system}{definition}
\definecolor{Gray}{gray}{0.9}
\definecolor{LightCyan}{rgb}{0.88,1,1}
\usepackage{tabularx}
\usepackage{caption}
\usepackage{tikz}
\usepackage{babel}
\usepackage{graphicx}
\usepackage{csquotes}
\usepackage{fancybox}
\MakeOuterQuote{"}
\usepackage[utf8]{inputenc}
\usepackage{amsmath, amsthm, amssymb}
\begin{document}

\chapter{My Chapter}
\end{document}

what am I doing wrong?


text:
Q: Adding object to list causes index out of range error? Trying to run this code ive worked on for way too long. Once I reach line "gameaccess.player.playerturn.Add(turn);" in method AddTurns() I get an indexoutofrange exception on the line "public Player player => PlayerList[playeraccess.Turnchecker];". This happens despite having added objects to "PlayerList" in method PlayGame(). I've tried pretty much everything and not sure why this occurs.
class Program
{
    static void Main(string[] args)
    {
        game dartgame = new game();
        dartgame.PlayGame();
    }
}

class game
{
    public List<Player> PlayerList = new List<Player>();

    Player playeraccess = new Player();
    public Player player => PlayerList[playeraccess.Turnchecker];

    public game(int playercount = 0, int turncounter = 0)
    {
        PlayerCount = playercount;
        Turncounter = turncounter;
    }

    public int PlayerCount { get; set; }
    public int Turncounter { get; set; }

    public void PlayGame()
    {
        Console.WriteLine("Välkommen och låt spelet börja!");
        Console.WriteLine("För att börja spelet, var vänlig ange antal spelare och spelarnas namn");
        Console.WriteLine("Skriv in antal spelare: ");
        PlayerCount = int.Parse(Console.ReadLine());
        Console.WriteLine("Okej! Du har angivit " + PlayerCount + " spelare.");
        for (int n = 0; n < PlayerCount; n++)
        {
            Console.WriteLine("Skriv nu in namn för spelare " + (n + 1) + ":");
            PlayerList.Add(new Player());
            PlayerList[n].PlayerName = Console.ReadLine();
        }

        Console.WriteLine("Ok, välkomna till spelet!");
        Console.WriteLine("Den spelare vars tur det är får kasta tre gånger");
        Console.WriteLine("genom att skriva 3 heltal");

        Player playeraccess = new Player();
        playeraccess.AddTurns();
    }

    public void winstate()
    {
        Console.WriteLine("Grattis till vinnaren!");
        Console.WriteLine("Du har lyckats samla 301 poäng!");
        Console.WriteLine("Vill ni spela igen? Y/N.");

        for (int exitloop = 0; exitloop == 1; exitloop++)
        {
            char restart = Console.ReadKey().KeyChar;

            if (restart == 'y')
            {
                PlayerCount = 0;
                PlayerList.Clear();
                PlayGame();
            }
            else if (restart == 'n')
            {
            }
            else
            {
                Console.WriteLine("Försök igen, något gick snett");
                --exitloop;
            }
        }
    }
}

class Player
{
    public List<Turns> playerturn = new List<Turns>();

    public Player(string playername = "", int throw1 = 0, int throw2 = 0, int throw3 = 0, int turnchecker = 0)
    {
        PlayerName = playername;
        Throw1 = throw1;
        Throw2 = throw2;
        Throw3 = throw3;
        Turnchecker = turnchecker;
    }

    public string PlayerName { get; set; }
    public int Throw1 { get; set; }
    public int Throw2 { get; set; }
    public int Throw3 { get; set; }
    public int Turnchecker { get; set; }

    public override string ToString()
    {
        return base.ToString();
    }

    public void CalculatePoints()
    {
        game gameaccess = new game();
        int calcpoints = gameaccess.player.playerturn[playerturn.Count].Throwscore1 + gameaccess.player.playerturn[playerturn.Count].Throwscore2 + gameaccess.player.playerturn[playerturn.Count].Throwscore3;

        Console.WriteLine("Du har " + calcpoints + " Poäng totalt.");

        if (calcpoints >= 301)
        {
            gameaccess.winstate();
        }
        else
        {
            if (Turnchecker >= gameaccess.PlayerCount - 1)
            {
                Turnchecker = 0;
                calcpoints = 0;
                AddTurns();
            }
            else
            {
                Turnchecker++;
                calcpoints = 0;
                AddTurns();
            }
        }
    }

    public void AddTurns()
    {
        game gameaccess = new game();
        {
            var turn = new Turns();
            Throw1 = 0;
            Throw2 = 0;
            Throw3 = 0;
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", skriv in ditt första kast.");
            Throw1 = int.Parse(Console.ReadLine());
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", skriv in ditt andra kast.");
            Throw2 = int.Parse(Console.ReadLine());
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", Skriv in ditt sista kast.");
            Throw3 = int.Parse(Console.ReadLine());

            gameaccess.player.playerturn[playerturn.Count].Throwscore1 = gameaccess.player.playerturn[playerturn.Count].Throwscore1 + Throw1;
            gameaccess.player.playerturn[playerturn.Count].Throwscore2 = gameaccess.player.playerturn[playerturn.Count].Throwscore2 + Throw2;
            gameaccess.player.playerturn[playerturn.Count].Throwscore3 = gameaccess.player.playerturn[playerturn.Count].Throwscore3 + Throw3;
            gameaccess.player.playerturn.Add(turn);
            Query();
        }
    }

    public void Query()
    {
        char query;

        for (int queryloop = 0; queryloop < 1; queryloop++)
        {
            Console.WriteLine("Vill du se dina poäng? Y/N");
            query = Console.ReadKey().KeyChar;

            if (query == 'y')
            {
                queryloop = 0;
                Turns turnsaccess = new Turns();
                turnsaccess.GetScore();
            }
            else if (query == 'n')
            {
                queryloop = 0;
                CalculatePoints();
            }
        }
    }
}

public class Turns
{
    public Turns(int turn1 = 0, int turn2 = 0, int turn3 = 0, int turntotal = 0)
    {
        Throwscore1 = turn1;
        Throwscore2 = turn2;
        Throwscore3 = turn3;
        Throwscoretotal = turntotal;
    }

    public int Throwscore1 { get; set; }
    public int Throwscore2 { get; set; }
    public int Throwscore3 { get; set; }
    public int Throwscoretotal { get; set; }

    public void GetScore()
    {
        Player playeraccess2 = new Player();
        Console.WriteLine("Du har fått såhär mycket poäng denna runda:");
        Console.WriteLine("Kast 1: " + playeraccess2.Throw1 + ".");
        Console.WriteLine("Kast 2: " + playeraccess2.Throw2 + ".");
        Console.WriteLine("Kast 3: " + playeraccess2.Throw3 + ".");
        playeraccess2.CalculatePoints();
    }
}

A: Main() sets up game dartgame = new game(); and starts to play dartgame.PlayGame(); but once you get into playeraccess.AddTurns(); the first thing that happens is game gameaccess = new game();.
There's your problem... this new local variable gameaccess has not been initialised, it has a PlayerCount of 0 and a PlayerList with no entries - which you then try to access PlayerList[anything]... Boom! IndexOutOfRange
This is not the only flaw but the common thread is "object relationships".  For example the fact that AddTurns() is a (non-static) method of class game and so when a Player object (different class) is told to AddTurns() it somehow has to "know the game it is in".
Time to re-think your design: maybe change the call to AddTurns(game) or save the game in a Player-member variable/property in a prior setup/initialisation method like Player.EnterGame(game).


text:
Q: PHP регулярное выражение, разбить строку по определенным символам одним запросом, крашится на символе точки Есть номера телефонов в формате (строка):
0930001122, 0960001122
0930001122; 0960001122
0930001122.0960001122.
Соответственно, я хочу разбить на массив по символам: , . ;
По запятой и точке с запятой оно заходит в массив, а вот по символу точки - не хочет.
Инфа подтягивается с таблицы БД (тип строка)
$kitchen = preg_split("/,/", $obj->phone);  // разбиваю по запятой

if(count($kitchen) == 1) {
    $kitchen = preg_split("/;/", $obj->phone);  // Если длина массива равна одному, то значит там или один телефон, или предыдущий сплит не сработал, пытаюсь разбить по точке с запятой.
}

if(count($kitchen) == 1) {
    $kitchen = preg_split("/./", $obj->phone);  // Если длина массива равна одному, то значит там или один телефон, или предыдущие сплиты не сработали. Пытаемся разделить строку по точке.
}

При таком коде первые два формата телефонов разбиваются на массив, а третий просто записывается как 0, пустота.

A: Непонятно в чём у вас проблема. Код вполне рабочий, но можно сократить до:
$phone = '0930001122, 0960001122,0930001122; 0960001122; 0930001122.0960001122.';
$kitchen = preg_split("/(\s+)?[.;,](\s+)?/", $phone);
print_r($kitchen);

Получаем результат
Array
(
    [0] => 0930001122
    [1] => 0960001122
    [2] => 0930001122
    [3] => 0960001122
    [4] => 0930001122
    [5] => 0960001122
    [6] =>
)


text:
Q: No puedo validar un formulario con Javascript, y enviar la informacion con php, pero me llegan los mensajes en blanco al correo Estoy desarrollando una pagina web, donde necesito crear un formulario de contacto en el cual los usuarios puedan contactarme enviandome un mensaje directamente al correo. Es decir, es un formulario de contact.
La validacion de los inputs esta hecha con Javascript, pero al momento de usar php para enviarlos a mi correo, los mensajes me llegan en blanco. No se si se deba a alguna incompatibilidad entre la validacion de Javascript y la validacion de php, o si tenga que primero almacenar la informacion en el localstorage. Alguna sugerencia???
PD: La web ya esta alojada en un webhost.

A: Tal vez esto te ayude...
codigo de formulario en el Front:
<form method="post" name="contact_form"
  action="contacto.php">
  Your Name:
  <input type="text" name="name">

  Email Address:
  <input type="text" name="email">

  Message:
  <textarea name="message"></textarea>

  <input type="submit" value="Submit">
</form>

codigo para recibir la data en el Back de php
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$to = 'tucorreo@website.com'

$email_subject = "El contacto que envio: $name";

$email_body = "Has recibido un nuevo mensaje. ".

" Aqui los detalles:\n Nombre: $name \n ".

"Correo: $email_address\n Mensaje\n $message";

$headers = "From: $myemail\n";

$headers .= "Reply-To: $email_address";

mail($to,$email_subject,$email_body,$headers);

echo "mensaje enviado";

recuerda que es la libreria de mail de php https://www.php.net/manual/es/function.mail.php


text:
Q: Web Application deployment and database/runtime data management I have decided to finally nail down my team's deployment processes, soup-to-nuts. The last remaining pain point for us is managing database and runtime data migration/management. Here are two examples, though many exist:

*

*If releasing a new "Upload" feature, automatically create upload directory and configure permisions. In later releases, verify existence/permissions - forever, automatically.

*If a value in the database (let's say an Account Status of "Signup") is no longer valid, automatically migrate data in database to proper values, given some set of business rules.

I am interested in implementing a framework that allows developers to manage and deploy these changes with the same ease that we manage and deploy our code.
So the first question is: 1. What tools/frameworks are out there that provide this capacity?
In general, this seems to be an issue in any given language and platform. In my specific case, I am deploying a .NET MVC2 application which uses Fluent NHibernate for database abstraction. I already have in my deployment process a tool which triggers NHibernate's SchemaUpdate - which is awesome.
What I have built up to address this issue in my own way, is a tool that will scan target assemblies for classes which inherit from a certain abstract class (Deployment). That abstract class exposes hooks which you can override and implement your own arbitrary deployment code - in the context of your application's codebase. the Deployment class also provides for a versioning mechanism and the tool manages the current "deployment version" of a given running app. Then, a custom NAnt task glues this together with the NAnt deployment script, triggering the hooks at the appropriate times.
This seems to work well, and does meet my goals - but here's my beef, and leads to my second question: 2. Surely what I just wrote has to already exist. If so, can you point me to it? and 3. Has anyone started down this path and have insight into problems with this approach?
Lastly, if something like this exists, but not on the .NET platform, please still let me know - as I would be more interested in porting a known solution than starting from zero on my own solution.
Thanks everyone, I really appreciate your feedback!

A: Each major release, have a script to create the environment with the exact requirements you need.
For minor releases, have a script that is split into the various releases and incrementally alters the environment. There are some big benefits to this

*

*You can look at the changes to the environment over time by reading the script and matching it with release notes and change logs.

*You can create a brand new environment by running the latest major and then latest minor scripts.

*You can create a brand new environment of a previous version (perhaps for testing purposes) by specifying it to stop at a certain minor release.


text:
Q: Why does my latex formula looks different to image? My tex should looks like that:

I can only do this:

My whole tex code:
\documentclass[12 pt, a4paper]{article}

\usepackage[cp1250]{inputenc}

\usepackage{polski,enumerate,amsmath,amssymb, multicol}

\begin{document}

$\displaystyle S_k = \sum^{\infty}_{1=1}u_{k,l} (k=1,2,3,\dots)$, mamy $\displaystyle S=\sum^{\infty}_{k=1}S_k$, skąd, w myśl $(3)$

(dla $a>0$):
$$
a^{s_{k}}=\prod_{l=1}^{\infty} a^{u_{k, l}} \quad \text { oraz } \quad a^{s}=\prod_{k=1}^{\infty} a^{s_{k}}=\prod_{k=1}^{\infty}\left(\prod_{l=1}^{\infty} a^{u_{k, l}}\right) \text {. }
$$

czyli

%here is my formula I want to fix
$$
\displaystyle a^{\displaystyle \sum^{\infty}_{k=1} \sum^{\infty}_{l=1}u_{k,\:l}} = \prod^{\infty}_{k=l} \prod^{\infty}_{l=1} a^{u_{k, l}}
$$
\end{document}

And used packages:
\usepackage{polski,enumerate,amsmath,amssymb, multicol}

I want sum symbols and prod symbols look like the ones in the picture, another problem is that theres big space between equal symbol and my is short in comparison.

A: You can use \limits rather than \displaystyle to use  limits below the summation, displaystyle forces the superscript to be unreasonably large and hard to recognise as a superscript.
I used stix2 to use a bolder, more robust font.
In the final expression I used a double length = if you really need that. I also fixed the typo: k=1 on the first product, your question has k=l

\documentclass[12pt, a4paper]{article}

%any code copied from stackexchage is UTF-8 not cp1250
%\usepackage[cp1250]{inputenc}

\usepackage{polski,enumerate,amsmath,amssymb, multicol}

\usepackage{stix2}

\begin{document}

$\displaystyle S_k = \sum^{\infty}_{1=1}u_{k,l} (k=1,2,3,\dots)$, mamy $\displaystyle S=\sum^{\infty}_{k=1}S_k$, skąd, w myśl $(3)$

(dla $a>0$):
\[
a^{s_{k}}=\prod_{l=1}^{\infty} a^{u_{k, l}} \quad \text { oraz } \quad a^{s}=\prod_{k=1}^{\infty} a^{s_{k}}=\prod_{k=1}^{\infty}\left(\prod_{l=1}^{\infty} a^{u_{k, l}}\right) \text {. }
\]

czyli

%here is my formula I want to fix
\[
a^{\sum\limits^{\infty}_{k=1} \sum\limits^{\infty}_{l=1}u_{k,\:l}} = \prod^{\infty}_{k=1} \prod^{\infty}_{l=1} a^{u_{k, l}}
\]

\[
a^{\sum\limits^{\infty}_{k=1} \sum\limits^{\infty}_{l=1}u_{k,\:l}} \!=\joinrel= \prod^{\infty}_{k=1} \prod^{\infty}_{l=1} a^{u_{k, l}}
\]
\end{document}


text:
Q: jQuery how to keep the style value when going back I've got an issue with the keeping style value when coming back to a page from another.
I've got a code in jQuery that is showing my menu.
$( "#burger" ).click(function() {
    if ($("#burger").hasClass("closed")) {
      $( "#menu" ).animate({
        marginLeft: "-400px"
      }, 600, function() {
        $("#burger").removeClass("closed");
        $("#burger").addClass("open");
      });
    } else {
        $( "#menu" ).animate({
        marginLeft: 0
      }, 600, function() {
        $("#burger").removeClass("open");
        $("#burger").addClass("closed");
      });
    }
});

And now when i enter other link: for example "gallery.html" and then go back to the "index.html" the menu is no longer there.
How can i keep the margin-left:-400px; in the memory, so when i go back the menu will still be there?
Also i don't wanna to menu will be open everytime i go back, cause in some cases it will be closed and it should remain - so in that case the value should be remembered as "margin-left:0px;"
Thanks for answers!

A: Here's a fiddle to round out this answer JS Fiddle
You can add an item with HTML5 Storage API using sessionStorage or localStorage.
sessionStorage.setItem("leftset", "yes");
localStorage.setItem("leftset", "yes");

the difference is that localStorage will save it indefinitely on the users computer. Session storage will remove it when the browser window is closed.
You can use
sessionStorage.getItem("leftset");
localStorage.getItem("leftset");

To pull from the storage object on page load or dom ready and then execute whether or not "leftset"(in this example, but you can set it up as whatever) has a value.
if you would like to remove an item from storage you can use the following:
sessionStorage.removeItem("leftset");
localStorage.removeItem("leftset");

learn more at w3Schools or check out the demo HTML5 Storage Demo

A: What's going on is that JQuery or any JS based language works on the client, so when you reload the page or your app cause a Postback every change the JQuery had done will be erased. As posted by zfrisch the best method is to "save" that the user has already clicked on the item and base it's position on whether or not has been changed.
//if you are interested on keeping it this way until browser is erased manually
localStorage.itemClicked = true;
//if the configuration is going to be reset on everytime the user opens his browser
sessionStorage.itemClicked = true;

and in the .ready function you change its position
$(function(){
    if(localStorage.itemClicked){
        $('#burger').addClass("open");
        $('#burger').css({margin-left:"-400px"});
    }
});

and your click event should look like this
$( "#burger" ).click(function() {
    if ($("#burger").hasClass("closed")) {

      $( "#menu" ).animate({
        marginLeft: "-400px"
      }, 600, function() {
        $("#burger").removeClass("closed");
        $("#burger").addClass("open");

        //save that was clicked
        localStorage.itemClicked = true;
      });
    } else {

        $( "#menu" ).animate({
        marginLeft: 0
      }, 600, function() {
        $("#burger").removeClass("open");
        $("#burger").addClass("closed");

        //remove the key so it is not wasting memory
        localStorage.removeItem("itemClicked");
      });
    }
});

Hope it helped


text:
Q: Process crashes during creation of RoboGuice injector, if there is a mocked instance in any module I have a problem with using RoboGuice and AndroidMock frameworks in unit testing.
I've created a simple project to show my problem. Here I create a mocked instance and register it in the RoboGuice.
But the process crashes between the "setUp()" and "test01()" methods.
As I guess, actually the process crashes when the Injector is created, if any module has a mocked instance inside.
If I replace the mocked instance with an instance of a class that implements the interface then everything works fine.
Does anybody know how to fix this problem?
Here is my test code:
public class testInjectMock extends RoboUnitTestCase<MyApplication> {
    protected void setUp() throws Exception {
        InterfaceToMock instance = AndroidMock.createNiceMock(InterfaceToMock.class);           AndroidMock.expect(instance.SimpleMethod()).andStubReturn("Hello!");
        MyModule myMockModule = new MyModule();
        myMockModule.setMockedInstance(instance);//Comment this string to get into the test01() method
        MyApplication.setMyModule(myMockModule);
        super.setUp();
    }
    public void test01() {
        //It never comes here
    }
}

Module source code:
public class MyModule extends AbstractAndroidModule {
        protected InterfaceToMock mockedInstance;
        public void setMockedInstance(InterfaceToMock mockedInstance) {
            this.mockedInstance = mockedInstance;
        }
        @Override
        protected void configure() {
            if(mockedInstance != null)
                bind(InterfaceToMock.class).toInstance(mockedInstance);
        }
    }

The logcat output:
05-23 16:17:07.135: INFO/DEBUG(27): Build fingerprint: 'generic/sdk/generic/:2.1-update1/ECLAIR/35983:eng/test-keys'
05-23 16:17:07.135: INFO/DEBUG(27): pid: 2025, tid: 2031  >>> InjectMock.test <<<
05-23 16:17:07.145: INFO/DEBUG(27): signal 11 (SIGSEGV), fault addr 00000000
05-23 16:17:07.155: INFO/DEBUG(27):  r0 0011b218  r1 43d1caa0  r2 00000000  r3 00000000
05-23 16:17:07.155: INFO/DEBUG(27):  r4 43d1caa0  r5 0011b218  r6 451c0e30  r7 4000a958
05-23 16:17:07.155: INFO/DEBUG(27):  r8 ad00f380  r9 00138de0  10 426bda34  fp 00138de0
05-23 16:17:07.155: INFO/DEBUG(27):  ip 00000002  sp 451c0dc0  lr ad05ad1d  pc ad05a804  cpsr 00000030
05-23 16:17:07.295: INFO/DEBUG(27):          #00  pc 0005a804  /system/lib/libdvm.so
05-23 16:17:07.305: INFO/DEBUG(27):          #01  pc 0005ad18  /system/lib/libdvm.so
05-23 16:17:07.305: INFO/DEBUG(27):          #02  pc 00054a4a  /system/lib/libdvm.so
05-23 16:17:07.315: INFO/DEBUG(27):          #03  pc 00013f58  /system/lib/libdvm.so
05-23 16:17:07.325: INFO/DEBUG(27):          #04  pc 00019888  /system/lib/libdvm.so
05-23 16:17:07.335: INFO/DEBUG(27):          #05  pc 00018d5c  /system/lib/libdvm.so
05-23 16:17:07.335: INFO/DEBUG(27):          #06  pc 0004d6d0  /system/lib/libdvm.so
05-23 16:17:07.345: INFO/DEBUG(27):          #07  pc 0004d702  /system/lib/libdvm.so
05-23 16:17:07.355: INFO/DEBUG(27):          #08  pc 00041c78  /system/lib/libdvm.so
05-23 16:17:07.365: INFO/DEBUG(27):          #09  pc 00010000  /system/lib/libc.so
05-23 16:17:07.365: INFO/DEBUG(27):          #10  pc 0000fad4  /system/lib/libc.so
05-23 16:17:07.375: INFO/DEBUG(27): code around pc:
05-23 16:17:07.385: INFO/DEBUG(27): ad05a7f4 ffff5ae0 fffe57c4 6801b5f8 6a8b1c05
05-23 16:17:07.385: INFO/DEBUG(27): ad05a804 1c30681e ff5ef7ff 28001c04 6840d018
05-23 16:17:07.395: INFO/DEBUG(27): ad05a814 d0152800 37101c27 d0112f00 f7ff1c28
05-23 16:17:07.395: INFO/DEBUG(27): code around lr:
05-23 16:17:07.405: INFO/DEBUG(27): ad05ad0c f7ff1c20 bd10ff7b 6804b510 fd70f7ff
05-23 16:17:07.405: INFO/DEBUG(27): ad05ad1c 28001c01 f7ffd102 e002f859 f7ff1c20
05-23 16:17:07.415: INFO/DEBUG(27): ad05ad2c bd10ff6d 4c24b5f0 1c0d1c06 48236a81
05-23 16:17:07.425: INFO/DEBUG(27): stack:
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d80  43d20870  /dev/ashmem/mspace/dalvik-heap/2 (deleted)
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d84  00000354
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d88  00000022
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d8c  ad043693  /system/lib/libdvm.so
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d90  ad07ff50  /system/lib/libdvm.so
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d94  00000024
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d98  00000354
05-23 16:17:07.425: INFO/DEBUG(27):     451c0d9c  ad0170ac  /system/lib/libdvm.so
05-23 16:17:07.425: INFO/DEBUG(27):     451c0da0  00000000
05-23 16:17:07.435: INFO/DEBUG(27):     451c0da4  afe0f2c0  /system/lib/libc.so
05-23 16:17:07.435: INFO/DEBUG(27):     451c0da8  ad080c00  /system/lib/libdvm.so
05-23 16:17:07.435: INFO/DEBUG(27):     451c0dac  00000002
05-23 16:17:07.435: INFO/DEBUG(27):     451c0db0  00000354
05-23 16:17:07.445: INFO/DEBUG(27):     451c0db4  43d20870  /dev/ashmem/mspace/dalvik-heap/2 (deleted)
05-23 16:17:07.445: INFO/DEBUG(27):     451c0db8  df002777
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dbc  e3a070ad
05-23 16:17:07.455: INFO/DEBUG(27): #00 451c0dc0  00000000
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dc4  43d1caa0  /dev/ashmem/mspace/dalvik-heap/2 (deleted)
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dc8  451c0e38
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dcc  451c0e30
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dd0  4000a958  /dev/ashmem/mspace/dalvik-heap/zygote/0 (deleted)
05-23 16:17:07.455: INFO/DEBUG(27):     451c0dd4  ad05ad1d  /system/lib/libdvm.so
05-23 16:17:07.465: INFO/DEBUG(27): #01 451c0dd8  417a0b5c  /data/dalvik-cache/system@framework@core.jar@classes.dex
05-23 16:17:07.475: INFO/DEBUG(27):     451c0ddc  ad054a4f  /system/lib/libdvm.so

A: Unfortunately, if there's an issue with the setup steps for RoboGuice & unit testing, you can get this sort of error.  No magic short answer, but rather a set of steps to follow exactly.
BTW, you're using RoboGuice 1.1 - AbstractAndroidModule & RoboUnitTest no longer exist in RoboGuice 2.0.  RoboGuice 1.1 is deprecated, so best overall solution is to move to newest version according to these instructions Upgrading to 2.0.
However, just in case you're attached to RoboGuice 1.1, here's some steps to follow:

*

*Don't have inconsistent generated code/build files after refactoring/changing package names etc.  Delete generated code, do a Clean & Build, even recreate a new project and copy source files in.

*Have your app code in one project (RoboGuice dependent, Instrumentation/RoboUnitTestCase/AndroidMock independent).  You app code project has within lib: guice-2.0-no_aop.jar and roboguice-1.1.2.jar.

*Have your unit test code in another project that references it (RoboGuice independent, Instrumentation/RoboUnitTestCase/AndroidMock independent).  Instructions here Before You Get Started.  Your test code project has within lib: AndroidMockGenerator.jar.

*In your app project, your App + Module classes look something like this:
package com.mypackage;

import android.app.Instrumentation;
import android.content.Context;

public class MyApplication extends roboguice.application.RoboApplication {

static MyModule myModule;

// this constructor usually called by app
public MyApplication(Context context) {
    super();
    attachBaseContext(context);
}
// This constructor called by unit tests.  This is unfortunately small amount of
// 'abstraction leakage' of unit test needs into app code.
public MyApplication(Instrumentation instrumentation) {
    super();
    attachBaseContext(instrumentation.getContext());
}
public static void setModule(MyModule module) {
    MyApplication.myModule = module;
}
public static MyModule getModule() {
    return MyApplication.myModule;
}
}

And
package com.mypackage;

public class MyModule extends roboguice.config.AbstractAndroidModule {
// this will be injected
protected UsefulObject myUsefulInstance;

public void setUsefulObject(UsefulObject usefulInstance) {
    this.myUsefulInstance = usefulInstance;
}
public UsefulObject getUsefulObject() {
    return this.myUsefulInstance;
}

@Override
protected void configure() {
    bind(UsefulObject.class).toInstance(myUsefulInstance);
}

}

*In your test project, your test case class looks something like this:
import android.test.suitebuilder.annotation.LargeTest;
import com.mypackage.MyApplication;
import com.mypackage.MyModule;
import com.mypackage.UsefulObject;
 //import com.mypackage.UsefulObjectSimpleImplementation;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.testing.mocking.AndroidMock;
import roboguice.test.RoboUnitTestCase;

public class TestMyModule extends RoboUnitTestCase<MyApplication> {

@Override
protected void setUp() throws Exception {
    UsefulObject instance = // new UsefulObjectSimpleImplementation();
                            AndroidMock.createNiceMock(UsefulObject.class);
    MyModule mockModule = new MyModule();
    mockModule.setUsefulObject(instance);
    MyApplication.setModule(mockModule);
    super.setUp();
}

// Make sure you use one of the @*Test annotations AND begin
// your testcase's name with "test"
@MediumTest
public void test01() {
    AndroidMock.expect(MyApplication.getModule().getUsefulObject().
         simpleMethod()).andStubReturn("Hello!");
}

}

*Ensure that for the test project, the AndroidManifest.xml file has the following entry:

   <instrumentation android:name="android.test.InstrumentationTestRunner"
     android:targetPackage="com.mypackage"
     android:label="Tests for com.mypackage"/>

*

*Before running your test, ensure your emulator is started and is running healthily, by running a different, simple "Hello World" app first.  When this succeeds, then run your app.  Lastly, run your test project.

Should work after this.  Best of luck & let me know!

A: Unfortunately this is a bug in Android itself. See the bug report here. The VM crashes when it tries to look for annotations on a Proxy, which is what AndroidMock uses when mocking an interface.
The workaround is to create in instance of a class that implements the interface, as you pointed out in your question. You could try making a pure abstract class that implements the interface without implementing any methods, then use AndroidMock to mock that class instead of the interface. This should avoid the creation of a Proxy.


text:
Q: iPython won't let me finish defining a function I want to define a function with multiple lines in it. But ipython seems to be considering a function complete as early as possible.
$ ipython
In [1]: def whatever():
   ...:     a = 1

In [2]:

How do I make ipython work like it used to, like,
$ ipython
In [1]: def whatever():
   ...:     a = 1
   ...:     print(a)
   ...:

In [2]:

I'm using Python 3.6, iPython --version 7.0.1, and Ubuntu 16.04

A: @daniel-roseman is right, I just needed to upgrade from iPython version 7.0.1 to 7.1.1. For me that was running the command
pipenv --update ipython


text:
Q: Javascript timer read interval from input value I have an input of type text where I add a value.
<input type="text" name="mydat" id="mydat" value="60000" />

This I have a timer which runs every minute.
<script>

window.setInterval(function(){

 //do something here

}, 60000);

</script>

In the code above the interval value is hardcoded.
How can I do this instead:
60000 = #mydat value
So, everytime it loops it reads the value from #mydat ?

A: Use setTimeout recursively instead.
var startTimer = function() {
    console.log("do something here");
    window.setTimeout(startTimer, parseInt($("#mydat").val(), 10));
});

startTimer();

A: "Every time it loops" implies that the value might change - so setInterval is incorrect, you'd need to use setTimeout repeatedly...
function DoSomething() {
    //Do Stuff
    setTimeout(DoSomething, document.getElementById('mydat').value);
}

should do what you need and update the timeout if the contents of the textbox changes (after the next event fires)

A: You can retrieve the value of an input using the value attribute.
var interval = document.getElementById('mydat').value;

window.setInterval(function() {
    // Some code...
}, interval);

or using jQuery
var $interval = $('#mydat').val();

window.setInterval(function() {
    // Some code...
}, $interval);


text:
Q: WriteLineAsync Error I have this code that I am trying to use to convert a JSON object into a CSV file:
 private async Task WriteListrackClient (SyncConfig settings, ISyncMonitor monitor)
   {
       ICollection<OrderComposite> orders = null;
       string jsonOrders = File.ReadAllText(settings.productJsonConfig.FullJSONOrderFilePath);
       orders = JsonConvert.DeserializeObject<ICollection<OrderComposite>>(jsonOrders);
       using (StreamWriter writer = File.CreateText(settings.listrakProductFeed.ListrakCustomersFileLocation))
       {
           await writer.WriteLineAsync((orders.Select(x => string.Join(",",x.Customer.EmailAddress.ToString(), x.OrderId.Value.ToString(), x.DateCreated.Value.ToString(), x.TotalSalePrice.Value.ToString(), x.TotalSaleTax.Value.ToString(),0,0,"","","","",x.TotalDiscount.Value.ToString(),"online"))));
       };
   }

I am getting two errors I need some help with.  The first is on the writer.WriteLineAsync method.  It is: The best overloaded method match for 'System.IO.TextWriter.WRiteLineAsync(char[]) has some invalid arguments.
The second is on the orders.Select statement: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable 'to 'char[]'
It seems to me the second error is a result of the first.  I am trying to use LINQ to pull in values as you can see.  Can anyone see what I am doing wrong?
Thanks.

A: It's kind of hard to see with the current formatting, but I think that at least part of your issue is that you're not doing a ".ToArray()" after your ".Select()"


text:
Q: Submit form without attached file I want to create JSF form with attached file. But also to give a option form the users to submit the for without attach file. I don't want this to be mandatory.
<h:form id="form" enctype="multipart/form-data">

            <h:inputText id="name" value="#{contacts.name}" pt:placeholder="Name*:"/>

        <h:inputTextarea value="#{contacts.comment}" pt:placeholder="Comment*:"/>

    <h:inputFile id="fileToUpload" value="#{contacts.file}" required="true" requiredMessage="No file selected ..."/>
    <h:commandButton value="Upload" action="#{contacts.upload()}">
        <f:ajax execute="fileToUpload" />
    </h:commandButton>
    <h:message showDetail="false" showSummary="true" for="fileToUpload" style="color:red"/>

        <h:commandLink id="submitlink" class="link" value="submit" action="#{contacts.sendEmail}" >
            <f:ajax render="@form" execute="@form" onevent="handleDisableButton" resetValues="true"/>
        </h:commandLink>

    <h:outputText id="output" value="#{contacts.result}" />
</h:form>

Is there a way to implement this because now if I try to submit the form I always get message No file selected ...?
Also when I attach a file using the button upload button no message appears for successful file upload.

A: You have your inputFile as required. That is why you have to upload first always.
Also, if you are not seeing any message it's because you are not rendering again your h:message. Try using this in your managed bean:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds()
.add("idMessage");

A: change
<h:inputFile id="fileToUpload" value="#{contacts.file}" required="true" requiredMessage="No file selected ..."/>

to
<h:inputFile id="fileToUpload" value="#{contacts.file}" />


text:
Q: Make Background Job generated files available for Download I have an action in my controller that generates reports of site usage based on date range selected (Start and End Date) with the condition that the start and end date has to be within the current quarter.
I want to implement a background job that will generate this report at the end of each quarter and make it available for download as a link on the view page.
Each quarter is 3 months and so for example - On March 31st 11:59 PM, I want it to generate the report of site usage from Jan 1st to March 31st and make it available for download in the view page.
I prefer using the whenever gem if possible, since i am already using it for re-indexing the models at definite intervals. All possible suggestions are welcomed !!
Please help me with how to go about this !!

A: I would recommend the Gems DelayedJob (2.1 for Rails 3.0+) or Resque for creating background jobs, placing them on multiple queues, and processing them later. There are good Railscasts for both.

A: You can add class ReportGenerator and use it in rails runner. This class will be calculate a date range, generate report and saves in under public direcotory of your application. You must notice that every file in public direcotry is accessible for anybody. If you wan't some authorization to access this file you can put in other directory for example - unpublic and serve it via your app (auth purpose) using X-Sendfile http header for Apache.
ReportGenerator.new(:quater => 4).generate

For recognize which quater you have:
quaters => {
  1 => "definition of 1st quater (date ranges)",
  2 => "definition of 2nd quater (date ranges)",
  3 => "definition of 3rd quater (date ranges)",
  4 => "definition of 4th quater (date ranges)".
}
quater = Date.today.month / 3


text:
Q: Catching execSync errors I'm using execSync to run a soffice command. The issue I'm having is when an error is thrown execSync just logs the error to the console there is no way of catching it. I've tried using a try catch statement but it still just logs the error to the console.
function convertToPdf(filepath, destpath) {
  var cmd = 'sofice command';

  try {
    var res = execSync(cmd, { encoding: 'utf8' });
  } catch (e) {
    console.log("Errors:", e);
  }

  console.log("res:", res);
}

convertToPdf("test.docx");

I run this and get this back:
Error: source file could not be loaded
res:

Notice how my catch statement is never logged even though an error was clearly thrown but another Error: message is logged automatically because I'm not logging that.

A: try this:
function myExecSync(command, trim = true, cwd = pwd, opts = {}) {
  const ret = execSync(command, { cwd, ...opts }).toString('utf-8');
  return trim ? ret.trim() : ret;
}

And write stdio: 'pipe' manually to prevent childprocess.stderr output to the console. like
myExecSync(command, true, cwd, { stdio: 'pipe' })


text:
Q: In what condition would a thread exit or stop running I am writing a server application in which there is a thread deployed to read/write many sockets connecting to clients. My manager tells me that it is not a good design, because if the thread  aborts due to unknown reason then all the read/write work will stop forever.
So I wonder in what conditions will a thread abort, except the case we return from the Run() function of a thread. Do we need consider the case that the thread stops running abnormally?

A:
I am writing a server application in which there is a thread deployed to read/write many sockets connecting to clients.

Not a good design. There should be at least one thread per client, in some circumstances two: one to read and one to write. If you're dealing in blocking I/O, servicing one client could block out all the others. (If you're dealing in non-blocking I/O you don't need threads at all.)

My manager tells me that it is not a good design, because if the thread aborts due to unknown reason then all the read/write work will stop forever.

He's right, for more reasons than he is advancing.

A: It depends. One thread per client can be a bad thing scalability wise, especially if the thread doesn't do that much work per client. In that circumstance it can be better to have a thread that handles a number of clients, the idea to achieve a good balance between the number of threads and having them do a decent amount of work.
If on the other hand each thread is doing a lot of work per client then one thread isn't such a bad idea, the overhead of the thread not being significant in comparison to the work load.
So setting that aside, a thread will abort if your code is written so that the thread returns or self-terminates. If another thread in your program knows the thread's handle/id then the library you're using may have a function with a name like thread_kill(). That would allow that other thread to kill this thread, though that's almost always a bad idea.
So as far as I'm concerned your thread will only abort and disappear if you've written your code to make that happen deliberately.
Handling exceptions is probably best done in its entirety within the thread where the exception arose. I've never tried to do otherwise (still writing in pure C), but the word is that it's difficult to handle them outside the thread. Irrespective of whether each thread handles one or many clients you still have to handle all errors and events within thread.
It may be simpler to get that correct if you write I so that a thread handles handles a single client. Getting it wrong could lead to a thread getting into a stalled state (eg waiting for the client that is listening too) and accumulating those as time goes past will eventually kill your whole system.


text:
Q: Animation freeze with swipelayout after adding 2 new features (swipelayout + animation) my ui freezes.
I have a recyclerview which includes movie objects. If i add/remove/modify a movie i call my moviemanager because there's a notify concept (all views which want to use the data have to be registered on this manager).
This all works fine before i added the new features.
I use this swipelayout:
https://github.com/daimajia/AndroidSwipeLayout
Currently the items looks like this:

After swiping:

The freeze is always reproducible if i have 4 items. I swipe on the second item and delete it. Then it will dissapear like i want. After im swiping the "new" second item there's a freeze for like 10-15 seconds.
The layout xml of the item:
<com.daimajia.swipe.SwipeLayout
    android:id="@+id/item_movie_swipe_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/item_movie_swipe_bottom_wrapper"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="#ff0000">

            <TextView
                android:id="@+id/item_movie_bottom_delete_desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableTop="@drawable/ic_delete_white_24dp"
                android:text="@string/delete"
                android:textColor="#fff"
                android:layout_gravity="center"
                android:padding="10dp"/>
        </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <ImageView
            android:id="@+id/item_movie_list_poster"
            style="@style/image_border_style"
            android:layout_width="68dp"
            android:layout_height="100dp"
            android:layout_marginRight="3dp"
            android:background="@android:color/black"/>

        <TextView
            android:id="@+id/item_movie_list_name_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="3dp"
            android:layout_toEndOf="@+id/item_movie_list_poster"
            android:layout_toRightOf="@+id/item_movie_list_poster"
            android:gravity="center|left"
            android:padding="3dp" android:text="name"/>

        <TextView
            android:id="@+id/item_movie_list_genre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/item_movie_list_name_year"
            android:layout_marginBottom="3dp"
            android:layout_toEndOf="@+id/item_movie_list_poster"
            android:layout_toRightOf="@+id/item_movie_list_poster"
            android:padding="3dp"
            android:text="Drama - Komödie - Action" android:textColor="@color/item_textyear"
            android:textSize="12dp"/>

        <TextView
            android:id="@+id/item_movie_list_viewed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/item_movie_list_poster"
            android:layout_toRightOf="@+id/item_movie_list_poster"
            android:paddingLeft="3dp" android:text="Gesehen: "
            android:textColor="@color/accept"
            android:textSize="12dp"/>
    </RelativeLayout>
</com.daimajia.swipe.SwipeLayout>

Relevant code of the adapter:
  @Override
  public void onBindViewHolder(final CDMMoviesAdapter.IC_ViewHolder p_Holder, final int p_iPosition) {

    // more unimportant code...

    p_Holder.m_SwipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

    // Drag From Right
    p_Holder.m_SwipeLayout.addDrag(SwipeLayout.DragEdge.Right, p_Holder.m_SwipeLayout.findViewById(R.id.item_movie_swipe_bottom_wrapper));

    // Handling different events when swiping
    p_Holder.m_SwipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
      @Override
      public void onClose(SwipeLayout layout) {
        //when the SurfaceView totally cover the BottomView.
      }

      @Override
      public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
        //you are swiping.
      }

      @Override
      public void onStartOpen(SwipeLayout layout) {

      }

      @Override
      public void onOpen(SwipeLayout layout) {
        //when the BottomView totally show.
      }

      @Override
      public void onStartClose(SwipeLayout layout) {

      }

      @Override
      public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
        //when user's hand released.
      }
    });

    p_Holder.m_SwipeLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View p_View) {
        if((((SwipeLayout) p_View).getOpenStatus() == SwipeLayout.Status.Close)) {
          Intent l_Intent = new Intent();
          Bundle l_Bundle = new Bundle();
          l_Bundle.putLong(CDMMovieDetailsActivity.ARG_MOVIE, l_MovieID);
          l_Intent.putExtras(l_Bundle);
          l_Intent.setClass(l_Context, CDMMovieDetailsActivity.class);
          l_Context.startActivity(l_Intent);
        }
      }
    });

    p_Holder.m_tvDelete.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View p_View) {
        Animation l_DeleteAnimation = AnimationUtils.loadAnimation(l_Context, R.anim.slide_out);
        l_DeleteAnimation.setAnimationListener(new Animation.AnimationListener() {
          @Override
          public void onAnimationStart(Animation animation) {
          }

          @Override
          public void onAnimationRepeat(Animation animation) {
          }

          @Override
          public void onAnimationEnd(Animation animation) {
            mItemManger.removeShownLayouts(p_Holder.m_SwipeLayout);
            CDMMovieManager.getInstance().removeMovieID(m_List, m_MovieIDs.get(p_iPosition));
            mItemManger.closeAllItems();
          }
        });

        p_Holder.m_View.startAnimation(l_DeleteAnimation);
      }
    });

    // mItemManger is member in RecyclerSwipeAdapter Class
    mItemManger.bindView(p_Holder.itemView, p_iPosition);

    // more unimportant code...
  }

  /**
   * This class is the viewholder. For internal use only.
   */
  public static class IC_ViewHolder extends RecyclerView.ViewHolder {

    /**
     * Constructor
     *
     * @param p_View the view
     */
    public IC_ViewHolder(View p_View) {
      super(p_View);

      m_View = p_View;
      m_SwipeLayout = (SwipeLayout) p_View.findViewById(R.id.item_movie_swipe_layout);

      m_tvNameYear = (TextView) p_View.findViewById(R.id.item_movie_list_name_year);
      m_ivPoster = (ImageView) p_View.findViewById(R.id.item_movie_list_poster);
      m_tvGenre = (TextView) p_View.findViewById(R.id.item_movie_list_genre);
      m_tvViewed = (TextView) p_View.findViewById(R.id.item_movie_list_viewed);

      m_tvDelete = (TextView) p_View.findViewById(R.id.item_movie_bottom_delete_desc);
    }

    public View m_View;
    public SwipeLayout m_SwipeLayout;

    public TextView m_tvNameYear;
    public ImageView m_ivPoster;
    public TextView m_tvGenre;
    public TextView m_tvViewed;

    public TextView m_tvDelete;
  }

In CDMMovieManager.getInstance().removeMovieID(m_List, m_MovieIDs.get(p_iPosition)); the movie will be removed and all registered views will be notified. In this case the fragment of this adapter will call m_Adapter.notifyDataSetChanged();
The animation file:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="250"
        android:fromXDelta="0%"
        android:toXDelta="-100%"/>
</set>

I tried things like View.clearAnimation() or Animation.setAnimationListener(null) but i always get this problem.
Plase ask if you need more informations.
Update:
Problem only occures if i try to swipe the next item. (For example delete 2nd item. After that try to swipe the 3rd item which is the new second item -> freeze on the item i tried to swipe). The freeze can only be removed on swiping on any other item.

A: I solved my problem. This answer helped me: How to animate RecyclerView items when they appear
I added this code to my adapter:
@Override
public void onViewDetachedFromWindow(IC_ViewHolder p_Holder) {
  p_Holder.m_View.clearAnimation();
}


text:
Q: Google BigQuery API force MaxResult I am trying to run a query on BigQuery table and store the the result in locally.
getQueryResults API has maxResult parameter. Which says I can specify maximum number of rows to fetch. However, even after specifying it to 10,000 it fetches only few rows and in random manner.
If I specify it to small number, i.e. 10, then it works perfectly fine.
is there a way I can force to fetch 10,000 rows ?
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/getQueryResults

A: getQueryResults returns up to maxResult rows in the response. If it returns fewer rows, you need to pass the pageToken returned in the response to another getQueryResults call in order to fetch the next page of rows from the server.
The client libraries implement paging so that you don't need to do this yourself


text:
Q: Enum class to constructor I am trying to understand how to pass enum variables to contructor in Java, here is my code. I am totally new in programming. Thank u for all help
public class PieceOfJewellery extends Valuable {
    private int amountOfGemstones;
    private enum Material {gold, silver};
    private Material material1 = Material.silver;
    private Material material2 = Material.gold;

    public PieceOfJewellery(String name, int amountOfGemstones) {
        super(name);
        this.amountOfGemstones = amountOfGemstones;

    }
}

A: Try this:
public PieceOfJewlery(String name, int amountOfGemstones, Material material) {
    (...)
}

A: So something like this?
public PieceOfJewellery(String name, int amountOfGemstones, Material mat) {
    super(name);
    this.amountOfGemstones = amountOfGemstones;
    this.material1 = mat;
}

You can use enums like any other type when you just want to pass them around.

A: As you write in your question, Enum is a class, so pass it as you would pass any other type defined by a class.


text:
Q: Animation not working on all devices
My animation works on SGS2 for example, but not on SGS 1 or the emulator (For some reason other animation that I built just the same works perfectly fine on every device)
In addition, even on devices that run the animation, when OnPostExcute is called the animation stops, while in other similar animations, which are also nested in ASyncTask, the animation doesn't stop until the stop() is called
The dimensions of each frame are 512x512
Here's the animation-list file:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">

    <item android:drawable="@drawable/logo0" android:duration="35" />
    <item android:drawable="@drawable/logo1" android:duration="35" />
    <item android:drawable="@drawable/logo2" android:duration="35" />
    <item android:drawable="@drawable/logo3" android:duration="35" />
    <item android:drawable="@drawable/logo4" android:duration="35" />
    <item android:drawable="@drawable/logo5" android:duration="35" />
    <item android:drawable="@drawable/logo6" android:duration="35" />
    <item android:drawable="@drawable/logo7" android:duration="35" />
    <item android:drawable="@drawable/logo8" android:duration="35" />
    <item android:drawable="@drawable/logo9" android:duration="35" />
    <item android:drawable="@drawable/logo10" android:duration="35" />
    <item android:drawable="@drawable/logo11" android:duration="35" />
    <item android:drawable="@drawable/logo12" android:duration="35" />
    <item android:drawable="@drawable/logo13" android:duration="35" />
    <item android:drawable="@drawable/logo14" android:duration="35" />
    <item android:drawable="@drawable/logo15" android:duration="35" />
    <item android:drawable="@drawable/logo16" android:duration="35" />
    <item android:drawable="@drawable/logo17" android:duration="35" />
    <item android:drawable="@drawable/logo18" android:duration="35" />
    <item android:drawable="@drawable/logo19" android:duration="35" />
    <item android:drawable="@drawable/logo20" android:duration="35" />
    <item android:drawable="@drawable/logo21" android:duration="35" />
    <item android:drawable="@drawable/logo22" android:duration="35" />
    <item android:drawable="@drawable/logo23" android:duration="35" />
    <item android:drawable="@drawable/logo24" android:duration="35" />
    <item android:drawable="@drawable/logo25" android:duration="35" />
    <item android:drawable="@drawable/logo26" android:duration="35" />
    <item android:drawable="@drawable/logo27" android:duration="35" />
    <item android:drawable="@drawable/logo28" android:duration="35" />
    <item android:drawable="@drawable/logo29" android:duration="35" />
    <item android:drawable="@drawable/logo30" android:duration="35" />
    <item android:drawable="@drawable/logo31" android:duration="35" />
    <item android:drawable="@drawable/logo32" android:duration="35" />
    <item android:drawable="@drawable/logo33" android:duration="35" />
    <item android:drawable="@drawable/logo34" android:duration="35" />
    <item android:drawable="@drawable/logo35" android:duration="35" />
    <item android:drawable="@drawable/logo36" android:duration="35" />
    <item android:drawable="@drawable/logo37" android:duration="35" />
    <item android:drawable="@drawable/logo38" android:duration="35" />
    <item android:drawable="@drawable/logo39" android:duration="35" />
    <item android:drawable="@drawable/logo40" android:duration="35" />
    <item android:drawable="@drawable/logo41" android:duration="35" />
    <item android:drawable="@drawable/logo42" android:duration="35" />
    <item android:drawable="@drawable/logo43" android:duration="35" />
    <item android:drawable="@drawable/logo44" android:duration="35" />
    <item android:drawable="@drawable/logo45" android:duration="35" />
    <item android:drawable="@drawable/logo46" android:duration="35" />
    <item android:drawable="@drawable/logo47" android:duration="35" />
    <item android:drawable="@drawable/logo48" android:duration="35" />
    <item android:drawable="@drawable/logo49" android:duration="35" />
    <item android:drawable="@drawable/logo50" android:duration="35" />
    <item android:drawable="@drawable/logo51" android:duration="35" />
    <item android:drawable="@drawable/logo52" android:duration="35" />
    <item android:drawable="@drawable/logo53" android:duration="35" />
    <item android:drawable="@drawable/logo54" android:duration="35" />
    <item android:drawable="@drawable/logo55" android:duration="35" />
    <item android:drawable="@drawable/logo56" android:duration="35" />
    <item android:drawable="@drawable/logo57" android:duration="35" />
    <item android:drawable="@drawable/logo58" android:duration="35" />
    <item android:drawable="@drawable/logo59" android:duration="35" />

</animation-list>

Here's the code that should start the animation:
    final ImageView logoAnimation = (ImageView) findViewById(R.id.logoAnimation);
    logoAnimation.setImageResource(R.drawable.none);
    logoAnimation.setBackgroundResource(R.drawable.logo_animation);
    final AnimationDrawable frameAnimation = (AnimationDrawable) logoAnimation
            .getBackground();

    class Init extends AsyncTask<Void, Boolean, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            frameAnimation.start();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (!isNetworkAvailable()) {
                return false;
            } else {
                try {
                    CheckAll();
                } catch (IOException e) {
                }
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            frameAnimation.stop();
            if (result) {
                Intent openMain = new Intent(c, Main.class);
                startActivity(openMain);
                Splash.this.finish();
            } else {

                Builder alertDialog = new AlertDialog.Builder(Splash.this);
                alertDialog
                        .setMessage(getString(R.string.noInternetConnection));
                alertDialog.setNegativeButton(getString(R.string.close),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Splash.this.finish();
                            }
                        });
                alertDialog.show();
            }
        }

    }
    new Init().execute();

And I don't know if it is needed, but here's the layout xml file:
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/splash"
        android:orientation="vertical" >

        <ImageView
        android:id="@+id/logoAnimation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/logo0"
        android:contentDescription="@null" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/logoAnimation"
        android:layout_centerHorizontal="true"
        android:text="@string/loading"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

A: Maybe you can use the built in ProgressBar and change it's drawable to whatever you want.


text:
Q: Swift - Child controller causes 'Receiver has no segue with identifier' I have a ViewController that has a child controller with a dynamic tableview.
On tapping a table cell I need to segue to a new view.
I've tried all kinds of methods, including directly control dragging from the cell (resulting in a 'detached controller' warning) with little success and the current situation is as follows.
Child Controller (currentName, currentType are globals that can be picked up by the parent, myHome)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    currentName = "John"
    currentType = 1
    let segueVC = myHome()
    segueVC.segueToMain()
}

Parent Controller (myHome)
func segueToMain() {
    dispatch_async(dispatch_get_main_queue()){
        self.performSegueWithIdentifier("home_myMain", sender: self)
    }
}

I know this is probably horrendous but it appears to work fine in that it stores the data and gets to the parent function. However the attempt to segue causes the 'Receiver has no segue with identifier' error. The segue id is exactly correct. It links to a Navigation Controller.
I have a feeling that I need some delegates etc but I'm not really sure how to deal with them. Getting rid of the navigation controller and segue direct to view didn't make any difference.
Any help with how to get this segue to trigger would be greatly appreciated.
EDIT
In relation to answers suggesting the segue direct from the child, here is the setup which seems to result in a 'detached' controller error. For the record, I would love to use this method but all attempts failed.
The Parent Controller (A) builds a PageMenu class that gets its page structure from Controller B. B has a table with cells directly segued to another view.
A constructs the menu as follows
self.addChildViewController(self.pageMenu!)
self.view.addSubview(pageMenu!.view)
self.pageMenu!.didMoveToParentViewController(self)

PageMenu uses class B as the template for each menu page.
There is no physical link between A and B on the storyboard - only that the class for A sets B as a child.
Segues from B fail with a 'detached controller' error so maybe there's something I'm missing from the child setup?
Thanks

A: You can't just allocate a new instance of your parent view controller and ask it to perform a segue - As you are instantiating the view controller directly, it won't be associated with the storyboard, this is why you get an exception stating that that view controller doesn't have a segue of the specified identifier.
Even if you did instantiate a new instance from the storyboard you would still get an error as that new instance wouldn't be on screen, resulting in a message that you attempted to present a view controller on a view controller that isn't in the view hierarchy.
You need your child view controller to have a reference to the parent view controller instance that contains it and then invoke the segue using that instance.
Also, there is no need for the dispatch_async - the tableview delegate method will be invoked on the main queue already.
Finally, by convention, class names start with an upper case letter, so myHome should be MyHome (or even better, something like MyHomeViewController)


text:
Q: Why isn't Android Studio Profiler showing activity on AsyncTask threads I have two AsyncTask threads that each move files from one folder to another however this activity is not showing on the Android Studio Profiler
Honestly completely lost as every now and then it will show activity for 200ms but only once and on one of the threads
In MainActivity:
    new AsyncThread().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,  true);
    new AsyncThread().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,  false);

AsyncTask:
protected Void doInBackground(Boolean... Upper) {
    while(startPoint <= (endPoint)){
       ...

        try {
            if (sourceFile.exists()) {
                try{
                    sourceFile.renameTo(targetLocation);
                    publishProgress();
                    startPoint++;
                } catch(Exception e){
                    System.out.println("Error");
                }
            } else {
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            Log.i("failed: ", "nullPointer");
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("failed: ", "exception e");
        }
        try {Thread.currentThread().sleep((int)(1000));
       } catch (InterruptedException e) {}
    }

    return null;
}
@Override
protected void onProgressUpdate(Void... progress) {
    try{
        MainActivity.semaphore.acquire();
        MainActivity.noOfFilesTransfered++;
        MainActivity.semaphore.release();
    } catch(Exception e){}
}

A: Threads that are sleep()-ing don't show activity on the profiler, because they are not running. Your threads spend most of their time sleeping.
It is not immediately clear what that 200ms of activity represents, but you can rest assured that your profiler is correct, and that 200ms represents a thread that is actively running.


text:
Q: Casting a generic object to an object with an interface of the generic type I have the following code:
public class EntityFilter<T>
{}

public interface IEntity
{}

public class TestEntity : IEntity
{}

class Program
{
    static void Main(string[] args)
    {
        var ef = new EntityFilter<TestEntity>();

        DoSomething((EntityFilter<IEntity>)ef); // <- casting fails
    }

    public static void DoSomething(EntityFilter<IEntity> someEntityFilter)
    {
    }
}

Visual Studio says:
Cannot convert type 'ConsoleApplication1.EntityFilter<ConsoleApplication1.TestEntity>' to 'ConsoleApplication1.EntityFilter<ConsoleApplication1.IEntity>'

I cannot convert the DoSomething method to be generic and accept EntityFilter<T> because in my application the type of T is unknown at the moment of DoSomething call. The type will be determined later inside of DoSomething using reflection.
How can I pass the ef variable to the DoSomething method without making the DoSomething method generic?

A: If EntityFilter<T> could be derived from an interface and that interface had a covariant generic parameter, you could do what you are asking without generics in the method.
Notice the "out" keyword in the IEntityFilter<out T> definition.
public class Program
{
    static void Main(string[] args)
    {
        var ef = new EntityFilter<TestEntity>();

        DoSomething(ef);
    }

    public static void DoSomething(IEntityFilter<IEntity> someEntityFilter)
    {
    }
}

public interface IEntityFilter<out T>
{ }

public class EntityFilter<T> : IEntityFilter<T>
{ }

public interface IEntity
{ }

public class TestEntity : IEntity
{ }


text:
Q: Unable to clone git repository When I clone the git repository, I got below error,
Cloning into 'samples'...
fatal: unable to access 'https://182.101.71.48:12453/devel/git/samples/samples.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Please, help me. Thanks in advance.

A: Apply below command,
git config --global http.sslVerify false

then, clone git repository.


text:
Q: np.where with datetimes producing Unix timestamp I have a dataframe with a column that has time stamp data with some nulls. I am trying to replace the nulls with the earliest date in the column using np.where.
The dataframe looks like this:
index   date
1       2019-06-30 22:40:25.799000+00:00
2       2019-06-30 22:40:25.799000+00:00
3       NaN

I'm writing my code as:
mini = df['date'].min()
df['date'] = np.where(df['date'].isnull(), mini, df['date'])

but the resulting column for date gives me a Unix Timestamp, with the NaN's filled correctly:
index       date
1       1552685510470841000
2       1555706405810536000
3       2015-05-07 13:49:51.072000+00:00

Why does this happen and how do I get it to all be timestamps?

A: numpy has a bias toward treating array's elements as floats. It saw NaN and Timestamp are both representable as floats so it converts df['date'] to float.
You can use fillna instead:
df['date'].fillna(mini, inplace=True)


text:
Q: How to make Break even trigger more than one time in one entry I now trying to make Break Even Code trigger more than one time,
example EA entry is 1.28000 and stop loss 1.28500
if current price reach 1.175000(50pips), sl move to break even such as to 1.28000(5pips).
EA will not make more modify order after condition are meet.
so how to trigger break even again if price reach 1.17000(100pips), sl move to (1.175000)(50 pips)
and again price reach 1.165000(150pips),sl move to 1.17000(100pips)
I want to make
BE_B_M(sl move to(example:5))

and
BE_B_T(price reach(example:50))

as variable and every time price reach target variable change to next value
so became
BE_B_M(sl move to(example:50)) and BE_B_T(price reach(example:100))

The entire code is as follows
extern double  BE_T_1      = 50;
extern double  BE_M_1      = 5;

extern double  BE_T_2      = 100;
extern double  BE_M_2      = 50;

extern double  BE_T_3      = 150;
extern double  BE_M_3      = 100;

double BE_S_M;
double BE_S_T;

void MOVE_BE_1()

  {
   for(int b=OrdersTotal()-1;b>=0;b--)
     {

      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()!=M_Number)continue;
      if(OrderSymbol()==Symbol())
         if(OrderType()==OP_BUY)
            if(Bid-OrderOpenPrice()>BE_S_T*Pips)
               if(OrderOpenPrice()>OrderStopLoss())
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
                     Print("eror");
     }

   for(int s=OrdersTotal()-1;s>=0;s--)
     {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()!=M_Number)continue;
      if(OrderSymbol()==Symbol())
         if(OrderType()==OP_SELL)
            if(OrderOpenPrice()-Ask>BE_S_T*Pips)
               if(OrderOpenPrice()<OrderStopLoss())
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
                     Print("eror");
     }

  }

i expect sl will move after price reach every 50pips from entry

A: Here you can put all the 3 break even levels on one function.
Note: you can use 1 for-loop for both OP_BUY and OP_SELL
Here is my OnInit()
// Global variable
double point;

int OnInit()
  {
   if(Digits == 5 || Digits == 3) point=Point*10;
   else point=Point;
   return(INIT_SUCCEEDED);
  }

Here is the BreakEven() function
//+------------------------------------------------------------------+
//| Break even the trade at 3  levels                                |
//+------------------------------------------------------------------+
void BreakEven()
  {
   // get the stop level for that symbol
   double stopLevel = SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL)*Point;

   for(int i=OrdersTotal()-1;i>=0;i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=M_Number)continue;
      if(OrderSymbol()!=Symbol())continue;

      if(OrderType()==OP_BUY)
        {
         double profitPips=Bid-OrderOpenPrice();
         double newSL=OrderStopLoss();

         if(profitPips>=BE_T_1*point && OrderStopLoss()<OrderOpenPrice()) // Break Even
           {
            newSL=OrderOpenPrice()+BE_M_1*point;
           }
         else if(profitPips>=BE_T_3*point) // 150/100
           {
            newSL=OrderOpenPrice()+BE_M_3*point;
           }
         else if(profitPips>=BE_T_2*point) // 100/50
           {
            newSL=OrderOpenPrice()+BE_M_2*point;
           }

         if(newSL>=OrderStopLoss()+Point && newSL<Bid-stopLevel)
            if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
               Print("Error at BE: ",GetLastError());
        }
      else if(OrderType()==OP_SELL)
        {
         double profitPips=OrderOpenPrice()-Ask;
         double newSL=OrderStopLoss();
         if(profitPips>=BE_T_1*point && (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0)) // Break Even
           {
            newSL=OrderOpenPrice()-BE_M_1*point;
           }
         else if(profitPips>=BE_T_3*point) // 150/100
           {
            newSL=OrderOpenPrice()-BE_M_3*point;
           }
         else if(profitPips>=BE_T_2*point) // 100/50
           {
            newSL=OrderOpenPrice()-BE_M_2*point;
           }

         if(newSL<=OrderStopLoss()-Point && newSL>Ask+stopLevel)
            if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
               Print("Error at BE: ",GetLastError());
        }
     }

  }

I didn't test this myself in a trade, but it should work.


text:
Q: How can I stretch the image in imagebutton to the whole area of the imagebutton? Here is a picture that will help you understand my problem:

I want to stretch the image shown inside ImageButton to the whole area of the ImageButton.
As you can see, the picture with the number 1 only take about 95% of the ImageButton and you can also see the boundaries of the ImageButton.
I still want to maintain the image button style
Here's how I am using ImageView:
<ImageButton
    android:id="@+id/secondActivityBbuttonDownRight"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="0.5"
    android:scaleType="fitStart"
    android:src="@drawable/111" />

I think I found out what is my problem.
I need a custom component that can contain only an image and have a clicking effect.

A: android:scaleType="fitXY" tested and works correctly.

A: You can also use
android:scaleType="centerCrop"
android:padding="0dp"

A: ImageButton is ImageView.
If you want your image to fill button
than set android:scaleType="fitXY", so the image you set in android:src will be stretched to fill whole image button.
ImageButton has a background under your image and padding.
If you do not want background
set android:background="@android:color/transparent".
If you do not want padding
set android:padding="0" or set background without padding.

A: Use below code :-
<ImageButton
        android:id="@+id/secondActivityBbuttonDownRight"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:scaleType="fitStart"
        android:background="@drawable/111" />

A: You should consider creating a 9-patch image to make the image fit correctly on an ImageButton in case you need to stretch it, but you don't want the image to become distorted.
To have a button with an image that completely covers it, you can use something like this:
<ImageButton android:id="@+id/iconBtn"
  android:layout_width="64dip"
  android:layout_height="64dip"
  android:src="@drawable/icon_button"
  android:scaleType="fitCenter"
  android:background="#00000000"/>

For a full tutorial on creating buttons with custom skins and the use of selectors to manage their states, you can check a tutorial I've written some time ago here (Creating a custom Android button with a resizable skin).

A: If your image "111" has no padding itself then simply use android:background"@drawable/111"

A: Just set this two attributes on the ImageButton:
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="centerCrop"

With those, you will get the provided src to be stretched, and also if you put some specific width and height on that ImageButton you won't get a rectangle around it.


text:
Q: How to take out x and y from my list so I can use it to create a graph
So I made my list but after that I don't know how to take out of it my x and y so I can use it later to create a graph

import random
import numpy as np
import matplotlib.pyplot as plt

tabuletson = []

for i in range(0, 10):
    x = round(random.uniform(-1000,1000),2)
    y = (2*x+1)
    tabuletson.append([x,y])

print(tabuletson)

wielomian = np.poly1d(np.polyfit(x,y,3))
linia = np.linspace(-2000,2000,2000)

plt.scatter(x,y)
plt.plot(linia,wielomian(linia))
plt.show()

A: The np.polyfit and plt.scatter functions you are using require separate lists of X and Y coordinates.
Try:
import random
import numpy as np
import matplotlib.pyplot as plt

tabuletson_x = []
tabuletson_y = []

for i in range(0, 10):
    x = round(random.uniform(-1000,1000),2)
    y = (2*x+1)
    tabuletson_x.append(x)
    tabuletson_y.append(y)

print(tabuletson_x)
print(tabuletson_y)

wielomian = np.poly1d(np.polyfit(tabuletson_x,tabuletson_y,3))
linia = np.linspace(-2000,2000,2000)

plt.scatter(tabuletson_x,tabuletson_y)
plt.plot(linia,wielomian(linia))
plt.show()

Note: referencing x and y after the for cycle will give you the last values from the randomly generated list:
list of x vals:  [-8.78, 554.81, -693.22, 955.8, 88.95, 235.55, -108.67, -804.08, 494.65, 754.58]
list of y vals:  [-16.56, 1110.62, -1385.44, 1912.6, 178.9, 472.1, -216.34, -1607.16, 990.3, 1510.16]
x:  754.58
y:  1510.16

For more info:
PyPlot Scatter documentation
PolyFit documentation

A: I think that this is a better way to do what you want according of how plt.scatter and plt.plot work. Hope it works as you want!
import random
import numpy as np
import matplotlib.pyplot as plt

x = []; y = []

for i in range(10):
    x.append(round(random.uniform(-1000,1000),2))
    y.append(2*x[i]+1)

wielomian = np.poly1d(np.polyfit(x,y,3))
linia = np.linspace(-2000,2000,2000)

plt.scatter(x,y)
plt.plot(linia,wielomian(linia))
plt.show()

A: All you have to do is to add one line of code after and outside your for loop. This command will create two lists containing x and y values. You can use the same variable names x and y.
x, y = zip(*tabuletson)

A: Your x and y are stored in your list tabuletson. Like this: [[x0,y0], [x1,y1], ..., [x,y]]
So you can, for example, get the value of x1 and y1 with x1 = tabuletson[1][0] and y1 = tabuletson[1][1]
Is that your question ?

A: tabuletson = np.array(tabuletson)
X, Y = tabuletson[:,0], tabuletson[:,1]

X will have all your xs from list
And, Y will have all your ys from list


text:
Q: What is the meaning of "a sense of failure over never..."
Logue is a man who must cure his own demons – a sense of failure over never having made it as a professional actor – and who is everywhere patronised as a colonial.

Sense of failure didn't allow him to become an actor or he didn't become an actor and it oppresses him now?

A: The word over here means: with regard to the subject of, in terms of, concerning, etc.
a sense of failure over [with regard to, about, concerning, on the subject of] never having made it as a professional actor
With words relating to situations, you will often find this word over,

*

*We had a disagreement over the money she owed me.

*I felt very bad over the situation that had developed.

*He had a sense of failure over the way the situation was handled.

A: "never having made it as a professional actor" does not mean that he never became a professional actor. It means that he did, but was not successful in that profession. He was always the chap who came on stage carrying a spear but with no words to speak, rather than the man who played Hamlet.


text:
Q: Masked functions when a package is loaded, but not reciprocal? I had the dplyr package loaded when I loaded the stringi package.  This message appeared (I dropped a couple of lines re ggplot2 being masked for %+%).
require(stringi)
Loading required package: stringi

Attaching package: 'stringi'

The following object is masked from 'package:dplyr':

    %>%

When I returned to using dplyr, I reloaded it.
require(dplyr)

Why did that last call not warn me that %>% is masked from stringi?
More generally, if you don't remember to reload a package (and presumably restore its use of some function masked by another package, how do you figure out the masking?

A: You can reload dplyr using the devtools package.
library(devtools)
reload(inst("dplyr"))


text:
Q: Count of Occurrences within Date Range I'm working on an analysis using SQL (SSMS).  Currently my dataset has two columns, a date that a product was added to our stock room and the date that the product was sold.  I need to add a new column to each row showing how many items total we had in stock on the date that the new product was added to the stock room.
Hope this makes sense. I've been playing around in SQL, but don't really now where to go from here.
Date_Added | Date_Sold  | Inventory
2011-01-08 | 2011-02-26 | 1
2011-01-11 | 2011-02-08 | 2
2011-01-11 | 2011-03-01 | 3
2011-01-15 | 2011-03-05 | 4
2011-01-15 | 2011-03-05 | 5
2011-02-10 | 2011-03-31 | 5
2011-03-04 | 2011-04-01 | 5
2011-03-06 | 2011-04-03 | 4