text:
Q: Write pixel data to FITS file Cfitsio I am trying to write and fill the image with pixel data to new fits file using cfitsio. I am not sure where I am doing wrong but all of the data are not being written to the fits file. I used binary vi to check out the data and image data is not properly created. I used the second image HST WFPC 2 fits file from NASA website. This is the code that I wrote:
#include <string.h>
#include <stdio.h>
#include "fitsio.h"

int main() {
    fitsfile *fptr;
    int status = 0, i;

    fits_open_file(&fptr, "WFPC2ASSNu5780205bx.fits", READONLY, &status);
    long naxes[2];
    fits_get_img_size(fptr, 3, naxes, &status);

    fitsfile *ofptr;
    fits_create_file(&ofptr, "o_nasa.fits", &status);
    fits_copy_header(fptr, ofptr, &status);

    long fp[2] = {1, 1};
    long nelements = naxes[0];

    float arr[nelements];
    for (i = 0; i < nelements; i++) {
        arr[i] = 100;
    }

    int ii, jj, kk;
    for (ii = 1; ii <= naxes[0]; ii++) {
        for (jj = 1; jj <= naxes[1]; jj++) {
            fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status); // this is not working
        }
    }
    fits_close_file(ofptr, &status);
    fits_close_file(fptr, &status);

    return status;
}

A: I found out what is wrong with the code. I just posted the answer since there doesn't seem to be a lot of community working on CFITSIO. The code is wrong in the lines in the double for loop with variables ii, jj. I thought fp, the first pixel array to point where the image array starts writing, is used once where to start the whole iterations but instead write_pix uses it throughout the iterations to know where to write. My code is also trying to write/update the 1, 1 pixel and it seems to be NULL. The correct code is:
for (fp[1] = 1; fp[1] <= naxes[0]; fp[1]++) {
    for (fp[0] = 1; fp[0] <= naxes[1]; fp[0]++) {
        fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status);
    }
}


text:
Q: Easiest way of finding photos with no tags using the Flickr API I'm working on a small project to help me tag content on Flickr.
I've been looking through the API and there's obvious ways to search for tagged content, but not a simple way of finding what content hasn't been tagged (without just looping through image ID's till I find one with no tag).
Has anyone come across this in the past and found an easy work around?
Cheers

A: flickr.photos.getUntagged will do that for your own photos. I'm pretty sure that there's no way to do it for more general searches, other than brute force.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Annotating a FilteredRelation on a ManyToManyField returns nothing Models
class User(AbstractUser):
    pass

class Report(Model):

    user = ForeignKey (
        "User",
        related_name="reports"
    )

    shared_doctors = ManyToManyField (
        "User",
        symmetrical = False,
        related_name="shared_reports"
    )

I have more fields on the models, but I have omitted them in the interest of shortening the problem.
Query
User.objects.annotate(
    shared_reports_user = FilteredRelation(
        'shared_reports',
        condition = Q(shared_reports__user=user)
    )
).annotate(
    shared_reports_user_count = Count('shared_reports_user')
)

I have brought down the query to the base level which is giving unexpected results. user in the first annotate is an instance of User.
The Query runs successfully, but the resulting QuerySet has no shared_reports_user key, though it has a shared_reports_user_count key, which has a value of 0.
As far as I understood from the documentation, FilteredRelation takes a field present on the Model that it will filter on, and a named argument, condition, that takes a Q object as a condition to be applied to the existing field value. This leads me to believe that the first annotation should return a QuerySet annotated with a subset of shared_reports satisfying the condition specified in the Q object.
I'm sure my database contains values satisfying the Q object (I have manually inspected the data), and even in case there is no output, I would have expected an empty QuerySet against the key shared_reports_user.
Am I missing something?

A: You can use Conditional aggregation in Django 2.0 like this:
User.objects.annotate(
shared_reports_user_count=Count('shared_reports', filter=Q(shared_reports__user_id=user.id))


text:
Q: How to read a file in windows 8 metro App I want to ship a text file along with my App and read it while executing my application. How can I read that particular file? I have set the file to content and copy if newer.

A: private async void ProjectFile()
{
    var _Path = @"Metro.Helpers.Tests\MyFolder\MyFolder.txt";
    var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    var _File = await _Folder.GetFileAsync(_Path);
    var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File);
}

Code to read project file which works for me. Hope it helps others too :)

A: The answer to your question is heavily dependant on how you want to read the file, and what it contains.
You can find a few examples of file access in the File Access Sample app on MSDN, from which one example is:
if (file != null)
{
    using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
    {
        using (DataReader dataReader = new DataReader(readStream))
        {
            UInt64 size = readStream.Size;
            if (size <= UInt32.MaxValue)
            {
                UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                string fileContent = dataReader.ReadString(numBytesLoaded);
                OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
            }
            else
            {
                OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.";
            }
        }
    }
}


text:
Q: PHP I thought I had defined username, why is my code telling me otherwise? I am struggling to understand why my code is telling me that my username is undefined whenever I try to load up this page. the error is Notice: Undefined index: username in /home/jmask072/public_html/login.php on line 12. Any help is appreciated.
<?php
    $users = array("user" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
        $isLoggedIn = false;
        $errors = array();
        $required = array("username", "pass");
        foreach ($required as $key => $value) {
            if (!isset($_POST[$value]) || empty($_POST[$value])) {
                $errors[] = "please fill out the form";
            }
        }

        if (array_key_exists($_POST['username'],$users)) {
            $userPassword = $_POST['pass'];
            $dbPass = $users[$_POST['username']];
            if (password_verify($userPassword,$dbPass) === true) {
                $isLoggedIn = true;
            } else {
                $isLoggedIn = false;
                $errors[] = "Username not found or password incorrect";
            }

        } else {
            $errors[] = "Username not found or password incorrect";
        }

require_once("Template.php");

$page = new Template("My Login");
$page->addHeadElement("<link rel=\"stylesheet\" href=\"styles.css\">");
$page->addHeadElement("");
$page->finalizeTopSection();
$page->finalizeBottomSection();

print $page->getTopSection();

if (count($errors) > 0) {
    foreach ($errors as $error) {
        print "Error";
    }
}
else if ($isLoggedIn === true) {
    print "Hello, you are logged in";
}

print "<form action =\"login_action.php\" method =\"POST\" class=\"form-signin\">";
print "
Please sign in
\n";
print "Username";
print "<input type=\"password\" name=\"pass\" id=\"inputPassword\" placeholder=\"password\">";
print "<button type=\"submit\"> Sign in</button>";

print $page->getBottomSection();
?>

A: first you should use a single quotes ' '
it is a very good alternative for backslash
and
 print "Username";

here  you add label for inputUser but i dont see any input ??

A: You do need to make the script work even if the page is not requested correctly because you have no control on the requests it will get. Then you have to make sure that YOU call it correctly when you do it (right now this is not the case).
You are seeing the notice because, even if your code does check for the existence of the POST variables it needs (lines 6-10), even if the check fails it still attempts to read them at line 12.
The whole code block if...then...else starting at line 12 should only be executed if the checks went well (i.e. if(empty($errors)) {...). Now if the page is requested incorrectly at least you will get a useful error message that will help you understand where the problem is.
In this case the error message is "please fill out the form". In fact the code expects a form with two input fields but the one it displays only has the password field (which is unhelpfully labelled "Username") and has no username field. You need to provide both fields and make sure that the name attributes match the POST variables you want to get the data from (the for attribute in the label tags should also match the field name exactly).


text:
Q: how to do a li with two lines? need do a navbar with a ul, but one link have one li with two lines, i need follow the design of .psd file. how i can do this?
below you can see the navbar screenshot of psd file, and my source code made by myself with html/css.

this is the source of my navbar:
http://jsfiddle.net/6xKL9/

empresa

<a href="<?php echo site_url("historia"); ?>">história

<a href="<?php echo site_url('politica_de_privacidade') ?>">política de privacidade

<a href="<?php echo site_url('certificacoes') ?>">certificações e prêmios

<a href="<?php echo site_url('produtos') ?>">produtos

<a href="<?php echo site_url('representantes') ?>">representantes

<a href="<?php echo site_url('distribuidores') ?>">eletricista

<a href="<?php echo site_url('informativo_tecnico') ?>" id="infotec">informativos tecnicos

generalidades

<a href="<?php echo site_url('informativo_tecnico_simbologia_instalacao') ?>">recomendações para instalações

<a href="<?php echo site_url('informativo_tecnico_conceitos_basicos') ?>">conceitos básicos sobre condutores

<a href="<?php echo site_url('informativo_tecnico_simbologia') ?>">simbologia

<a href="<?php echo site_url('informativo_tecnico_criterio_dimensionamento_circuito') ?>">critério de dimensionamento de circuitos

<a href="<?php echo site_url('informativo_tecnico_queda_tensao') ?>">queda de tensão

dimencionamento de eletrodutos

<a href="<?php echo site_url('informativo_tecnico_correntes_maximas') ?>">correntes máximas de curto-circuito

<a href="<?php echo site_url('eventos') ?>">eventos

<a href="<?php echo site_url('videos') ?>">videos

fale conosco

<a href="<?php echo site_url('fale_conosco') ?>">fale conosco

<a href="<?php echo site_url('trabalhe_conosco') ?>">trabalhe conosco

seja nosso representante

seja nosso distribuidor

A: Use
vertical-align: middle

along with
max-width

to achieve the effect:
http://jsfiddle.net/6xKL9/1/
remove the padding to prevent the hovering issue: http://jsfiddle.net/6xKL9/5/
note that vertical-align only works with elements which are inline and you can only set sizes for elements which are blocks so i've made the  inline-block in order to enjoy both worlds.

A: Set display: table-caption; on your links. This triggers a new line for each word.
FIDDLE
.sub-menu .menu li a {
  ...
  display: table-caption; /* <-- */
  text-align: center;
}

A: You can just use a line break

So for your example:

informativos
tecnicos


text:
Q: How to use valgrind's massif-out-file option correctly? When running valgrind --tool=massif benchmark1 --massif-out-file=test.out on MacOS (10.12.6) with version valgrind-3.13.0, output is produced, but only in the default filename format, i.e. massif.out.\d+. No test.out file is generated. Exemplary output is:
==32233== Massif, a heap profiler
==32233== Copyright (C) 2003-2017, and GNU GPL'd, by Nicholas Nethercote
==32233== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==32233== Command: benchmark1 --massif-out-file=./test.out
==32233==

What am I missing, or is this feature ignored for the MacOS version? I tried also to put the file name in quotes with no success.

A: According to the trace above, you have given the valgrind --massif-out-file=./test.out
option to benchmark1, which has probably silently ignored it.
You have to do:
   valgrind ...valgrind options...   your_program ....your program options....

So, try something like:
valgrind --tool=massif --massif-out-file=./test.out benchmark1

A: After working with some valgrind tools (memcheck and massif), I found that we must follow follow it's rule:
valgrind --tool=... valgrind_option=... your_program program_argument


text:
Q: How to access nested element in MongoDB C# Driver I have a MongoDB Driver implemented in My .Net Core Application. I will add Data Model Classes as following,
namespace Test.Database
{
    public class DocumentFields
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonElement("account_id")]
        public string AccountId { get; set; }
        [BsonElement("document_types")]
        public DocumentType[] DocumentTypes { get; set; }
        [BsonElement("document_themes")]
        public DocumentTheme[] DocumentThemes { get; set; }
        [BsonElement("created_at")]
        public DateTime CreatedAt { get; set; }
    }
    public class DocumentType
    {
        [BsonElement("id")]
        public string id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
    }
    public class DocumentTheme
    {
        [BsonElement("id")]
        public string id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
    }

}

But when I try to fetch the Data using this Model Class, it gives this error.
System.FormatException: An error occurred while deserializing the DocumentThemes property of class Test.Database.DocumentFields:
Element 'id' does not match any field or property of class Test.Database.DocumentTheme.

The document I'm trying to access is something like this.
{
    "_id" : ObjectId("6234410f0f4dd20dd96fb9dd"),
    "account_id" : "96f35500-584e-4db9-94cd-ebd93cce13b7",
    "created_at" : ISODate("2022-03-18T08:21:35.695+0000"),
    "document_themes" : [
        {
            "id" : "6ad3eac9-e44c-4fdd-b54a-f0ff9165ba3e",
            "name" : "Theme 1"
        },
        {
            "id" : "2dd625f2-de57-41f7-9d89-a0e28c62dc65",
            "name" : "Theme 2"
        },
        {
            "id" : "af3347c7-12cc-421a-8945-65ce80bf8a0f",
            "name" : "Theme 3"
        }
    ],
    "document_types" : [
        {
            "id" : "c0934926-9e1d-468c-9a47-97a62d83228d",
            "name" : "Type 1"
        },
        {
            "id" : "331ad071-7d91-4b84-bdf1-733f9868b979",
            "name" : "Type 2"
        },
        {
            "id" : "630bbcad-34ec-4b4d-84e4-89724bd8ae17",
            "name" : "Type 3"
        }
    ]
}

How I can overcome this obstacle?

A: Late to the answer.
Similar to this question, the .NET/C# driver will bind the property id / Id / _id to the _id field in the document.
Solution 1
Implement the class map to override the default behavior of id property.
BsonClassMap.RegisterClassMap<DocumentType>(cm =>
{
    cm.AutoMap();
    cm.UnmapField(x => x.id);

    cm.MapMember(x => x.id)
        .SetElementName("id");
});

BsonClassMap.RegisterClassMap<DocumentTheme>(cm =>
{
    cm.AutoMap();
    cm.UnmapField(x => x.id);

    cm.MapMember(x => x.id)
        .SetElementName("id");
});

Demo

Solution 2
Apply [BsonNoId] attribute to the DocumentType and DocumentTheme classes to suppress the default Id behavior.
[BsonNoId]
public class DocumentType
{
    ...
}

[BsonNoId]
public class DocumentTheme
{
    ...
}

Demo


text:
Q: How to perform conditional join with time column in spark scala I am looking for help in joining 2 DF's with conditional join in time columns, using Spark Scala.
DF1

time_1
revision
review_1

2022-04-05 08:32:00
1
abc

2022-04-05 10:15:00
2
abc

2022-04-05 12:15:00
3
abc

2022-04-05 09:00:00
1
xyz

2022-04-05 20:20:00
2
xyz

DF2:

time_2
review_1
value

2022-04-05 08:30:00
abc
value_1

2022-04-05 09:48:00
abc
value_2

2022-04-05 15:40:00
abc
value_3

2022-04-05 08:00:00
xyz
value_4

2022-04-05 09:00:00
xyz
value_5

2022-04-05 10:00:00
xyz
value_6

2022-04-05 11:00:00
xyz
value_7

2022-04-05 12:00:00
xyz
value_8

Desired Output DF:

time_1
revision
review_1
value

2022-04-05 08:32:00
1
abc
value_1

2022-04-05 10:15:00
2
abc
value_2

2022-04-05 12:15:00
3
abc
null

2022-04-05 09:00:00
1
xyz
value_6

2022-04-05 20:20:00
2
xyz
null

As in the case of row 4 of the final output (where time_1 = 2022-04-05 09:00:00, if multiple values match during the join then only the latest - in time - should be taken).
Furthermore if there is no match for a row of df in the join then there it should have null for the value column.
Here we need to join between 2 columns in the two DF's:

*

*review_1 === review_2 &&

*time_1 === time_2 (condition : time_1 should be in range +1/-1 Hr from time_2, If multiple records then show latest value, as in value_6 above)

A: Here is the code necessary to join the DataFrames:
I have commented the code so as to explain the logic.
TL;DR
import org.apache.spark.sql.expressions.Window

val SECONDS_IN_ONE_HOUR = 60 * 60

val window = Window.partitionBy("time_1").orderBy(col("time_2").desc)

df1WithEpoch
    .join(df2WithEpoch,
          df1WithEpoch("review_1") === df2WithEpoch("review_2")
          && (
              // if `time_1` is in between `time_2` and `time_2` - 1 hour
              (df1WithEpoch("epoch_time_1") >= df2WithEpoch("epoch_time_2") - SECONDS_IN_ONE_HOUR)
              // if `time_1` is in between `time_2` and `time_2` + 1 hour
              && (df1WithEpoch("epoch_time_1") <= df2WithEpoch("epoch_time_2") + SECONDS_IN_ONE_HOUR)
          ),
          // LEFT OUTER is necessary to get back `2022-04-05 12:15:00` and `2022-04-05 20:20:00` which have no join to `df2` in the time window
          "left_outer"
         )
    .withColumn("row_num", row_number().over(window))
    .filter(col("row_num") === 1)
    // select only the columns we care about
    .select("time_1", "revision", "review_1", "value")
    // order by to give the results in the same order as in the Question
    .orderBy(col("review_1"), col("revision"))
    .show(false)

Full breakdown
Let's start off with your DataFrames: df1 and df2 in code:
val df1 = List(
    ("2022-04-05 08:32:00", 1, "abc"),
    ("2022-04-05 10:15:00", 2, "abc"),
    ("2022-04-05 12:15:00", 3, "abc"),
    ("2022-04-05 09:00:00", 1, "xyz"),
    ("2022-04-05 20:20:00", 2, "xyz")
).toDF("time_1", "revision", "review_1")

df1.show(false)

gives:
+-------------------+--------+--------+
|time_1             |revision|review_1|
+-------------------+--------+--------+
|2022-04-05 08:32:00|1       |abc     |
|2022-04-05 10:15:00|2       |abc     |
|2022-04-05 12:15:00|3       |abc     |
|2022-04-05 09:00:00|1       |xyz     |
|2022-04-05 20:20:00|2       |xyz     |
+-------------------+--------+--------+

val df2 = List(
    ("2022-04-05 08:30:00", "abc", "value_1"),
    ("2022-04-05 09:48:00", "abc", "value_2"),
    ("2022-04-05 15:40:00", "abc", "value_3"),
    ("2022-04-05 08:00:00", "xyz", "value_4"),
    ("2022-04-05 09:00:00", "xyz", "value_5"),
    ("2022-04-05 10:00:00", "xyz", "value_6"),
    ("2022-04-05 11:00:00", "xyz", "value_7"),
    ("2022-04-05 12:00:00", "xyz", "value_8")
).toDF("time_2", "review_2", "value")

df2.show(false)

gives:
+-------------------+--------+-------+
|time_2             |review_2|value  |
+-------------------+--------+-------+
|2022-04-05 08:30:00|abc     |value_1|
|2022-04-05 09:48:00|abc     |value_2|
|2022-04-05 15:40:00|abc     |value_3|
|2022-04-05 08:00:00|xyz     |value_4|
|2022-04-05 09:00:00|xyz     |value_5|
|2022-04-05 10:00:00|xyz     |value_6|
|2022-04-05 11:00:00|xyz     |value_7|
|2022-04-05 12:00:00|xyz     |value_8|
+-------------------+--------+-------+

Next we need new columns which we can do the date range check on (where time is represented as a single number, making math operations easy:
// add a new column, temporarily, which contains the time in
// epoch format: with this adding/subtracting an hour can easily be done.
val df1WithEpoch = df1.withColumn("epoch_time_1", unix_timestamp(col("time_1")))
val df2WithEpoch = df2.withColumn("epoch_time_2", unix_timestamp(col("time_2")))

df1WithEpoch.show()
df2WithEpoch.show()

gives:
+-------------------+--------+--------+------------+
|             time_1|revision|review_1|epoch_time_1|
+-------------------+--------+--------+------------+
|2022-04-05 08:32:00|       1|     abc|  1649147520|
|2022-04-05 10:15:00|       2|     abc|  1649153700|
|2022-04-05 12:15:00|       3|     abc|  1649160900|
|2022-04-05 09:00:00|       1|     xyz|  1649149200|
|2022-04-05 20:20:00|       2|     xyz|  1649190000|
+-------------------+--------+--------+------------+

+-------------------+--------+-------+------------+
|             time_2|review_2|  value|epoch_time_2|
+-------------------+--------+-------+------------+
|2022-04-05 08:30:00|     abc|value_1|  1649147400|
|2022-04-05 09:48:00|     abc|value_2|  1649152080|
|2022-04-05 15:40:00|     abc|value_3|  1649173200|
|2022-04-05 08:00:00|     xyz|value_4|  1649145600|
|2022-04-05 09:00:00|     xyz|value_5|  1649149200|
|2022-04-05 10:00:00|     xyz|value_6|  1649152800|
|2022-04-05 11:00:00|     xyz|value_7|  1649156400|
|2022-04-05 12:00:00|     xyz|value_8|  1649160000|
+-------------------+--------+-------+------------+

and finally to join:
import org.apache.spark.sql.expressions.Window

val SECONDS_IN_ONE_HOUR = 60 * 60

val window = Window.partitionBy("time_1").orderBy(col("time_2").desc)

df1WithEpoch
    .join(df2WithEpoch,
          df1WithEpoch("review_1") === df2WithEpoch("review_2")
          && (
              // if `time_1` is in between `time_2` and `time_2` - 1 hour
              (df1WithEpoch("epoch_time_1") >= df2WithEpoch("epoch_time_2") - SECONDS_IN_ONE_HOUR)
              // if `time_1` is in between `time_2` and `time_2` + 1 hour
              && (df1WithEpoch("epoch_time_1") <= df2WithEpoch("epoch_time_2") + SECONDS_IN_ONE_HOUR)
          ),
          // LEFT OUTER is necessary to get back `2022-04-05 12:15:00` and `2022-04-05 20:20:00` which have no join to `df2` in the time window
          "left_outer"
         )
    .withColumn("row_num", row_number().over(window))
    .filter(col("row_num") === 1)
    // select only the columns we care about
    .select("time_1", "revision", "review_1", "value")
    // order by to give the results in the same order as in the Question
    .orderBy(col("review_1"), col("revision"))
    .show(false)

gives:
+-------------------+--------+--------+-------+
|time_1             |revision|review_1|value  |
+-------------------+--------+--------+-------+
|2022-04-05 08:32:00|1       |abc     |value_1|
|2022-04-05 10:15:00|2       |abc     |value_2|
|2022-04-05 12:15:00|3       |abc     |null   |
|2022-04-05 09:00:00|1       |xyz     |value_6|
|2022-04-05 20:20:00|2       |xyz     |null   |
+-------------------+--------+--------+-------+


text:
Q: Finding general solutions of a differential equations, with specific solutions so I'm not a native english speaker, so bear with me.
Let there be an equation $y'+p(x)y=q(x)$.
$y_1=4e^{-2x}+2x-1$ and $y_2=2x-1$ are "private solutions" or "specific solutions" - not sure of the English term.
And the questions is - finding the general solution.
How do I solve this?
Thank you,
 Vova

A: The equation you have is linear, so it follows that $y=e^{-2x}$ is a solution to the homogeneous problem $y'+p(x)y=0$ and the general solution is of the form $y=2x-1+Ce^{-2x}$.
Since $y_1,y_2$ satisfy the non-homogeneous problem, it follows that $y_1-y_2=4e^{-2x}$ solves the homogeneous problem $Ly=0$ by linearity of the differential operator $L=d/dx+p(x)\operatorname{Id}$ as $L[y_1-y_2]=L[y_1]-L[y_2]=q(x)-q(x)=0$. That $y=Ce^{-2x}$ is the general solution to the homogeneous problem follows readily.


text:
Q: How to add a GUI to a minimal install of CentOS? I did a minimal install of CentOS 6.3 and now want to add a GUI. I tried using yum to install a GUI, but it is unable to resolve the CentOS repository server  mirror.centos.org. I tried to install networking packages but I get directory not found for /etc.
How can I install and enable Gnome Desktop on CentOS?

A: try yum groupinstall basic-desktop desktop-platform x11 fonts
But apparently your yum is unable to connect to the yum repository. that is mirror.centos.org.
Do check your network configuration.


text:
Q: Hiding columns in Excel based on cell value I would like to hide certain columns in my Excel sheet (called "Template account") based on a value from a picklist that is selected in cell AC5.
The logic is as follows:
1) If the picklist value in cell AC5 is "Energy and Resources" then I'd like the columns BJ:BO to be hidden.
2) If the picklist value in cell AC5 is "Defence" then I'd like the columns BP:CA to be hidden and so on..
3) Else if AC5 contains none of the picklist values in AC5 then don't hide anything
The code I attempted looks like this, however it does not work. Can someone please provide me with some input?
 Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Dim cellvalue As String
 Dim ws As Worksheet
 Set ws = Sheet("Template account")

If cellvalue Like "*Energy and Resources*" Then
Columns("BJ:BO").EntireColumn.Hidden = True
Else
If cellvalue Like "*Defence*" Then
Columns("BP:CA").EntireColumn.Hidden = True
Else
Exit Sub
End If
End Sub

A: to detect a change in a cell value you must use Worksheet_Change() event handler
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address(False, False) = "AC5" Then '<-- check for changed cell to be in AC5
        Select Case Target.Value '<-- act correspondingly to changed cell value
            Case "Energy and Resources"
                Columns("BJ:BO").EntireColumn.Hidden = True
            Case "Defence"
                Columns("BP:CA").EntireColumn.Hidden = True
            Case "...."
                ' go on with other cases
        End Select
    End If
End Sub

should you want to unhide columns BJ:BO and BP:CA when neither "Energy and Resources" nor "Defence" is the value of the changed pickup cell, then the code slightly changes in the last part of the Select Case block
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address(False, False) = "AC5" Then '<-- check for changed cell to be in AC5
        Select Case Target.Value '<-- act correspondingly to changed cell value
            Case "Energy and Resources"
                Columns("BJ:BO").EntireColumn.Hidden = True
            Case "Defence"
                Columns("BP:CA").EntireColumn.Hidden = True
            Case Else
                Union(Columns("BJ:BO"), Columns("BP:CA")).EntireColumn.Hidden = False
        End Select
    End If
End Sub

A: Place your code under the Workbook_SheetChange. Currently the event you are under will only trigger when you select different cell not when actual changes are happening in cells. Also as @BruceWayne states you never pass the value of cell AC5 to your cellvalue variable. Code with some changes:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Sh.Name = "Template account" And Target.Address = "$AC:$5" Then
        Application.EnableEvents = False
        Dim cellvalue As String
        cellvalue = Target.Value2

        If cellvalue Like "*Energy and Resources*" Then
            Sh.Columns("BJ:BO").EntireColumn.Hidden = True
        ElseIf cellvalue Like "*Defence*" Then
            Sh.Columns("BP:CA").EntireColumn.Hidden = True
        Else
            Sh.Columns("BJ:BO").EntireColumn.Hidden = False
            Sh.Columns("BP:CA").EntireColumn.Hidden = False
        End If
        Application.EnableEvents = False
    End If
End Sub

Added a check to confirm changes are on the correct sheet and cell. Disabled events while code is running so hiding the columns doesn't trigger the event again. Enabled at the end. Added showing the columns again on the Else. Have not tested.


text:
Q: Kotlin delegated property by map throwing NoSuchElementException if not present in map I have a kotlin object defined as such:
data class UserUpdateRequest(val map: Map<String, Any?>) {
    @get:Email
    val email: String? by map
    val firstName: String? by map
    val lastName: String? by map
}

So that works just fine, so the problem I'm having is that the properties are nullable, and when I access one, say by doing instance.email it throws a NoSuchElementException if said property is not set in the map.
Instead, it'd be more convenient if it returned null, since it's optional/nullable. Is there any way to achieve this without writing my own delegate?

A: You can basically use the .withDefault { ... } extension that wraps a Map for delegation, so that it executes the lambda to calculate a value on absent key:
data class UserUpdateRequest(val map: Map<String, Any?>) {
    private val defaultMap = map.withDefault { null }

    @get:Email
    val email: String? by defaultMap
    val firstName: String? by defaultMap
    val lastName: String? by defaultMap
}

Note that simple defaultMap.get(key) and defaultMap[key] queries are not handled by this wrapper, it only affects the defaulMap.getValue(key) calls (which also happen to be used by the delegation implementation).

A: Here is a delegate implementation, if you want to have more control over what the delegate does and understand how it works.
First of a demonstration how it could be used in your scenario:
data class UserUpdateRequest(val map: Map<String, Any?>) {

        var email: String? by valueFromMap(map = map)
        var firstName: String? by valueFromMap(map = map)
        var lastName: String? by valueFromMap(map = map)
        var age: Int? by valueFromMap(map = map)
    }

    val myInitialMap = mutableMapOf<String,Any?>()
    myInitialMap["email"] = "1234@something.com"
    myInitialMap["age"] = 34

    val request = UserUpdateRequest(myInitialMap)
    request.lastName = "Genericname"

    println("email: ${request.email}, firstNme: ${request.firstName}, lastName: ${request.lastName}, age: ${request.age}")

    request.lastName = null

    println("lastName after setting to null: ${request.lastName}")

This will print:
email: 1234@something.com, firstName: null, lastName: Genericname, age: 34
lastName after setting to null: null
So the variables are set to the initialMap's values if they exist and the value's type matches the variable type. Else the variable is set to null.
The Delegate Implementation
fun <R>valueFromMap(key: (KProperty<*>) -> String = KProperty<*>::name,
                map: Map<String, Any?>): ReadWriteProperty<Any, R?>{

    val myMap = map.toMutableMap()

    return object : ReadWriteProperty<Any, R?> {

    override fun getValue(thisRef: Any, property: KProperty<*>): R? {
        return (myMap.getOrDefault(key(property), null) as? R)?: return null
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: R?) {
        if(value == null){
            myMap.remove(key(property))
        } else {
            myMap[key(property)] = value
        }
    }
}

}
So valueFromMap(map = map) is a function that returns a ReadWriteProperty for a val/var(KProperty) that uses the KPproperty's name as key to look for a value in the map, passed as argument.
So when we call:
request.lastName = "Genericname"

In the above example, actually we call .
initialMap["lastName"] = "Genericname"

If the variable name and the corresponding key differ you could even pass your key as argument.
With this approach you're able to handle the value access on your own in the getValue and setValue functions.
Hope this helps anybody.


text:
Q: iOS swift 4 Add notification listener for network connection status from any class I am using ashleymills/Reachability.swift to check network connection status. When I use it in a particular class in viewWillAppear method, it works just fine.
But currently I have more that 40 classes and I don't think I need to implement the notification listener in each of them.
So, I have been trying to run it in AppDelegate's application didFinishLaunchingWithOptions method. I tried for one class, like, if I have a class named DashboardVC, I wrote:
var reachability = Reachability()!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = DashboardVC()
Notificationcenter.default.addObserver(vc, selector: #selector(reachabilityDidChange(notification:)), name: .reachabilityChanged, object: nil)
return true
}

And the reachabilityDidChange(notification:) function:
func reachabilityDidChange(notification: Notification) {

let reachability1 = notification.object as! Reachability
switch reachability1.connection {
case .wifi:
   print("Reachable via WiFi")
case .cellular:
   print("Reachable via Cellular")
case .none:
   print("Network not reachable")  }
}

But this didn't work when I turned on/off the internet connection or switched from wifi to cellular network right when DashboardVC was the topmostViewController.
Please help me:

*

*If there's a way to achieve my goal with ashleymills/Reachability.swift

*If there's a way to achieve this without ashleymills/Reachability.swift

*If there's any other way to keep track of network connection status

Regards!


text:
Q: Visual Studio 2015 Find dialog loses selection and no longer defaults to search Selection In Visual Studio 2015, when I select some text and press Ctrl+F or Ctrl+H, it doesn't default to search within the Selection. This is a huge breaking change to my workflow.
Additionally, it seems like sometimes it even removes my selection, though I haven't confirmed this for sure (I use the dark theme and sometimes it's hard to tell what's selected).
Is there any way to get the old behavior back, where if I launch the find dialog with a selection in the active window, it defaults to search within "Selection" instead of "Current Document"?
For those who want to get in on the action, I've reported this as a bug at Microsoft Connect.

A: I had no idea this was a setting! The solution is as simple as checking a box—Go to Tools -> Options -> Environment -> Find and Replace and check "Automatically limit search to selection".

Microsoft has acknowledged this change in behavior from the previous version—I received an email that Visual Studio 2015 Update 2 will have this option set by default for fresh installations.
Thank you, Microsoft!


text:
Q: Import NavLinks from different class to NavBar Class in React Hey I am a beginner in React trying to make a navbar component using materialize css. I have two different classes for loggedinlinks and loggedoutlinks but when I import them in my Navbar class and run the app the links DO NOT show up. Please Help
Navbar
import { Component } from "react"
import React from 'react'
import { Link } from "react-router-dom";
import { Icon } from 'react-materialize';
import './navbar.css'
import Logo from '../assets/ptslogo.png'
import loggedinlinks from './signlinks/loggedinlinks';    /////<=it is also little darkened out in vscode

class Navbar extends Component {
    render() {
        return (

                        <Link to="/">

</Link>
                        <Icon>menu</Icon>
                        <loggedinlinks/>

        );
    }
}
export default Navbar;

loggedinlinks class
import React,{Component} from 'react'
import {NavLink} from 'react-router-dom'

class loggedinlinks extends Component {
    render(){
        return (

<NavLink className="white-text" to="/">Home</NavLink>

<NavLink className="white-text " to="/about">About</NavLink>

<NavLink className="white-text" to="/events">Events</NavLink>

<NavLink className="white-text"  to="/register">Register</NavLink>

<NavLink className="white-text"  to="/login">Login</NavLink>

<NavLink className="white-text"  to="/contact">Contact</NavLink>

        );
    }
}
export default loggedinlinks;

A: In react all custom components require a capital letter for the first letter of the component name. Therefore in this instance all you need to do is update you component to:
Navbar
<LoggedInLinks />

LoggedInLinks
class LoggedInLinks extends React.Component { /* logic goes here */ }

export defualt LoggedInLinks;


text:
Q: Iphone communication between 2 cell phones I am developing an application for an Iphone and I need to know if there is a way to communicate between 2 iphones either through some kind of messaging or anything similar to that.  Kind of like a yahoo messanger.
Thanks
Saro

A: You should read about GameKit and it's p2p connectivity. Question with some example can be found here


text:
Q: PHPMailer body message empty error using tutorials I pasted and filled the following PHPMailer php file and made the following html form. However after send the error appears "Message could not be sent.Mailer Error: Message body empty". Please help.
<?php
require 'phpmailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;

$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'xxx@gmail.com';
$mail->Password = 'xxx';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('xxx@gmail.com', 'Joe User');
$mail->addReplyTo('info@example.com', 'Information');

$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
$mail->isHTML(true);

$mail->Subject = 'Here is the subject';
$mail->From = $email;
$mail->FromName = $name;
$mail->Body    = $message;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

?>

and here is the form
<form name="contactform" method="post" action="email.php">

    <div class="input-text-container clear">
    <input type="text" name="name" id="name" placeholder="Your Name"
     class="input-text input-text-left">

    <input type="text" name="email" id="email" placeholder="Your E-mail"
    class="input-text input-text-right">
    </div>

    <textarea type="text" name="message" id="message" placeholder="Your
    Message" class="textarea"></textarea>

    <button type="submit" value="submit Form" class="submit">SUBMIT</button>

</form>

A: Your script seems to rely on request parameters being available as global variables. But this is a very uncommon (and insecure) practice.
Use $_POST['message'] instead $message and the message body should contain data from the form. Do the same for the other parameters.


text:
Q: Injecting values of DataFrame to NaN of Series with different length How can I inject values of dataframe and complement NaN of series with different length like those:
series             dataframe
                           0
0      NaN       0  0.468979
1      3.0       1  0.470546
2      NaN       2  0.458234
3      3.0       3  0.427878
4      NaN       4  0.494763
       ...          ...
886    NaN     682  0.458234
887    2.0     683  0.501460
888    NaN     684  0.458234
889    3.0     685  0.494949
890    NaN     686  0.427878
891    2.0
892    3.0
893    1.0

I need to find something that can inject values of dataframe to NaN of series like below:
0    0.468979  <- row0 of dataframe
1         3.0
2    0.470546  <- row1 of dataframe
3         3.0
4    0.458234  <- row2 of dataframe
     ...
886  0.458234  <- row684 of dataframe
887       2.0
888  0.494949  <- row685 of dataframe
889       3.0
890  0.427878  <- row686 of dataframe
891       2.0
892       3.0
893       1.0

Actually, I can get the above result by this code:
j = 0
for i, c in enumerate(series):
    if np.isnan(c):
        series[i] = dataframe[0][j]
        j += 1

but it makes SettingWithCopyWarning.
How can I inject values of dataframe and complement NaN of series without the warning?
According to the previous question: How to remove nan value while combining two column in Panda Data frame?
I tried below, however, it doesn't work well due to the different length:
series = series.fillna(dataframe[0])

0      0.468979  <- row0 of dataframe
1      3.000000
2      0.458234  <- row2 of dataframe
3      3.000000
4      0.494763  <- row4 of dataframe
         ...
886         NaN
887    2.000000
888         NaN
889    3.000000
890         NaN
891    2.000000
892    3.000000
893    1.000000


text:
Q: How to make onload script work again after content changed I have a page where you select between 2 pictures, when you click one of them, the content of the div changes. The new content also has 2 pictures which will load another content when clicked. I am using javascript, but the script only loads once, so when I get to the second content, it doesn't change anymore.
I got 3 files:
Main.html - content1.html - content2.html - script.js
Main.html:

Here is the content that will be replaced in the class change:
content1.html:

this is the content that i want to replace on the next click:
content2.html:

This is the script that suppose to do that:
window.onload = function() {

    document.getElementById("water").onclick = function()
    {
        $('#change').load('content1.html');

    };

    document.getElementById("water3").onclick = function() {
        $('#change').load('content2.html');

    };

If I click the image with id water, it replace with content1, then I click the image with water3, nothing happens

A: You can use the complete call back to bind the new element:
window.onload = function() {

    document.getElementById("water").onclick = function()
    {
        $('#change').load('content1.html', function() {
             document.getElementById("water3").onclick = function() {
                $('#change').load('content2.html');

            };
        });

    };
 };

Reference: http://api.jquery.com/load/


text:
Q: Drawing text (open gl es, android) I'm new to open gl in android and I need to draw some text in my GLSurfaceView. I found only one solution - to create bitmap with text and display it like texture (like this, for example; http://giantandroid.blogspot.ru/2011/03/draw-text-in-opengl-es.html). I tried to do like this, but it didn't work for me. What is textures array in this code? And is there any simplier way to display text?

A: openGL by itself doesn't offer any "simpler" way to render text - it even doesn't "know" anything about the way glyphs may be represented in bitmap or outline font sets.
Using some other library "knowing" how to handle different font sets and how to rasterize them to directly let them paint into an openGL texture doesn't seem so complicated that any other approach may claim to be a lot easier.
You might want to take a look at both this (see: Draw text in OpenGL ES) article here on stackoverflow as well as into the linked pages to get an overview of other methods available to choose the one that seems best to you.
Regarding your second question about the textures array in the code sample you linked the array is just used to fulfill the API requirements of the call to glGenTextures() as it expects an array as the second argument.
In fact just a single texture id is allocated in this line:
gl.glGenTextures(1, textures, 0);

Taking a look at the spec (see: http://docs.oracle.com/javame/config/cldc/opt-pkgs/api/jb/jsr239/javax/microedition/khronos/opengles/GL10.html) it turns out there is just a single texture id allocated stored at index 0 in the textures array.
Why then a (pseudo) array at all?
The seemingly complex signature of the java method
public void glGenTextures(int n, int[] textures, int offset)

is due to the fact that there are no pointers in java while the C function that gets wrappped requires a pointer as it's second argument:
void glGenTextures(GLsizei n, GLuint *textures);

As in C code allocating a single texture can be done with:
  GLuint texture_id;
  glGenTextures (1, &texture_id);

there is no need for a special function just returning a single texture id, so there's only a single glGenTextures() function available.
To allow for allocations that can be done with pointer arithmetic like:
  GLuint textures[10];
  glGenTextures (3, textures + 5);

in C the java wrapper allows for a third parameter specifying the starting index from which to assign allocated texture ids.
The corresponding method invocation in java would look like this:
   int[] textures = new int[10];
   glGenTextures (3, textures, 5);

Thus one more parameter in java wrapper and the requirement to use an array even if only a single id is needed.


text:
Q: To find a value and delete previous two records I want to find the value "No Results" and remove the row and two rows above it.
Name 1(A1)
  (A2 is empty)     App(B2)     Efforts (C2)

No Results(A3)
Name 3 (A4)
Valid  (A5)
Name 2(A6)
(A7 is empty)
No Results(A8)

I am able to remove the record were the value is, but not the records above it. Tried Cells(i-2, "A").EntireRow.Delete but it removes all records above it. Could you please help.
Sub Macro1()
    Last = Cells(Rows.Count, "A").End(xlUp).Row
    For i = Last To 1 Step -1
      If (Cells(i, "A").Value) = "No Results" Then
        Cells(i, "A").EntireRow.Delete
      End If
    Next i
End Sub

A: Something like this should do the trick:
Public Sub Macro1()
    Dim i As Long

    For i = Cells(Rows.Count, "A").End(xlUp).Row To 1 Step -1
        If Cells(i, "A").Value = "No Result" Then
            Range((i-2) & ":" & i).Delete
        End If
    Next i
End Sub

This works only if the sheet you want to 'filter' is the currently active sheet, if this is intended to run from a module it would be best to specify the sheet explicitly e.g. Sheets("Sheet1").Cells(i, "A").
The only real change I've made to your own attempt is the use of Range rather than Cells within your If statement. With the Range function we can reference an Excel range using a string e.g. Range("A1"). In this case specifically we construct a string referencing the rows (i-2) to i, so for i = 9 we are executing Range("7:9").Delete.


text:
Q: Flutter UI freezez while rendring a large list of widgets What would be the proper way to render a huge number of widgets in a list without blocking UI? I have almost 700+ tags in firebase and I am trying to display them on a page using StreamBuilder like this:
class _TagsManagementPageState extends State<TagsManagementPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Search Tags"),
      ),
      body: Center(
        child: ListView(
          padding: EdgeInsets.all(20),
          shrinkWrap: true,
          children: <Widget>[
            StreamBuilder(
              stream:
                  FirebaseManager.firebaseDatabase().ref("search_tags").onValue,
              builder: (BuildContext context, AsyncSnapshot snap) {
                if (!snap.hasError && snap.hasData) {
                  DataSnapshot snapshot = snap.data.snapshot;
                  if (snapshot.hasChildren()) {
                    List tagsList = Map.from(snapshot.val()).values.toList()
                      ..sort((a, b) {
                        var tagA = a["title"] ?? "";
                        var tagB = b["title"] ?? "";
                        return tagA.toLowerCase().compareTo(tagB.toLowerCase());
                      });
                    return Wrap(
                      spacing: 8.0, // gap between adjacent chips
                      runSpacing: 4.0, // gap between lines
                      children: tagsList
                          .map((searchTag) => _TagItem(searchTag))
                          .toList(),
                    );
                  } else {
                    return Center(
                      child: Text(
                        "No Tag Available...!",
                        style: TextStyle(
                            fontSize: 25, fontWeight: FontWeight.bold),
                      ),
                    );
                  }
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            )
          ],
        ),
      ),
    );
  }
}

class _TagItem extends StatelessWidget {
  final searchTag;

  final delRef = FirebaseManager.firebaseDatabase().ref("search_tags");

  _TagItem(this.searchTag);

  @override
  Widget build(BuildContext context) {
    return InputChip(
      elevation: 3,
      deleteIconColor: Colors.red,
      label: Text(searchTag['title'] ?? "null"),
    );
  }
}

It works fine till loading from firebase but after that UI freezes for a while and then displays content on screen? How can I avoid this?

A: Try pagination for large amount of data, which will download data in small chunks. https://blog.solutelabs.com/paginate-your-data-in-flutter-7744995febd1

A: I think it is because of your sorting algorithm. You could try it without sorting first to see if that's the problem. If so you should take it out of your build method, put it into an async method and display a progress indicator while it's computing.


text:
Q: Cutting down UIImage memory usage I'm trying to find ways to cut down memory usage for my app right now, and I have an idea regarding UIImages. I make pretty extensive usage of UIImages, some of them common to multiple views. Is it a lot more memory efficient to instantiate a single UIImage and then use a pointer to that same image throughout the app rather than allocating a new UIImage for the same image in each view? Or, is the OS smart enough to sort of automatically cache a UIImage so that it is only stored in memory once? (doubt that's the case but I have to ask)
Thanks.

A: Straight from UIImage apple reference docs for imageNamed:

This method looks in the system caches for an image object with the
  specified name and returns that object if it exists. If a matching
  image object is not already in the cache, this method loads the image
  data from the specified file, caches it, and then returns the
  resulting object.

A: You use a lot of images, so remember that [UIImage imageNamed:@""]; caches the images, so if you are having low memory problem use instead [UIImage imageWithContentsOfFile:@""]; that doesn't cache it. Maybe that can help you cut down memory usage.

A: When a view unloads set the GUI properties to nil in the viewDidUnload method of UIViewController subclasses.

A: Yes, it is more efficient to store a single UIImage and use pointers to it.
It is unlikely that the OS caches images in this way, and even if it did, using pointers gives you more fine control of when the image is released / deallocated so that you don't have to hope the OS is going to take care of it.


text:
Q: How can I specify type for an "opaque" struct declaration with Cython? (empty struct `pa_threaded_mainloop` in PulseAudio) So first, the high-level problem (though the question is, I think a general cython question):
I'm using a raspberry pi to control some LEDs over an I2C bus. I'd like to control these by snooping the audio and doing fun signal-processing things, and it seems the most robust way to do this would be with PulseAudio (for example, registering callbacks is something I can't do with ALSA AFAICT). Available python bindings to PulseAudio aren't for the right version, and since I'm planning to use some relatively heavy signal processing libraries (which would work with numpy arrays), I may as well use cython.
I'm not sure it's relevant, but Raspbian wheezy ships with PulseAudio 2.0. If you're using a synchronous system to interact with PulseAudio, the docs recommend using the threaded mainloop. In particular, /usr/include/pulse/pulse/thread-mainloop.h includes these declarations:
/** An opaque threaded main loop object */
typedef struct pa_threaded_mainloop pa_threaded_mainloop;

/** Allocate a new threaded main loop object. You have to call
 * pa_threaded_mainloop_start() before the event loop thread starts
 * running. */
pa_threaded_mainloop *pa_threaded_mainloop_new(void);

This seems like a reasonable place to get started. In particular, my understanding is that cython doesn't need full type information specified in the .pyx file - I have no plan of digging into the guts of that struct, and simply letting the pulseaudio functions operate on it. So, here's my pulse.pyx file:
cimport cython

cdef extern from "pulse/thread-mainloop.h":
    cdef struct pa_threaded_mainloop:
        pass
    pa_threaded_mainloop pa_threaded_mainloop_new()

Just that much will actually compile. (I think I should be using a cdef here, but I get the same errors with a ctypedef.) If I add a line that just calls that function at the end of pulse.pyx:
pa_threaded_mainloop_new()

That works. But if I try to do anything with the return value, like:
mainloop = pa_threaded_mainloop_new()

or specifying a cdefed variable (or doing the cdef on a different line):
cdef mainloop = pa_threaded_mainloop_new()

I get an error at compile time:
pulse.c: In function 'initpulse':
pulse.c:659:3: error: type of formal parameter 1 is incomplete
pulse.c: At top level:
pulse.c:873:88: error: parameter 1 ('s') has incomplete type

I get a slightly different error with cdef pa_threaded_mainloop mainloop:
pulse.c: In function 'initpulse':
pulse.c:656:3: error: '__pyx_v_5pulse_mainloop' has an incomplete type

So, how might I go about correctly letting cython know about the PulseAudio 2.0 library? Note that I have directly installed cython 0.21, and more prosaic stuff like calling out to the standard C library works fine.


text:
Q: filter a view with date I have made a view in order to analyze a specific subject with PowerBI(I can't use other program). In My case the dataBase is according to the following ERD:
The ERD
I've created the following view:
CREATE VIEW sales_based_foodstyless AS
            (
                     SELECT   food_style,
                              total_quantities=Sum(quantity),
                              average_dish_price=Avg(d.price),
                              total _revenue=sum(quantity*price),
                              orders_amount=count(DISTINCT o.orderid),
                              total_vendors_operating=count( v.vendorid)
                     FROM     vendors  AS v
                     JOIN     food_style AS fs
                     ON       fs.vendorid=v.vendorid
                     JOIN     dishes AS d
                     ON       v.vendorid=d.vendorid
                     JOIN     dish_quantities AS dq
                     ON       d.vendorid=dq.vendorid
                     JOIN     orders AS o
                     ON       dq.orderid=o.orderid
                     GROUP BY food_style
            )

I want in the PowerBI to filter the data by date which is to be found as Order_Date of the joined table in the select statement of the view. however I cannot managed to do it.
Help Please

A: You can add a filter for example
  CREATE VIEW sales_based_foodstyless AS
  (
    SELECT
      food_style,
      total_quantities=Sum(quantity),
      average_dish_price=Avg(d.price),
      total _revenue=sum(quantity*price),
      orders_amount=count(DISTINCT o.orderid),
      total_vendors_operating=count( v.vendorid)
    FROM vendors  AS v
    JOIN food_style AS fs      ON fs.vendorid=v.vendorid
    JOIN dishes AS d           ON v.vendorid=d.vendorid
    JOIN dish_quantities AS dq ON d.vendorid=dq.vendorid
    JOIN orders AS o           ON dq.orderid=o.orderid
    WHERE YEAR(order_date) = 2018
    GROUP BY food_style
  )

However, if you want to do this dynamically you would have to use a stored procedure or parameterized view.

A: You can do this with a table-valued function:
CREATE FUNCTION fSelectSalesBasedFoodstyles (
    @StartDate DATE
    , @EndDate DATE
    )
RETURNS TABLE
AS
RETURN

    SELECT   food_style,
            total_quantities=Sum(quantity),
            average_dish_price=Avg(d.price),
            total _revenue=sum(quantity*price),
            orders_amount=count(DISTINCT o.orderid),
            total_vendors_operating=count( v.vendorid) ,
            order_date
    FROM     vendors  AS v
    JOIN     food_style AS fs
    ON       fs.vendorid=v.vendorid
    JOIN     dishes AS d
    ON       v.vendorid=d.vendorid
    JOIN     dish_quantities AS dq
    ON       d.vendorid=dq.vendorid
    JOIN     orders AS o
    ON       dq.orderid=o.orderid
        -- CAST only necessary if OrderDate is a DATETIME:
    WHERE CAST(o.order_date AS DATE) >= @StartDate
        AND CAST(o.order_date AS DATE) <= @EndDate
    GROUP BY food_style

GO


text:
Q: Ruby on Rails - doesn't recognise gem - installation issue? I'm just trying to build an app on rails to do a simple search on flickr. Unfortunately, before I can do anything remotely interesting, it doesn't seem to recognise the 'flickr' gem I installed. As a simple test, all I did was to generate a controller called flickr with a method called flickrsearch. In that method, all I put in there is
    require 'flickr'

but in the browser, I have the following error:
    cannot load such file -- flickr

In fact, I originally wanted to require 'flickr' in config/environment.rb but the server wouldn't even fire up. It gave me errors saying it couldn't load flickr. I've tried it with other installed gems as well but same result.
A month ago when I first played around with Ruby, I installed Ruby and some gems as well. Everything worked fine...but recently, I installed Rails using Railsinstaller on http://railsinstaller.org/ (I use Windows 7). So I'm guessing it's looking in the wrong place for gems.
So it looks like I originally had gems in c:\Ruby193 and now I also have gems in c:\RailsInstaller\Ruby1.9.3
So...I decided to delete the whole c:\Ruby193 in a moment of madness...I know, probably not the cleanest way to do it.
Then reinstalled the flickr gem (gem install flickr). This time, it actually create the gem files for flickr in c:\RailsInstaller\Ruby1.9.3. Which is what I expected but I'm still having the problem of Rails not recognising the flickr gem.
Please help...Many thanks.
Sam

A: You should not have to explicitly require gems in Rails. Just make sure you've added the flickr gem to your Gemfile and you've run the bundle install command.


text:
Q: finduser query returning nil Parse and swift I'm trying to find which user commented on the blog post. but it always returns nil and total objects 0, i'm not sure what am i doing wrong. This is my code to get the user's username
var finduser:PFQuery = PFUser.query()
finduser.whereKey("ObjectId", equalTo: commentclass.objectForKey("byuser").objectId)
finduser.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
    if error == nil {
        if let aobjects = objects {
           let puser = (aobjects as NSArray).lastObject as? PFUser
            cell.userName.text = puser?.username
            println(puser) // returns nil
            println(aobjects.count) // returns 0
        }
    }
}

A: It should be objectId and not ObjectId, also make sure there is no ACL set for the user object that might prohibit the requesting user from seeing this object.


text:
Q: How to differentiate between key "5" and "%" on keydown in jquery? I want to be able to have a trigger on keypress for %. So far, I have this:
$(iframeDocument).find('body').on('keydown', function(event) {
    if (event.which == 53) {
        alert("% pressed");
    }
});

But, it will also trigger when I press "5". How can I differentiate between the two?

A: You can use shiftKey property in the event object to check if the SHIFT is pressed when the event occurred.
var keyCode = event.which || event.keyCode;

if (event.shiftKey && keyCode === 53) {
    // Shift key is pressed
    console.log('% pressed');
}

A: Use event.key. It's visible on the demo in the jQuery documentation for .keydown().
$(iframeDocument).find('body').on('keydown', function(event) {
    if (event.key === '%') {
      console.log(event.key + ' pressed');
    }
});

MDN describes this property:

If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.

Just so you're aware, this property is not completely cross-browser compatible. See caniuse for a comprehensive list of supported and unsupported browsers.
If you're curious to mess around and see what values it yields, try this demo (it uses React just for fun):

class Label extends React.Component {
  static keydownListener(event) {
    this.setState({ label: event.key });
  }

  constructor() {
    super();

    this.state = { label: 'Press any key' };
    this.listener = Label.keydownListener.bind(this);

    window.addEventListener('keydown', this.listener);
  }

  componentWillUnmount() {
    window.removeEventListener('keydown', this.listener);
  }

  render() {
    return (
      <div>{this.state.label}</div>
    );
  }
}

ReactDOM.render(<Label />, document.body);

window.focus();
html, body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


text:
Q: Postgresql check if exists listen/notify function with specific name In one of DB migrations there are next commands:
CREATE OR REPLACE FUNCTION notify_document_package_update() RETURNS TRIGGER AS $$
    BEGIN
    PERFORM pg_notify('document_package_update','');
    RETURN NULL;
    END;

DROP TRIGGER IF EXISTS trigger_document_package_update ON invoices;
CREATE TRIGGER trigger_document_package_update
  AFTER UPDATE OR DELETE OR INSERT OR TRUNCATE
  ON invoices
  EXECUTE PROCEDURE notify_document_package_update();

Now I want to ensure that notify_document_package_update() exist in the database. (Insure that all fine on test/stage db).
How to do it with SQL query ?

A: It can be done with next query:
SELECT routine_name FROM information_schema.routines where routine_name='notify_document_package_update';


text:
Q: Windows 7 x64 - Junctions I've created a junction from a folder on the C: drive to a folder on a different drive. For some reason the data in the C folder is still being stored / written to the C drive folder, but also into the folder on the other drive.
Every other junction I've created have worked correctly.
(it's my iPhone backup folder)

A: Unlike shortcuts, the files in junctions will always show the "fake" path like C:\JunctionFolder\Subfolder\Data even though in reality once you're in C:\JunctionFolder, you are really working in another drive.

*

*Doing a search for files on your C drive will find files in a junction  by their fake names C:\JunctionFolder\etc.).

*Also, selecting several or all folders in your C drive and opening properties will count the number and size of files in your junction target as well, thus showing more files and total disk usage than what your C drive really contains.
However, the pie chart showin the properties of your drive partition (C) is reliable (right-click C drive, properties) - it will only include data that is written for real. To test this, copy a big file in your junction, and check these properties again.

A: If this were true, then that means you have two folders that are mirrored in real time.
Are you sure this is the case??
My guess is the junction is working correctly and the junction is working so transparently that it is fooling you.
You can confirm the junction is working correctly by simply looking at the junction under Explorer.  Right click and look for its target.


text:
Q: JMS auto persistance and auto recovery I'm trying to solve the next task:

*

*I have 1 output queue and 1 input queue and database.

*If output queue is not available, I need to persist all input messages to DB.

*As soon as output queue being available, input queue (or broker) should start send all messages from DB and, at the same time, delete these messages from DB. All should be done automatically, not manually.

Are any message brokers (ActiveMQ, RabbitMQ) have "out of the box" solution or not?

A: I don't think any of the messaging providers provide out of the box support that you are asking for. You need to write an application to do that job. The application can be very simple that uses global transactions to coordinate putting messages to queue and removing from database.
If your business logic allows, I would suggest you to look at the possibility of using persistent messages when putting to input queue. This way you can avoid persisting messages to a database when output queue is not available. When the output queue becomes available, your application can pull messages from input queue, process and put to output queue.


text:
Q: Regex: Previous statement must have mached at least 1 character I have a case-insensitive regex:
f?a?(x|csim)?(mob)?(ile\s*?)?(tel)?(e)?(phone|p|t|m)?\s*?:?\s*?(\s*?\(*?\d\)*?){8,10}
And here are my test cases:
I want these to match:

*

*Tel: 9555 5454

*telephone 08 9555 5454

*mobile 0411111 111

*Mob 0411 111 111

*Mobile : (0411) 111 111

*Telephone: (08) 9555 5454

*M0411111111

*phone : (08) 9555 5454

*p : (08)95 55 54 54

*T:0895555454

*Facsimile: (08) 9555 5353

*Fax 95555353

*F 95 55 53 53

But I don't want these to match

*

*0411 111 111

*(08) 9555 5454

*0411111111

Basically, I want to match things I identify as being a phone number, but only if they are prepended by an identifier to that effect.
My regex will successfully match the prefixed identifier, but because the whole thing is non-greedy, the "non-matching" test cases fail, because my regex specifies "match the prefix if it is there, but don't require it".
Any ideas?

*

*Please note: I am using the Perl/PHP version of regex.

A: My advise is to keep regular expressions simple. Your current regexp already include the required prefixes, but the work to minimize the size of the regexp has incidentally made them optional.
If you keep the minimization to a minimum it would help:
\b(tel(ephone)?|mob(ile)?|facsimile|fax|[tmpf]):?\s?(\(\d+\))(\d|\s)+

The would make the prefix non-optional and also prevent a lot of garbage to be accepted. For example:
axilep: (08) 9555 5454

A: You could have a positive lookahead at the start of the match, for something other than space, digit, parentheses or colon
so your:
f?a?(x|csim)?(mob)?(ile\s*?)?(tel)?(e)?(phone|p|t|m)?\s*?:?\s*?(\s*?\(*?\d\)*?){8,10}

becomes:
(?=[^\s\d:()])f?a?(x|csim)?(mob)?(ile\s*?)?(tel)?(e)?(phone|p|t|m)?\s*?:?\s*?(\s*?\(*?\d\)*?){8,10}

However, this doesn't help the axilep problem as pointed out by pmakholm - his solution of explicit alternatives is much nicer to read, and less likely for you to leave some weird edgecase open.

A: What about this:
(f?a?(x|csim)?(mob)?(ile\s*?)?(tel)?(e)?(phone|p|t|m)?)(?(1)\s*?:?\s*?(\s*?\(*?\d\)*?){8,10})

A: Alternatively to answer you question literally: You can do it by adding a zero-width look behind assertion matching a single character between the part of the regexp matching the prefix and the rest:
f?a?(x|csim)?(mob)?(ile\s*?)?(tel)?(e)?(phone|p|t|m)?(?<=.)\s*?:?\s*?(\s*?\(*?\d\)*?){8,10}

This means that after having found a match for the prefix it takes a second look to see if there is actually a character.


text:
Q: Dynamically Loading Images not cached I am trying to load an animated image on top of an element, and to do this I am switching between a list of pngs (labelled 1 - 124) and creating an image element for each of them and giving them a src.
The idea is I can have an empty image element and run a function to swap the src every 25 milliseconds with the next image in the list to give an animated image effect.
This works fine on Mac (chrome) as it loads the images ONCE and then seemlesly changes the src without loading any more images (I checked this by looking in the network tab of the chrome dev tools).
But for some reason on my windows PC it is sluggish and is trying to load the image from the server again every 25 miliseconds ..
cycle_images: function() {
    this.imageCount = (this.imageCount < 123) ? this.imageCount + 1 : 0;
    document.querySelector('.animated_image').html = this.imageList[this.imageCount];
},

This is the code I am using and I am confused why it works fine on my macbook but not my pc. Is there any way to force images to not re-load and just looad from cache?

A: One solution could be creating 124 img and make them invisible on the page and then change your image accordingly.
But a most promissing and proper way could be concatenating these image into one gif file and load it once! This way use internal engine to render and it is much more effecient and also does not affect on user experience.


text:
Q: Trying to translate a SAS GLM to R sasLM::GLM I have a data set like this:
X1 Record  Plot   Row Column    Cp   Csp Entry  Year Location Genotype Trait Value Whole_plot
 <dbl>  <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <chr>    <chr>    <chr> <dbl> <chr>
 1  3256    717   566     6      7     0     2   717  2019 Preston  Novelty  STD       5 6 + 7
 2  3263    716   567     6      7     0     1   716  2019 Preston  Flanders STD       4 6 + 7
 3  3893    716   657     7      8     0     1   716  2019 Preston  Flanders STD       2 7 + 8
 4  3900    717   658     7      8     0     2   717  2019 Preston  Novelty  STD       2 7 + 8
 5  4698    716   772     9      3     0     1   716  2019 Preston  Flanders STD       3 9 + 3
 6  4712    717   774     9      3     0     2   717  2019 Preston  Novelty  STD       3 9 + 3
 7  3257    717   566     6      7     0     2   717  2019 Preston  Novelty  V1        5 6 + 7
 8  3264    716   567     6      7     0     1   716  2019 Preston  Flanders V1        4 6 + 7
 9  3894    716   657     7      8     0     1   716  2019 Preston  Flanders V1        3 7 + 8
10  3901    717   658     7      8     0     2   717  2019 Preston  Novelty  V1        3 7 + 8

the SAS code is
PROC GLM DATA=MAD.MDA_plot_subplot_controls outstat=MAD.subplot_control_anova_stat;
    BY Year Location Trait;
    CLASS  Whole_plot Genotype;
    MODEL Value = Whole_plot Genotype/SS3;
    RANDOM Whole_plot;
    LSMEANS Whole_plot;
RUN;
QUIT;

what I tried was this
  require(sasLM)
  glm(Value ~ factor(Row) + factor(Column),MDA_plot_controls)

but I do get an error
Error in glm(Value ~ factor(Row) + factor(Column), MDA_plot_controls) :
  'family' not recognized
In addition: Warning message:
Unknown or uninitialised column: `family`.

i don't understand the 'family' column.


text:
Q: Firebase Real Time Database Has Been Deleted but Can still log in Yesterday my firebase app was working fine, and all of a sudden the Real-time database has been deleted. Is anyone else experiencing this? I can log in ok, but all my clients cannot fetch their data and neither can I. Please tell me this has happened before and it will come back to normal. I am currently on a flame plan with firebase.
Not a good look with my clients =(
any feedback is appreciated.
Thanks
C

A: Firebase Real Time Database and Firebase Auth both are different section and keep data separately. If your Firebase Real Time database has been deleted that means not deleted data of Auth.

A: Firebase Support was awesome in helping, however just received an email that they did not restore my data. Really weird, that it popped up out of nowhere. Has anyone else experienced this? In my console, the data branches where not there and it all looked deleted, I then had to click create a database and go to Real-time database and all of a sudden, an hour later, all my data showed on my screen. How is this possible? Crazy crazy crazy...


text:
Q: How to change a language of a third-party dll? I have a hird-party dll that need to be installed alongside with my app. In order to create a correct installer, all .dll files must have a LANGUAGE defined. Unfortunately, this third-party dll don't have a LANGUAGE :(. Is it any way to set a language for it without a recompilation? Maybe some command-line tool in Microsoft SDK?

A: I don't know if there's a tool to do it, but you can write one yourself. See http://www.codeproject.com/KB/cpp/UpdateVersion.aspx
Here's the sample code:
HANDLE hResource = BeginUpdateResource(lpszFile, FALSE);
if (NULL != hResource)
{
    UINT uTemp;

    // get the language information
    if (VerQueryValue(lpBuffer,
                      _T("\\VarFileInfo\\Translation"),
                      (LPVOID *) &lpTranslate,
                      &uTemp) != FALSE)
    {
        // could probably just use LANG_NEUTRAL/SUBLANG_NEUTRAL
        if (UpdateResource(hResource,
                           RT_VERSION,
                           MAKEINTRESOURCE(VS_VERSION_INFO),
                           lpTranslate->wLanguage,
                           lpBuffer,
                           dwSize) != FALSE)
        {
            EndUpdateResource(hResource, FALSE);
        }
    }
}


text:
Q: use bash function in sed command I have a file called d1.txt
line1
line2

and a.sh
#!/bin/bash
read -p  'Name : ' domain
#Not Working Command: sed -i s/$/' >> domain-js-m1-1.js/ d1.txt

I want to add ' >> $domain-1.js in the last of every line in d1.txt using script a.sh
I try this cmd but this is not adding text from input
sed -i s/$/' >> $domain-1.js/ d1.txt

read -p 'Name: ' domain  If I give shin in input
then I want this in output
line1' >> shin-1.js
line2' >> shin-1.js

Thanks In Advance

A: You just need to use backslash and double qoutes, like so:
sed -i 's/$/'\'" >> $domain-1.js/" d1.txt


text:
Q: SQL query ordering and using group by products
id          product_cat_id         product_type_id         title       ordering
1               42                        1                 "a"            1
2               42                        1                 "b"            2
3               42                        2                 "c"            1
4               43                        1                 "d"            1

product_cats
id             title               ordering
1                "n"                   1
2                "b"                   2
3                "h"                   3

product_types
id             title               ordering
1                "b"                   1
2                "n"                   2
3                "m"                   3

My SQL query is this:
SELECT
`products`.`title`,
`product_types`.`title`
FROM
`products`,
`product_cats`,
`product_types`
WHERE
`products`.product_cat_id=42
ORDER BY `product_types`.`ordering`,`products`.`ordering` ASC

But my SQL query returns all of the titles which do not even have a product_cat_id equal to 42. I tried using group_by and was was still unsuccessful.
I am looking for this:
product_title         product_type_title
    "a"                        "b"
    "b"                        "b"
    "c"                        "n"

A: SELECT p.title AS product_title, pt.title AS product_type_title
FROM products p
INNER JOIN product_types pt
    ON p.product_type_id = pt.id
WHERE p.product_cat_id = 42
ORDER BY pt.ordering, p.ordering

A: SELECT
    `products`.`title`,
    `product_types`.`title`
FROM
    `products`
INNER JOIN
    `product_types` ON `products`.`product_type_id` = `product_types`.`id`
WHERE
    `products`.product_cat_id=42
ORDER BY
    `product_types`.`ordering`,`products`.`ordering` ASC


text:
Q: iTerm2 & Atom - Switch profiles based on input bash commands in ~/.bash_profile, looking for suggestions The weather has gotten pretty decent where I am at and recently I've been working outside more often than not. Usually when inside I use a dark theme that is comfortable for the eye, but outside, obviously, I can't see crap and resort to changing iTerm & Atom themes' to ones with a light background.
I'm a man of shortcuts, and after doing some investigation online and some Googling I haven't seen anything that would allow me to change iTerm's or Atom's configuration directly via the terminal. The objective would be to type light to change my Atom's and iTerm's configuration to a lighter theme, and dark to change them back to dark (via ~/.bash_profile).
Regarding iTerm in specific, my idea was to directly modify the configuration file at ~/Library/Prferences/com.googlecode.iterm2.plist when the commands are run. More specifically (so I don't have to deal with converting .plist files to .xml and then back) I would just set up two git branches and flip between them on command.
However, the solution above is extremely bootleg, and not effectively transferable over to other machines, which I do like to be the cases I reformat my computer (yearly clean). I was wondering if someone would have an idea, or has encountered something similar to this and would be willing to give some suggestions that might possibly work.
Much appreciated!

A: If you're on 10.14 or later (with system dark theme) you can have both of those applications sync with the system dark theme...
To make iTerm sync with system dark, follow these instructions. Basically make a Dark and Light profile in iTerm, and drop this in a bash profile. More details at that link if needed.
if [[ "$(uname -s)" == "Darwin" ]]; then
    sith() {
        val=$(defaults read -g AppleInterfaceStyle 2>/dev/null)
        if [[ $val == "Dark" ]]; then
            i
        fi
    }

    i() {
        if [[ $ITERM_PROFILE == "Terminal" ]]; then
            echo -ne "\033]50;SetProfile=Dark\a"
            export ITERM_PROFILE="Dark"
        else
            echo -ne "\033]50;SetProfile=Terminal\a"
            export ITERM_PROFILE="Terminal"
        fi
    }

    sith
fi

To make Atom sync with the system dark theme, use dark-mode or mojave-dark-mode.
Finally, you can easily toggle between light and dark mode either from Alfred with this plugin, an app called Shifty, or via /usr/bin/osascript with this command... (you can call it from a bash script and wire it up however you need).
systemEvents.appearancePreferences.darkMode = !systemEvents.appearancePreferences.darkMode()


text:
Q: Motion of a projectile We all are aware how we can use the forces and vectors to describe a classical projectile motion (No drag forces).
Major things we already know include:

*

*Position-time dependence of projectiles

*Range of projectile

*Distance traversed by projectile

*Curvature at any point

My question relates to a 3D-Geometrical interpretation of the motion.
Consider a cubical environment with appropriate dimensions and align the x,y,z axes with the cube.
We start a projectile at one of the bottom corner and throw it such that it reaches the diagonally opposite corner. Take the angle of launch to be $\theta$ and the initial velocity as $u$.
My interests and questions:

*

*I want to find the system of equations of planes which will intersect at a point and give me the coordinates.

*How many varieties of such planes are possible?

A: That movement is ruled by an acceleration, which is the second derivative of position.
That means that you only need to specify two things: initial position, and initial velocity, (That includes magnitude and direction).
Given the initial position and the velocity, the plane in which the movement occurs is perfectly determined. So you would just choose that plane and work in two dimensions. It is not necessary to complicate it.
However, if you want to work in 3D, you can also do it. Just split your initial position and your initial velocity into its three components and you've got it:
$$ \begin{cases} \displaystyle x=x_0+v_{ox}t+ \frac{1}{2} a_x t^2 \\
y=y_0+v_{oy}t+ \frac{1}{2} a_y t^2 \\
 z=z_0+v_{oz}t+ \frac{1}{2} a_z t^2
\end{cases} $$

Edit:
Now that I see your comment, I understand what you mean.
Of course there are infinite possible moving planes whose intersection is one moving point.
The easiest solution is the one I said, just set:
$$ \begin{cases} \displaystyle x=x_0+v_{ox}t+ \frac{1}{2} a_x t^2 \\
y=y_0+v_{oy}t+ \frac{1}{2} a_y t^2 \\
 z=z_0+v_{oz}t+ \frac{1}{2} a_z t^2
\end{cases} $$
and those are actually three planes. The first one is $x=x_{particle}$, and so on.
Then, since they are planes
Any linear combination of those planes gives you another plane with the same solution.
That's the key of linear equations.
Check that all those planes depend on a parameter: $t$, which coincides with the time, but it is a free parameter after all.
One last thing, check that this question should belong to Mathematics SE


text:
Q: elFinder Issue with double clicking files I have integrated elFinder with an Asp.Net Mvc application using the information here.
Whenever a user double clicks a file the filesystem's path to the file is sent to the browser instead of the URL path.  However using the download button works perfectly. The files are in a folder not under the web folder.
Anyone seen this before? Know of a fix?
I am assuming the files (and their) paths are stored locally since I do not see a call to the server to "open" the file. I do see a server call to "open" folders. If that's the case it would appear the file path isn't being converted to the url path.

A: I ended up adding this option
            getFileCallback: function(file, fm) {
                $('#elfinder').elfinder('instance').exec('download');
            }

Works like a charm.

A: You can also overwrite the doubleclick handler
//
var elf = $('#elfinder').elfinder(
{
    url: 'example.com/connector.php',
    //Other settings
    handlers:
    {
        dblclick: function(event, elfinderInstance)
        {
            elfinderInstance.exec('download');
        }
    }
}).elfinder('instance');


text:
Q: Prevent ReadFile or ReadAll from reading EOF I start learning Go and I am a bit puzzled by the fact it includes the EOF when using the ioutil.ReadFile function. I want, for example, to read a file and parse all its lines on a field separator.
Sample input File:
CZG;KCZG;some text
EKY;KEKY;some text
A50;KA50;some text
UKY;UCFL;some text
MIC;KMIC;some text
K2M;K23M;some text

This is what I do to read and parse that file:
import(
    "fmt"
    "log"
    "io/ioutil"
    "strings"
    )

func main() {
    /* Read file */
    airportsFile := "/path/to/file/ad_iata"
    content, err := ioutil.ReadFile(airportsFile)
    if err != nil {
        log.Fatal(err)
    }

    /* split content on EOL */
    lines := strings.Split(string(content), "\n")

    /* split line on field separator ; */
    for _, line := range lines {
        lineSplit := strings.Split(line, ";")
        fmt.Println(lineSplit)
    }
}

The string.Split function adds a empty element at the end of the lineSplit slice when it sees the EOF (nothing to parse). Therefore, if I want to access the second index of that slice (lineSplit[1]) I run into a panic: runtime error: index out of range. I have to restrict the range by doing this
/* split line on field separator ; */
lenLines := len(lines) -1
for _, line := range lines[:lenLines] {
    lineSplit := strings.Split(line, ";")
    fmt.Println(lineSplit[1])
}

Is there a better way if I want to keep using ReadFile for its terseness ?
The same problem occurs when using ioutil.ReadAll

A: There is no such thing as an "EOF byte" or "EOF character". What you are seeing is probably caused by a line break character ('\n') at the very end of the file.
To read a file line by line, it's more idiomatic to use bufio.Scanner instead:
file, err := os.Open(airportsFile)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    line := scanner.Text()
    // ... use line as you please ...
}

if err := scanner.Err(); err != nil {
    log.Fatal(err)
}

And this actually addresses your problem, because Scanner will read the final newline without starting a new line, as evidenced by this playground example.

A: Your input File seeems to be CSV file, so you can use encoding/csv
airportsFile := "/path/to/file/ad_iata"
content, err := os.Open(airportsFile)
    if err != nil {
        log.Fatal(err)
    }
r := csv.NewReader(content)
r.Comma = ';'
records, err := r.ReadAll()  /* split line on field separator ; */
if err != nil {
    log.Fatal(err)
}
fmt.Println(records)

which looks terse enough for me and provide correct output
[[CZG KCZG some text] [EKY KEKY some text] [A50 KA50 some text] [UKY UCFL some text] [MIC KMIC some text] [K2M K23M some text]]

A: You may use scanner.Err() to check for errors on file read.
// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
    if s.err == io.EOF {
        return nil
    }
    return s.err
}

In general in go the idiomatic way to read and parse a file is to use bufio.NewScanner which accept as an input parameter the file to read and returns a new Scanner.
Considering the above remarks here is a way you can read and parse a file:
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    input, err := os.Open("example.txt")

    if err != nil {
        panic("Error happend during opening the file. Please check if file exists!")
        os.Exit(1)
    }

    defer input.Close()

    scanner := bufio.NewScanner(input)
    for scanner.Scan() {
        line := scanner.Text()
        fmt.Printf("%v\n", line)
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading input:", err)
    }
}


text:
Q: DOCTYPE CSS problem When I added
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

line to the top of my html file, my css rules disappear in firefox. Also i can't see them with firebug.
Do you have any idea about this problem ?

A: Make sure that the files are sent by the server with the correct MIME type (text/css). Have a look in the error console ( IIRC the menu should be Tools / Error Console in the English version).
Usually, if the file ends with .css, this should happen automatically, however there are still badly configured servers around. If you are using a Apache web server, you may be able to correct this with a .htaccess file, otherwise you'll need to ask your support.
Details: https://developer.mozilla.org/en/incorrect_mime_type_for_css_files

A: You need to add attributes to your start-html tag to get it right. This is done since XHTML really is XML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <link href="style.css" rel="stylesheet" type="text/css" />

    ...

The code above suggest you to have the style.css file in the root-catalog of your website.

A: Please check it
http://www.w3schools.com/tags/tag_doctype.asp
i think you have more idea of doctype
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

 Content

 Side Content


text:
Q: Is there a php function like python's zip? Python has a nice zip() function. Is there a PHP equivalent?

A: Solution
The solution matching zip() very closely, and using builtin PHP functions at the same time, is:
array_slice(
    array_map(null, $a, $b, $c), // zips values
    0, // begins selection before first element
    min(array_map('count', array($a, $b, $c))) // ends after shortest ends
);

Why not simple array_map(null, $a, $b, $c) call?
As I already mentioned in my comment, I tend to favor nabnabit's solution (array_map(null, $a, $b, ...)), but in a slightly modified way (shown above).
In general this:
array_map(null, $a, $b, $c);

is counterpart for Python's:
itertools.izip_longest(a, b, c, fillvalue=None)

(wrap it in list() if you want list instead of iterator). Because of this, it does not exactly fit the requirement to mimic zip()'s behaviour (unless all the arrays have the same length).

A: You can find zip as well as other Python functions in Non-standard PHP library. Including operator module and defaultarray.
use function nspl\a\zip;
$pairs = zip([1, 2, 3], ['a', 'b', 'c']);

A: array_combine comes close.
Otherwise nothing like coding it yourself:
function array_zip($a1, $a2) {
  for($i = 0; $i < min(length($a1), length($a2)); $i++) {
    $out[$i] = [$a1[$i], $a2[$i]];
  }
  return $out;
}

A: Try this function to create an array of arrays similar to Python's zip:
function zip() {
    $args = func_get_args();
    $zipped = array();
    $n = count($args);
    for ($i=0; $i<$n; ++$i) {
        reset($args[$i]);
    }
    while ($n) {
        $tmp = array();
        for ($i=0; $i<$n; ++$i) {
            if (key($args[$i]) === null) {
                break 2;
            }
            $tmp[] = current($args[$i]);
            next($args[$i]);
        }
        $zipped[] = $tmp;
    }
    return $zipped;
}

You can pass this function as many array as you want with as many items as you want.

A: As long as all the arrays are the same length, you can use array_map with null as the first argument.
array_map(null, $a, $b, $c, ...);

If some of the arrays are shorter, they will be padded with nulls to the length of the longest, unlike python where the returned result is the length of the shortest array.

A: This works exactly as Python's zip() function, and is compatible also with PHP < 5.3:
function zip() {
    $params = func_get_args();
    if (count($params) === 1){ // this case could be probably cleaner
        // single iterable passed
        $result = array();
        foreach ($params[0] as $item){
            $result[] = array($item);
        };
        return $result;
    };
    $result = call_user_func_array('array_map',array_merge(array(null),$params));
    $length = min(array_map('count', $params));
    return array_slice($result, 0, $length);
};

It merges the arrays in the manner Python's zip() does and does not return elements found after reaching the end of the shortest array.
The following:
zip(array(1,2,3,4,5),array('a','b'));

gives the following result:
array(array(1,'a'), array(2,'b'))

and the following:
zip(array(1,2,3,4,5),array('a','b'),array('x','y','z'));

gives the following result:
array(array(1,'a','x'), array(2,'b','y'))

Check this demonstration for a proof of the above.
EDIT: Added support for receiving single argument (array_map behaves differently in that case; thanks Josiah).

A: I wrote a zip() functions for my PHP implementation of enum.
 The code has been modified to allow for a Python-style zip() as well as Ruby-style. The difference is explained in the comments:
/*
 * This is a Python/Ruby style zip()
 *
 * zip(array $a1, array $a2, ... array $an, [bool $python=true])
 *
 * The last argument is an optional bool that determines the how the function
 * handles when the array arguments are different in length
 *
 * By default, it does it the Python way, that is, the returned array will
 * be truncated to the length of the shortest argument
 *
 * If set to FALSE, it does it the Ruby way, and NULL values are used to
 * fill the undefined entries
 *
 */
function zip() {
    $args = func_get_args();

    $ruby = array_pop($args);
    if (is_array($ruby))
        $args[] = $ruby;

    $counts = array_map('count', $args);
    $count = ($ruby) ? min($counts) : max($counts);
    $zipped = array();

    for ($i = 0; $i < $count; $i++) {
        for ($j = 0; $j < count($args); $j++) {
            $val = (isset($args[$j][$i])) ? $args[$j][$i] : null;
            $zipped[$i][$j] = $val;
        }
    }
    return $zipped;
}

Example:
$pythonzip = zip(array(1,2,3), array(4,5),  array(6,7,8));
$rubyzip   = zip(array(1,2,3), array(4,5),  array(6,7,8), false);

echo '<pre>';
print_r($pythonzip);
print_r($rubyzip);
echo '<pre>';

A: /**
 * Takes an arbitrary number of arrays and "zips" them together into a single
 * array, taking one value from each array and putting them into a sub-array,
 * before moving onto the next.
 *
 * If arrays are uneven lengths, will stop at the length of the shortest array.
 */
function array_zip(...$arrays) {
    $result = [];
    $args = array_map('array_values',$arrays);
    $min = min(array_map('count',$args));
    for($i=0; $i<$min; ++$i) {
        $result[$i] = [];
        foreach($args as $j=>$arr) {
            $result[$i][$j] = $arr[$i];
        }
    }
    return $result;
}

Usage:
print_r(array_zip(['a','b','c'],[1,2,3],['x','y']));

Output:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
            [2] => x
        )

    [1] => Array
        (
            [0] => b
            [1] => 2
            [2] => y
        )

)

A: // create
$a = array("a", "c", "e", "g", "h", "i");
$b = array("b", "d", "f");
$zip_array = array();

// get length of the longest array
$count = count(max($a, $b));

// zip arrays
for($n=0;$n<$count;$n++){
    if (array_key_exists($n,$a)){
        $zip_array[] = $a[$n];
        }
    if (array_key_exists($n,$b)){
        $zip_array[] = $b[$n];
        }
    }

// test result
echo '<pre>'; print_r($zip_array); echo '<pre>';

A: function zip() {
    $zip = [];
    $arrays = func_get_args();
    if ($arrays) {
        $count = min(array_map('count', $arrays));
        for ($i = 0; $i < $count; $i++) {
            foreach ($arrays as $array) {
                $zip[$i][] = $array[$i];
            }
        }
    }
    return $zip;
}

A: This works like in Python
function zip(...$arrays) {
  return array_filter(
      array_map(null, ...(count($arrays) > 1 ? $arrays : array_merge($arrays, [[]]))),
      fn($z) => count($z) === count(array_filter($z)) || count($arrays) === 1
  );
}

A: To overcome the issues with passing a single array to map_array, you can pass this function...unfortunately you can't pass "array" as it's not a real function but a builtin thingy.
function make_array() { return func_get_args(); }

A: Dedicated to those that feel like it should be related to array_combine:
function array_zip($a, $b)
{
    $b = array_combine(
        $a,
        $b
        );

    $a = array_combine(
        $a,
        $a
        );

    return array_values(array_merge_recursive($a,$b));
}

A: you can see array_map method:
$arr1 = ['get', 'method'];
$arr2 = ['post'];

$ret = array_map(null, $arr1, $arr2);

output:
[['get', 'method'], ['post', null]]

php function.array-map


text:
Q: Triggering jQuery functions with PHP So far during my site development I have been storing all my jQuery functions in an external .js file, below are two examples of the functions inside:
// Loads the login form into the page.
function loadLoginForm() {
  $('[name=loadLoginForm]').click(function() {
    $("#loadingImage").css({ display:"block" });
    $("#mainWrap").load("modules/web/loginForm.php", null, function(data) {
      loadRegisterForm(this, data);
      validateLoginDetails(this, data);
      characterSelect(this, data);
    });
  });
}

// Loads the register form into the page.
function loadRegisterForm() {
  $('[name=loadRegisterForm]').click(function() {
    $("#loadingImage").css({ display:"block" });
    $("#mainWrap").load("modules/web/registerForm.php", null, function(data) {
      loadLoginForm(this, data);
      registerUser(this, data);
    });
  });
}

The way I have been triggering these functions was to echo a link onto the page using PHP such as this;
Click here to login.

The problem I am facing now is how do I let the PHP side of the code trigger an event instead of it giving the user a link to trigger it?
The only answer I came up with was to get the PHP to echo some JavaScript so when the page loads the JavaScript will trigger the function needed, but I don't know how to code this.
A situation where this will need to be used is for example when the user has successfully logged in, I don't won the PHP to give the user a link to go to the next part I wont it to go there automatically.

A: I think it's best to have a whole bunch of Javascript functions externally like you seem to be doing. No (or little) code should be executed in that common external JS File. Then in your HTML pages themselves you add some dynamic Javascript:

Alternatively you can put the ready() code inside the functions. This way only the minimal and necessary code gets executed on a page.
Trust me, I've done it the other way (where all the code gets executed on every page) and the page load times get stupidly high very quickly.
Edit: if you simply want to invoke an event, say you have:
Delete

you just need:
$(function() {
  $("#delete").click();
});

(assuming the click handler has been assigned). click() with no arguments triggers a click event.
You can also effectively set "this" in manually called Javascript. Imagine you have:
$("#delete").click(delete_stuff);

function delete_stuff() {
  alert($(this).attr("href"));
  return false;
});

you can call that elsewhere with:
delete_stuff.call($("#delete")[0]);

That is explicitly setting "this". See JavaScript call and apply.
Does that help?

A:
The problem I am facing now is how do
  I let the PHP side of the code trigger
  an event instead of it giving the user
  a link to trigger it?

Perhaps use the load event? When the '[name=loadRegisterForm]' or '[name=loadLoginForm]' appear on the page they should run the code in the callback. I've not tested this, and am not sure whether this was what you were asking for, but I believe this is how the event works...
Have you considered doing this another way, however? You should avoid using javascript if there is anyway that the correct html can be created by the php on page load -- after all, that's what it's there for. I'm not normally the kind of guy that suggests that you should make a website always run without javascript, but it should be completely possible here and is good practice.