text:
Q: Disable Windows XP File Caching Background:
I have an application which plays video files from disc. When I play these files the first time the file reading sometimes lags. However, the second time it is played there is never any lag, I suspect this is because the file is put into the windows file cache the first time it is played.
The requirements of my application is that it should be able to play any video at any time (the same video is almost never played twice, thus making the cache unnecessary), this makes the current problem quite critical.
In order to debug this problem I would need to disable windows xp file caching.
Question
Is there a way to disable windows xp file caching?
EDIT/More Info
Im using ffmpeg, and have no access to the actual file read calls. The problem can occur even if several other files have been played previously (warm up).

A: In general, you can't just force FILE_FLAG_NO_BUFFERING. It requires aligned buffers, and typically these aren't provided. Besides, it's the wrong thing. You don't care whether Windows reads 32KB ahead.
The only thing that you'd like Windows to do is discard file contents from cache after you've read them. The correct flag for that is FILE_FLAG_SEQUENTIAL_SCAN. This hints Windows that you (probably) won't seek back, so there is no reason to keep those bytes in cache.

A: You can try passing FILE_FLAG_NO_BUFFERING to CreateFile() to avoid caching. This imposes some requirements on your buffers. Specifically, their size must be a multiple of the sector size and their addresses must be aligned on the sector size. See MSDN for more details.

A: Assuming you have access to the CreateFile call which ultimately opens your file, you can use FILE_FLAG_NO_BUFFERING when you open it:
http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
If you're not calling CreateFile directly yourself, but via some kind of library, you'll need to see if they provide a way to let you set this flag indirectly.
You might also find that the initial delay is caused by loading-up of the enormous number of DLLs which can make up the media stack in Windows, in which case altering the way the media file itself is opened won't help.
You could test this by making an extremely short media file, which you play at app startup, to 'warm-up' the stack.


text:
Q: How can I add additional links to bootstrap when collapsed For the website I am working on I have two sets of links. The first is in a navbar at the top of the screen and consists of my account and login. Then I have a second nav a little ways down on the page and I was wondering if there is a way I can add those links to the collapsed menu. As of now the collapsed menu only displays the two links that are in the navbar.
Note: I have tried adding the second navbar to the navbar-collapse and collapse classes. This makes it so that the 2nd nav does not display when the page is < 768px and the 2nd nav links do appear when you click the icon (3 horizonal '-'). The links from the 2nd nav, however, do not appear with the two links from the main navbar.
The code below should help clarify what I am trying to say:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap Project - Landing Page</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>

Welcome to Celebrity Beauty Online!

 My Account

 Login

XYZ
BEAUTY SUPPLY &#38 SALON

Home

About

Salon

Current Sales!

Contact Us

Thank you for the help!

A: You could duplicate the menu items into your navbar but make them hidden for bigger displays.
If you add this to your navbar it will be hidden for the md and lg displays.

About

If you want to hide your second menu container you created you could add the classes to the div to hide it in the smaller displays

redpajama_set_name: RedPajamaStackExchange


text:
Q: For loop does not repeat results in data frame format I would like to return results from year 2009 to 2017 in a data frame format  with each year as column name and rows names as 0.25,0.5 and 0.75 but my code only returns results for year 2009.
for (y in 2009:2017){
  i <- filter(proj, Year.of.Inflow==y)
  y <- quantile(i$Gross.Salary, probs = c(0.25,0.5,0.75))
  return(as.data.frame(y))
}

Would appreciate your advice to my missing code, thanks.
      y
25% 2891.625
50% 3391.860
75% 4402.775

A: Using only base R functions, you can  use the by function to perform functions by groups, then cbind the results list into a data.frame as follows:
do.call(cbind,
    by(proj$Gross.Salary, proj$Year.of.Inflow,
        function(x) quantile(x, c(0.25,0.5,0.75)))
)

sample data:
set.seed(0L)
yrs <- rep(2009:2017, each=10)
proj <- data.frame(Year.of.Inflow=yrs, Gross.Salary=runif(length(yrs))*1e6)

output:
        2009     2010     2011     2012     2013     2014     2015     2016
25% 422306.3 249489.7 225912.1 375781.8 490352.4 262665.9 303301.2 357510.0
50% 644955.9 440901.5 384251.0 546553.6 600048.3 457858.4 432948.0 626836.0
75% 897966.6 709969.6 746002.4 709899.9 770278.0 626162.4 607789.2 858114.7
        2017
25% 265454.4
50% 417326.9
75% 712166.3


text:
Q: How to quickly find all children of children of a given root I have a dictionary that contains key as stringID and the list of values that have all its children.
For example: parent P1 has childId: A,B,C,D. And child B its child id E, child D has its child id F. So output of parent P1 = A,B,C,D,E,F
    var pcLookUp = new Dictionary<string, List<string>>();
    var list = new List<string>();
    list.Add("A");list.Add("B");list.Add("C");list.Add("D");
    pcLookUp.Add("P1", list);

    pcLookUp.Add("B", new List<string>() {"E"} );
    pcLookUp.Add("D", new List<string>() {"F"} );

    foreach( var k in pcLookUp)
    {
        Console.Write(k.Key + ": ");
        foreach(var v in k.Value)
        {
            Console.Write(v + " ");
        }
        Console.WriteLine();
    }

What is the efficient way to solve this problem?

A: Based on my understanding, it looks like you want to flatten a list of nodes, along with all descendents, into a single list.
A real-world analogy might be sending invitations to a family gathering to your children, telling them to invite their children, and so on then wanting a list of everyone who will attend the gathering. The analogy breaks down because I understand from your question that each node can have only zero or one child nodes. If a given node can have zero to N child nodes, the same idea still applies.
var dict = new Dictionary<string, List<Node>>
{
    { "P1", new List<Node>()
        {
            new Node() { Name = "A" },
            new Node() { Name = "B", Child = new Node() { Name = "E" } },
            new Node() { Name = "C" },
            new Node() { Name = "D", Child = new Node() { Name = "F" } },
        }
    }
};

// Output will hold the flattened tree
var output = Flatten(dict["P1"]);

List<Node> Flatten(List<Node> tree)
{
    IEnumerable<Node> SelfAndDescendents(Node node)
    {
        yield return node;
        var child = node.Child;
        // Walk the nodes to discover all children in the tree.
        while (child != null)
        {
            yield return child;
            child = child.Child;
        }
    }
    var flat = new List<Node>();
    foreach (var node in tree)
    {
        flat.AddRange(SelfAndDescendents(node));
    }
    return flat;
}

class Node
{
    public string Name { get; set; }
    public Node Child { get; set; }
}

A: readonly Dictionary<string, List<string>> _lookup = new()
{
    { "P1", new() { "A", "B", "C", "D" } },
    { "B", new() { "E" } },
    { "D", new() { "F" } },
    // { "E", new() { "B" } }, // a cycle between 'B' and 'E' is handled and won't affect the output
};

private void GetKidsOfNode(string root,
    HashSet<string> visitedNodes,
    HashSet<string> kids)
{
    if (!_lookup.ContainsKey(root)) return;
    foreach (var node in _lookup[root])
    {
        if (visitedNodes.Contains(node)) continue;
        visitedNodes.Add(node);
        kids.Add(node);
        GetKidsOfNode(node, visitedNodes, kids);
    }
}

[Test]
public void Test_GetKidsOfNode()
{
    var kids = new HashSet<string>();
    var visitedNodes = new HashSet<string>();
    GetKidsOfNode("P1", visitedNodes, kids);
    Console.WriteLine(string.Join(", ", kids.ToList()));
}

Output
A, B, E, C, D, F


text:
Q: SQL Server 2012 create assembly failed - invalid attribute I'm trying to integrate a DLL into my SQL Server 2012 database, following the example from here.
The command is:
CREATE ASSEMBLY Excel_Procs_IF
FROM 'd:\MyDir\UWQ_Excel_Compute.dll'
WITH PERMISSION_SET = SAFE ;

and I get the following error message:

Msg 6215, Level 16, State 1, Line 1
  CREATE ASSEMBLY failed because method 'get__Default' on type 'Microsoft.Office.Interop.Excel.Range' in safe assembly 'UWQ_Excel_Compute' has invalid attribute 0x1083.

I have no idea what this means nor how to tackle the issue.

A: You need to change the PERMISSION_SET in your CREATE ASSEMBLY statement to be UNSAFE. Then it should work.
As stated on the MSDN documentation page for Office Primary Interop Assemblies:

To use the features of a Microsoft Office application from an Office project, you must use the primary interop assembly (PIA) for the application. The PIA enables managed code to interact with a Microsoft Office application's COM-based object model.

And, the page for Primary Interop Assemblies states:

A primary interop assembly is a unique, vendor-supplied assembly that contains type definitions (as metadata) of types implemented with COM.

COM is unmanaged code, and that requires the UNSAFE Permission Set.


text:
Q: Accessibility: Can a label have children besides the input? Accessibility question: Can a ... have children besides an <input ... />? We're using Material UI on a project and their <Switch /> component is built like:

        <input />

which is triggering an accessibility error in HTML_Codesniffer.
Not sure if it's just not used to this structure and expects the label to be the direct parent of input or if it's an actual error.

A:
Can a label have children besides the input?

Yes, and fortunately (or it will be impossible to format the text label). The following is permitted for instance

  My input label
  <input type="text" />

According to the documentation it can contain any phrasing content:

Phrasing content, but with no descendant labelable elements unless it is the element's labeled control, and no descendant label elements

In your example, you can't have a div as it's a flow content not a phrasing content although browser and assistive technologies have support for it.
Note that the accessibility error in HTML_Codesniffer might not be linked to that problem, but to the fact that this tool does not link correctly the label with the input.

A: inline elements aren't actually designed for containing elements maybe you should use "div" instead of "span"


text:
Q: Codeigniter: How to loop a result array in view page? I have to forech an array result, when I print_r the array, I got this result:

Array ( [0] => stdClass Object ( [reqcount] => 35 ) [1] => stdClass
  Object ( [reqcount] => 3 ) [2] => stdClass Object ( [reqcount] => 1 )
  [3] => stdClass Object ( [reqcount] => 1 ) [4] => stdClass Object (
  [reqcount] => 1 ) [5] => stdClass Object ( [reqcount] => 1 ) [6] =>
  stdClass Object ( [reqcount] => 1 ) [7] => stdClass Object (
  [reqcount] => 1 ) [8] => stdClass Object ( [reqcount] => 1 ) [9] =>
  stdClass Object ( [reqcount] => 1 ) [10] => stdClass Object (
  [reqcount] => 1 ) [11] => stdClass Object ( [reqcount] => 1 ) [12] =>
  stdClass Object ( [reqcount] => 1 ) [13] => stdClass Object (
  [reqcount] => 1 ) [14] => stdClass Object ( [reqcount] => 1 ) [15] =>
  stdClass Object ( [reqcount] => 1 ) [16] => stdClass Object (
  [reqcount] => 1 ) [17] => stdClass Object ( [reqcount] => 1 ) [18] =>
  stdClass Object ( [reqcount] => 2 ) [19] => stdClass Object (
  [reqcount] => 1 ) [20] => stdClass Object ( [reqcount] => 1 ) [21] =>
  stdClass Object ( [reqcount] => 1 ) [22] => stdClass Object (
  [reqcount] => 1 ) [23] => stdClass Object ( [reqcount] => 1 ) [24] =>
  stdClass Object ( [reqcount] => 1 ) [25] => stdClass Object (
  [reqcount] => 1 ) [26] => stdClass Object ( [reqcount] => 1 ) [27] =>
  stdClass Object ( [reqcount] => 1 ) [28] => stdClass Object (
  [reqcount] => 1 ) [29] => stdClass Object ( [reqcount] => 1 ) [30] =>
  stdClass Object ( [reqcount] => 1 ) [31] => stdClass Object (
  [reqcount] => 1 ) [32] => stdClass Object ( [reqcount] => 1 ) [33] =>
  stdClass Object ( [reqcount] => 1 ) [34] => stdClass Object (
  [reqcount] => 2 ) [35] => stdClass Object ( [reqcount] => 1 ) [36] =>
  stdClass Object ( [reqcount] => 2 ) [37] => stdClass Object (
  [reqcount] => 1 ) [38] => stdClass Object ( [reqcount] => 1 ) [39] =>
  stdClass Object ( [reqcount] => 1 ) [40] => stdClass Object (
  [reqcount] => 1 ) [41] => stdClass Object ( [reqcount] => 1 ) [42] =>
  stdClass Object ( [reqcount] => 1 ) [43] => stdClass Object (
  [reqcount] => 1 ) [44] => stdClass Object ( [reqcount] => 1 ) [45] =>
  stdClass Object ( [reqcount] => 2 ) [46] => stdClass Object (
  [reqcount] => 1 ) [47] => stdClass Object ( [reqcount] => 2 ) [48] =>
  stdClass Object ( [reqcount] => 1 ) [49] => stdClass Object (
  [reqcount] => 1 ) [50] => stdClass Object ( [reqcount] => 2 ) [51] =>
  stdClass Object ( [reqcount] => 1 ) [52] => stdClass Object (
  [reqcount] => 2 ) [53] => stdClass Object ( [reqcount] => 1 ) [54] =>
  stdClass Object ( [reqcount] => 1 ) [55] => stdClass Object (
  [reqcount] => 1 ) [56] => stdClass Object ( [reqcount] => 1 ) [57] =>
  stdClass Object ( [reqcount] => 1 ) [58] => stdClass Object (
  [reqcount] => 2 ) [59] => stdClass Object ( [reqcount] => 2 ) [60] =>
  stdClass Object ( [reqcount] => 1 ) [61] => stdClass Object (
  [reqcount] => 1 ) [62] => stdClass Object ( [reqcount] => 1 ) [63] =>
  stdClass Object ( [reqcount] => 1 ) [64] => stdClass Object (
  [reqcount] => 1 ) [65] => stdClass Object ( [reqcount] => 1 ) [66] =>
  stdClass Object ( [reqcount] => 1 ) [67] => stdClass Object (
  [reqcount] => 1 ) [68] => stdClass Object ( [reqcount] => 1 ) [69] =>
  stdClass Object ( [reqcount] => 1 ) [70] => stdClass Object (
  [reqcount] => 1 ) [71] => stdClass Object ( [reqcount] => 1 ) [72] =>
  stdClass Object ( [reqcount] => 1 ) [73] => stdClass Object (
  [reqcount] => 1 ) [74] => stdClass Object ( [reqcount] => 1 ) [75] =>
  stdClass Object ( [reqcount] => 1 )

Please help me to foreach the result in view page

A: You are getting result in object form you can get values in foreach loop as:
Example:
foreach ($yourArr as $value) {
    echo $value->reqcount;
}

One more solution, if you want to convert object into array than you can just change the typecast by following this:
$array =  (array) $yourObjectArr;

A: This is not technically array, this array of objects, which means that when you foreach it, you need to access objects by pointer ->.
foreach ($array as $result) {
  echo $result->reqcount;
}

A: Your array is object type so use this code
foreach($yourarrray as $value)
{
 echo $value->reqcount;
}

A: Well you have an Array with Object-Values in there.
To access your reqcount values, take a look on this iteration:
foreach($array as $key => $value){
    echo $value->reqcount.PHP_EOL;
}

This should do what you want.


text:
Q: How format latex code in [] What editor allows you to do automatic indentation as in the example in []
[]1

If I use TexStudio it does so
Or is it all done by hand?

A: Texstudio has a function to automatically indent stuff:

*

*Mark everything within []

*menu bar -> idefix -> indent


text:
Q: Adding a fullscreen button to a Windows media player object in HTML Is there a way to tell a Windows Media player object to have a button for fullscreen in this HTML?
<div id="player" style="position: relative; top: 20px; left: 35px; width: 64.5%; border: 2px solid grey; z-index: 40;">
             <object id="MediaPlayer" width="100%" height="377" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" style="left: 0px; top: 0px; background-repeat: no-repeat; background-position: center center; z-index: 40;" type="application/x-oleobject">
                    <param name="uiMode" value="full" />
                    <param name="AutoStart" value="FALSE" />
                    <param name="AllowChangeDisplaySize" value="TRUE" />
                    <param name="AutoSize" value="TRUE" />
                    <param name="Volume" value="100" />
                    <param name="URL" value=mms://bstreamlivewm.fplive.net/bstreamlive-live/bstream2 />
                    <embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" name="MediaPlayer" src=mms://bstreamlivewm.fplive.net/bstreamlive-live/bstream2 width="100%" height="377" showcontrols="1" showtracker="1" autostart="0" volume="100" />
            </object>
</div>

A: The video will automatically shown in fullscreen if you doubleclick the video. That is a proprietary handling by Windows Media Player. You can even disable nor enable it. The only options you have to customize the GUI of the WMP is by changing the uiMode to e.g. mini.


text:
Q: Game theory: Mixed Strategies and Nash Equilibrium So I've recently become interested in game theory, and I've visited this site to help me understand what exactly game theory is and the applications of it.
In the lesson, they use an example of tennis and one of the players is at the net and the other is at the baseline. The player at the baseline is determining where to hit her shot: right or left, and where the volleyer will move left, or right. They called the probability that the volleyer will volley to the left is q, and to the right is 1- q.
They then state that in order to determine the nash equilibrium, the "expected payoffs" must be equal? Could someone please explain to me why? This pdf may also be of help to you. This pdf may help as well.
I also have another question. I'm thinking about using game theory in my science fair project to determine where tennis players should hit their balls (right, left, middle, short, or deep) based on the data from the two players facing one another in order for one of them to win the point. If the data was already given, would it be possible for you to conduct this experiment using game theory?
My try was to use the knowledge that I had learned up above but I didn't know how to handle multiple cases, in the example provided you only had to deal with 2 cases.
Thanks in advance to anyone who can help.

A: I think you already understand why the players need to take expectations. Now why do the expectations need to be equal? The idea is, if there was one strategy which gave you strictly higher expected payoff, you would just stick to playing that strategy, instead of randomizing between 2 or more strategies, right?
So, the only reason that might prompt you to play a mixed strategy is when all strategies give equal expected payoff. $\\$
Also, you can obviously extend this to randomizing over 3 or more strategies. Do you know about the previous applications of game theory in sports? I would encourage you to do some research into that before embarking into the project. For example, https://econ.duke.edu/uploads/assets/dje/2006_Symp/Wiles.pdf

A: Related work:
Minimax Play at Wimbledon,
Walker and Wooders,
The American Economic Review, 2001
http://www.johnwooders.com/papers/Wimbledon.pdf


text:
Q: Closing stop channel does not stop goroutines INTRODUCTION:
I am just starting to learn the Go language and have reached the lesson about concurrency.
I have invented a small task for myself to try to implement what I have learned about closing goroutines.
PROBLEM:
If we close channel it's case will always be selected in the select statement, which is a great way to broadcast cancelation signal to all goroutines.
Below I have 2 goroutines and a quit channel that never gets received.
Code timeouts on Playground.
If I comment out default part in the goroutines then quit signal gets received.
QUESTION:
I really do not understand why is this happening and how to fix it, although I am trying.
Can somebody please explain me what is the problem and offer some advice on how to solve it?
package main

import (
    "fmt"
    "sync"
    "time"
)

func positive_numbers(quit chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    i := 1
    for {
        select {
        case <-quit:
            fmt.Println("[+]Quiting...")
            return
        default:
            fmt.Printf("%v ", i)
            i++
        }
    }
}

func negative_numbers(quit chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    i := -1
    for {
        select {
        case <-quit:
            fmt.Println("[-]Quiting...")
            return
        default:
            fmt.Printf("%v ", i)
            i--
        }
    }
}

func main() {
    quit := make(chan struct{})

    wg := sync.WaitGroup{} // so we can wait for all goroutines to finish
    wg.Add(2)

    go positive_numbers(quit, &wg)
    go negative_numbers(quit, &wg)

    go func(quit chan struct{}) {
        defer close(quit)
        time.Sleep(1 * time.Second)
    }(quit)

    wg.Wait()
}

A: This code works alright in real life; it's just not compatible with the playground's "fake time" because positive_numbers and negative_numbers don't block, and the runtime can't decide how many iterations of each get to run before the Sleep expires (basically, the prints take zero emulated wallclock time, so they try to produce infinite output, and you hit the playground CPU usage limit without ever advancing the wallclock time at all). On real machines, where you can only print finite output in finite time, you get reasonable behavior.
In the playground, if you add something like time.Sleep(time.Millisecond) after each print, you force the fake clock to move forward, and the program also terminates.


text:
Q: ActionBar Flickering while hiding/showing in RecyclerView So in my case I am using a RecyclerView to display a list of items but when I try to hide the action bar while scrolling I get this annoying flickering of the screen. I have searched the web for an answer to my problem but so far there has been no luck. So can anyone tell me what I am doing wrong?
here is my java for hiding the action bar:
     @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    this.container = container;
    this.inflater = inflater;
    timePassed = System.currentTimeMillis();
    if(hasMoreResults) {
        rootView = inflater.inflate(R.layout.home_zone, container, false);

        rootView.findViewById(R.id.imgAdsMap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, AdsMap.class));
            }
        });

        recyclerViewZone = (RecyclerView) rootView.findViewById(R.id.recyclerViewZone);
        recyclerViewZone.setVerticalScrollBarEnabled(true);

        // 2. set layoutManger
        manager = new LinearLayoutManager(context);
        recyclerViewZone.setLayoutManager(manager);
        recyclerViewZone.setItemAnimator(new DefaultItemAnimator());

        recyclerViewZone.setOnScrollListener(new RecyclerView.OnScrollListener()
        {
            int mLastFirstVisibleItem = 0;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && !generatedAdsFromScroll)
                {
                    generatedAdsFromScroll = true;
                    runSplitRequest(10);
                }
            }

            //Hiding the Action Bar for better view of the listed items

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                final int currentFirstVisibleItem = manager.findFirstVisibleItemPosition();

                if (currentFirstVisibleItem > this.mLastFirstVisibleItem)
                {

                    ActionBar bar = getActivity().getActionBar();
                    bar.hide();

                    myButton = (RadioGroup)getActivity().findViewById(R.id.radioButtonGroup);
                    myButton.setVisibility(View.GONE);
                }
                else if (currentFirstVisibleItem < this.mLastFirstVisibleItem)
                {
                    ActionBar bar = getActivity().getActionBar();
                    bar.show();
                    myButton = (RadioGroup)getActivity().findViewById(R.id.radioButtonGroup);
                    myButton.setVisibility(View.VISIBLE);
                }

                this.mLastFirstVisibleItem = currentFirstVisibleItem;
            }
        });

        runSplitRequest(20);
    }
    else
        rootView = inflater.inflate(R.layout.error_internet_connection, container, false);

    return rootView;
}

This is the XML of the recyclerview:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent" >

<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/recyclerViewZone"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?android:attr/actionBarSize"
    android:clipToPadding="false"
    android:scrollbarStyle="outsideOverlay"
    tools:context=".MainActivity"
    android:scrollbars="vertical" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imgAdsMap"
    android:src="@drawable/map_button_map_down"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

and the style of the action bar:
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:windowActionBarOverlay">true</item>
</style>

<dimen name="image_detail_height">200dp</dimen>

So as you can see I have enabled the action bar to overlay. I have also tried with calling the overlay of the action bar in the activity I call the recyclerview class but the problem remains... no luck the flickering is still there and even if I add padding to the recyclervie XML i just get a black rectangle with the size of the action bar.
Here is the xml of the activity I display the recyclerview:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:background="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#353535"/>

    <RadioGroup
        android:id="@+id/radioButtonGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center_horizontal">

z
        <RadioButton
            android:button="@null"
            android:checked="true"
            android:contentDescription="ZONA"
            android:background="@drawable/tab_back_selector"
            android:textColor="@color/tab_text_color"
            android:textSize="12sp"
            android:layout_weight="1"
            android:id="@+id/tabZoneHome"
            android:padding="14dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/home_tab_zone"
            android:gravity="center"/>

        <RadioButton
            android:button="@null"
            android:contentDescription="VISITADAS"
            android:background="@drawable/tab_back_selector"
            android:textColor="@color/tab_text_color"
            android:textSize="12sp"
            android:layout_weight="1"
            android:id="@+id/tabVisitedHome"
            android:padding="14dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/home_tab_visited"
            android:gravity="center"
            android:checked="false" />

        <RadioButton
            android:button="@null"
            android:contentDescription="SUGERENCIAS"
            android:background="@drawable/tab_back_selector"
            android:textColor="@color/tab_text_color"
            android:textSize="12sp"
            android:layout_weight="1"
            android:id="@+id/tabSuggestionsHome"
            android:padding="14dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/home_tab_suggestions"
            android:gravity="center"
            android:checked="false" />

    </RadioGroup>

    <RelativeLayout
        android:id="@+id/ad_detailholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="6dp"
            android:background="@drawable/quickview_top_gradient"/>

    </RelativeLayout>

    <!-- Framelayout to display Fragments -->

</LinearLayout>
<!-- Listview to display slider menu -->


text:
Q: derivative $f(z)=\sqrt [n] {g(z)}$ and $f(z)=\log(g(z))$ How I can compute the derivative at a point of function $f(z)=\sqrt [n] {g(z)}$ and $f(z)=\log(g(z))$ if I know $f(z_0)$ for a fixed $z_0$ and if I have a suitable plane cut?
Is it true that we can not care about $\log(g(z))$ because every brunch has the same derivative and we can say that $(\log (g(z))'(a)= \frac {g'(z)}{g(z)}(a)$?

A: It is true that for $f(z) = \log(g(z))$ one has
$$
 f'(z) = \frac{g'(z)}{g(z)}
$$
independently of the branch. That reflects the fact that different local branches of the logarithm differ by a constant.
That is not the case for $f(z)=\sqrt [n] {g(z)}$ where different local branches differ by a constant factor. Taking the logarithmic derivative of $(f(z))^n = g(z)$ gives
$$
 f'(z) = \frac 1n f(z) \frac{g'(z)}{g(z)}
$$
so that $f'(z)$ depends on the branch chosen for $f(z)$.


text:
Q: Getting to a number with the smallest number of steps. An agent acts on a set $A$ of positive integers by fiddling with the following process.
$\bullet$ Initialize $j = 0$, $A = \{1\}$, some given natural number $n$.
$\bullet$ If $x,y \in A$ then you can append the set $A$ with the number $x+y$ and increase $j$ by $1$, if $n \in A$ then return $j$.
The agent strives to output the smallest $j$ which we will call $W(n)$.
Find $\limsup_{n \rightarrow \infty}\frac{\log_{2}(W(n))}{\log_{2}(n)}$. I know that it is at most $2$ due to the reason below.
I know that if $n$ is of the form $2^{a_{d}}+2^{a_{d-1}}+...+2^{a_{1}}$ where $a_{d}>a_{d-1}...>a_{1}\geq 0$ then the agent can arrive at this number in almost $a_{d}+d-1$ steps.


text:
Q: Why has the parsing of the   in tables changed? I am used to using the   HTML character to visually fill out the width and/or height of tables so they are used to their full potential:

So that instead of this:
I get this:

Looks much better, right?

I use a string of non-breaking spaces within the cell that doesn't use its space within the table optimally.
However, since I think a few months, the parsing of the non-breaking space character in tables has changed, and now I get this:

While the images are neatly evened out, and the table with both cells still renders at the width of the post, there is an empty space rendered to the right of the table, outside of both cells, which can be navigated to using a scrolling bar. But this is completely useless, and both uses up space and is bad UI/UX design.
What's strange is that I use the exact same trick in the top table here, and it renders like I'm used to - that is, without the extra space and the scrollbar - which makes me think this 'problem' is site-dependent.
The documented case here happens on Worldbuilding, here. There is no difference in behaviour between creating an answer or a question.
After testing it on Arts & Crafts, I get this same new behaviour (also both in questions and answers) where I'm certain it wasn't the case before.
Does anyone know why and/or when this happens?
It might have something to do with whitespace:nowrap of the <th> elements. When removed, the table behaves like I remember it.

Environment this behaviour is seen on:

*

*Windows 10 Pro, 21H2

*Firefox 95.0.2 (64-bit) (I was able to reproduce it in Edge  97.0.1072.62 (64-bit), without plugins)

*Scripts: Privacy Badger, Decentraleyes, HTTPS Everywhere, and Tampermonkey with AutoReviewComments, FlagFilter, Helpful Moderator Userscripts, kbd formatting button for stackexchange, StackExchange Moderator Tools Improved

*Screen resolution: 1920 x 1200

(I've brought up the possibility of implementing a custom method of evening out the width of the cells in my other question here.)

Related table experiments in the Formatting Sandbox

A: There has been no change
There's nothing to explain here. There has been no change in how tables render with respect to this issue. There is no per-site difference. You are misremembering what you've done/seen in the past and/or confusing between the rendering of two different pieces of Markdown.
Your examples are different on different sites
Your example table in this question puts the images and   HTML entities into a table body cell (a <td>), while your example answer puts the   HTML entities into a table header cell (a <th>). These elements have different CSS.
Table header cells, <th> elements, have the following CSS which table body cells, <td> elements, do not have:
.s-table th {
    font-weight: bold;
    color: var(--fc-dark);
}
.s-table thead th {
    vertical-align: bottom;
    white-space: nowrap;
    background-color: var(--black-025);
    line-height: 1.15384615;
}

This partially overrides the <td> and <th> CSS of
.s-table th, .s-table td {
    padding: 8px;
    border-top: 1px solid var(--bc-medium);
    border-left: 1px solid var(--bc-medium);
    border-right: 1px solid var(--bc-medium);
    vertical-align: middle;
    color: var(--fc-medium);
    text-align: left;
}

The CSS is very similar to what it was years ago
This CSS has only changed a bit over the time tables have been a feature on SE. On 2020-11-13, about 10 days prior to tables being available on SE, the CSS for these elements was:
.s-table th,
.s-table td {
    padding: 8px;
    border-top: 1px solid var(--black-100);
    border-left: 1px solid var(--black-100);
    border-right: 1px solid var(--black-100);
    vertical-align: middle;
    color: var(--fc-medium);
    text-align: left
}
.s-table th {
    font-weight: bold;
    color: var(--fc-dark)
}
.s-table thead th {
    vertical-align: bottom;
    white-space: nowrap;
    background-color: var(--black-025);
    line-height: 1.15384615;
    text-transform: uppercase;
    letter-spacing: .05em
}
.s-table thead th:not(.s-table--bulk) {
    font-size: 11px
}
.s-table tbody th {
    font-weight: normal
}


text:
Q: Apex Email Services not running as expected I thought this would be simple enough but apparently I can't get it to work since I'm doing something really stupid here.

*

*I have an account named CVB in my test org.

*I send an email to Salesforce using my email ID and with just CVB in the body.

*The Email is being read fine since the first System.debug statement does show the string as CVB.

*What my code fails to do is update the CVB account with the datetime.
The issue is with the SOQL query since I'm getting the following error in the log:

FATAL_ERROR System.QueryException: List has no rows for assignment to SObject

  I have tried running my SOQL query separately in the dev console and it runs just fine but the code for some reason isn't being able to grab the Account and is populating an empty List. Any ideas?

global class ProcessTelerikEmail implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail  email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        String accName = email.plainTextBody;
        System.debug('Account Name is:' + accName);
        Datetime myDateTime = Datetime.newInstance(2015, 6, 3);
        Account accs =  new Account();
        accs = [SELECT Id, Burn_script_run_time__c, Name from Account WHERE Name= :accName ];
        System.debug('Account name is: ' + accs.Name);
        accs.Burn_script_run_time__c = myDateTime ;
        return result;
    }
}

A: As analysed by @crop1645, seems like the email service is counting a white space character as well.. Do something like this. Always use a list to assign values from soql. Avoid using sObjects for that.
List<Account>accs = [SELECT Id, Burn_script_run_time__c, Name from Account WHERE Name= :accName.trim() limit 1];

accs[0].Burn_script_run_time__c = myDateTime ;

This should work for you.


text:
Q: Using a PHP variable as a variable in jQuery I'm having a hard time understanding how to import a specific variable for use with jQuery.
Some links on a Wordpress theme are using
<?php  if( get_post_meta($post->ID, "portfolio_link", true) ): ?>

                <a target="_blank" href="<?php the_field('portfolio_link'); ?>">
                    <?php the_field('portfolio_title'); ?> p

        <?php else: ?>

<?php the_field('portfolio_title'); ?>

<?php endif; ?>

As you can see the href is set as
href="<?php the_field('portfolio_link'); ?>"

Now I have a jQuery script as follows

This script currently works. It opens google in a new tab as a placeholder until I know how to make it open the same result as the href.
Now what I can't understand is how to set '$phpVar' to have the same effect as the 'href' I showed before instead of 'http://www.google.com';

A: Not sure just how the WordPress handling of this is, but given that the_field('portfolio_title'); returns a valid URL, you can simply assign the JavaScript variable the output of this variable.
var phpVariable = "<?php the_field('portfolio_link'); ?>";


text:
Q: Pickle a frozen dataclass that has __slots__ How do I pickle an instance of a frozen dataclass with __slots__? For example, the following code raises an exception in Python 3.7.0:
import pickle
from dataclasses import dataclass

@dataclass(frozen=True)
class A:
  __slots__ = ('a',)
  a: int

b = pickle.dumps(A(5))
pickle.loads(b)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 3, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'a'

This works if I remove either the frozen or the __slots__. Is this just a bug?

A: Starting in Python 3.10.0, this works but only if you specify the slots via slots=True in the dataclass decorator. It does not work, and probably will never work, with __slots__ manually specified.
import pickle
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class A:
  a: int

b = pickle.dumps(A(5))
pickle.loads(b)  # A(a=5)

A: The problem comes from pickle using the __setattr__ method of the instance when setting the state of the slots.
The default __setstate__ is defined in load_build in _pickle.c line 6220.
For the items in the state dict, the instance __dict__ is updated directly:
 if (PyObject_SetItem(dict, d_key, d_value) < 0)

whereas for the items in the slotstate dict, the instance's __setattr__ is used:
if (PyObject_SetAttr(inst, d_key, d_value) < 0)

Now because the instance is frozen, __setattr__ raises FrozenInstanceError when loading.
To circumvent this, you can define your own __setstate__ method which will use object.__setattr__, and not the instance's __setattr__.
The docs give some sort of warning for this:

There is a tiny performance penalty when using frozen=True: __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__().

It may also be good to define __getstate__ as the instance __dict__ is always None in your case. If you don't, the state argument of __setstate__ will be a tuple (None, {'a': 5}), the first value being the value of the instance's __dict__ and the second the slotstate dict.
import pickle
from dataclasses import dataclass

@dataclass(frozen=True)
class A:
    __slots__ = ('a',)
    a: int

    def __getstate__(self):
        return dict(
            (slot, getattr(self, slot))
            for slot in self.__slots__
            if hasattr(self, slot)
        )

    def __setstate__(self, state):
        for slot, value in state.items():
            object.__setattr__(self, slot, value) # <- use object.__setattr__

b = pickle.dumps(A(5))
pickle.loads(b)

I personally would not call it a bug as the pickling process is designed to be flexible, but there is room for a feature enhancement. A revision of the pickling protocol could fix this in future. Unless I am missing something and aside of the tiny performance penalty, using PyObject_GenericSetattr for all the slots might be a reasonable fix?

A: If you only need the class to be hashable, you can force generate __hash__ function with unsafe_hash=True option. You will not get the immutability guarantee, but immutability in python is impossible anyways.
Relevant python documentation states:

Although not recommended, you can force dataclass() to create a __hash__() method with unsafe_hash=True. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully.

import pickle
from dataclasses import dataclass

@dataclass(unsafe_hash=True)
class A:
    __slots__ = ('a',)
    a: int

b = pickle.dumps(A(5))
hash(pickle.loads(b))  # works and can hash!


text:
Q: Python daemon can see database, but complains that tables do not exist I have a vanilla python that connects to a sqlite database.
Everything works fine until I try to run it as a daemon. Here is the code I'm using to do that:
def start(self):
  if self.lockfile.is_locked():
    exit_with_code(7, self.pid_file)

  # If we're running in debug, run in the foreground, else daemonise
  if self.options['debug']:
    try:
      self.main()
    except KeyboardInterrupt:
      pass
    finally:
      self.close_gracefully()
  else:
    context = daemon.DaemonContext(
      files_preserve = [self.logger.socket(), self.lockfile]
    )

    context.signal_map = {
      signal.SIGTERM: self.close_gracefully
    }

    with context: self.main()

I can run it in the foreground with python -m starter -debug and everything is fine, my app writes into the database, but when I leave the debug flag off I see the following when I try to write:
no such table: Frontends

I know that the frontends table exists because I've opened the database up. I assume that python is finding the database, because there would be an entirely different error message otherwise.
All my files are owned by vagrant, and ls -l shows the following:
-rwxrwxrwx 1 vagrant vagrant 9216 Nov  9 18:09 development.sqlite

Anyone got any tips?
Update
As requested, here is the code for my db
import os
import sqlite3

class Database(object):

    def __init__(self, db_file='/vagrant/my_daemon/db/development.sqlite'):

        self.db = sqlite3.connect(db_file)

        if os.path.exists(db_file):
            print "db exists"

And when I run this it prints "db exists". I instantiate the database in starter.py with a call to Database().

A: Python daemon closes all open file descriptors (except stdin, stout and stderr) when you daemonise.
I spent ages trying to figure out which files to keep open to prevent my database from being inaccessible, and in the end I found that it's easier to initialise the database inside the daemon context rather than outside. That way I don't need to worry about which files should stay open.
Now everything is working fine.


text:
Q: Support with Logic Gate Simulation program in Python I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.
This is what I have so far:
print ("Logic Gate Simulation")

def AND (a,b):

    if a == 1 and b == 1:
        return 1
    else:
        return 0

def NAND (a,b):
    if a == 1 and b == 1:
        return 0
    else:
        return 1

def OR(a,b):
    if a == 1:
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR (a,b):
    if a != b:
        return 1
    else:
        return 1

def Main():
    question = input("what type of gate do you want to simulate - OR, AND  or NAND?  ")

    if question == 'AND':
        a = input("enter value for input 1")
        b = input("enter value for input 2")
        x= AND(a,b)
        print (x)

    else:
        print ("")
Main()

When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.

A: this works:
def AND (a,b):
    a=int(a)
    b=int(b)
    if a == 1 and b == 1:
        return 1
    else:
        return 0

you have to tell python that a and b are integers - (there are better ways of doing that than the method shown)

A: This is my version of the code (I had to this for homework for AS Level, this may help you!) :
print("Logic Gate Calculator")

def AND(a, b):  # AND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # AND Gate logic
        return 1
    else:
        return 0

def NAND(a, b):  # NAND Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 1:  # NAND Gate logic
        return 0
    elif a == 1 and b == 0:
        return 0
    elif a == 0 and b == 1:
        return 0
    else:
        return 1

def OR(a, b):  # OR Gate
    a = int(a)
    b = int(b)
    if a == 1:  # OR Gate Logic
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR(a, b):  # NOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # NOR Gate Logic
        return 1
    elif a == 0 and b == 1:
        return 1
    elif a == 0 and b == 0:
        return 1
    else:
        return 0

def XOR(a, b):  # XOR Gate
    a = int(a)
    b = int(b)
    if a == 1 and b == 0:  # XOR Gate Logic
        return 1
    elif a == 1 and b == 1:
        return 1
    else:
        return 0

def main():  # The main program
    run = True
    while run:  # While loop
        question = input("What type of gate do you want to use OR, AND, NOR, or NAND or (Q)uit")  # Logic Gate chooser
        if question == "AND" or question == "and" or question == "And":  # If the user selects AND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = AND(a, b)  # Calling the AND Function
            print("The output will be:", x)  # Output result
        elif question == "OR" or question == "or" or question == "Or":  # If the user selects OR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = OR(a, b)  # Calling the OR Function
            print("The output will be:", x)  # Output result
        elif question == "NOR" or question == "nor" or question == "Nor":  # If the user selects NOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NOR(a, b)  # Calling the NOR function
            print("The output will be:", x)  # Output result
        elif question == "NAND" or question == "nand" or question == "Nand":  # If the user selects NAND
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = NAND(a, b)  # Calling the NAND function
            print("The output will be:", x)  # Output result
        elif question == "XOR" or question == "xor" or question == "Xor":  # If the user selects XOR
            a = input("Enter value for input 1 (1 or 0):")  # Getting the Logic Gate's 1st input
            b = input("Enter value for input 2 (1 or 0):")  # Getting the Logic Gate's 2nd input
            x = XOR(a, b)  # Calling the XOR function
            print("The output will be:", x)  # Output result
        elif question == "Q" or question == "q":  # Quiting the program
            run = False
        else:
            print("Please enter one of the shown logic gates")  # Error handling

main()

A: a=True
b=True
output=a and b
print (output)
a=True
b=False
output=a and b
print (output)
Please try this

A: It works. Use
if a == 1:
if b == 1:
return 1
else
return 0


text:
Q: How to route between subnets Experienced, but very limited network knowledge - please bear with me.
I have a simple PPTP VPN server on my Ubuntu 18.04 server PC (yes, I know it's insecure, etc.). The router, PPTP server and VPN clients all live on the same subnet 192.168.1.x and all works well. I do a little NAT to the server from the router.
My goal is to specify a different subnet for the clients - say 192.168.0.250-252.
Try as I have, no luck. Obviously, there is routing involved which I have no knowledge of. Please, can someone tell me what to do? I would also like, if possible, for the solution to be at the server end, rather than at the client.
This is my current setup:
192.168.1.1   Router
192.168 1.100 PPTP server on enp1s0:
192.168.1.250-252 VPN clients on ppp0:
What I am looking for is
192.168.1.1   Router
192.168 1.100 PPTP server on enp1s0:
192.168.0.250-252 VPN clients on ppp0:

A: I don't know if there is a option of PPT VPN to push route dynamically. If there is, You can write script an push route dynamically ,
In openvpn (free) there is this option via
--client-connect you_script


text:
Q: Keep form data when opening and closing extension? I am developing an extension for Google Chrome, where users fill out a form through this.
How it works:

*

*User clicks on the extension icon and a popup appears with form;

*Start filling out the form;

*Ends filling;

*Send form;

*End.

Problem:

*

*The user clicks on the extension icon and a popup appears with form;

*Start filling out the form;

*User clicks on the extension icon inadvertently or out of the popup;

*Extension closes;

*User opens again;

*Data already filled were lost;

*Extension becomes unfeasible;

*End.

I need to know how not to lose this data, but I do not even know how to Google it. Can you help me?

A: In a nutshell, here's how one can do it:

*

*On every input change, save it to a persistent storage

*On popup load, load the saved data

*On successful completion of the form, clear the saved data

There are different options for persistent storage in Chrome extensions, but the most "native" is the chrome.storage API. You can find samples in the docs and here on SO.
That covers loading and saving the data, but how to catch input change? Well, there's a helpful oninput event for form fields.
So the basic idea:
var keys = [/* a list of your fields' ids as keys */];

document.addEventListener("DOMContentLoaded", function() {
  chrome.storage.local.get(keys, function(data) {
    /* find the form fields and set their state from data, for example
       (depends on the field type - maybe not .value) */
    for (let key of keys) {
      let field = document.getElementById(key);
      field.value = data[key];
      field.oninput = saveData;
    }
  });
})

function saveData(e) {
  chrome.storage.local.set({[this.id]: this.value});
}

function clearData() { // To be called when you submit your data
  chrome.storage.local.remove(keys);
}

It's a very rough draft; try to get the idea and adapt it from there.


text:
Q: Remove unneeded columns from geographic data file? I have some GML data that has some unneeded columns in it. I'd like to remove these columns in order to reduce the file size. (To clarify: I mean that the file has many points in it, and each of these points has some metadata attached, and I don't need all of the metadata.)
I'd also like to do this from the command line, as I have many files.
I can convert the GML files into different formats using ogr2ogr, so my question is this: what's the easiest way to remove a column from a geographic data file, from the command line?
I'm a Python programmer so my instinct would be to convert the file to GeoJSON, then use Python's JSON-parsing methods to read and rewrite the JSON file.
But perhaps there's a more direct way, using a GDAL tool or similar.

A: Shapefile as a temporary file format is not necessary and it may also alter the GML data (shorten attribute names, cut strings to max 255 characters, change DATETIME to DATE etc.)
I would use ogr2ogr not by dropping unwanted attributes but by selecting those which are wanted. The SQLite SQL dialect is more standard than the defauld OGR dialect, that's why I use that even it is not necessary for this query.
ogr2ogr -f GML -dialect SQLite -sql "SELECT attr1, attr2, attr3,... FROM layer" output.gml input.gml

A: You can delete a field using OGR SQL and choosing an OGR format which supports the field deletion. Unfortunately GML doesn't support it, so you have to pass through another format, e.g. SHP:
ogr2ogr temp.shp input.gml
ogrinfo temp.shp -sql "ALTER TABLE temp DROP COLUMN field_to_drop"
ogr2ogr -f GML output.gml temp.shp


text:
Q: ArrayList of custom class to ArrayAdapter for ListView I've succesfully figured out how to get my soap object in memory.  Now i'm trying to get what I've returned into a ListView.
My Custom Class looks like this
public class JudgmentInformationClass {
    public static class PipelineGridViewClass {
        private String CaseId;
        private double Amount;
        private String CaseDescription;
        private Date JudgmentDate;
    }
}

This returns exactly what i'm looking for 10 rows of this information.
Now I want to send it to a basic listview.
I have a custom List working but i cannot figure out how to make my custom arraylist.  I get the following error.
Error:(103, 53) error: no suitable constructor found for ArrayAdapter(MainActivity,int,ArrayList<PipelineGridViewClass>)
constructor ArrayAdapter.ArrayAdapter(Context,int,int,List<String>) is not applicable
(actual and formal argument lists differ in length)
constructor ArrayAdapter.ArrayAdapter(Context,int,List<String>) is not applicable
(actual argument ArrayList<PipelineGridViewClass> cannot be converted to List<String> by method invocation conversion)
constructor ArrayAdapter.ArrayAdapter(Context,int,int,String[]) is not applicable
(actual and formal argument lists differ in length)
constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not applicable
(actual argument ArrayList<PipelineGridViewClass> cannot be converted to String[] by method invocation conversion)
constructor ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable
(actual argument ArrayList<PipelineGridViewClass> cannot be converted to int by method invocation conversion)
constructor ArrayAdapter.ArrayAdapter(Context,int) is not applicable
(actual and formal argument lists differ in length)

.
 private void SetListView(Activity activity) {

    activity.runOnUiThread(new Runnable() {
        public void run() {
            ArrayList<JudgmentInformationClass.PipelineGridViewClass> pipelineview = JudgmentInformationClass.PipelineGridViewClass.PipelineGridView();
            //ArrayList<JudgmentInformationClass.PipelineGridView>
            lv = (ListView) findViewById(R.id.listview);
            /*List<String> your_array_list = new ArrayList<String>();
            your_array_list.add("foo");
            your_array_list.add("bar");*/
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                    MainActivity.this,
                    android.R.layout.simple_list_item_1,
                    pipelineview);

            lv.setAdapter(arrayAdapter);
        }
    });
}

A: You can't use the ArrayAdapter in this way.
Since you are declaring ArrayAdapter<String> arrayAdapter you can't use a constructor with
ArrayAdapter(MainActivity,int,ArrayList<PipelineGridViewClass>)

It is the reason of your issue:

Error:(103, 53) error: no suitable constructor found for ArrayAdapter(MainActivity,int,ArrayList)
  constructor ArrayAdapter.ArrayAdapter(Context,int,int,List) is not applicable

You can use somenthing like this:
 ArrayAdapter<PipelineGridViewClass> arrayAdapter = new ArrayAdapter<PipelineGridViewClass>(
                    MainActivity.this,
                    android.R.layout.simple_list_item_1,
                    pipelineview);

Pay attention to the doc:

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

It means that you have to override the toString() of your PipelineGridViewClass class.


text:
Q: selenium getXpathCount HI there
selenium.getXpathCount does not find element, any one hoas any idea ? Here is my code:
if (existArtist){
int result = selenium.getXpathCount("//*[@id='chugger-results']/div[1]/ul/li").intValue();
  if (result>0){

//DO THIS

A: Either you have a broken DOM (Do a W3C Validation and see if you have any unclosed tags) or your XPath is looking for an element that doesn't exist.
We would need to see the entire HTML of the page to be able to answer your question (more visibility of your test code would be useful too)


text:
Q: AC breaker switch that opens circuit when load is off Scenario: power outlet in the yard for electric vehicle, to avoid running an ugly extension from inside home and leaving an open window; I need to avoid that anyone just comes and uses my power though.
Enter the switch I'm looking for.
This would be the operational flow:

*

*Attach the charging cable of the vehicle to the outdoor outlet (no current will flow since the outlet is not powered - yet)

*get inside, arm said switch, current will start flowing as the vehicle begins charging, and the switch will stay on

*Either the vehicle stops charging, or I unplug it, or someone else does because they want to use my energy for free: the switch will detect no more current flowing through it, and will disarm, leaving the outdoor outlet inactive

I found two somewhat similar questions:
Need a switch/circuit breaker that stops power supply to equipment when power comes back after outage (not good for me, since it is intended to check for incoming power, not outgoing current flow)
I'm looking for a circuit breaker that interrupts the circuit when current drops to zero (not good, as it is for DC rather than AC)
Is there a name for this peculiar kind of switch, and/or is DIY easily accessible?

A: There are control panels for pool/submersible pumps with dry run protection (switch off when current is below a setup value). Maybe you find some one-phase starter that can fit your needs.

A: One can buy current switch modules, such as these (google "current switch"), basically a current transformer and electronics to operate a switch contact based on the measured current in one module.
A relay circuit can be designed that allows activating the relay using a momentary start button. A normally open contact from the current switch module placed in parallel with the start button would keep the relay enabled after the start button has been released, but when the monitorred current drops too low the contact opens and the relay turns off.
Current switch requirements:

*

*Self powered - These "steal" the energy required to operate themselves from the conductor being monitorred. Not requiring a power supply simplifies the circuit.

*Adjustable setpoint for the current level at which the contact enables, so you can tune for your load.

*Monitor side must be rated for AC mains and the current your load requires.

*Contact side must be rated for AC mains and the current the relay coil requires. Normally open contact that closes when the current is above the setpoint.

Relay requirements:

*

*DPST (or DPDT) with contacts rated for AC mains and the current your load requires.

*Coil that runs on AC mains.

simulate this circuit – Schematic created using CircuitLab

A: If a fixed power-on time is acceptable, then a lamp timer or bathroom heat lamp/fan timer can be wired in series with the outlet.  This would make power available for 4 hours (for example) no matter how dead the vehicle's batteries are.  Granted, someone could still come up and steal your power, but not for very long, and not at all after the timed period (like overnight).  If nothing else, this is a temporary solution until you get a sensing circuit built.

A: Install a security camera.   What you describe is definitely theft and is prosecutable.   The presence of a camera should be enough to dissuade folks anyhow.   This isn't like porch pirates who can come and go in a few seconds...someone using your juice would be vulnerable to detection for quite a long time.


text:
Q: array merging into multi dimensional array I need a way to merge
Array(
  [0] => Array
     (
      [event_id] => 1
      [time] => '21:00pm'
      [day] => 'Monday'
     )
  [1] => Array
    (
      [event_id] => 2
      [time] => '18:00pm'
      [day] => 'Monday'
     )
  [2] => Array
    (
      [event_id] => 3
      [time] => '21:00pm'
      [day] => 'Tuesday'
     )
 )

into:
Array (
  [0] => Array
      (
          [event_id] => Array
                (
                 [0] => 1
                 [1] => 2
                )
          [time] => Array
               (
                 [0] => '21:00pm'
                 [1] => '18:00pm'
                )
          [day] => 'Monday'
      )
   [1] => Array
     (
          [event_id] => 3
          [time] => '21:00pm'
          [day] => 'Tuesday'
     )
)

So the new array is grouped by the day key and if the values are different between the merged arrays then the merged value becomes an array.

A: I can't think of a built in function that will do this for you. I think you will have to loop through, group the events by day, then loop through the group and convert to the correct output format.
E.g.
This does not take into account the fact that the days may not always be in the same case, and also does not order the events by time, which may also be required.
function convert_event_array ($array) {

  // Declare the arrays we will use
  $temp = array(
    // Declare the day keys, so they appear in the right order in the output
    'Monday'=>array(),
    'Tuesday'=>array(),
    'Wednesday'=>array(),
    'Thursday'=>array(),
    'Friday'=>array(),
    'Saturday'=>array(),
    'Sunday'=>array()
  );
  $out = array();

  // Put events into temp array, grouped by day
  foreach ($array as $event) $temp[$event['day']][] = array('event_id'=>$event['event_id'],'time'=>$event['event_id']);

  // Convert grouped array to the correct format
  foreach ($temp as $day => $events) if (count($events)) {
    $index = count($out);
    foreach ($events as $event) {
      $out[$index]['event_id'][] = $event['event_id'];
      $out[$index]['time'][] = $event['time'];
    }
    $out[$index]['day'] = $day;
  }

  return $out;

}

print_r(convert_event_array($myInputArry));

A: This should work.
$output = getMergedArray($input); // $input is your sample array

function getMergedArray($input_array) {
  $output_array = array();
  foreach ($input_array as $key => $value) {
    $event_id = $value['event_id'];
    $time = $value['time'];
    $day = $value['day'];
    $day_id = getDay($output_array, $day);
    if (count($output_array) > 0 && $day_id >= 0) {
      if (!is_array($output_array[$day_id]['event_id'])) {
        $output_array[$day_id]['event_id'] = array($output_array[$day_id]['event_id']);
        $output_array[$day_id]['time'] = array($output_array[$day_id]['time']);
      }
      array_push($output_array[$day_id]['event_id'],$event_id);
      array_push($output_array[$day_id]['time'],$time);
    } else {
      $output_array[] = $value;
    }
  }
  return $output_array;
}

function getDay($output_array, $day) {
  if (count($output_array) > 0)
    foreach($output_array as $key => $value)
      if ($value['day'] == $day)
        return $key;

  return -1;
}

A: I 'd propose this method which is fully generic and extensible:
// YOUR INPUT GOES HERE
$input = (...);

// Stage 1: group elements of the initial array into sub-arrays based on their 'day' key
$groupLambda = function($aggr, $val) {
                   $aggr[$val['day']][] = $val; return $aggr;
               };
$grouped = array_reduce($input, $groupLambda, array());

// Stage 2: for each "same day" group, make an array of values for each property
//          instead of an array of items with scalar properties
$coalesceLambda = function($group) {
                      $mapLambda = function($aggr, $val) {
                          foreach($val as $k => $v) {
                              if($k == 'day') continue;
                              $aggr[$k][] = $v;
                          }
                          return $aggr;
                      };
                      return array_reduce($group, $mapLambda, array());
                  };
$coalesced = array_map($coalesceLambda, $grouped);

// Get the result
print_r($coalesced);

Advantages:

*

*There is only one magic value (the string "day"), which can be easily made into a variable and the whole thing factored out into a function (so you could reuse this function to perform the same transformation over any other property you might want to).

*Should be plenty fast due to using the built-in functions array_reduce and array_map instead of manually doing the same work in PHP.

Disadvantages:

*

*Requires PHP >= 5.3 due to the use of anonymous functions and the third parameter of array_reduce.

*Not very easy to understand (although code that does this kind of data massaging won't be too easy to visualize in any case).


text:
Q: How can i let C# search for a specific file in a specific map and use it as bitmap I have a form application and it's ready to be used but it only works on my PC because now the path is Dylan/desktop/... but I want it to work for everyone.
I now have:
background = new Bitmap(@"D:\Dylan\Desktop\project/background.jpg");

I want C# to search for the map project and then pick background.jpg and put it into the Bitmap background.
Here is more of the code:
    Bitmap background;
    background = new Bitmap("./background.jpg");

    this.Width = 1200;
    this.Height = 850;
    this.Text = "BoompjeOrders Bot Orderer";
    this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
    this.BackgroundImage = (Image)background;
    this.BackgroundImageLayout = ImageLayout.Stretch;

A: You should be using a relative path
When you publish your app as an .exe or other filetypes, the folder the .exe is in will be "." so, if you should just place the image you need in the same folder and in the code reference it as .\background.jpg or ..\foldermyappisin\background.jpg


text:
Q: PendingIntent Multiple Task Hello this is my first question :3 ,
So i have this code
Intent intent = new Intent(context, vidfolder.class);
 intent.putExtra("foo", fid);

 PendingIntent pIntent =
            PendingIntent.getActivity(
                    context,
                    0,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

     Notification n = new Notification.Builder(context)
            .setContentTitle( "(" + fid + ") "   + fidName )
            .setContentText("Your folder is ready")
            .setSmallIcon(R.drawable.ic_launcher)
    .setVibrate(new long[] {0, 1000, 200,1000 })
    .setDefaults( Notification.DEFAULT_SOUND |
    Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS )

            .setContentIntent(pIntent).setAutoCancel(true)
            .setPriority(Notification.PRIORITY_MAX)
            .setStyle(new
   Notification.BigTextStyle().bigText(longText))
            .build();
         NotificationManager notificationManager =
     (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
     int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
final int random = new Random().nextInt(999) + 26;
int m2 = m * random;
    notificationManager.notify(m2, n);

it's will generate multiple notifications let say
Folder 1 is reaady
Folder 2 is ready
and in my vidfolder i am retreiving the data with this code
   Intent intent = getIntent();
   String sharedText = intent.getStringExtra("foo");

my problem is when 2 folders are ready i get 2 notifications but they both have the same Extra ( the one of the last notification ) ,
How can i make multiple pending intents :/
Also i tried to change FLAG_UPDATE_CURRENT to 0 , after i do this the second notification don't work :/

A: oh i changed my code to
          int m3 = (int) ((new Date().getTime() / 1000L) %
  Integer.MAX_VALUE);
final int random3 = new Random().nextInt(999) + 26;
int m4 = m3 * random3;

        Intent intent = new Intent(context, vidfolder.class);
   intent.putExtra("foo", fid);

      PendingIntent pIntent =
            PendingIntent.getActivity(
                    context,
                    m4,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

it's working now :)


text:
Q: Next.js does not delete dynamic page deleted in CMS I am using next.js 10 and have a [slug] page which creates dynamic pages from Contentful CMS.
I am changing the slug inside CMS and run next dev the old slug correctly returns 404 and the new slug works.
However when I build and run next start the old slug still returns a cached page, the new slug works properly.
I am returning revalidate 10 and have assumed the page should refresh after 10sec
export const getStaticProps: GetStaticProps<SlugRoutePageProps> = async ({
  params,
}) => {
  ....
  ....
  const pageData = await getPageData(params.slug)
  if (pageData.total === 0) return { notFound: true }

  return {
    props: {
      pageType: "DynamicPage",
      pageProps: {
        pageData,
      },
      revalidate: 10,
    },
  }
}

in getStaticPaths I have fallback: "blocking", also tried fallback: true with no difference.
Edit:
getPageData is a basic call to the contentful api - no caching
   const getPageData = async (
      slug: string,
    ): Promise<FetchPagesResult> => {
      const client = createContentfulClient()
      return client.getEntries<Page>({
        content_type: "page",
        "fields.slug": slug,
        include: 5,
        order: "-sys.updatedAt",
        limit: 1,
      })
    }


text:
Q: Simple HTML standards question, DOCTYPE messes the CSS a very basic question:
When I include the DOCTYPE at the beginning of  my .html document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

It messes only a small part styling of the page.
Here you can see a live example:
Without DOCTYPE (Right)   -    With DOCTYPE (Wrong)
I think I kind of "know the answer", (besides that the HTML and CSS seems to be written by a smart chimp), the problem seems to be that some of the elements of the CSS I'm using are not part of the standards of the DOCTYPE I'm using and because of this, some parts are not loaded (in plain English).
That's just me guessing but if this is the case, I would like to know which elements am I using that I should´t and (if specific enough) a "general guide" as to how should they be used.
Thanks in advance!

A: Try adding px after the 700 in your body style (and everywhere you specify a width in css)
The reason for this is that adding a doctype puts the browser into standards mode (a good thing). You should run your css through a validator to catch errors you get in standards mode.

Sorry! We found the following errors (5)
line # Error
2     body    Value Error : width only 0
  can be a length. You must put a unit
  after your number : 700 700
18    p.titulo    Property text-shadow
  doesn't exist in CSS level 2.1 but
  exists in : 2px 2px 2px #aaa 2px 2px
  2px #aaa
140   #rect   Value Error : width only 0
  can be a length. You must put a unit
  after your number : 235 235
151   #form   Value Error : width only 0
  can be a length. You must put a unit
  after your number : 235 235
174   #navcontainer ul    Value Error :
  margin only 0 can be a length. You
  must put a unit after your number : 5
  5

A: The only thing a browser uses the DOCTYPE declaration for is to switch between "Standards Mode" and "Quirks Mode" (and sometimes "Almost Standards Mode"). What it affects is slightly different across browsers.
The main difference (and the biggest one) is that in IE6 it switches between IE's old proprietary CSS Box Model and the "standard" W3C box model which affects how widths and heights are calculated.
http://en.wikipedia.org/wiki/Quirks_mode
http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
Unless you know what you're doing you are much better off choosing a DOCTYPE that puts you in Standards Mode

A: The CSS for your page is perfectly fine, in the sense that they are valid and correct. Remember that Quirk mode, which is the mode that browsers go into when there's no/invalid doctype is IE5.5 mode, what you were really doing before this was to compensate for the semi-broken box model introduced by IE5.5.
Having said that, you might want to clean up your HTML first before moving on to the CSS. The <b> tag is officially deprecated are not recommended because they are presentational elements, so you should wrap a span around that bit of the title, and giving it a font-weight: bold instead.
You should also be using labels for your forms. You can then group the label - input pairs together using a list.
Finally, as for the title, you can simply remove all the relative positioning, and use text-align: center, or, if you need the text to be centered but right aligned, a fixed width and margin: 0 auto. Do the same for your main content, and throw away all of the relative positioning and negative margin used to center your content.

A: Note that the doctype you're using lands you in "limited quirks mode"/"almost standards mode". The right one would be
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

if you insist on XHTML (you shouldn't), or
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

if you insist on an obsolete version (you shouldn't), or
<!DOCTYPE html>

if all you need from a doctype is standards mode (it is).


text:
Q: How to represent a math expression in spark SQL DSL While I much prefer using straight SQL instead of the DSL there is a case where the latter is required: when we want to perform a custom aggregation on the rows of a grouping.
What I am uncertain about is how to then transform this straightforward computation to the DSL:
 100.0 * (count(*)-sum(dep_delayed))/count(*)

What is the equivalent in the DSL ?  Is it necessary to create a UDF (/ AggUDF) and if so how would that be done?

A: I ran across the answer today: use
 expr("some sql clause")

So the code can be implemented as
.agg(expr("100.0 * (count(*)-sum(dep_delayed))/count(*)"))


text:
Q: Magento - get categories and subcategories in a collection I have the following category structure in my magento store
- root
    - category 0 (ID 26)
        - category 1 (main)
            - category A (sub)
            - category V (sub)
        - category 2 (main)
            - category G (sub)
            - category J (sub)
            - category E (sub)
        - category 3 (main)
            - category L (sub)

and so on...
On a page i want to be able to output the following:
1. get each (main) category and its name and url
    2. get the first (sub) category in (main) and its icon (custom attribute)

So it would output this for each:

 main-cat-name

Giving something like:
<category 1 link><category A icon img></link>
<category 1 link><category 1 name>

<category 2 link><category G icon img>
<category 2 link><category 2 link>

<category 3 link><category L icon img>
<category 3 link><category 3 link>

What is the best way of doing so? So far I have:
<?php
$_id = 26 // category 0
$_main_categories = Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('parent_id', array('eq'=>$_id))
->addAttributeToFilter('is_active', 1)
->addAttributeToSelect(array('id','name','url'))

foreach($_main_categories as $_main_cat)
{
    // load full main category
    $_category = Mage::getModel('catalog/category')->load($_main_cat->getId());
    // get sub category's children
    $_main_cat_subs = $_category->getChildrenCategories();

    // loop through sub catagories, get icon in first and break
    foreach($_main_cat_subs as $_sub_cat)
    {
        // load full sub category
        $_sub = Mage::getModel('catalog/category')->load($_sub_cat->getId());
        $i++;
            $_icon = $_sub_cat->getIcon();
        }
        if( $i >= 1 ){
            break; // as i only want the first one
        }
    }

    // output
    ?>
    <a href="<?php echo $_main_cat->getUrl() ?>">
        <img src="<?php echo $_icon ?>">

    <a href="<?php echo $_main_cat->getUrl() ?>">
        <?php echo $_main_cat->getName() ?>

<?php
}
?>

This works but seems very bad practice to load the full category models in a foreach loop twice and when the site grows could take a long time.
What is the best way of doing the above performance wise?

A: What you could optimize is this:
$_category = Mage::getModel('catalog/category')->load($_main_cat->getId());

Here you are loading the category (again) from the database. Though you already loaded a collection, you should put all the categories you need in that collection with the right attributes.
Then instead of the code above, use this handful collection function to get the category entity:
$_category = $_main_categories->getItemById($_main_cat->getId());
//...
$_sub = $_main_categories->getItemById($_sub_cat->getId());

You should see a clear improvement in the performance, especially if you have a lot of categories.


text:
Q: Contracts With Multiple Arguments I started coding with contracts in c#. I want to express the following property in c#
ISet<Tuple<A,B>> set;
Contract.Requires(!Contract.Exists(set, (e1,e2) => (((e1 != null) && (e2 != null)) &&    (e1.Item1 == e2.Item1) && (e1.Item2 != e2.Item2))));

i.e. if the first elements of two tuples are the same the second one should be the same aswell.
The problem here is that (e1,e2) => ...  is not a valid expression because of the two arguments. Does anybody now how to express this contract with the both e1 and e2? Or how to rewrite it?

A: Thanks for the clarification with the template. What I wanted to say was the following:
\forall s,t in ISet< Tuple< A,B>>: (s.a==t.a) -> (s.b==t.b)
I guess it was somehow unclear. I finally solved it the following way (previously not knowing that it is possible to nest Contract.Exist and Contract.ForAll and after some logic reformulating)
ISet<Tuple<A,B> set;
Contract.Invariant(Contract.ForAll(set, s => s != null && Contract.ForAll(set, t => t != null && ((s.Item1 != t.Item1)||(s.Item2 == t.Item2)))));

A: Template argument of Contract.Exist() is collection element so in your case Tuple<A, B>. You can't disjoint them (A and B from Tuple<A, B> because for ISet<T> template T is Tuple<A, B>).
Rewrite it as (if I did understand you require tuple's elements aren't equal and they're not null, in case just change it):
Contract.Requires(!Contract.Exists(set,
    x => x.Item1 == null || x.Item2 == null || x.Item1 == x.Item2));


text:
Q: acessar valor de field dentro do django template É possível acessar os valores dentro de uma variável no django templates?
Por exemplo, tenho esse model:
 class Avaliacao(models.Model):
 post = models.TextField()
 data_inclusao = models.DataField()

no campo post é gravado dados uma dict, dessa forma:
 {'joao': ['gostei', 8], 'carla': ['nao gostei', 1] }

Digamos que no meu template/html, eu queira popular uma tabela, como que eu conseguiria acessar as chaves e os valores dessa string ?
Imaginem que os dados foram renderizados para a variável dados:
{% for avaliacao in dados %}
 {{ avaliacao.post }}
{% endfor %}

A saída esperar seria:

Nome
Avaliacao:
Nota:

JOAO
GOSTEI
8

CARLA
NAO GOSTEI
1

A: Como o tipo de dados é um dictionary, podes aceder assim:
{% for key, values in dados.items %}
    {{ key }}
    {% for item in values %}
        {{ item }}
    {% endfor %}
{% endfor %}

NOTA: No primeiro for, irás aceder ao valor da key do teu dict, como é um dict tens key/value, no value como tens um array, precisas de outro for para percorrer todos os valores deste.

A: Consegui resolver criando uma função no model que retorna os dados em formato Json, dessa forma consigo chamar a função o no template e navegar da dict.
MODEL
class Avaliacao(models.Model):
post = models.TextField()
data_inclusao = models.DataField()

FUNÇÃO NO MODEL
@property
def post_dict(self):
    try:
        return json.loads(self. post)
    except ValueError:
        return {}

VIEW
 queryset = Avaliacao.objects.all()
{'dados': queryset}

TEMPLATE
{% for avaliacao in dados.post_dict.items %}
 {{ avaliacao.0 }}
 {{ avaliacao.1 }}
{% endfor %}


text:
Q: How to change Caption of an event in TcxScheduler? How to change Caption of an event in TcxScheduler? I have tried the following code:
cxScheduler.SelectedEvents[i].Caption := 'X';
cxScheduler.Invalidate;

But Caption is obsolete until current event will be changed.
Also if you try to edit Caption by inplace editor and then cancel edit mode you'll see an obsolete value again.
The correct caption should be on the screen and on the related DataSet to save data.
Thanks a lot for the help!
P.S. Related DevExpress issue link: DevExpress Support Center

A: DevExpress team solution:
This behavior is caused by the fact that you changed the caption of the control event, but not the TcxSchedulerEvent item itself. I suggest you use the following code, instead:
if cxScheduler.SelectedEventCount > 0 then
    cxScheduler.SelectedEvents[0].Source.Caption := 'X';

A: Try to use OnCustomDrawEvent, like:
procedure TForm1.cxScheduler1CustomDrawEvent(Sender: TObject;
  ACanvas: TcxCanvas; AViewInfo: TcxSchedulerEventCellViewInfo;
  var ADone: Boolean);
begin
   AViewInfo.EventViewData.Caption := 'New Caption';
end;

And please - DevExpress has the one of the best support center I've ever seen - be advice to use it next time.


text:
Q: Parsing error in react with style-components I'm creating a light/dark mode switch in React with this tutorial - Tutorial Link
After adding GlobalStyles from styled-components even that I was doing all according to tutorial I receive this error:
./src/Components/Global.js
  Line 13:40:  Parsing error: Unterminated template

  11 |     align-items: center;
  12 |     background: ${({ theme }) => theme.body};
> 13 |     color: ${({ theme }) => theme.text};
     |                                        ^
  14 |     display: flex;
  15 |     flex-direction: column;
  16 |     justify-content: center;

Here is code from Global.js
import { createGlobalStyle } from 'styled-components';

export const GlobalStyles = createGlobalStyle`
  *,
  *::after,
  *::before {
    box-sizing: border-box;
  }

  body {
    align-items: center;
    background: ${({ theme }) => theme.body};
    color: ${({ theme }) => theme.text};
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100vh;
    margin: 0;
    padding: 0;
    font-family: BlinkMacSystemFont, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    transition: all 0.25s linear;
  }

And here is my App.js
import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { GlobalStyles } from './Components/Global';
import { ThemeProvider} from 'styled-components';
import { lightTheme, darkTheme} from './Components/Theme'

function App() {
  return (
    <ThemeProvider theme={lightTheme}>
    <>
      <GlobalStyles />
      <button>Toggle theme</button>

It's a light theme!

    </>
  </ThemeProvider>
  );
}

export default App;

Question: How I can fix that error and did I miss something in syntax which leads to this error?


text:
Q: Turning an array of objects, into a single object with the same value for all keys? I am working on a list of optional checkbox elements and want to have a checkAll function. With this function I am passing the rowsArray as the argument and want to turn it from an array of objects to one single object, with all the options in there with their ids as the key and their value as true.
So from this
rowsArray →
[{name: '0years', id: '0 TO 1'}, {name: '1years', id: '1 TO 2'}{name: '2years', id: '2 TO 3'}, ~~~~~] (there are 17 objects inside)
to this
return{ '-1 TO 0': true, '0 TO 1': true,'1 TO 2': true }
I don't need the name value anymore and want to give it a new value of true, but am not sure how to add that.
So far I have this, but I am not sure where to go from here:
function convertRowsToObject(rowsArray) {
        // rowsArray [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}]
        // return an object that looks like
        // { '-1 TO 0': true, '1 TO 2': true }
       let allTrue = Object.assign({}, ...rowsArray)
        console.log(`rowsArray → `, rowsArray)
        return {}
      }

This unfortunately only gives me back the final object of the array 17 times...
allTrue →  {name: '100+ years', id: "100 TO 150"}
Should I be using reduce here? Removing the name and replacing it with a single value of 'true' is stumping me.
Any ideas on how to progress with this?
Cheers!

A: You could use Array.prototype.reduce() like this:

const rowsArray = [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}];

function convertRowsToObject(rowsArray) {
  // rowsArray [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}]
  // return an object that looks like
  // { '-1 TO 0': true, '1 TO 2': true }
  return rowsArray.reduce((acc, { id }) => ({ ...acc, [id]: true }), {});
}

const result = convertRowsToObject(rowsArray);

console.log(result);

Not sure why you need this though, because the true value doesn't provide any information, a simple array may be enough:

const rowsArray = [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}];

function convertRowsToObject(rowsArray) {
  return rowsArray.map(({ id }) => id);
}

const result = convertRowsToObject(rowsArray);

console.log(result);


text:
Q: MySQL Config File for Large System We are running MySQL on a Windows 2003 Server Enterpise Edition box.  MySQL is about the only program running on the box.  We have approx. 8 slaves replicated to it, but my understanding is that having multiple slaves connecting to the same master does not significantly slow down performance, if at all.  The master server has 16G RAM, 10 Terabyte drives in RAID 10, and four dual-core processors.  From what I have seen from other sites, we have a really robust machine as our master db server.  We just upgraded from a machine with only 4G RAM, but with similar hard drives, RAID, etc.  It also ran Apache on it, so it was our db server and our application server.  It was getting a little slow, so we split the db server onto this new machine and kept the application server on the first machine.  We also distributed the application load amongst a few of our other slave servers, which also run the application.  The problem is the new db server has mysqld.exe consuming 95-100% of CPU almost all the time and is really causing the app to run slowly.  I know we have several queries and table structures that could be better optimized, but since they worked okay on the older, smaller server, I assume that our my.ini (MySQL config) file is not properly configured.  Most of what I see on the net is for setting config files on small machines, so can anyone help me get the my.ini file correct for a large dedicated machine like ours?  I just don't see how mysqld could get so bogged down!
FYI: We have about 100 queries per second.  We only use MyISAM tables, so skip-innodb is set in the ini file.  And yes, I know it is reading the ini file correctly because I can change some settings (like the server-id and it will kill the server at startup).
Here is the my.ini file:
#MySQL Server Instance Configuration File
# ----------------------------------------------------------------------
# Generated by the MySQL Server Instance Configuration Wizard
#
#
# Installation Instructions
# ----------------------------------------------------------------------
#
# On Linux you can copy this file to /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options
# (@localstatedir@ for this installation) or to
# ~/.my.cnf to set user-specific options.
#
# On Windows you should keep this file in the installation directory
# of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To
# make sure the server reads the config file use the startup option
# "--defaults-file".
#
# To run run the server from the command line, execute this in a
# command line shell, e.g.
# mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini"
#
# To install the server as a Windows service manually, execute this in a
# command line shell, e.g.
# mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL Server     X.Y\my.ini"
#
# And then execute this in a command line shell to start the server, e.g.
# net start MySQLXY
#
#
# Guildlines for editing this file
# ----------------------------------------------------------------------
#
# In this file, you can use all long options that the program supports.
# If you want to know the options a program supports, start the program
# with the "--help" option.
#
# More detailed information about the individual options can also be
# found in the manual.
#
#
# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]

port=3306

[mysql]

default-character-set=latin1

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]

# The TCP/IP Port the MySQL Server will listen on
port=3306

#Path to installation directory. All paths are usually resolved relative to this.
basedir="D:/MySQL/"

#Path to the database root
datadir="D:/MySQL/data"

# The default character set that will be used when a new schema or table is
# created and no character set is defined
default-character-set=latin1

# The default storage engine that will be used when create new tables when
default-storage-engine=MYISAM

# Set the SQL mode to strict
#sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
# we changed this because there are a couple of queries that can get blocked otherwise
sql-mode=""

#performance configs
skip-locking
max_allowed_packet = 1M
table_open_cache = 512

# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
max_connections=1510

# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size=168M

# The number of open tables for all threads. Increasing this value
# increases the number of file descriptors that mysqld requires.
# Therefore you have to make sure to set the amount of open files
# allowed to at least 4096 in the variable "open-files-limit" in
# section [mysqld_safe]
table_cache=3020

# Maximum size for internal (in-memory) temporary tables. If a table
# grows larger than this value, it is automatically converted to disk
# based table This limitation is for a single table. There can be many
# of them.
tmp_table_size=30M

# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't
# more than thread_cache_size threads from before.  This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn't give a notable performance
# improvement if you have a good thread implementation.)
thread_cache_size=64

#*** MyISAM Specific options

# The maximum size of the temporary file MySQL is allowed to use while
# recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.
# If the file-size would be bigger than this, the index will be created
# through the key cache (which is slower).
myisam_max_sort_file_size=100G

# If the temporary file used for fast index creation would be bigger
# than using the key cache by the amount specified here, then prefer the
# key cache method.  This is mainly used to force long character keys in
# large tables to use the slower key cache method to create the index.
myisam_sort_buffer_size=64M

# Size of the Key Buffer, used to cache index blocks for MyISAM tables.
# Do not set it larger than 30% of your available memory, as some memory
# is also required by the OS to cache rows. Even if you're not using
# MyISAM tables, you should still set it to 8-64M as it will also be
# used for internal temporary disk tables.
key_buffer_size=3072M

# Size of the buffer used for doing full table scans of MyISAM tables.
# Allocated per thread, if a full scan is needed.
read_buffer_size=2M
read_rnd_buffer_size=8M

# This buffer is allocated when MySQL needs to rebuild the index in
# REPAIR, OPTIMZE, ALTER table statements as well as in LOAD DATA INFILE
# into an empty table. It is allocated per thread so be careful with
# large settings.
sort_buffer_size=2M

#*** INNODB Specific options ***
innodb_data_home_dir="D:/MySQL InnoDB Datafiles/"

# Use this option if you have a MySQL server with InnoDB support enabled
# but you do not plan to use it. This will save memory and disk space
# and speed up some things.
skip-innodb

# Additional memory pool that is used by InnoDB to store metadata
# information.  If InnoDB requires more memory for this purpose it will
# start to allocate it from the OS.  As this is fast enough on most
# recent operating systems, you normally do not need to change this
# value. SHOW INNODB STATUS will display the current amount used.
innodb_additional_mem_pool_size=11M

# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.
innodb_flush_log_at_trx_commit=1

# The size of the buffer InnoDB uses for buffering log data. As soon as
# it is full, InnoDB will have to flush it to disk. As it is flushed
# once per second anyway, it does not make sense to have it very large
# (even with long transactions).
innodb_log_buffer_size=6M

# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system.  Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not
# set it too high.
innodb_buffer_pool_size=500M

# Size of each log file in a log group. You should set the combined size
# of log files to about 25%-100% of your buffer pool size to avoid
# unneeded buffer pool flush activity on log file overwrite. However,
# note that a larger logfile size will increase the time needed for the
# recovery process.
innodb_log_file_size=100M

# Number of threads allowed inside the InnoDB kernel. The optimal value
# depends highly on the application, hardware as well as the OS
# scheduler properties. A too high value may lead to thread thrashing.
innodb_thread_concurrency=10

#replication settings (this is the master)
log-bin=log
server-id = 1

Thanks for all the help.  It is greatly appreciated.

A: I got some good responses over at ServerFault. Turns out the main problem is with disk I/O on the new server.  The I/O is significantly less than the old 32-bit machine, so I am tracking that down now.  Thanks.