Fixtures PHP algorithm

Question: Struggling with  this tournament fixtures algorithm.
The code is working perfectly but I need help inserting the data to mysql
I cant seem to access the $varables..
any tweaking by a php pro greatly appreciated ...
$teamnames = "Arsenal|Tottenham|Leeds|Man United|Liverpool";

        # XXX check for int
        print show_fixtures(isset($_GET['teams']) ?  nums(intval($_GET['teams'])) : explode("|", trim($teamnames)));

function nums($n) {
    $ns = array();
    for ($i = 1; $i <= $n; $i++) {
        $ns[] = $i;
    }
    return $ns;
}

function show_fixtures($names) {
    $teams = sizeof($names);

    print "
Fixtures for $teams teams.
";

    // If odd number of teams add a "ghost".
    $ghost = false;
    if ($teams % 2 == 1) {
        $teams++;
        $ghost = true;
    }

    // Generate the fixtures using the cyclic algorithm.
    $totalRounds = $teams - 1;
    $matchesPerRound = $teams / 2;
    $rounds = array();
    for ($i = 0; $i < $totalRounds; $i++) {
        $rounds[$i] = array();
    }

    for ($round = 0; $round < $totalRounds; $round++) {
        for ($match = 0; $match < $matchesPerRound; $match++) {
            $home = ($round + $match) % ($teams - 1);
            $away = ($teams - 1 - $match + $round) % ($teams - 1);
            // Last team stays in the same place while the others
            // rotate around it.
            if ($match == 0) {
                $away = $teams - 1;
            }
            $rounds[$round][$match] = team_name($home + 1, $names)
                . " v " . team_name($away + 1, $names);

        }
    }

    // Interleave so that home and away games are fairly evenly dispersed.
    $interleaved = array();
    for ($i = 0; $i < $totalRounds; $i++) {
        $interleaved[$i] = array();
    }

    $evn = 0;
    $odd = ($teams / 2);
    for ($i = 0; $i < sizeof($rounds); $i++) {
        if ($i % 2 == 0) {
            $interleaved[$i] = $rounds[$evn++];
        } else {
            $interleaved[$i] = $rounds[$odd++];
        }
    }

    $rounds = $interleaved;

    // Last team can't be away for every game so flip them
    // to home on odd rounds.
    for ($round = 0; $round < sizeof($rounds); $round++) {
        if ($round % 2 == 1) {
            $rounds[$round][0] = flip($rounds[$round][0]);
        }
    }

    // Display the fixtures
    for ($i = 0; $i < sizeof($rounds); $i++) {
        print "

Round " . ($i + 1) . "
\n";
        foreach ($rounds[$i] as $r) {

      print $r . "
";

        }
        print "
";
    }
    print "
Second half is mirror of first half";
    $round_counter = sizeof($rounds) + 1;
    for ($i = sizeof($rounds) - 1; $i >= 0; $i--) {
        print "

Round " . $round_counter . "
\n";
        $round_counter += 1;
        foreach ($rounds[$i] as $r) {
            print flip($r) . "
";
        }
        print "
";
    }
    print "
";

    if ($ghost) {
        print "Matches against team " . $teams . " are byes.";
    }
}

function flip($match) {
    $components = split(' v ', $match);

    return "$components[1]" . " v " . "$components[0]";

}

function team_name($num, $names) {
    $i = $num - 1;
    if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) {
        return trim($names[$i]);
    } else {
        return "BYE";
    }
}

Comment: What exactly is wrong with the given code? What doesn't work?
Comment: Where is it bombing out?
Comment: The code works I just need help on the insert
Comment: @Webby, That isn't helpful....  **What** do you need help with?  Be specific.  **Where** in the code do you need help?  **What have you tried?**
Comment: I need help Inserting the generated fixtures into mysql
Comment: @Webby, I am not upset.  Blunt perhaps, but if you read what I have written in these comments, I have told you exactly how to solve the problem that you have.  I don't know the answer to your question, because I have no idea what your question is.  You said you need help inserting stuff into a database.  That leaves 1,000+ possible questions, from installing the MySQL extension for PHP to getting your query replicated to slave servers.  My guess is that you need the basics, and I linked you to a tutorial for just that.  I don't see the problem here.
Answer: I'm not entirely sure what you're hung up on (you should really be more specific in your questions, as specified by the FAQ), but I suspect it is a matter of scope.
When you set a variable within a function, that variable is only accessible within that function.  For example:
function do_something() {
    $a = 'something!';
}
do_something();
echo $a;

This should result in PHP notice telling you that PHP doesn't know what $a is in the scope that it is trying to echo.  Now, if I modify this script...
$a = '';
function do_something() {
    global $a; // Lets PHP know we want to use $a from the global scope
    $a = 'something!';
}
do_something();
echo $a;

This will work and output "something!", because $a is being "defined" in the scope outside of the function.
You can read more about variable scope in the PHP documentation:  http://php.net/manual/en/language.variables.scope.php
Now, something else you need to pay attention to is outputting user data.  In your script, you take data straight from $_GET and print it out to the page.  Why is this bad?  Someone could inject some nice JavaScript into your page (or anything they wanted) and steal users' sessions.  You should be using htmlspecialchars() any time you need to output a variable.  Even if it is just a team name, you never know when some team will stick a ; or < or > or some other reserved character in there.
Finally, I strongly recommend not mixing your logic with your computation.  Let your program figure everything out, and then loop through the data for your output.  You should be able to save the entire data for this type of problem in a nice associative array, or some crafty object you come up with.
Comment: PHP isn't JavaScript. Your second example will not work. You have to use `global $a;` to make it global/ override the global $a.
Comment: Thanks for update seems it was a global issue.. I've not come across this before.. many thanks!

Fixtures PHP algorithm


AngularJS Routing Configuration not called

Question: I am running through a course at the moment on AngularJS and it has just introduced the concept of routing.
My problem is the app.config function is setup in app.js however, the function doesn't seem to ever be called and therefore the routes are not setup.
The common problem is the ngRoute not being declared however, it is. I'm not sure if there is a problem with the versions of Angular that I'm using but these were taken from the online course.
I have a public plnkr for anyone to view and have a look at    http://plnkr.co/edit/L2FG4M?p=preview
(function() {
  var app = angular.module("githubViewer", ["ngRoute"]);

  app.config(function($routeProvider) {
    // If we navigate to /main then the page used will be main.html and the controller
    // MainController, if however something else is provided then we will
    // redirect to /main as well
    $routeProvider.when("/main", {
      templateUrl: "main.html",
      controller: "MainController"
    })
    .otherwise({
      redirectTo: "/main"
    });
  });
}());

Any help is appreciated, I've exhausted my options now.
Thanks
Marc
Comment: You're using angular 1.3.14 with ngRoute 1.2.14. Use the same version for both.
Answer: In your MainController.js file, you defined a new module with same name as in app.js:
angular.module("githubViewer", []);

What you want to do is retrieve the already defined module. You can acheive that by removing the []:
angular.module("githubViewer");

Look here at the "Creation versus Retrieval" section.


Pachner moves for graph of 4-valent nodes

Question: For 3-simplices (i.e. tetrahedra), I understand the basic idea behind the Pachner moves 1 $\leftrightarrow$ 4, which takes one tetrahedron and replaces it with four (or vice versa), and 2 $\leftrightarrow$ 3, which shifts between 2 and 3 tetrahedra. These moves can also be defined on the dual graph to the tetrahedron, where the graph has a 4-valent node corresponding to each 3-simplex, and each edge in the graph corresponds to a face of the tetrahedron.
However, I am curious specifically about performing this 2 $\leftrightarrow$ 3 move on an arbitrary 4-valent graph. Is there an ambiguity about which edges you put together at each of the new nodes, when you go in the 2 $\to$ 3 direction? Since you seem to lack information about whether a triangulation is dual to the graph, it appears to me you have six possible choices of how to join the edges up. Going the other direction, 3 $\to$ 2, also seems to have an ambiguity in how to group edges into two groups of three.
Answer: Yes, the ambiguity that you mention does exist. This is because the dual graphs do not completely represent a triangulation. Each triangulation has one dual graph; but each such dual graph can be created from many triangulations.
Self plug: If you want to see a modification of the dual graph representation that does not lose any information of this information, feel free to read through http://arxiv.org/abs/1412.2169. In this setting you can perform the $2 \leftrightarrow 3$ and $1 \leftrightarrow 4$ Pachner moves without any ambiguity.


Casorati-Weierstraß theorem - dense

Question: I try to understand the Casorati-Weierstraß theorem. But I don't understand when a picture is dense in C. $e^{1/z}$ is dense, $1/z$ isn't. But why?
Thanks.
Answer: No function is (or isn't) dense. That theorem says that if $V$ is a neighborhood of an essential singularity at $a$ of a function $f$, then $f(V\setminus\{a\})$ is dense. Well, $0$ is not an essential singularity of $\frac1z$ (it's a simple pole), but it is an essential singularity of $\exp\left(\frac1z\right)$.

Casorati-Weierstraß theorem - dense


Collect controls in a form c#

Question: I have a form in which there are some buttons. I'd like put their references in an array.Is it possible with a foreach ?
I want to do this:
    public Form1()
    {
        InitializeComponent();
        Button[] all = new Button[5];
        all[0] = button1;
        all[1] = button2;
        all[3] = button3;
        all[4] = button4;
    }

I've already tried
int i=0;
foreach (Button p in Form1)
{
    all[i]= p;
    i++;
}

But I can't use a foreach on a Form.
The same thing if the buttons are in a panel.
What can I do to collect all buttons quickly?
Thanks :)
Comment: WinForms? WebForms? ASP.NET MVC? WPF? SilverLight?
Comment: The simplest way would probably be `Form1.Controls.OfType()`. If you *really* need it as an array, you can tack on `.ToArray()`.
Comment: You would have to iterate the this.Controls collection.  And keep your fingers crossed that they are in the order you want them.  Clearly there is nothing wrong with doing it explicitly.  Use the initializer syntax to make it more condense.  And declare the variable correctly, it is pretty useless as a local variable of your constructor.
Answer: You're looking for the Controls collection of your form or container, which contains every control directly in it.
Beware that this will also include non-Buttons; call .OfType<Button>() to filter.
So instead of the foreach you can initialize an array like this:
Button[] all = this.Controls.OfType<Button>().ToArray();

Comment: Thanks :) lucky doesn't matter the order in the array :)
Answer: Every Control has a Controls property which is a ControlCollection. You can get all Buttons on a Control (as a Form or a Panel) like this:
foreach(var button in control.Controls.OfType<Button>())
{ ... }

But this will only give you the Buttons that are contained directly by this control. If you want to get all Buttons in your Form on all Panels, GroupBoxs etc, you need to recurse through the Controlslike in this example:
public class Form1 : Form
{
    // ...

    private static IEnumerable<Button> GetAllButtons(Control control)
    {
        return control.Controls.OfType<Button>().Concat(control.Controls.OfType<Control>().SelectMany(GetAllButtons));
    }

    private void DoSomethingWithAllButtons()
    {
        foreach(var button in GetAllButtons(this))
        { // do something with button }
    }
}

Comment: Thanks :) lucky doesn't matter the order in the array :)

Collect controls in a form c#


Straight line in complex plane

Question: I searched and found that the line
$$y=mx+b$$
is expressed in complex plane as
$$0=\mathrm{Re}((m+i)z+b)$$
My question is : why not expressing it simply as $$ z=x + i (mx+b) $$
Comment: In complex analysis we primarily deal with complex valued functions of a complex variable. The former expression exhibit the line $y=mx+b$ as the zero set of the real part of the 1st degree polynomial $(m+i)z+b$, while the later just parametrizes it as we would do in $\mathbb{R}^2$. Why bringing complex analysis into the playground if we are not gonna use it?
Answer: Note that if $z = x+i(mx+b)$, then $$
(m+i)z + b = (m+i)(x+i(mx + b)) + b\\
= mx+mi(mx + b) + ix -(mx + b) + b\\
= mx -mx-b+b + i(m^2x + mb + x)\\
= i(m^2x + mb + x)
$$
which is pure imaginary (with real part $0$). On the other hand, if $z$ is such that $(m+i)z + b$ is pure imaginary, then if we set $z = x+iy$ with $x, y$ real we get
$$
(m+i)z + b = (m+i)(x+yi) + b\\
= mx + xi + myi - y + b\\
= mx-y+b + i(x+my)
$$
which implies that $mx - y + b = 0$ or $y = mx + b$. This gives $z = x + i(mx + b)$.
This means that the two criteria are equivalent. Why would you choose one over the other? That depends entirely on what you want to do with it afterwards. I can't read the minds of whichever author gave you the $0=\operatorname{Re}((m+i)z+b)$ criterion, but presumably, it was the best choice for whatever they wanted to use it for.

Straight line in complex plane


IntelliJ IDEA running Android Native Activity application

Question: I am trying to run the native activity sample that comes with the Android NDK. I remember it used to run fine with Eclipse but with IntelliJ IDEA I always get an error saying "Default Activity not found" when I select "Launch default Activity" from the run configuration dialog. If I try to enter the custom activity name like "android.app.NativeActivity" it again cannot find it.
Am I stuck with Eclipse or is there a workaround for this problem?
Comment: If you have the Ultimate Edition you should really contact JetBrains. They provide good support.
Answer: I'm afraid there is no support for launching NDK Activity right now, please submit a feature request.


Pyspark: flattem Array column

Question: I am parsing Azure EventHub avro message. The last column in a Array. I am trying to flatten it.
Before:
{"records":[{"time":"2020-01-28T04:50:20.0975886Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Start","resultSignature":"Started.","durationMs":"0","callerIpAddress":"184.108.40.206","correlationId":"xxxxxxx"},{"time":"2020-01-28T04:50:20.1122888Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Success","resultSignature":"Succeeded.NoContent","durationMs":"14","callerIpAddress":"18.104.22.168","correlationId":"xxxxxxx"}]}

This is what I have came up with, I think I am very close. I got the struct and I am able to remove the first value "records" but unable to handle the Array inside it.
from pyspark.sql.types import StringType, IntegerType, StructType, StructField
from pyspark.sql.functions import from_json, col
from pyspark.sql.functions import explode, flatten
from pyspark.sql.types import StringType, StructField, StructType, BooleanType, ArrayType, IntegerType

# Creates a DataFrame from a specified directory
df = spark.read.format("avro").load("/mnt/test/xxxxxx/xxxxxxxx/31.avro")

# cast a binary column(Body) into string
df = df.withColumn("Body", col("Body").cast("string"))

sourceSchema= StructType([
        StructField("records", ArrayType(
            StructType([
                StructField("time", StringType(), True),
                StructField("resourceId", StringType(), True),
                StructField("operationName", StringType(), True),
                StructField("category", StringType(), True),
                StructField("resultType", StringType(), True),
                StructField("resultSignature", StringType(), True),
                StructField("durationMs", StringType(), True),
                StructField("callerIpAddress", StringType(), True),
                StructField("correlationId", StringType(), True)
            ])
        ), True)
    ])

df = df.withColumn("Body", from_json(df.Body, sourceSchema))

# Flatten Body
for c in df.schema['Body'].dataType:
    df2 = df.withColumn(c.name, col("Body." + c.name))
    display(df2)

After:
[{"time":"2020-01-28T04:50:20.0975886Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Start","resultSignature":"Started.","durationMs":"0","callerIpAddress":"18.104.22.168","correlationId":"xxxxxxx"},{"time":"2020-01-28T04:50:20.1122888Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Success","resultSignature":"Succeeded.NoContent","durationMs":"14","callerIpAddress":"22.214.171.124","correlationId":"xxxxxxx"}]

Comment: It's unclear which result you are expecting to get, maybe add an example by manually flatting part of the string
Comment: I need each entry to go a separate column, like 'time' in one, 'resourceId' in another and go on..
Comment: does [this](https://stackoverflow.com/questions/45967562/how-to-use-from-json-with-schema-as-string-i-e-a-json-encoded-schema) answer your query?
Answer: maybe try this:
import pandas as pd
from pandas.io.json import json_normalize
s = {"records":[{"time":"2020-01-28T04:50:20.0975886Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Start","resultSignature":"Started.","durationMs":"0","callerIpAddress":"188.8.131.52","correlationId":"xxxxxxx"},{"time":"2020-01-28T04:50:20.1122888Z","resourceId":"/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME","operationName":"MICROSOFT.COMPUTE/DISKS/DELETE","category":"Administrative","resultType":"Success","resultSignature":"Succeeded.NoContent","durationMs":"14","callerIpAddress":"184.108.40.206","correlationId":"xxxxxxx"}]}
json_normalize(s).values

The result you'll get is:
array([[list([{'time': '2020-01-28T04:50:20.0975886Z', 'resourceId': '/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME', 'operationName': 'MICROSOFT.COMPUTE/DISKS/DELETE', 'category': 'Administrative', 'resultType': 'Start', 'resultSignature': 'Started.', 'durationMs': '0', 'callerIpAddress': '18.104.22.168', 'correlationId': 'xxxxxxx'}, {'time': '2020-01-28T04:50:20.1122888Z', 'resourceId': '/SUBSCRIPTIONS/xxxxxxxxxxxx/RESOURCEGROUPS/xxxxx-xxxxxxxI/PROVIDERS/MICROSOFT.COMPUTE/DISKS/7C3E07DE8xxxxxxx-0-SCRATCHVOLUME', 'operationName': 'MICROSOFT.COMPUTE/DISKS/DELETE', 'category': 'Administrative', 'resultType': 'Success', 'resultSignature': 'Succeeded.NoContent', 'durationMs': '14', 'callerIpAddress': '126.96.36.199', 'correlationId': 'xxxxxxx'}])]],
  dtype=object)

Answer: I see lot of people have this question, hope this helps.
# Read Event Hub's stream
# if reading from file: Supported file formats are text, csv, json, orc, parquet

conf = {}
conf["eventhubs.connectionString"] = "Endpoint=sb://xxxxxxxxxxxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=jxxxxxxxxxxxx/xxxxxxxxxxxx=;EntityPath=eventhub"

# define dataframe for reading stream
read_df = (
  spark
    .readStream
    .format("eventhubs")
    .options(**conf)
    .option('multiLine', True)
    .option('mode', 'PERMISSIVE')
    .load()
)

# define struct for writing
sourceSchema= StructType([
        StructField("records", ArrayType(
            StructType([
                StructField("time", StringType(), True),
                StructField("resourceId", StringType(), True),
                StructField("operationName", StringType(), True),
                StructField("category", StringType(), True),
                StructField("resultType", StringType(), True),
                StructField("resultSignature", StringType(), True),
                StructField("durationMs", StringType(), True),
                StructField("callerIpAddress", StringType(), True),
                StructField("correlationId", StringType(), True)
            ])
        ), True)
    ])

# convert binary to string
decoded_df = read_df.select(F.from_json(F.col("body").cast("string"), sourceSchema).alias("payload"))

# write to memory
query1 = (
  decoded_df
    .writeStream
    .format("memory")
    .queryName("read_hub")
    .start()
)

Pyspark: flattem Array column


Windows Identity Foundation with Claims based Authentication and Multiple Roles

Question: We are implementing a Secure Token Service (STS) which uses Windows Identity Foundation to provide Claims based authentication and authorisation.
My question is really about best practices and how we should handle multiple roles for a given identity.
When creating claims for a user after they have successfully logged in, we need to be able to add the roles that the user is a member of to the claims before returning to the Relying Party.
The Claim object does not accept a collection of strings so I'm wondering how this should be done. I can think of two ways:

I can add multiple Claims of type ClaimTypes.Role with different values and these can be read on the other side (I have tested and this seems to work without any errors)
I could also put the roles into a single claim and delimit them by ; or something like that.

My question is really about which of the above is better, or am I missing something better? Neither solution is perfect as it will require parsing on the other side.
Thanks,
John
Answer: If you use ADFS as the STS, it inserts multiple roles into the claim
e.g.

...claims/role  Editor
...claims/role  Approver

etc.
The advantage of this is that WIF can then use the standard IsInRole constructs etc.
Comment: Thanks. We are using our own form of Authentication but if this is the way ADFS handles it then we can do the same.


Countering MMM + Vikings as Protoss?

Question: I was in a match on Blistering Sands versus a Terran that was going MMM. I naturally built Colossi, and to counter he got Vikings. Granted, in that match I was really bad on letting my opponent have intel (he owned both watch towers from about 6 minutes in), but I'm not sure what to do. Do you simply attack before he gets many Vikings? Or is there a Protoss unit that can down them effectively? I had at least as many Stalkers as he had Vikings but they couldn't protect my Colossi enough so that they would survive. (Maybe that's just my bad micro though :P)
Comment: what were your relative food counts?  did you have at least as big an army as him?  did you have as many workers?  Those factors are often more important to winning/losing than vikings vs colossi.
Comment: @Peter: He was going MMM, so without the vikings I would have curbstomped his army. He was expanding more than me though. I'm really bad at multitasking >.<
Answer: As Protoss you have the ability to tech switch (due to warp gates) significantly faster than a Terran player.  While Protoss has the ability to defend Collosus from Terran with stalkers or (not recommended:) phoenix there are smarter choices.
Instead of attempting to counter them, you could instead exploit what his army -doesn't- have.  (If you have an hour to spend, watch this day9 video where Gretorp discusses the value of exploiting what an army is lacking, not what counters it)  Your Collosus tech was built to counter his MMM.  Is it the only solution to MMM?
Once the Terran player has exposed his viking tech you can switch to high templar easily through warp gates, a direct counter to the MMM ball. (I'm assuming this is fairly late game) By doing this, your Terran enemy has wasted resources on Vikings which have very little utility against a Protoss ground army.
Abuse the fact that you can switch tech's faster then the Terran and make him counter you.  High level Zerg's are amazing at this!  You have the ability to set the momentum of the fights where Terran is looking to seize the moment when his ball can finally overwhelm you.
If this seems like a lot of work, out number his vikings 2 to 1 with stalkers + blink, but expect him to be able to snipe a few colossus due to his amazing 9 range.
Hope this helps!
Comment: Butbutbut i wanted to use my towering brains of doom! ;)
Comment: Don't we all =)

Countering MMM + Vikings as Protoss?


How to use webklex AttachmentMask class getContentBase64Encoded or getImageSrc

Question: I am having problems using the getImageSrc and getContentBase64Encoded under the AttachmentMask::class webklex.
The error message shows Method Webklex\IMAP\Message::getImgSrc() is not supported and Method Webklex\IMAP\Message::getContentBase64Encoded () is not supported.
$oClient = new Client([
 'host'          => $imap['host'],
'port'          => $account->imap_port_no,
'encryption'    => $ssl,
'validate_cert' => true,
'username'      => $account->user_name,
'password'      => $account->password,
]);

$oFolder = $oClient->getFolder($folder_name);
$oMessage = $oFolder->getMessage($message_id, null, null, true, true, true);

$test = $oMessage->getImgSrc();
    //or this
$test = $oMessage->getContentBase64Encoded();

Answer: got it working already using these line of codes.
$attachment_mask = \Webklex\IMAP\Support\Masks\AttachmentMask::class;

    $oClient->setDefaultAttachmentMask($attachment_mask);
    $attachment  = $oMessage->getAttachments()->first();
    $masked_attachment = $attachment->mask();

    $link = $masked_attachment->getImageSrc()

;


error while run npm run dev after adding extension for App Lock theme in shopify app MERN

Question: ━━━━━━ Error ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Command failed with exit code 1: bundle install
Your lockfile was created by an old Bundler that left some things out.
Because of the missing DEPENDENCIES, we can only install gems one at a time, instead of installing 4 at a time.
You can fix this by adding the missing gems to your Gemfile, running bundle install, and then removing the gems from your Gemfile.
The missing gems are:
* mini_portile2 depended upon by nokogiri
--- ERROR REPORT TEMPLATE -------------------------------------------------------
<code>```
NoMethodError: undefined method `full_name' for nil:NilClass

  warning << "* #{unmet_spec_dependency}, depended upon #{spec.full_name}, unsatisfied by #{@specs.find {|s| s.name == unmet_spec_dependency.name && !unmet_spec_dependency.matches_spec?(s.spec) }.full_name}"
                                                                                ^^^^^^^^^^
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:124:in `block (2 levels) in check_for_unmet_dependencies'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:123:in `each'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:123:in `block in check_for_unmet_dependencies'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:122:in `each'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:122:in `check_for_unmet_dependencies'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:100:in `call'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer/parallel_installer.rb:71:in `call'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer.rb:254:in `install_in_parallel'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer.rb:209:in `install'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer.rb:89:in `block in run'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/process_lock.rb:12:in `block in lock'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/process_lock.rb:9:in `open'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/process_lock.rb:9:in `lock'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer.rb:71:in `run'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/installer.rb:23:in `install'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/cli/install.rb:62:in `run'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/cli.rb:257:in `block in install'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/settings.rb:131:in `temporary'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/cli.rb:256:in `install'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/vendor/thor/lib/thor.rb:392:in `dispatch'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/cli.rb:31:in `dispatch'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/vendor/thor/lib/thor/base.rb:485:in `start'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/cli.rb:25:in `start'
  C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.3.23/exe/bundle:48:in `block in <top (required)>'
  C:/Ruby31-x64/lib/ruby/site_ruby/3.1.0/bundler/friendly_errors.rb:120:in `with_friendly_errors'
  C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/bundler-2.3.23/exe/bundle:36:in `<top (required)>'
  C:/Ruby31-x64/bin/bundle:33:in `load'
  C:/Ruby31-x64/bin/bundle:33:in `<main>'

```

## Environment

```
Bundler       2.3.23
  Platforms   ruby, x64-mingw-ucrt
Ruby          3.1.2p20 (2022-04-12 revision 4491bb740a9506d76391ac44bb2fe6e483fec952) [x64-mingw-ucrt]
  Full Path   C:/Ruby31-x64/bin/ruby.exe
  Config Dir  C:/ProgramData
RubyGems      3.3.23
  Gem Home    C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/ruby/3.1.0
  Gem Path    C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/ruby/3.1.0
  User Home   C:/Users/reeba
  User Path   C:/Users/reeba/.local/share/gem/ruby/3.1.0
  Bin Dir     C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/ruby/3.1.0/bin
OpenSSL
  Compiled    OpenSSL 1.1.1n  15 Mar 2022
  Loaded      OpenSSL 1.1.1n  15 Mar 2022
  Cert File   C:/Ruby31-x64/ssl/cert.pem
  Cert Dir    C:/Ruby31-x64/ssl/certs
Tools
  Git         2.32.0.windows.2
  RVM         not installed
  rbenv       not installed
  chruby      not installed
```

## Bundler Build Metadata

```
Built At          2022-10-05
Git SHA           250d9d485d
Released Version  true
```

## Bundler settings

```
path
  Set for your local app (C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/.bundle/config): "C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0"
```

## Gemfile

### Gemfile

```ruby
source 'https://rubygems.org'
gem 'shopify-cli', '2.25.0'
```

### Gemfile.lock

```
<No C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/Gemfile.lock found>
```

--- TEMPLATE END ----------------------------------------------------------------

Unfortunately, an unexpected error occurred, and Bundler cannot continue.

First, try this link to see if there are any existing issue reports for this error:
https://github.com/rubygems/rubygems/search?q=undefined+method+%60full_name%27+for+nil+NilClass&type=Issues

If there aren't any reports for this error yet, please fill in the new issue form located at https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md, and copy and paste the report template above in there.
Fetching gem metadata from https://rubygems.org/.............
Resolving dependencies...
Using ast 2.4.2
Using concurrent-ruby 1.1.10
Using bugsnag 6.24.2
Using bundler 2.3.23
Using ffi 1.15.5
Using liquid 5.4.0
Using rb-fsevent 0.11.2
Using rb-inotify 0.10.1
Using listen 3.7.1
Using racc 1.6.0
Installing nokogiri 1.13.8 with native extensions
</code>
Answer: I had the same problem and this worked for me:
If you are using shopify cli 3.0+ and ruby 3.1.2 then copy Gemfile.lock from => *ruby path installed folder */lib/ruby/gems/2.7.0/gems/shopify-app/Gemfile.lock
OR in other versions it will be in *ruby path installed folder */lib/ruby/gems/2.7.0/gems/shopify-cli-2.27.0/Gemfile.lock
Add the Gemfile.lock in C:\Users\reeba\AppData\Local\shopify-cli-nodejs\Cache\vendor\ruby-cli\2.27.0
And also add same file at C:\Users\reeba\AppData\Local\shopify-cli-nodejs\Cache\vendor\theme-check\1.10.3
Answer: I've got the same error message.
First of all I've made the gem update and the bundler updates:
gem install bundler
gem update --system
And then:
You should find the Gemfile.lock file in the directory .../path to your installed folder/lib/ruby/gems/2.7.0/gems/shopify-cli-2.27.0/Gemfile.lock and copy in to the folder  C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/
Generally it says - that the Gemfile.lock is not found:
Gemfile.lock
<code><No C:/Users/reeba/AppData/Local/shopify-cli-nodejs/Cache/vendor/ruby-cli/2.25.0/Gemfile.lock found>
</code>
That should help.


In C#, how can I get the name of the calling project from within a referenced project?

Question: I have three projects: My.Business, My.WebSite and My.WebService
I need my logging class to be able to identify when a request is made from the website versus the web service. I used to have the web service running as a separate application underneath the web site, so I'd just use different config files, which worked fine. But I want the web service now to run under the same application.
If I could figure out if the request was coming from My.WebSite or My.WebService, I'd be set, but I'm not sure how to do this.

Assembly.GetExecutingAssembly() returns back My.Business
Assembly.GetEntryAssembly() is null
I could check the StackTrace, but that seems sloppy and how for back would I have to go? Especially because the logging may be triggered by code in My.Business that was originally invoked from one of the other projects.

Since the web service requests end in ".asmx", the following concept works, but it just doesn't feel right.
return HttpContext.Current.Request.Path.IndexOf(".asmx") >= 0 ? "My.WebService" : "My.WebSite";

Thanks!
Comment: I would say you could do with some inversion of control here; The My.Business classes should be "given" the information they need to work (in different manners), rather than trying to find it... what if you introduce a 3rd application... now you have to change My.Business again.
Comment: I considered this, but logging occurs in all three projects. So I'm not sure how to have My.Business do logging and pass in information about whether to log to the WebSite or WebService.
Answer: You should be able to use Assembly.GetCallingAssembly():
return Assembly.GetCallingAssembly().FullName;

This will return the assembly that invoked the current executing method, so you can capture whoever is calling into your My.Business assembly that way.
With that said, I tend to agree with the comment above by Meirion Hughes.  You might like to consider passing in any info that is required to your logging class, especially if it is likely to be used across more applications in the future.
Comment: That's returning back My.Business
Comment: Also, I don't want the assembly that invoked the current executing method, because logging could have been triggered from a function within My.Business. I want it to know whether My.WebSite or My.WebService initiated it.
Comment: I'm guessing it's returning 'My.Business' because, as you've described in your second comment, your logging method isn't an entry point to your assembly.  You could capture the calling assembly when you instantiate your BLL object as a private member or property and refer to it as needed.
Answer: this.GetType().Assembly.FullName will give you the name of the assembly name for the current class.


PostCSS nested variable

Question: I have this code in my postcss file
.btn.color1>button{background:$graph_1;}
.btn.color2>button{background:$graph_2;}
.btn.color3>button{background:$graph_3;}
.btn.color4>button{background:$graph_4;}
.btn.color5>button{background:$graph_5;}

well, i thought this could be shorten by using for loops
@for $i from 1 to 5 {
    .btn.color$i>button{background:$graph_$i;}
}

but there was a problem. $graph_$i couldn't be resolved like $graph_1,
it just remained as $graph_$i.
is there any good solutions for this situation?
Answer: ANSWER 1
I had to run postcss-advanced-variables twice. So, i remove precss from dependencies, and add it's inner dependencies directly on my project.
This is what I wrote in my webpack config file.
postcss: function(webpack) {
    return [
        ...
        require("postcss-advanced-variables"),
        require("postcss-advanced-variables"),
        ...
    ]
}

and in my PostCSS file,
@for $i from 1 to 5 {
    .btn.color$i > button{
        background: $(graph_$(i));
    }
}

ANSWER 2
I submit an issue at postcss-simple-vars, and Andrey Sitnik accepted it. Nested interpolation can used like this. But, it can't used with @for loop of postcss-advanced-variables

PostCSS nested variable


How to change a certain columnname in R within a loop

Question: I have a Code like this
for(i in 1:length(data_files)) {
 assign(paste0("t",i),substr(data_files[i],9,14))
 assign(paste0("data", i),read.csv2(paste0("D:/Radar/Duerre/Files/NFK/",data_files[i])))
 names("data",i)[5] <- (paste0("nfk"),substr(data_files[i],9,14))
}

Error in names("data", i)[5] <- assign(paste0("nfk"), substr(data_files[i], :
target of assignment expands to non-language object
What I want to do, is to rename the 5th column with string(nfk) and concatenate this with a substr out of a list(whis is looking sth like this ("_04_05") . In the end the col 5 should have a name like "nfk_04_05" and so on
I have tried several things but nothing has worked so far….
Do you have a clue ?
Many thanks in advance !
BR
Wollbrecht
Answer: could you add some sample data? Little tricky to know what you mean without more detail.
Otherwise below is guess, is there any reason names(data)[5] <- (paste0("nfk_",substr(data_files[i],1,3))) won't do the trick for you?
I think I got what you're looking for here:
#generate sample vector and dataframe to try and match your equestion
data_files = c(
  "abcd_1234",
  "efg_567"
)

data = data.frame(
  one = NA,
  two = NA,
  three = NA,
  four = NA,
  five = NA
)

#test a similar loop
for(i in 1:length(data_files)) {
  cat("\n",names(data)) #print column names for validation
  names(data)[5] <- (paste0("nfk_",substr(data_files[i],1,3))) #rename
  cat("\n",names(data)) #recheck
}

Comment: Hi, thanks for your answer. Your Code works very well. But not as soon as I want that in a loop for 35 data tables. In every table I would need to change the 5th columnname.
Comment: Each data table has the following header (col,row,lon,lat,nFK,dtime). Normally it would be enough if I could add a suffix like described in the example to the coname nFK but I tried to replace the whole colname. So it seems I have rather problems in the loop: maybe I should try in a first loop to import all data  and in a second to change the colname.....
Comment: Hmmm, if I understand you correctly I think maybe you should loop a list of each data table right?

e.g, for (i in 1:length(list_of_data_table)){
names(list_of_data_table[i])[5] =
}


How to get data from Firebase and show it in Android

Question: I need help with getting data from Firebase. I've been working for a few hours and still can't get it right.
It's either throw a Nullpointer or another error I don't understand.
I admit I don't have any experience in Java or Android and this is my first attempt to make a simple database operation.
any help to help me understand is very appreciated
EDIT
I modified my database reference into :
fDatabase = FirebaseDatabase.getInstance().getReference().child("pelanggan").child("nama");

here is my database structure
here is my Acitivity :
package com.example.training;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.training.model.pelanggan;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class orderActivity extends AppCompatActivity{
    private Button submitOrder;
    DatabaseReference fDatabase;
    private TextView retrieveTV;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_activity);

        fDatabase = FirebaseDatabase.getInstance().getReference().child("pelanggan").child("nama");
        retrieveTV = findViewById(R.id.idTVRetrieveData);

        getname();
    }

    private void getname() {
        fDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String results = dataSnapshot.getValue(String.class);;

                retrieveTV.setText(results);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(orderActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

I also have a model class
package com.example.training.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class pelanggan {
    @SerializedName("ID")
    @Expose
    private String ID;

    @SerializedName("Nama")
    @Expose
    private String Nama;

    @SerializedName("Alamat")
    @Expose
    private String Alamat;

    @SerializedName("Ruang")
    @Expose
    private String Ruang;

    //Constructor
    public pelanggan (){}

    public pelanggan (String Nama, String Alamat, String Ruang){
        this.Nama = Nama;
        this.Alamat = Alamat;
        this.Ruang = Ruang;
    }

    public String getNama() {return Nama;}

    public String getAlamat() {return  Alamat;}

    public String getRuang() {return Ruang;}
}

I have tried doing it like this too, but instead give me nullpointer exception
Alternate version
private void getname() {
        fDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                pelanggan pelanggan = dataSnapshot.getValue(pelanggan.class);
                String nama = pelanggan.getNama();

                retrieveTV.setText(nama);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(orderActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
            }
        });
    }

This is my LOGTCAT
2022-06-26 14:24:03.006 20151-20151/? I/xample.trainin: Late-enabling -Xcheck:jni
2022-06-26 14:24:03.033 20151-20151/? E/xample.trainin: Unknown bits set in runtime_flags: 0x48000
2022-06-26 14:24:03.537 20151-20151/com.example.training I/Perf: Connecting to perf service.
2022-06-26 14:24:03.574 20151-20151/com.example.training I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2022-06-26 14:24:03.599 20151-20151/com.example.training I/FirebaseCrashlytics: Initializing Firebase Crashlytics 18.2.11 for com.example.training
2022-06-26 14:24:03.604 20151-20186/com.example.training I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:73 and remote module com.google.android.gms.measurement.dynamite:74
2022-06-26 14:24:03.604 20151-20186/com.example.training I/DynamiteModule: Selected remote version of com.google.android.gms.measurement.dynamite, version >= 74
2022-06-26 14:24:03.605 20151-20186/com.example.training V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
2022-06-26 14:24:03.635 20151-20186/com.example.training W/xample.trainin: ClassLoaderContext type mismatch. expected=PCL, found=DLC (PCL[] | DLC[];PCL[/data/app/com.example.training-cGP13cDlR449jFz3H3Slsw==/base.apk*196330711:/data/app/com.example.training-cGP13cDlR449jFz3H3Slsw==/base.apk!classes2.dex*3787358178:/data/app/com.example.training-cGP13cDlR449jFz3H3Slsw==/base.apk!classes3.dex*1858276209:/data/app/com.example.training-cGP13cDlR449jFz3H3Slsw==/base.apk!classes4.dex*1863173146])
2022-06-26 14:24:03.635 20151-20186/com.example.training W/xample.trainin: Found duplicate classes, falling back to extracting from APK : /data/user_de/0/com.google.android.gms/app_chimera/m/000000af/MeasurementDynamite.apk
2022-06-26 14:24:03.635 20151-20186/com.example.training W/xample.trainin: NOTE: This wastes RAM and hurts startup performance.
2022-06-26 14:24:03.635 20151-20186/com.example.training W/xample.trainin: Found duplicated class when checking oat files: 'Landroid/support/v4/app/RemoteActionCompatParcelizer;' in /data/app/com.example.training-cGP13cDlR449jFz3H3Slsw==/base.apk and /data/user_de/0/com.google.android.gms/app_chimera/m/000000af/MeasurementDynamite.apk
2022-06-26 14:24:03.635 20151-20186/com.example.training W/xample.trainin:
2022-06-26 14:24:03.736 20151-20151/com.example.training I/FirebaseInitProvider: FirebaseApp initialization successful
2022-06-26 14:24:03.744 20151-20196/com.example.training V/FA: App measurement collection enabled
2022-06-26 14:24:03.745 20151-20196/com.example.training V/FA: App measurement enabled for app package, google app id: com.example.training, 1:44525531754:android:c57282d36986f9bcb05013
2022-06-26 14:24:03.746 20151-20196/com.example.training I/FA: App measurement initialized, version: 65003
2022-06-26 14:24:03.746 20151-20196/com.example.training I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2022-06-26 14:24:03.746 20151-20196/com.example.training I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.example.training
2022-06-26 14:24:03.746 20151-20196/com.example.training D/FA: Debug-level message logging enabled
2022-06-26 14:24:03.757 20151-20151/com.example.training I/FeatureParser: can't find citrus.xml in assets/device_features/,it may be in /vendor/etc/device_features
2022-06-26 14:24:03.773 20151-20151/com.example.training E/libc: Access denied finding property "ro.vendor.df.effect.conflict"
2022-06-26 14:24:03.759 20151-20151/com.example.training W/xample.training: type=1400 audit(0.0:456294): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=16963 scontext=u:r:untrusted_app:s0:c61,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2022-06-26 14:24:03.774 20151-20151/com.example.training E/libc: Access denied finding property "ro.vendor.knock.type"
2022-06-26 14:24:03.759 20151-20151/com.example.training W/xample.training: type=1400 audit(0.0:456295): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=16963 scontext=u:r:untrusted_app:s0:c61,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2022-06-26 14:24:03.786 20151-20196/com.example.training V/FA: Connecting to remote service
2022-06-26 14:24:03.799 20151-20196/com.example.training V/FA: Connection attempt already in progress
2022-06-26 14:24:03.806 20151-20196/com.example.training V/FA: Connection attempt already in progress
2022-06-26 14:24:03.860 20151-20186/com.example.training V/FA: onActivityCreated
2022-06-26 14:24:03.948 20151-20151/com.example.training W/xample.trainin: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2022-06-26 14:24:03.949 20151-20151/com.example.training W/xample.trainin: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2022-06-26 14:24:04.106 20151-20196/com.example.training V/FA: Activity resumed, time: 4280644798
2022-06-26 14:24:04.111 20151-20196/com.example.training I/FA: Tag Manager is not found and thus will not be used
2022-06-26 14:24:04.132 20151-20151/com.example.training W/Looper: PerfMonitor looperActivity : package=com.example.training/.orderActivity time=355ms latency=679ms running=325ms  procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.LaunchActivityItem] lifecycleRequest=android.app.servertransaction.ResumeActivityItem } historyMsgCount=1 (msgIndex=1 wall=705ms seq=2 running=651ms runnable=8ms late=2ms h=android.app.ActivityThread$H w=110)
2022-06-26 14:24:04.133 20151-20151/com.example.training W/Looper: PerfMonitor looperActivity : package=com.example.training/.orderActivity time=0ms latency=1034ms running=0ms  procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=2 (msgIndex=1 wall=705ms seq=2 running=651ms runnable=8ms late=2ms h=android.app.ActivityThread$H w=110) (msgIndex=2 wall=355ms seq=3 running=325ms runnable=9ms late=679ms h=android.app.ActivityThread$H w=159)
2022-06-26 14:24:04.136 20151-20196/com.example.training V/FA: Connection attempt already in progress
2022-06-26 14:24:04.138 20151-20196/com.example.training V/FA: Connection attempt already in progress
2022-06-26 14:24:04.154 20151-20208/com.example.training D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-06-26 14:24:04.180 20151-20203/com.example.training I/AdrenoGLES-0: QUALCOMM build                   : 243b6bc, I98aee2b40e
    Build Date                       : 12/08/20
    OpenGL ES Shader Compiler Version: EV031.29.00.16
    Local Branch                     :
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.8.15.R1.10.00.00.643.066
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
2022-06-26 14:24:04.180 20151-20203/com.example.training I/AdrenoGLES-0: Build Config                     : S P 8.0.16 AArch64
2022-06-26 14:24:04.180 20151-20203/com.example.training I/AdrenoGLES-0: Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
2022-06-26 14:24:04.186 20151-20203/com.example.training I/AdrenoGLES-0: PFP: 0x016ee188, ME: 0x00000000
2022-06-26 14:24:04.276 20151-20196/com.example.training D/FA: Connected to remote service
2022-06-26 14:24:04.278 20151-20196/com.example.training V/FA: Processing queued up service tasks: 5
2022-06-26 14:24:09.346 20151-20196/com.example.training V/FA: Inactivity, disconnecting from the service

Here is the LOGCAT where there is nullPointer Exception I will copy paste only the red letters :
E/libc: Access denied finding property "ro.vendor.df.effect.conflict"
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.training, PID: 22287
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.training.model.pelanggan.getNama()' on a null object reference
        at com.example.training.orderActivity$1.onDataChange(orderActivity.java:38)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:226)
        at android.app.ActivityThread.main(ActivityThread.java:7592)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

This Logcat only happes when I use Alternate Version and it forces closes the application unlike the first code
Comment: Where in your logcat are you getting a NullPointerException? Show us also the line that produces it.
Comment: @AlexMamo I have added it to my question
Comment: The child of `pelanggan` is `pg81894` and you are trying to search for `mama` in `pelanggan`.
Answer: You're getting the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.training.model.pelanggan.getNama()' on a null object reference

Because you're trying to read the value of name from an incorrect reference. When you're using the following line of code:
fDatabase = FirebaseDatabase.getInstance().getReference().child("pelanggan").child("nama");

It means that you're trying to read a value from the following location:
root/pelanggan/nama

Which actually doesn't exist. Seeing your database schema, you're missing a child. So the correct reference should be:
fDatabase = FirebaseDatabase.getInstance()
                            .getReference()
                            .child("pelanggan")
                            .child("pg89814") //
                            .child("nama");

If you, however, want to read that child, as an object of type pelanggan, then you should use the following lines of code:
private void getname() {
        DatabaseReference db = FirebaseDatabase.getInstance().getReference();
        DatabaseReference ref = db..child("pelanggan").child("pg89814");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                pelanggan pelanggan = dataSnapshot.getValue(pelanggan.class);
                String nama = pelanggan.getNama();

                retrieveTV.setText(nama);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(orderActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
            }
        });
    }

Comment: actually after carefully reading your answer, you have helped me to understand how firebase reference works. so Thank you this will be all
Comment: Ok it's no longer throws nullpointer exception, but I still can't show it in TextView. did it failed to retrieve the value of `nama` ? in the logcat there are 2 red letters _E/libc: Access denied finding property "ro.vendor.df.effect.conflict"_ and _E/libc: Access denied finding property "ro.vendor.knock.type"_
Comment: Without seeing the code that produces that, I can't be much of a help. Problems that derive from the initial question, should be considered separate questions. So please post a new question here on Stackoverflow, so I and other Firebase developers can take a look at it.
Comment: Besides that, can I help you with other information, regarding the initial issue?
Comment: Thank you. sorry for the late response, I was just cooling my head. I guess I asked the wrong question. I don't know how to ask the right question for my problem since my question should've been answered before, I read many solution that is very similar to my problem it does not work
Comment: "it does not work" doesn't provide enough information so I can help. What exactly doesn't work? Do you have any errors?
Comment: Hey Caelles. Have you solved the issue?
Comment: Yeah sorry for the late response, I just misunderstood how Firebase reference works. Once I understood it I know how it works.
Comment: So can I help you with other information?


Brightness Controls doesn't work in HP G62 (Ubuntu 12.04)

Question: I have installed Ubuntu 12.04 and I think everything is working except for the brightness controls of the laptop. Please answer.
Comment: what is graphics driver of your system? edit the question and post result of these two commands `lspci | grep VGA` and `ls /sys/class/backlight/*/brightness`
Answer: I have a same problem and this is the only solution I know...that is to assign different combo for the brightness,as fn key is undetected
1) Install XDoTool and Compiz
sudo aptitude install xdotool compizconfig-settings-manager
2) Open Compiz
Command : ccsm
3) Go to commands and add these lines:
xdotool key XF86MonBrightnessUp
xdotool key XF86MonBrightnessDown
In commandLine1 and commandLine2 respectively.
Now click on Key Bindings Tab and Click on disabled button
On the pop-up box click Grab Key Combination and choose desired keys (I use Super(win)+f4, Super(win)+f3)
Don't forget to check Enable Commands on left hand panel
I hope it helps :-)
If you come across the keyboard layout for hp g62 please do post it...I too need it :-P


Xubuntu failed to start load kernel modules

Question: I booted my pc today and everything was fine. An update was installed and I clicked on restart and then this error message appeared.

I found a similar problem here Failed to start Load Kernel Modules Ubuntu 16.04
When I run journalctl | grep modules it shows this

I have internet connection.
Answer: I couldn't find a solution, so I used recovery mode to save my files and install XUbuntu again.


Will an x86_64 CPU notice that a page-table entry has changed to not-present while setting the dirty flag in the PTE?

Question: There is a scenario as follows:
The pte a of PAGE A set following field:

BIT(0) present
BIT(1) writable
BIT(M-1,12) page  frame
dirty flag is NOT SET

CPU0                                     CPU1
                                         cached translation information
                                         about the PTE a (TLB)
modify pte a present flags to 0.
(not exec tlb shootdown)
                                         write a virtual address translated by pte a

Now, will this write operation execute normally or will it cause a page fault?

The issue comes from a Linux kernel commit. Based on the code logic of the
commit, I tend to believe that the situation mentioned above can cause page
faults.
Information about this COMMIT:
commit d950c9477d51f0cefc2ed3cf76e695d46af0d9c1
Author: Mel Gorman <email@example.com>
Date:   Fri Sep 4 15:47:35 2015 -0700

    mm: defer flush of writable TLB entries

The code is no longer shown here, and the approximate logic is:
When kswapd was performing memory reclamation, it was found that a page could
be reclaimed. First, unmap it. The unmap operation will modify the page table
structures After modification, it is necessary to perform a tlb flush (may
execute tlb shootdown) However, the kernel may delay the tlb flush action in
order to perform batch flush (as tlb shootdown requires sending ipi, batch
flush will reduce the number of ipi sent to one). But it needs to be determined
whether the PTE is dirty before the clear PTE,
If it's dirty, you need to flush immediately If it weren't dirty, you can batch
flush it after page_out()
I think it may be due to the following reasons:
If the page is dirty, it indicates that someone has recently accessed the page,
and if there is no flush tlb remote, other CPUs may still be able to access it
normally without generating PF. However, if the page is not dirty, after
clearing the pte, even if other CPUs use old tlb to access it (the dirty flag
in old tlb is 0), the dirty flags will be updated and a full check will be made
to generate PF. (The above is my own understanding, I cannot guarantee it is
correct).

If modify PTE's dirty bit 1 to 0, but not flush tlb. This situation is
described in Intel SDM
If software modifies a paging-structure entry that identifies the final
 physical address for a linear address(either a PTE or a paging-structure
entry in which the PS flag is 1) to change the dirty flag from 1 to 0,
failure to perform an invalidation may result in the processor not setting
 that bit in response to a subsequent write to a linear address whose
translation uses the entry. Software cannot interpret the bit being clear as
an indication that such a write has not occurred

But regarding the issue mentioned at the beginning, it was not
found in Intel SDM.

Thanks for Peter's testing suggestion. I have written a kernel module based
on the Linux kernel. The testing code is not specifically presented, but the
program flow is as follows(single thread):

set or clear PTE dirty bit
flush tlb all
read the page pointed by this PTE in order to establish new tlb.
clear P or RW bit of this PTE(after changing PTE, DO NOT flush TLB)
write the page pointed by this PTE.

The test results are as follows:

set dirty, clear present, (set RW) : normally execute
set dirty, clear RW(read only), (set present) : normally execute
set not dirty, clear present, (set RW) : cause #PF
set not dirty, clear RW(read only), (set present) : cause #PF

NOTE
Set/clear the dirty bit is to set the initial state of TLB

my test link

According to Peter and prl's answers, it seems that CET will affect the test results But I don't know the details of CET. I do a simple test by using the RDMSR instruction to read IA32_U_CET in the kernel module and this instruction will cause a # GP, does this mean that my CPU does not support the CET function ?
Comment: Does CPU1 start with the PTE cached in its TLB?  If not, then obviously it would page fault.  But if it did, then IDK if the RMW to update the Dirty bit would also result in a new check of the other bits.  (This would probably be the same as a single-core situation where you modify the PTE in memory but don't run `invlpg` or reload CR3; some microarchitectures do some snooping for TLB coherency, but not for changing present to not-present.  https://blog.stuffedcow.net/2015/08/pagewalk-coherence/)
Comment: Oh, I'm sorry.  I forgot to specify the TLB status of CPU 1. As you commented, CPU1 has already cached translation information about pte a (TLB) before CPU 0 modifies it.
Comment: Hello, Peter. It seems that code blocks are not supported in comments. I added an answer below.
Comment: If you're going to post an answer, write it as an answer to the question for future readers, not a reply to me.  As is, it seems like you're guessing at an answer based on some evidence from a Linux kernel change.  If the evidence isn't strong enough for it to be an actual answer, an edit to the *question* is a good place to put more details.
Comment: Thank  for your suggestion. I will integrate the following answers into the question part.
Comment: What hardware did you test on?  It might be interesting to test on some much older hardware from long before the CET feature.   (The older CPUs that can sometimes set the Dirty flag in a PTE without the write bit set might not have been the generation right before CET; they might just have documented it with CET because there wasn't a CPUID feature bit directly associated with the change in TLB / PTE handling.)
Comment: 3. set not dirty, clear present, (set RW) : cause #PF - that is interesting, I wasn't able to replicate this with a test module + QEMU KVM. I kept not seeing any #PF (though I might have done something wrong).
Comment: How are you sure that the entry is still in TLB at the moment of the write and hasn't been removed by the CPU?
Comment: @PeterCordes hello, Peter, I tested on the `Intel(R) Core(TM) i7-9750H`
Comment: @MarcoBonelli I tested on host. However, according to the Intel manual, TLB has the same behavior in VMX non root operation and VMX root operation.I will then test the program in a virtual machine launched by KVM. I cannot guarantee that the TLB of this PTE has not been invalidated (the CPU may implicitly invalidate them) . At the software level, it is possible to minimize the cycle between TLB generation and write operations. However, according to "set dirty, clear present, (set RW)", there are no results for cause # PF, indicating that TLB has not been invalidated yet
Comment: @MarcoBonelli But from your testing of the "set not dirty, clear present, set PW" condition, but no # PF results were generated.  I'm not sure if you're doing something wrong or if your CPU is different from mine Please perform the following steps in order:`1. insmod tlb_test.ko  2. echo 1 > /proc/fuqiang/my_page_proc 3. echo 3 > /proc/fuqiang/my_page_misc_proc`
Comment: @MarcoBonelli  hi~ Marco,  I tested  on a virtual machine and the results were the same  on a physical machine
Comment: @wangfuqiang yeah my bad, works as you report and I get a page fault. Interesting then, your initial assumption seems correct. Maybe you can write a self-answer.
Comment: Thanks, Marco. But I still don't know the details of CET or whether it will affect my test results After I confirm, I will write an answer. Thank you very much for your patience in this test  : )
Answer: The Intel SDM, volume 3, section 4.8, says:

If software on one logical processor writes to a page while software
on another logical processor concurrently clears the R/W flag in the
paging-structure entry that maps the page, execution on some
processors may result in the entry's dirty flag being set (due to the
write on the first logical processor) and the entry's R/W flag being
clear (due to the update to the entry on the second logical
processor). This will never occur on a processor that supports
control-flow enforcement technology (CET). Specifically, a processor
that supports CET will never set the dirty flag in a paging-structure
entry in which the R/W flag is clear.
Comment: That note from the SDM doesn't seem to help much. In the case at hand, nobody touches the R/W flag, which stays in the PTE and cached in TLB. The present flag is the one being cleared. As Peter notes, considering multiple CPUs also doesn't seem to matter in this case. The real question is whether HW checks the current present flag in the PTE when trying to set the dirty flag and therefore issues a page fault OR simply relies on the fact that a TLB entry exists and updates the dirty flag without a page fault (meaning that even if P=0 on the PTE, HW will set D=1).
Comment: @Peter, it cannot write to the page without setting D. That would cause data corruption when the OS discards the contents of the page because it apparently hasn't changed.
Comment: Right, but I thought HW architects might consider it software's fault if they rely on those bits not being modified while other cores still have valid TLB entries caching this PTE.  That seemed like a plausible design.  If it's not the actual design, then that's the answer to the OP's question, along with your point about definitely never allowing writes without setting the Dirty bit.  HW that doesn't require waiting for a reply from TLB shootdowns being complete seems obviously more convenient and efficient for software, so it makes sense, but I wasn't sure it would work this way.
Comment: While it's true that "when P is 0, the remaining 63 bits of the PTE are available to software", when a TLB entry exists that means that for what the HW knows the page is present, so I wouldn't rule out a silent PTE update anyway. After all, again as Peter is saying, it seems like it would be the programmer's fault to not have correctly flushed the TLB in such case. It'd be interesting to find something about this in the SDM vol 3, but I could not find much (mainly looking at sections 4.8 and 4.10).
Comment: Interesting that it doesn't say anything about what will happen to the store itself (#PF from store to a non-writeable page, or just works but still doesn't set the Dirty bit, like adding extra logic to the microcode-assist atomic RMW to mask the new dirty bit with the inverted R/W bit from memory).  The former mechanism (#PF) would probably also apply for the PTE becoming invalid (not Present), but the documentation only talks about the R/W bit.  Interesting and related but far from definitive.  Probably needs experimental testing.  (On the same core is probably fine and easy to test.)
Comment: Oh right, that rules out doing the write anyway without setting D.  So on CPUs without CET, would it also be possible for other cores to set the D flag in a PTE with the Present bit cleared, like is possible when clearing the R/W bit?  If so, OSes would have to check D again after invlpg and after hearing back from other cores that a TLB shootdown is complete, if there's a backing-store for this page which has to get its data.
Comment: @Peter, when P is 0, the remaining 63 bits of the PTE are available to software.


how to paste and copy out multiple cells values in qt table widget

Question: I am very new in programming. Please help me in this regards. Thanks in advance.
Here is my code:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):

    def clear_table(self):
        self.tableWidget_2.clearContents()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1920, 1080)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget_2 = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget_2.setGeometry(QtCore.QRect(10, 100, 1800, 700))
        self.tableWidget_2.setObjectName("tableWidget_2")
        self.tableWidget_2.setColumnCount(3)
        self.tableWidget_2.setRowCount(500)
        # self.tableWidget_2.cellChanged.connect(self.c_current)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(300, 20, 150, 50))
        self.pushButton_2.setText("Import table")
        self.pushButton_2.setObjectName("pushButton_2")

        #####
        ###
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(10, 20, 150, 50))
        self.pushButton.setText("Clear table")
        self.pushButton.clicked.connect(self.clear_table)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 18))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

output table:

For example, I want to paste this data table into the qt widget table:
1 2 3
6 7 8
10 11 12

Similarly I also want to copy out the whole data from qt table using CLT+C or mouse right button click and the copy.
like this:
Answer: If you only need internal copy and paste operations, you can use a local variable to store the item data (row, column and content), then use an event filter to trigger those operations.
In the following example I created two simple functions that can be called when using the keyboard shortcuts (ctrl+c or ctrl+v) or through a context menu.
When one or more items are selected, they can be copied.
If the "clipboard" has contents and one index is selected (the "current index"), those contents will be pasted relative to it.
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.model = QtGui.QStandardItemModel(10, 10)
        self.tableView = QtWidgets.QTableView()
        self.tableView.setModel(self.model)

        self.tableView.installEventFilter(self)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.tableView)

        self.clipboard = []

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.KeyPress:
            if event == QtGui.QKeySequence.Copy:
                self.copySelection()
                return True
            elif event == QtGui.QKeySequence.Paste:
                self.pasteSelection()
                return True
        elif event.type() == QtCore.QEvent.ContextMenu:
            # a context menu for the copy/paste operations
            menu = QtWidgets.QMenu()
            copyAction = menu.addAction('Copy')
            copyAction.triggered.connect(self.copySelection)
            pasteAction = menu.addAction('Paste')
            pasteAction.triggered.connect(self.pasteSelection)
            if not self.tableView.selectedIndexes():
                # no selection available, both copy and paste are disabled
                copyAction.setEnabled(False)
                pasteAction.setEnabled(False)
            if not self.clipboard:
                # no clipboard contents, paste is disabled
                pasteAction.setEnabled(False)
            menu.exec(event.globalPos())
            return True
        return super(Window, self).eventFilter(source, event)

    def copySelection(self):
        # clear the current contents of the clipboard
        self.clipboard.clear()
        selected = self.tableView.selectedIndexes()
        rows = []
        columns = []
        # cycle all selected items to get the minimum row and column, so that the
        # reference will always be [0, 0]
        for index in selected:
            rows.append(index.row())
            columns.append(index.column())
        minRow = min(rows)
        minCol = min(columns)
        for index in selected:
            # append the data of each selected index
            self.clipboard.append((index.row() - minRow, index.column() - minCol, index.data()))

    def pasteSelection(self):
        if not self.clipboard:
            return
        current = self.tableView.currentIndex()
        if not current.isValid():
            # in the rare case that there is no current index, use the first row
            # and column as target
            current = self.model.index(0, 0)

        firstRow = current.row()
        firstColumn = current.column()

        # optional: get the selection model so that pasted indexes will be
        # automatically selected at the end
        selection = self.tableView.selectionModel()
        for row, column, data in self.clipboard:
            # get the index, with rows and columns relative to the current
            index = self.model.index(firstRow + row, firstColumn + column)
            # set the data for the index
            self.model.setData(index, data, QtCore.Qt.DisplayRole)
            # add the index to the selection
            selection.select(index, selection.Select)

        # apply the selection model
        self.tableView.setSelectionModel(selection)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

Note that I didn't use your code, as that is the output generated from pyuic, which should never be modified. Those files are only meant to be imported, and the program logic must be implemented on a separate script. Read the documentation about using Designer to know how to correctly use UI files, otherwise just create the interface by subclassing the qwidget as done in my example.


Save a max of 5 searches to LocaHost

Question: I need to be able to save a max of 5 searches to the sidebar. When the user clicks on the search it will re-execute the saved search. Right now I'm using the LocalStorage in order to save these. At the moment I can save the newest search as a string converted from a javascript object. Any help is very much appreciated! Here is the code:

var searchObject = {};

$('.search-button').click(function () {
  var business = $('#business-name-button').val();
  var industry = $('#industry-button').val();
  var job = $('#job-title-button').val();
  var revenue = $('#annual-revenue-button').val();
  var employeeNumber = $('#number-of-employees-button').val();
  var companyYears = $('#company-years-button').val();
  var locationAll = $('#location-all-button').val();
  var locationSingle = $('#location-single-button').val();
  var locationHeadquarter = $('#location-headquarter-button').val();
  var locationBranch = $('#location-branch-button').val();
  var minorityNone = $('#minority-none-button').val();
  var minorityOnly = $('#minority-only-button').val();
  var womenNone = $('#women-none-button').val();
  var womenOnly = $('#women-only-button').val();
  searchObject = {
    business: [business],
    industry: [industry],
    job: [job],
    revenue: [revenue],
    employeeNumber: [employeeNumber],
    companyYears: [companyYears],
    locationAll: [locationAll],
    locationSingle: [locationSingle],
    locationHeadquarter: [locationHeadquarter],
    locationBranch: [locationBranch],
    minorityNone: [minorityNone],
    minorityOnly: [minorityOnly],
    womenNone: [womenNone],
    womenOnly: [womenOnly]
  };
  var searchHistory = '';
  if (business != '') {
    //   searchObject.business == $('#business-name-button').val();
    searchHistory += "Business Name: " + '' + searchObject.business + "  — ";
  };
  if (industry != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Industry: " + '' + searchObject.industry + "  — ";
  };
  if (job != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Job: " + '' + searchObject.job + "  — ";
  };
  if (revenue != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Anuual Revenue: " + '' + searchObject.revenue + "  — ";
  };
  if (employeeNumber != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "# Of Employees: " + '' + searchObject.employeeNumber + "  — ";
  };
  if (companyYears != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Years in  Business: " + '' + searchObject.companyYears + "  — ";
  };
  if (locationAll != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "All Locations: " + '' + searchObject.locationAll + "  — ";
  }; if (locationSingle != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Single Locations: " + '' + searchObject.locationSingle + "  — ";
  };
  if (locationHeadquarter != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Headquarter Locations: " + '' + searchObject.locationHeadquarter + "  — ";
  };
  if (locationBranch != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Branch Locations: " + '' + searchObject.locationBranch + "  — ";
  };
  if (minorityNone != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Omit Minorities: " + '' + searchObject.minorityNone + "  — ";
  };
  if (minorityOnly != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Only Minorities: " + '' + searchObject.minorityOnly + "  — ";
  };
  if (womenNone != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Omit Women: " + '' + searchObject.womenNone + "  — ";
  };
  if (womenOnly != '') {
    //   searchObject.business == $('#industry-button').val();
    searchHistory += "Only Women: " + '' + searchObject.womenOnly + "  — ";
  };
  $('.middle-content').show('fast');
  $('.user-instruct').hide();
  $('.saveSearch').prepend(
    "
" + "Search" + "
" +
    "
" + searchHistory.slice(0, -19)  + "
");
  var saveSearchDisplay = $('.saveSearch').html();
  localStorage.setItem('saveSearch', JSON.stringify( searchObject ));
  localStorage.setItem('saveSearchDisplay', saveSearchDisplay);
  return false;
});

if (localStorage.getItem('saveSearchDisplay')) {
  $('.saveSearch').html(localStorage.getItem('saveSearchDisplay'));
}

var restoredSession = JSON.parse(localStorage.getItem('saveSearch'));

/*if(localStorage.getItem('saveSearch')) {
            $('.saveSearch').html(localStorage.getItem('saveSearch'));
        };*/

$('#clearsave').click(function () {
  window.localStorage.clear();
  location.reload();
  return false;
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-success search-button" type="button">Search</button>

Previous Searches

Comment: If you have to do this client side, you could try to stringify an array containing five search objects to json.
Comment: I also would recommend using json for all your data structuring needs (not just in JavaScript either!)  It's the most elegant way to store structured data like preferred lists.
Answer: The following will error when run here, but can be pasted into the console.

function createCircularQ(maxLength, arr) {
    const q = arr ? arr.splice(0, maxLength) : [];
    q.enqueue = enqueue.bind(null, q, maxLength);
    q.dequeue = q.shift;
    return q;
}

function enqueue(target, maxLength, o) {
   if(target.length === maxLength) {
     Array.prototype.pop.call(target);
   }
   return Array.prototype.unshift.call(target, o);
}

var searches = createCircularQ(5, JSON.parse(localStorage.getItem('searches')));
function search(str) {
    searches.enqueue(str);
    saveSearches();
    // perform search...
}
function saveSearches() {
    localStorage.setItem('searches', JSON.stringify(searches));
}

search('foo');
search('bar');
search('bam');
search('bat');
search('baz');
search('bop');
console.log(JSON.stringify(searches));
searches = null;
searches = createCircularQ(5, JSON.parse(localStorage.getItem('searches')));
console.log(JSON.stringify(searches));

Save a max of 5 searches to LocaHost


A way to enter standart letters using shortcuts

Question: So from time to time my letters O,L and . stop working on my keyboard, which means I have to type using help from screen keyboard. I am looking for a way to assign these characters to shortcuts such as Ctrl + P for O and etc. Is that possible?
Answer: Try in console xdotool:
xdotool keydown ctrl  click p keyup ctrl
put it in bash script, and use shortcuts to execute the script.


Is beauty universal for user interfaces?

Question: I am a sales person for a building automation company.  Without getting into the weeds, we put small computers on heating and cooling equipment to allow them to run most efficiently.  We also provide a user interface to allow the building operators to interact with the system.
I have mechanical type engineers build the graphics for the building operators interface.  I sometimes question the beauty (let alone UX!) of their graphics implementation, and they say "each building operator is unique and wants their own look, and what we built is exactly what they wanted".
Do you feel beauty is "somewhat" universal for user interfaces, or totally unique for each viewer?  If the former, how would you respond to someone who states the latter?
Comment: No, sorry, not. Consider the colorblind. You lose.
Comment: @Joshua  I actually am.  Some reds and greens.  But I do appreciate some things more than others.
Comment: *facepalm* I failed at imagination.
Comment: @Joshua  Took me a while to appreciate your last comment.  Probably shouldn't admin, but had too google "facepalm".
Comment: @Joshua  PS.  Note that in my original post, I said "somewhat".  Yes, I might be an enigma, but is beauty universal for most for a given time?  Apple seemed to have figured it out.
Comment: @user1032531 Apple figured it out for people who like Apple products (or just attracted people who already liked that glossy aesthetic (which I personally dislike)).
Answer: Beauty is a very subjective concept, and as such, your engineers are correct, it's totally unique. So, by their own words, it's really weird that they know what other people wants! (note: I have NEVER, EVER seen an engineer building something aesthetically pleasant. I heard tales of engineers that can do it, but they're like ghosts: they exist, but nobody saw one!)
Out of jokes, beauty is subjective, but it's also a creation that molds a certain context, whether it's a time context, a location context or both at the same time. Your conception of beauty is molded but different factors, most of them created in a design lab of sort. Thus, certain color combinations that may look horrible for you today, will be like "wow, how beautiful that color combination is!". Same goes with fashion, music, literature, theatrical arts, architecture and whatever you could think of. On top of that, the economic dogma of "satisfying a need" goes into full effect because at the same time, there's people creating new needs you didn't have before
Now, this "designed beauty" also considers many technical aspects, including, of course, usability. As the technology "state of the art" evolves, so does the behaviors that have to adapt to those changes. As few as 15 years ago, nobody would have think of having phone, videos and GPS on a phone. Now, nobody can live without it (new needs have been created!).
All this intro is to explain why, while your engineers might be somehow correct in a broad sense, they're absolutely wrong at the same time. If your system evolved, your usability has to evolve. And connection with every day contexts and pleasant aesthetics will make your users more prone to use your system. Showing that you care means a lot more that showing you don't care at all. As blunt as it sounds. If in doubt, check Apple. Or tell them to drive a Lada. It does the same that any car, it will take you home. But well...
If you want to go deeper into these subjects, tale a look to the following resources:

Functional Beauty and User Experience
Usability vs Beauty in web design: Can good UX be ugly?
How Visual Design Makes for Great UX
Utility vs. Beauty
Comment: I know I am not to say +1, but you get +1 for saying "I have NEVER, EVER seen an engineer building something aesthetically pleasant".  Let me digest your response more, however, I probably should ask a different question asking how to make an aesthetically pleasant building engineer interface.
Answer:
Do you feel beauty is "somewhat" universal for user interfaces, or totally unique for each viewer? If the former, how would you respond to someone who states the latter?

I'd say beauty is "somewhat" universal for UIs, but I'd also suggest not to focus much on beauty, and certainly don't try to determine what is and isn't universal beauty - it's simply not very relevant. Instead focus on heuristics and convention. Begin learning about heuristics, or principles of UIs, here and here.

they say "each building operator is unique and wants their own look

How do they know that? And is it important to give them what they want? You probably do want to give them what they want if it increases sales, but you probably don't want to give them what they want if it doesn't increase sales but does decrease your customers' effectiveness. In other words, are your customers qualified to design their own systems? This is not to say "don't listen to your customers" (you should always listen to your customers), but the fact is most software designers are better at software design than their customers. Giving your customers exactly what they want usually isn't beneficial to your customers. Sometimes it is, and sometimes it's a business necessity, but usually the producer of the system, with feedback from multiple customers, will be in a better position to design an effective system than any single customer. In my experience customers usually want something more complicated than they need, while experienced system designers are good at pruning the unnecessary stuff and distilling requirements into a more effective, usable, system (again: not always - sometimes people know exactly what they need to do their job, but usually they don't).
Comment: Thanks obelia,  Should I always listen to my customers?  That may increase short-term sales, but not necessarily long-term sales which I want.  My end-user customer is sometimes an engineer and more often a crafts person, and while most are good at what they do, 99% of them are not artistic and don't really know what they want.  We could and we currently do what the customer asks, but the end result will only look nice to them (which I actually doubt), and will not look nice to their management or future predecessor.
Answer: Beauty is in the eye of the beholder, and it is not uncommon for people to share similar values when it comes to beauty. Yet when you break it down into the different reasons why people find things aesthetically pleasing, it is a unique combination of the same factors for each individual.
Having said that, we often limit our acceptance of beauty based on the perceived value of others (or society as a whole), but when you are open and can expand your mind to accept other types/forms of beauty, you'll find that in fact everything is beautiful in their own way, and it is just a matter of whether you are able to tune yourself to that perspective or not.
But I wouldn't argue that beauty isn't even a criteria for the interfaces used in building management systems (I have designed a few of them in my time), yet when it is simple and easy to use, plus you introduce some infographics and data visualization design, then the users find it 'beautiful' in the way it works.
Comment: "I wouldn't argue that beauty isn't even a criteria".  So you believe beauty isn't important?  My concern is beauty can represent quality upon first impression, and perceptions often means more than reality.
Comment: @user1032531 I think that for the building operators the first thing they look at or think about isn't beauty, but whether the interface has the features that will help them get their job done.
Comment: Yes, that is what they say.  But remember, I am a sales guy that wants future business.
Comment: @user1032531 And if you want future business, it is better to be able to get testimonies from building operators that say the product gets the job done rather than a beautiful interface (usually you don't mention what you can't sell on - with or without stretching the truth). I think appearance is important if your primary lead/source of contact is online and people don't get a chance to read and find out more details (especially if there are many competitor products).
Comment: I see you know my industry!  My company's strength is actually the "under the hood" features and we have (and appreciate) very strong customer loyalty.  We do, however, discount aesthetic qualities as well as field implemented UX aspects, and I personally believe we should pay more attention to the latter.
Comment: @user1032531 I wouldn't say I know the industry well, but I have designed a few interfaces for BMS so I got to know some of the users and use cases. I think it is nice to be able to show a fancy dashboard as part of a sales presentation, but if that dashboard looks pretty and does nothing, you can be sure no one is going to come back for more or recommend it to other people. Get the dashboard design right then make it pretty, not the other way around I say. Hence my original answer stands.
Answer: There is some objective aspect of beauty (in general, at least), as witnessed by Wikipedia's article on Aesthetics:
TL;DR: the shorter possible a description is the more beautiful
(taking into account the observer's previous knowledge and language)

Scientific analysis of aesthetics
In the 1990s, Jürgen Schmidhuber described an algorithmic theory of beauty which takes the subjectivity of the observer into account and postulates: among several observations classified as comparable by a given subjective observer, the aesthetically most pleasing one is the one with the shortest description [emphasis added], given the observer's previous knowledge and his particular method for encoding the data. This is closely related to the principles of algorithmic information theory and minimum description length. For example: mathematical beauty. Another example describes an aesthetically pleasing human face whose proportions can be described with very little information, drawing inspiration from less detailed 15th century proportion studies by Leonardo da Vinci and Albrecht Dürer. Schmidhuber's theory explicitly distinguishes between what is beauty and what is interesting, stating that the latter corresponds to the first derivative of subjectively perceived beauty. The premise is that any observer continually tries to improve the predictability and compressibility of the observations by discovering regularities such as repetitions and symmetry and self-similarity.
Mathematical considerations, such as symmetry and complexity, are used for analysis in theoretical aesthetics. The fact that judgments of beauty and judgments of truth both are influenced by processing fluency has been presented as an explanation for why beauty is sometimes equated with truth. Recent research found that people use beauty as an indication for truth in mathematical pattern tasks.


Do you lose your stuff when you go to point lookout

Question: If I play Point Lookout will all of my stuff (weapons, armor, followers, stimpaks, caps) come with me or do they stay in the Capital Wasteland? I have a bunch of awesome equipment, two companions, and more caps than I know what to do with. Will I be able to use them in Point Lookout or only the Wasteland?
Answer: You don't lose anything when you go to Point Lookout, you continue to use all your gear - it's just another area you can go to. Like the other DLC-only regions, however, your companions will not accompany you to Point Lookout, but you can find them back in their "home area" when you return.
If you don't care about spoilers, here is where you can find the list of possible companions, and you can click one of them to see where they go to when you embark on a DLC area.


Axelrod's Prisoner's Dilemma source code

Question: I'm analyzing the prisoner's dilemma and want to reproduce Axelrod's historic computer tournaments (Robert Axelrod, "Effective Choice in the prisoner's dilemma", Journal of conflict resolution).
Does anyone know if the original source code or algorithms are available?
Axelrod does describe the entered programs in his paper, but I would rather not rewrite them based on the descriptions which might introduce wrong assumptions (and waste effort :).
Comment: Have you thought about emailing Axelrod and asking if the code is published anywhere?
Comment: It seems unlikely anybody here would be able to provide the source, unless Axelrod reads here. :) In any event, the paper is not what one would traditionally call mathematics, since it is entirely experimental. Game theory is definitely mathematical, but not all game theory is mathematics, just as not all economics or physics is mathematics. A fascinating paper, however.
Comment: Eckhart Arnold programmed a platform to run those iterated prisoner's dilemma tournaments, and it includes most strategies mentioned in the book (but these were, as far as I know, also just programmed after the verbal descriptions). See http://www.eckhartarnold.de/apppages/coopsim.html
Comment: @Thomas yes indeed not traditional mathematics.  It is, a dynamical system though.
Comment: @ Daniel: absolutely :) although he has probably replied to thousands of such mails over the past 30 years.  If the internet doesn't know the source code though, this is what I'll do.
Comment: @Nameless, Thanks, I'm checking it out.  Looks like a good place to start.  I'll post back about it later.
Comment: There is also an ongoing recreation of Axelrod's tournament on GitHub:
https://github.com/drvinceknight/Axelrod
Answer: The link provided on Robert Axelrod's homepage is broken.  But he has provided me with the following link.
http://www-personal.umich.edu/~axe/research/Software/CC/CC2.html
Source code is unfortunately / obviously in Fortran.  Hopefully this helps.  If I ever get around to translating this into python I'll be sure to post here.
Comment: There are free Fortran compilers around so using the code as is shouldn't be too hard.


SQL to Criteria using propel

Question: I have this sql:
SELECT link.ID, link.URL, link.ANCHOR, link.HOME, link.CREATED_AT
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING count(linkcategory.category_id) =(select count(*) from categoria)

And I'm trying to generate the criteria, this is the criteria that doesn't work:
$c = new Criteria();
$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addAsColumn('catCount','(SELECT COUNT(*) FROM CATEGORIA)');
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);
$having = $c->getNewCriterion(count(LinkcategoryPeer::CATEGORY_ID),$c->getColumnForAs('catCount'));
$c->addHaving($having);
return self::doSelect($c);

The returning sql of this criteria is this one:
SELECT (SELECT COUNT(*) FROM CATEGORIA) AS catCount
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING 1='(SELECT COUNT(*) FROM CATEGORIA)'

I really don't know why the criteria convert the sql incorrectly. Anyone knows where is the mistake?
Answer: Try with this query. I don't remember how to perform a link.* using Propel. But I think the problem with having is that you are using the PHP count function insteand of the MySQL one.
$c = new Criteria();
$c->addSelectColumn(self::ID);
$c->addSelectColumn(self::URL);
$c->addSelectColumn(self::ANCHOR);
$c->addSelectColumn(self::HOME);
$c->addSelectColumn(self::CREATED_AT );

$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);

$having = $c->getNewCriterion(
  'COUNT('.LinkcategoryPeer::CATEGORY_ID.')'),
  $c->getColumnForAs('catCount')
);
$c->addHaving($having);

return self::doSelect($c);

SQL to Criteria using propel