Q: Count The Number of Duplicate Values during the preceding timeperiod I am looking to count how many duplicate values there are in a previous time period (24 hours to make it simple).
For example in this data set

I am looking to come up with values such as this

Here is some how to create the below dataframe
data = [("5812", "2020-12-27T17:28:32.000+0000"),("5812", "2020-12-25T17:35:32.000+0000"), ("5812", "2020-12-25T13:04:05.000+0000"), ("7999", "2020-12-25T09:23:01.000+0000"),("5999","2020-12-25T07:29:52.000+0000"), ("5814", "2020-12-25T12:23:05.000+0000"),  ("5814", "2020-12-25T11:52:57.000+0000"), ("5814", "2020-12-24T11:00:57.000+0000") ,("5999", "2020-12-24T07:29:52.000+0000")]
df = spark.createDataFrame(data).toDF(*columns)

I have been using windowed functions to get things such as distinct counts, sums etc, but I can't quite figure out how to get a count of duplicate values over the same time period.

A: Let's try this step by step

*

*Cast column timestamp to TimestampType format.

*Create a column  of collect_list of mcc (say mcc_list) in the last 24 hours using window with range between interval 24 hours and current row frame.

*Create a column of set/unique collection of mc_list (say mcc_set) using array_distinct function. This column could also be created using collect_set over the same window in step 2.

*For each value of mcc_set, get its count in the mcc_list. Duplicated mcc value will have a count of > 1 so we can filter it. After that, the array will only contain the duplicated mcc, use size to count how many mcc are duplicated in the last 24 hours.

These steps put into a code could be like this
import pyspark.sql.functions as F
from pyspark.sql.types import *

df = (df
      .withColumn('ts', F.col('timestamp').cast(TimestampType()))
      .withColumn('mcc_list', F.expr("collect_list(mcc) over (order by ts range between interval 24 hours preceding and current row)"))
      .withColumn('mcc_set', F.array_distinct('mcc_list'))
      .withColumn('dups', F.expr("size(filter(transform(mcc_set, a -> size(filter(mcc_list, b -> b = a))), c -> c > 1))"))
    #   .drop(*['ts', 'mcc_list', 'mcc_set']))
)
df.show(truncate=False)

# +----+----------------------------+-------------------+------------------------------------+------------------------+----+
# |mcc |timestamp                   |ts                 |mcc_list                            |mcc_set                 |dups|
# +----+----------------------------+-------------------+------------------------------------+------------------------+----+
# |5812|2020-12-27T17:28:32.000+0000|2020-12-27 17:28:32|[5812]                              |[5812]                  |0   |
# |5812|2020-12-25T17:35:32.000+0000|2020-12-25 17:35:32|[5999, 7999, 5814, 5814, 5812, 5812]|[5999, 7999, 5814, 5812]|2   |
# |5812|2020-12-25T13:04:05.000+0000|2020-12-25 13:04:05|[5999, 7999, 5814, 5814, 5812]      |[5999, 7999, 5814, 5812]|1   |
# |5814|2020-12-25T12:23:05.000+0000|2020-12-25 12:23:05|[5999, 7999, 5814, 5814]            |[5999, 7999, 5814]      |1   |
# |5814|2020-12-25T11:52:57.000+0000|2020-12-25 11:52:57|[5999, 7999, 5814]                  |[5999, 7999, 5814]      |0   |
# |7999|2020-12-25T09:23:01.000+0000|2020-12-25 09:23:01|[5814, 5999, 7999]                  |[5814, 5999, 7999]      |0   |
# |5999|2020-12-25T07:29:52.000+0000|2020-12-25 07:29:52|[5999, 5814, 5999]                  |[5999, 5814]            |1   |
# |5814|2020-12-24T11:00:57.000+0000|2020-12-24 11:00:57|[5999, 5814]                        |[5999, 5814]            |0   |
# |5999|2020-12-24T07:29:52.000+0000|2020-12-24 07:29:52|[5999]                              |[5999]                  |0   |
# +----+----------------------------+-------------------+------------------------------------+------------------------+----+

You can drop unwanted columns afterwards.


Q: Formatting off in Safari vs Chrome I am using this template to build this website.
In chrome and edge, the services tiles look right:

In safari, the rows are messed up:

I am not a pro at this stuff ... I am just a freelancer trying to do everything ... and poked around and cannot spot the source of this problem.  The index.html and style.css code is pasted below.
[index.html header]
    <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Velodu - Market Research & Consulting</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="https://fonts.googleapis.com/css?family=Raleway:100,200,300,400,500,600,700,800,900" rel="stylesheet">

    <link rel="shortcut icon" href="img/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="css/magnific-popup.css" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <link rel="stylesheet" type="text/css" href="css/skins/purple.css" />

    <link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/settings.css" />
    <link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/layers.css" />
    <link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/navigation.css" />

["Services" code in index.html]

About Us

Who We Are

Business keeps moving faster, so nobody has time for slow agencies who add complexity.

We deliver high-quality, high-velocity market research and consulting services because we are great at identifying and removing bottlenecks, especially when the bottleneck is us.

                        Our Services

                            Founder's LinkedIn Profile

Why Choose Us

Diverse experience across tech, CPG, retail, etc.

Deep knowledge of research methodologies

Strategic business lens

Leverage the latest tools and tech

Our Services

What We Do

Quantitative Research

Of course we do surveys.  Concept tests, attitude and usage studies, pricing studies, brand tracking ... the list is long.  We do them better because of our advanced programming, and dashboarding skills that complement our deep methodological knowledge.

Qualitative Research

We're experts at setting up and conducting interviews, ethnographical research, and focus groups.  At the end, you'll get concise insights that tell a strategic story, rather than a text-heavy mess that you have to decipher yourself.

Secondary Research

The best data is data that already exists.  Let us help you find information that is already out there, and compile it in a story that inspires action.

Innovation

Achieve breakthrough results by defining your problem, vision, hypotheses, experiments, etc. in addition to developing new concepts.  We help you add structure to the innovation process so it is more efficient and fruitful.

Facilitation

Running a good meeting or workshop requires preparation and reflection time, which you may not have to devote.  Let us help you with your next brainstorming, team-building, or alignment-gathering session.

Other

Have another need?  Surprise us with a new request.

["Services" code in style.css]
/* Services
---------------------------------------- */

.services {
    background-color: #efefef;
}
.services .services-box {
    margin: 25px 0;
}
.services .services-box:before {
    content: "";
    display: table;
}
.services .services-box:after {
    content: "";
    display: table;
    clear: both;
}
.services .services-box-item {
    position: relative;
    color: #717c8e;
    text-decoration: none;
    -webkit-perspective: 750px;
    -ms-perspective: 750px;
    -o-perspective: 750px;
    perspective: 750px;
    margin: 15px 0;
    float: left;
}
.services .services-box-item:hover,
.services .services-box-item:focus,
.services .services-box-item.hover {
    text-decoration: none;
}
.services .services-box-item:hover> .services-box-item-cover,
.services .services-box-item:focus> .services-box-item-cover,
.services .services-box-item.hover> .services-box-item-cover {
    -webkit-transform: rotateY(180deg);
    transform: rotateY(180deg);
}
.services .services-box-item:hover> .services-box-item-content,
.services .services-box-item:focus> .services-box-item-content,
.services .services-box-item.hover> .services-box-item-content {
    -webkit-transform: rotateY(360deg);
    transform: rotateY(360deg);
}
.services .services-box-item-cover,
.services .services-box-item-content {
    position: relative;
    border-radius: 3px;
    background: #fff;
    -webkit-transition: -webkit-transform 0.3s;
    transition: -webkit-transform 0.3s;
    transition: transform 0.3s;
    transition: transform 0.3s, -webkit-transform 0.3s;
    -webkit-transform: rotateY(0deg);
    transform: rotateY(0deg);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
}
.services .services-box-item-cover {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: 0px 15px;
    box-shadow: 0px 0px 3px 1px #ddd;
    border-radius: 7px;
}
.services .services-box-item-cover:before,
.services .services-box-item-cover:after {
    position: absolute;
    top: 50%;
    left: 50%;
}
.services .services-box-item-cover:before {
    margin: -40px 0px 0px -20px;
    font-size: 40px;
}
.services .services-box-item-cover:after {
    content: attr(data-headline);
    font-family: "Raleway";
    left: 0;
    width: 100%;
    margin: 20px 0 0;
    font-size: 18px;
    text-align: center;
    font-weight: 500;
}
.services .services-box-item-content {
    overflow: hidden;
    margin: -16px -6px;
    padding: 30px 40px;
    font-size: 14px;
    -webkit-transform: rotateY(180deg);
    transform: rotateY(180deg);
    border-radius: 7px;
}
.services .services-box-item-content:before {
    position: absolute;
    top: 0;
    right: 0;
    margin: -60px;
    font-size: 228px;
    opacity: 0.2;
}
.services .services-box-item-content h2 {
    position: relative;
    margin: 8px 0;
    font-size: 16px;
    font-weight: 500;
    text-transform: Capitalize;
}
.services .services-box-item-content p {
    line-height: 23px;
    position: relative;
    margin: 12px 0;
    font-size: 13px;
}
.services[data-icon]:before,
.services[class^="icon-"]:before,
.services[class*=" icon-"]:before {
    -webkit-font-smoothing: antialiased;
    font-smoothing: antialiased;
    text-rendering: geometricPrecision;
    text-indent: 0;
    display: inline-block;
    position: relative;
}
.services[data-icon]:before {
    content: attr(data-icon);
}
.services[data-icon].after:before {
    content: none;
}
.services[data-icon].after:after {
    content: attr(data-icon);
    -webkit-font-smoothing: antialiased;
    font-smoothing: antialiased;
    text-rendering: geometricPrecision;
    text-indent: 0;
    display: inline-block;
    position: relative;
    margin-left: 4px;
}

Any ideas/help is appreciated!

A: I was able to figure it out with more googling.
This great article.
I replaced this in style.css:
.services .services-box:before {
    content: "";
    display: table;
}
.services .services-box:after {
    content: "";
    display: table;
    clear: both;
}

With this:
.services .services-box:before {
    content: "";
    display: table;
    table-layout: fixed;
    max-width: none;
    width: auto;
    min-width: 100%;
}
.services .services-box:after {
    content: "";
    display: table;
    clear: both;
    table-layout: fixed;
    max-width: none;
    width: auto;
    min-width: 100%;
}

And problem solved.


Q: How to do a Second Commit in Github Can anybody explain how can use github to store my project. I have created an account,created a repository, uploaded my files to it all these are done mechanically by following their help.  But i dont know what to do next. How can i do a second commit.
and what is mean by branch please explain it as to a beginner i am not understanding their help too.

A: As noted in the comments, the Git Community Book is a great resource for learning all about git, from basic usage right up to really advanced stuff.
If for some reason that's not to your liking, then this question links to a large number of reference guides for using git. You may want to look at the "beginner's references" section. Also some answers to that question point to GUI tools for Git that you may find useful.
The basic commands you're going to need to learn to use git effectively include add, status, diff, commit, pull, push, checkout, merge, and branch. You can get basic help for each command by using git help followed by the command you need help for (e.g. git help add).


Q: Android Circle Shape in 16 to 23 Android Version I want to make a circle that is perfect in all Android versions.
I tried to create a drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
...color..stroke...
</shape>

And in my layout, I created a TextView like:
<TextView
    android:background="@drawable/shape_circle"
    android:layout_width="64dp"
    android:layout_height="64dp"
/>

The problem is that is some devices shows a circle view, and some others shows a oval view.

*

*Moto G2 - 5.0.2 = Circle

*Samsung S2 - API 16 = Oval

*Samsung S3 - API 18 = Circle

*Samsung S3 - API 16 = Oval

*Nexus 5 - API 22 = Circle

EDIT:
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="8dp"
    >

    <TextView
        android:id="@+id/text_table_empty"
        android:text="14"
        android:gravity="center"
        android:textColor="@color/medium_gray"
        android:textSize="18sp"
        android:background="@drawable/shape_table"
        android:layout_width="64dp"
        android:layout_height="64dp"
        />

    <TextView
        android:id="@+id/text_table_used"
        android:text="14"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:background="@drawable/shape_table_used"
        android:layout_width="64dp"
        android:layout_height="64dp"
        />

    <TextView
        android:layout_marginTop="2dp"
        android:layout_marginRight="2dp"
        android:textSize="12sp"
        android:textColor="@color/white"
        android:id="@+id/text_table_num_orders"
        android:layout_alignRight="@+id/text_table_used"
        android:layout_alignTop="@+id/text_table_used"
        android:gravity="center"
        android:background="@color/light_green"
        android:text="1"
        android:layout_width="20dp"
        android:layout_height="20dp"/>

</RelativeLayout>

drawable shape_table:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="@color/light_gray"/>
    <stroke android:width="1dp"
            android:color="@color/medium_gray"
        />
    <size
        android:width="64dp"
        android:height="64dp"/>
</shape>

OBS: The drawable shape_table_used is the same as shape_table, without stroke and other color.

A: please use this
 you can also remove the size tag but in this case your view hight and width must be  equal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <stroke
        android:width="1dp"
        android:color="#E0D8D0" />

    <size
        android:width="80dp"
        android:height="80dp"/>
</shape>

A: Actually you almost get it right. A circle is an oval with with same width and height so you can just set the width and height inside the shape and you will get circle in every device
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/white"/>

    <size
        android:width="100dp"
        android:height="100dp"/>
</shape>

A: if You want a  circle You use this but your View hight and width must be equal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <gradient
        android:angle="270"
        android:endColor="#80FF00FF"
        android:startColor="#FFFF0000" />

</shape>

and You also use this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <gradient
        android:angle="270"
        android:endColor="#80FF00FF"
        android:startColor="#FFFF0000" />
    <size
        android:width="80dp"
        android:height="80dp"/>
</shape>


Q: Javascript array of hrefs I am trying to create an array with different hrefs to then attach to 5 separate elements.
This is my code:
var link = new Array('link1', 'link2', 'link3', 'link4', 'link5');

                    $(document.createElement("li"))
                    .attr('class',options.numericId + (i+1))
                    .html(''+ '')
                    .appendTo($("."+ options.numericId))

As you can see I am trying to append these items from the array to the end of my page so each link will take the user to a different section of the page. But i have not been able to do this. Is there a way to to create elements with different links?
I am new to javascript so I am sorry if this doesn't make a whole lot of sense. If anyone is confused by what i am asking here I can try to clarify if I get some feedback.
The code I would Like output is:

Which is similar to what I am getting, however when I apply the fix that andres descalzo has supplied, my list elements are each repeating themselves 5 times.
Any solutions would be greatly appreciated.
Thanks,
jason

A: I'm not sure exactly what you want, as there is some undefined values and syntax errors in your code, but here is an example on how to create elements from an array and add to an existing ul element:
$(function(){
    $.each(['link1', 'link2', 'link3', 'link4', 'link5'], function(i, link){
        $('
')
        .append(
            $('')
            .attr({ 'class': 'c' + i, ref: i, href: 'page.php#' + link })
            .text(link)
        ).appendTo('ul');
    });
});

With the existing ul element, it produces:

link1

link2

link3

link4

link5

(In place of the array literal [...] you could of course use an array variable.)

A: something like this?:
*Edit II * for comment
var link = ['strategy', 'branding', 'marketing', 'media', 'management'],
          refNumericId = $("."+ numericId);

  $(link).each(function(i, el){

      $("

")
            .attr("id", numericId + "_" + (i+1))
            .attr("class", numericId + (i+1))
            .html("")
            .appendTo(refNumericId);

  });

I saw your code in the file 'easySlider1.7.js' and you're including in 'for' of the line 123 the code 'var link = [' strategy,''which should go after this 'for'


Q: Write this function without bitsets Trying to write a function that gives all ways to cover a R rows by 2 columns figure, I find this function but uses a approach with bitsets, was wondering how can i do this wihtout using binary operators.
This the function explanation: left_obstacles is a bitset of size R    in which each 1 represents an obstacle in the left column, in which this function generates all possible ways to cover the rest of the  left column using 1x1 and 2x2 blocks, and for each of them it returns    the bitset of cells covered in the right column.
def place22blocks(left_obstacles):

    options = set([ (left_obstacles,0) ])
    for add in range(R//2):
      new_options = set()
      for option in options:
         new_options.add(option)
         left, right = option
         for i in range(R-1):
             if (left & (3<<i)) == 0:
                 new_options.add( (left | (3<<i), right | (3<<i)) )
         options = new_options
    return [ option[1] for option in options ]

A: If I understand you correctly, you want to have 2 "columns" (variables) that contain obstacles but cannot both contain obstacles in the same "row" (bit)
If this is the case the first observation I would make is that any time there is a blockage in the left column the possible options of the right column on both sides of that blockage are totally independent, in fact if my left column looks something like this:
000110000

Then really I just need to find all combinations of obstacles for R=3 and also for R=4 then the final answer will be the Cartesian product of filling those 2 gaps with the combinations.
So first we can write some code to make all possible permutations of obstacles for a given R which we can do recursively, you indicated you wanted to move away from bitwise so I'll use tuple concatenation as it will likely be a little easier to manipulate for your actual task than bit operations.
def obstacle_combos(R):
    """
    yields all sequences of obstacles with size 'size'
    obstacle_patterns is a set of tuples representing different obstacles
    """
    if R==0:
        # cannot fit any blocks of size 0
        yield ()
        return
    if R==1:
        # this ensures the loop below can always check combo[-1] without index error
        yield (0,)
        return
    for combo in obstacle_combos(R-1):
        yield combo + (0,)
        if combo[-1] == 0:
            # when the last element is empty we could instead put a block of 1s as well.
            yield combo[:-1] + (1,1)

print(*obstacle_combos(5), sep="\n")

The way this works is relatively straight forward, the base case of R=0 and R=1 are the trivial case, otherwise we check for R-1 and that combo with an extra 0 at the end is a valid obstacle combo  for R, but also if the last element is 0 we can stick a 11 at the end as well  so that becomes a conditional extra case.
The next step would be to identify runs of consecutive 0s, this is also not particularly complicated we just iterate over the sequence and implement some logic when we switch from 0 to 1 or 1 to 0 etc:
def find_gaps(obstacle_sequence):
    "yields (slice, size) for each range of concecutive 0s in the sequence"
    in_seq = False #whether we are currently in a run of 0s
    for i,elem in enumerate(obstacle_sequence):
        if not in_seq and elem == 0:
            in_seq = True
            start_idx = i
        elif in_seq and elem == 1:
            in_seq = False
            yield slice(start_idx, i), i-start_idx
    # after the loop if the last elements were 0s then yield the final sequence
    if in_seq:
        yield slice(start_idx, len(obstacle_sequence)), len(obstacle_sequence)-start_idx

One thing here that is slightly unorthodox is that I am creating slice objects directly, this is what happens internally if you do x[a:b] it is the same as x[slice(a,b)], the goal here being that later we can use the values this function produces to do something like:
Y = [0]*len(X) # some sequence of same size as X
for idx_range, size in find_gaps(X):
    Y[idx_range] = generate_seq_of_length(size)

to set ranges of Y (which will end up being our right_obstacles eventually) with minimal effort outside the find_gaps function.
Now the tricky part, we want a function to take a left_obstacles sequence of 1s and 0s, find all the runs of 0s by calling find_gaps and at the same time find all the combinations of obstacles we could put in that section. Then go over all combinations (cartesian product) of the obstacles that can be laid out in each region.
import itertools
def place22blocks(left_obstacles):
    # start by making a sequence of the same size as left_obstacles
    right_obstacles = [0 for _ in left_obstacles]
    # then we will find all the gaps and setup the obstacle_combos for each one
    gap_ranges = []
    seq_filling_iterators = []
    for idx_range, size in find_gaps(left_obstacles):
        gap_ranges.append(idx_range)
        seq_filling_iterators.append(obstacle_combos(size))
    # at this point each element of seq_filling_iterators is an iterator
    # that will give the different possibilities of obstacles for each region,
    # the final result of possible obstacles is the cartesian product of all of them
    for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators):
        # list_of_obstacles_per_gap is now a list of the sequences to fill in each gap, it is the "generate_seq_of_length(size)" in the previous example essentially.
        for idx_range, seq in zip(gap_ranges, list_of_obstacles_per_gap):
            right_obstacles[idx_range] = seq
        # since we are reusing the right_obstacles variable every loop we will need to make a copy for each valid obstacle list, will make it a tuple so it is immutable but you could also do list(right_obstacles) if you wanted.
        yield tuple(right_obstacles)

print(*place22blocks((0,0,0,1,1,0,0,0)),sep="\n")

This function I will admit is very complicated to fully wrap your head around for how short it is. gap_ranges is the list of ranges where we have space to put obstacles which is parallel to list_of_obstacles_per_gap that is the list of sequences, each element matching with the indices stored in gap_ranges which is why we zip them together.  The way list_of_obstacles_per_gap is generated is a little harder to grasp though, the first thing is that product is like a nested loop:
# example loop:
for x in range(5):
    for y in ["a","b","c"]:
        for z in range(10):
            things = (x,y,z)
# that would be equivalent to
for things in itertools.product(range(5), ["a","b","c"], range(10)):
    pass

so an example that might help would be to think about how the code would work if there were exactly 2 gaps to put obstacles:
for obs_seq1 in obstacle_combos(3):
    for obs_seq2 in obstacle_combos(4):
        right_obstacles[0:3] = obs_seq1
        right_obstacles[5:9] = obs_seq2
        print(right_obstacles)

so in the function above the outer loop is collapsing an arbitrary number of nested loops and the inner loop is performing all those sequence assignments.
No idea if any of this will actually help you, I'm still not sure exactly what you are trying to accomplish but I had fun working through this, happy coding :)

Also note if you wanted to implement this more efficient algorithm with bitwise operations that would be very doable as well:

import itertools

def obstacle_combos(R):
    """
    yields all sequences of obstacles with size 'size'
    obstacle_patterns is a set of tuples representing different obstacles
    """
    if R<=1:
        # cannot fit any blocks of size 0
        yield 0
        return
    for c in obstacle_combos(R-1):
        # shift the original combo so that we are inserting at the least significant bits,
        # is a little simpler than tracking how much to shift the 3 by.
        combo = c<<1
        yield combo
        if combo&3 == 0:
            # when the last element is empty we could instead put a block of 1s as well.
            yield combo | 3

#print(*obstacle_combos(5), sep="\n")

def find_gaps(obstacle_sequence, R):
    "yields (slice, size) for each range of consecutive 0s in the sequence, where slice is the bit position of the least significant bit that is 0"
    in_seq = False #whether we are currently in a run of 0s
    for i in range(R):
        elem = obstacle_sequence & (1<<i)
        if not in_seq and elem == 0:
            in_seq = True
            start_idx = i
        elif in_seq and elem > 0:
            in_seq = False
            yield start_idx, i-start_idx
    # after the loop if the last elements were 0s then yield the final sequence
    if in_seq:
        yield start_idx, R-start_idx

def place22blocks(left_obstacles, R):
    # start by making a sequence of the same size as left_obstacles
    gap_ranges = []
    seq_filling_iterators = []
    for idx_range, size in find_gaps(left_obstacles, R):
        gap_ranges.append(idx_range)
        seq_filling_iterators.append(obstacle_combos(size))

    for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators):
        yield sum(x<<i for i,x in zip(gap_ranges, list_of_obstacles_per_gap))

print("\n\n")
print(*map("{:09b}".format, place22blocks(0b000110000, 9)),sep="\n")


Q: Draw Line between two Geo Points in JMapViewer I'm working with OpenStreet Maps in Java with JMap Viwer http://wiki.openstreetmap.org/wiki/JMapViewer I can load the maps and everything ok but I don't know how to draw a line between two points from a latitude and longitude.
Any body know the function to draw this kind of lines?
Thank you.

A: The addMapPolygon() method of JMapViewer works for this, but paintPolygon() silently rejects a polygon having fewer than three vertices. For a line between two points, just repeat the last Coordinate.
Coordinate one = new Coordinate(...);
Coordinate two = new Coordinate(...);
List<Coordinate> route = new ArrayList<Coordinate>(Arrays.asList(one, two, two));
map.addMapPolygon(new MapPolygonImpl(route));

A: I am also working on this software and using the JMapviewer.jar. Yet, I do not seem to have the addMapPolygon nor the MapPolygonImpl ... Is there a specific version I should be working with ? (I downloaded my version here: enter link description here


Q: C# Linq-to-SQL Insert row into datacontext without committing to database I'm writing this Web app that is associated with a Microsoft sql database.
I want the user to be able to insert rows, view rows, and then edit those rows on the page.
When the user clicks a submit button, I want to commit all of the changes that the user made to the database in one large transaction.
Now I have this System.Data.Linq.DataContext object and I'm trying to insert a row into it without submitting changes to the database.
how do i do this?

A: InsertOnSubmit shouldn't actually write anything until you call SubmitChanges(). Failing that, stick all your objects to add in a list or something, and iterate over them later to insert.


Q: How to mount context-referenced Tomcat application with mod_jk? I have an WAR application running in Tomcat at /foo context, meaning that its URL is http://example.com:8080/foo. Now I'm trying to connect Apache HTTP Server to Tomcat through mod_jk. This is my workers.properties file:
worker.list=foo
worker.foo.port=8009
worker.foo.host=localhost
worker.foo.type=ajp13
worker.foo.mount=/foo/*

Works fine, but at this URL: http://example.com/foo. I would like it to be at http://example.com. What am I missing?
ps. This is my mod-jk.conf, which is included into httpd.conf:
LoadModule jk_module modules/mod_jk.so
JkWorkersFile /usr/local/tomcat/conf/workers.properties
<VirtualHost *:80>
  ServerName foo.example.com
  JkMount /* foo
</VirtualHost>

A: You basically have two options:

*

*Modify your Tomcat configuration to mount the WAR at the root. How this is done depends on how exactly you're deploying your application. This is the cleaner approach unless there's some preventing factor.

*Handle the problem on the Apache side by using mod_rewrite to rewrite URLs starting with / to /foo, at which point it will be passed through your JkMount to Tomcat

For the second option, your Apache configuration would look something like this:
# Turn on mod_rewrite
RewriteEngine On
# This is the rule. Use regexp to match any URL beginning with /, and rewrite it to
# /foo/remaining_part_of_URL. The [PT] (pass-through) is necessary to make rewritten
# requests go through JkMount
RewriteRule ^/(.*) /foo/$1 [PT]

# Forward all URLs starting with foo to Tomcat
JkMount /foo/* worker

(this isn't actually tested, hope it works as is!). You may also need to enable mod_rewrite in your Apache (check out your distribution, a mods-enabled directory might be the answer).
And if you need to know more about mod_rewrite (quite a powerful beast), go here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule

A: Here is a Mod Rewrite Solution
WORKERS.PROPERTIES
worker.list=worker1
worker.worker1.port=8009
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.mount=/foo/*           #THIS IS THE APP NAME: "FOO"

HTTPD.CONF
<VirtualHost *:80>
   RewriteEngine On
   RewriteRule ^/(.*)/Foo/$1 [PT]
   ServerName example.com             #DOMAIN NAME: "example.com"
   ServerAlias www.example.com
   JkMount /foo/* worker1
 </VirtualHost>


Q: Android OpenGL reading pixel color at the center of the screen I'm rendering a texture in OpenGL. I want to retrieve the pixel color value at the center of the screen.
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.order(ByteOrder.nativeOrder());
GLES20.glFinish();
GLES20.glReadPixels(0, 0, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
byte[] byteArray = new byte[4];
byteBuffer.get(byteArray);
int r = ((int) byteArray[0]) & 0xFF;
int g = ((int) byteArray[1]) & 0xFF;
int b = ((int) byteArray[2]) & 0xFF;
String key = r + " " + g + " " + b;
Log.i(TAG, key);

As a test, I'm rendering a red square to the center of the screen, and expect to log (255 0 0) but I only get back (255 0 0) when I render the entire screen red.

A: The coordinates/sizes passed to glReadPixels() are in window coordinates. The window coordinate system has its origin in the lower left corner of the window, with a unit of pixels.
This is not to be confused with the NDC (normalized device coordinates) system used for vertex coordinates, which has its origin in the center of the window, and has a range of [-1.0, 1.0] in both the x- and y-directions.
So in your example:
GLES20.glReadPixels(0, 0, 1, 1,
    GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);

you are reading one pixel in the lower left corner of the rendering surface. To read a pixel in the center, you need:
GLES20.glReadPixels(width / 2, height / 2, 1, 1,
    GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);

where width and height are the dimensions of the rendering surface in pixels.


Q: how to write Powershell script to identify any azure resource with a creation date in the last 30 days in multiple subscriptions how to identify all azure resources with a creation date in the last 30 days in multiple subscriptions using PowerShell script

A: Well, first you should note what you are using is a really old AzureRm module command, it was deprecated and will not be updated. So I recommend you to use the new Az module, you could refer to the doc to migrate Azure PowerShell from AzureRM to Az.
Then use the script below, it will get all the resources from all the subscriptions your logged user account/service principals can access.
$subs= Get-AzSubscription
foreach($sub in $subs){
    Set-AzContext -Subscription $sub.Id -Tenant $sub.TenantId
    Write-Host "login to subscription - "$sub.Name
    $groups = (Get-AzResourceGroup).ResourceGroupName
    foreach($group in $groups){
        Get-AzResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
    }
}

If you still want to use the old AzureRm module, then the script should be:
$subs= Get-AzureRmSubscription
foreach($sub in $subs){
    Set-AzureRmContext -Subscription $sub.Id -Tenant $sub.TenantId
    Write-Host "login to subscription - "$sub.Name
    $groups = (Get-AzureRmResourceGroup).ResourceGroupName
    foreach($group in $groups){
        Get-AzureRmResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
    }
}


Q: NHibernate/Hibernate - Forced to apply sorting twice on pagination I'm having an issue currently where I have to apply sorting twice in a query.
Since I want paginated results, I'm using a DetachedCriteria approach and using it as a Subquery for the main Criteria.
Issue is, that if I apply the sorting only on the DetachedCriteria, I don't get back the results sorted.
This is because the sql "IN" clause does not guarantee that the results will come back sorted.
So I need to apply the same sorting again on the main Criteria.
var detachedCriteria = DetachedCriteria.For<User>()
     .SetProjection(Projections.Id())
     .setMaxResults(20).setFirstResult(0)
     .AddOrder(Order.Asc("Name"));

 session.CreateCriteria<User>
    .Add(Subqueries.PropertyIn("Id", detachedCriteria))
    .AddOrder(Order.Asc("Name"))
    .List();

This would work, if could instead apply the DetachedCriteria as a JOIN clause, but as far as I know this is not supported by NHibernate.
Does anybody know of a different approach?


Q: Adjust the width of the mat-side-nav while it is open When the nav-bar is clicked open, the width of the nav-bar is to be adjusted automatically with the content.
 <mat-sidenav #sidenav  mode="side" class="primary-color main-sidenav nav-
 shadow" opened="true" [@sidenavState]="sidenavState"
 (@sidenavState.done)="endAnimation()" *ngIf="layout === 'modern' ||
 forceModern">
 ....
 </mat-sidenav>

When I set the width of the side-nav in SCSS as
.mat-side-nav{
   width: auto !important
 }

The nav-bar is opened by default without being clicked to open. Also it is not closed with the click

A: Your problem:
when you are doing the below:
.mat-side-nav{
   width: auto !important
 }
This is kind of hard coding the width to take whatever it contains.
Solution:
Find the class which is active while its open and set the width: auto, for that class.


Q: Why I can't insert new data in my database using SQLITE? public class SQLiteJDBCDriverConnection {

This block is to connect to sqlite database and create "warehouses" table with three columns.
public static Connection connect() {
    Connection conn = null;
    try {
        // db parameters
        String url = "jdbc:sqlite:chinook.db";
        String sql = "CREATE TABLE IF NOT EXISTS warehouses (\n"
                + " id integer PRIMARY KEY,\n"
                + " name text NOT NULL,\n"
                + " capacity real\n"
                + ")";
        // create a connection to the database
        conn = DriverManager.getConnection(url);
        //Create table
        Statement state = conn.createStatement();
        state.executeUpdate(sql);

        System.out.println("Connection to SQLite has been established.");

    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
    return conn;

}

This block is to create object with three parameters to insert new records for three columns.
public static void newItem(int id, String name, int capacity) {
    Connection con = connect();
    PreparedStatement state;
    String sql = "INSERT INTO warehouses(id,name,capacity) VALUES(?,?,?)";
try {
    state = con.prepareStatement(sql);

    state.executeUpdate();
}catch(Exception e) {

}
}

This block executes the newItem function.
public static void main(String[] args) {
    newItem(4009,"plywood",5000);
}
}

A: You do not set parameters to your SQL query.
After state = con.prepareStatement(sql); you need to set actual parameters using state.setXXX(index, value);
state = con.prepareStatement(sql);
state.setInt(1, id);
state.setString(2, name);
state.setInt(3, capacity);
state.executeUpdate();

And as mentioned in comments you need to at least add logging to your catch blocks. And connection and preparedStatement objects should be closed when are not needed anymore.
EDIT
In your connect method you close connection object in finally block and return closed connection. And then you try to use closed connection in your newItem() method.


Q: How to tell a gem not to be installed on JRuby? How can I configure a gem so that it couldn't be installed on JRuby?

A: in *.gemspec:
s.platform = 'ruby'

possible platform values:
ruby
C Ruby (MRI) or Rubinius, but NOT Windows

ruby_18
ruby AND version 1.8

ruby_19
ruby AND version 1.9

mri
Same as ruby, but not Rubinius

mri_18
mri AND version 1.8

mri_19
mri AND version 1.9

rbx
Same as ruby, but only Rubinius (not MRI)

jruby
JRuby

mswin
Windows

mingw
Windows 'mingw32' platform (aka RubyInstaller)

mingw_18
mingw AND version 1.8

mingw_19
mingw AND version 1.9


Q: Clearing the screen for new graphics in Java (awt) I have this code which is basically a home menu with two clickable rectangles.

*

*Start Game

*Info

Start Game works fine.
Info is what is not really working. When pressed, the info screen will appear, but the home menu buttons will still be there though not visible (can be clicked).. it seems that when the info menu is appearing, the home menu buttons are not getting cleared.
Also, any point on the info menu is clickable and will show the home menu again. (not what intended, only the back buttons should do that).
How can I fix those problems ?
package test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;

public class HomeMenu extends JComponent implements MouseListener, MouseMotionListener {

    private static final String GAME_TITLE = "BRICK DESTROY";
    private static final String START_TEXT = "START";
    private static final String INFO_TEXT = "INFO";
    private static final String howtoPlay = """
            1- Click Start\n
            2- Choose the mode\n
            3- Each mode has 3 levels\n
            4- To play/pause press space, use 'A' and 'D' to move\n
            5- To open pause menu press 'ESC'\n
            6- To open DebugPanel press 'ALT-SHIFT-F1'""";
    private static final String backText = "BACK";

    private static final Color BORDER_COLOR = new Color(200,8,21); //Venetian Red
    private static final Color DASH_BORDER_COLOR = new  Color(255, 216, 0);//school bus yellow
    private static final Color TEXT_COLOR = new Color(255, 255, 255);//white
    private static final Color CLICKED_BUTTON_COLOR = Color.ORANGE.darker();;
    private static final Color CLICKED_TEXT = Color.ORANGE.darker();
    private static final int BORDER_SIZE = 5;
    private static final float[] DASHES = {12,6};

    private Rectangle menuFace;
    private Rectangle infoFace;
    private Rectangle startButton;
    private Rectangle infoButton;
    private Rectangle backButton;

    private BasicStroke borderStoke;
    private BasicStroke borderStoke_noDashes;
    private Image img =  Toolkit.getDefaultToolkit().createImage("1.jpeg");
    private Font gameTitleFont;
    private Font infoFont;
    private Font buttonFont;
    private Font howtoPlayFont;

    private GameFrame owner;

    private boolean startClicked;
    private boolean infoClicked = false;
    private boolean backClicked = false;

    public HomeMenu(GameFrame owner,Dimension area){

        this.setFocusable(true);
        this.requestFocusInWindow();

        this.addMouseListener(this);
        this.addMouseMotionListener(this);

        this.owner = owner;

        menuFace = new Rectangle(new Point(0,0),area);
        infoFace = new Rectangle(new Point(0,0),area);
        this.setPreferredSize(area);

        Dimension btnDim = new Dimension(area.width / 3, area.height / 12);
        startButton = new Rectangle(btnDim);
        infoButton = new Rectangle(btnDim);
        backButton = new Rectangle(btnDim);

        borderStoke = new BasicStroke(BORDER_SIZE,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,0,DASHES,0);
        borderStoke_noDashes = new BasicStroke(BORDER_SIZE,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);

        gameTitleFont = new Font("Calibri",Font.BOLD,28);
        infoFont = new Font("Calibri",Font.BOLD,24);
        buttonFont = new Font("Calibri",Font.BOLD,startButton.height-2);
        howtoPlayFont = new Font("Calibri",Font.PLAIN,14);

    }

    public void paint(Graphics g){
        drawMenu((Graphics2D)g);

    }

    public void drawMenu(Graphics2D g2d){

        if(infoClicked) {
            drawInfoMenu(g2d);
            return;
        }else{
            drawContainer(g2d);

            Color prevColor = g2d.getColor();
            Font prevFont = g2d.getFont();

            double x = menuFace.getX();
            double y = menuFace.getY();

            g2d.translate(x,y);

            //methods calls
            drawText(g2d);
            drawButton(g2d);

            //end of methods calls

            g2d.translate(-x,-y);
            g2d.setFont(prevFont);
            g2d.setColor(prevColor);
        }

        Toolkit.getDefaultToolkit().sync();

    }

    private void drawContainer(Graphics2D g2d){
        Color prev = g2d.getColor();

        //g2d.setColor(BG_COLOR);
        g2d.drawImage(img,0,0,menuFace.width,menuFace.height,this);
        //g2d.fill(menuFace);

        Stroke tmp = g2d.getStroke();

        g2d.setStroke(borderStoke_noDashes);
        g2d.setColor(DASH_BORDER_COLOR);
        g2d.draw(menuFace);

        g2d.setStroke(borderStoke);
        g2d.setColor(BORDER_COLOR);
        g2d.draw(menuFace);

        g2d.setStroke(tmp);

        g2d.setColor(prev);
    }

    private void drawText(Graphics2D g2d){

        g2d.setColor(TEXT_COLOR);

        FontRenderContext frc = g2d.getFontRenderContext();

        Rectangle2D gameTitleRect = gameTitleFont.getStringBounds(GAME_TITLE,frc);

        int sX,sY;

        sY = (int)(menuFace.getHeight() / 4);

        sX = (int)(menuFace.getWidth() - gameTitleRect.getWidth()) / 2;
        sY += (int) gameTitleRect.getHeight() * 1.1;//add 10% of String height between the two strings

        g2d.setFont(gameTitleFont);
        g2d.drawString(GAME_TITLE,sX,sY);

    }

    private void drawButton(Graphics2D g2d){

        FontRenderContext frc = g2d.getFontRenderContext();

        Rectangle2D txtRect = buttonFont.getStringBounds(START_TEXT,frc);
        Rectangle2D mTxtRect = buttonFont.getStringBounds(INFO_TEXT,frc);

        g2d.setFont(buttonFont);

        int x = (menuFace.width - startButton.width) / 2;
        int y =(int) ((menuFace.height - startButton.height) * 0.5);

        startButton.setLocation(x,y);

        x = (int)(startButton.getWidth() - txtRect.getWidth()) / 2;
        y = (int)(startButton.getHeight() - txtRect.getHeight()) / 2;

        x += startButton.x;
        y += startButton.y + (startButton.height * 0.9);

        if(startClicked){
            Color tmp = g2d.getColor();
            g2d.setColor(CLICKED_BUTTON_COLOR);
            g2d.draw(startButton);
            g2d.setColor(CLICKED_TEXT);
            g2d.drawString(START_TEXT,x,y);
            g2d.setColor(tmp);
        }
        else{
            g2d.draw(startButton);
            g2d.drawString(START_TEXT,x,y);
        }

        x = startButton.x;
        y = startButton.y;

        y *= 1.3;

        infoButton.setLocation(x,y);

        x = (int)(infoButton.getWidth() - mTxtRect.getWidth()) / 2;
        y = (int)(infoButton.getHeight() - mTxtRect.getHeight()) / 2;

        x += infoButton.getX();
        y += infoButton.getY() + (startButton.height * 0.9);

        if(infoClicked){
            Color tmp = g2d.getColor();
            g2d.setColor(CLICKED_BUTTON_COLOR);
            g2d.draw(infoButton);
            g2d.setColor(CLICKED_TEXT);
            g2d.drawString(INFO_TEXT,x,y);
            g2d.setColor(tmp);
        }
        else{
            g2d.draw(infoButton);
            g2d.drawString(INFO_TEXT,x,y);
        }

    }

    private void drawInfoMenu(Graphics2D g2d){

        FontRenderContext frc = g2d.getFontRenderContext();

        Rectangle2D infoRec = infoFont.getStringBounds(INFO_TEXT,frc);

        Color prev = g2d.getColor();

        Stroke tmp = g2d.getStroke();

        g2d.setStroke(borderStoke_noDashes);
        g2d.setColor(DASH_BORDER_COLOR);
        g2d.draw(infoFace);

        g2d.setStroke(borderStoke);
        g2d.setColor(BORDER_COLOR);
        g2d.draw(infoFace);

        g2d.fillRect(0,0,infoFace.width,infoFace.height);

        g2d.setStroke(tmp);

        g2d.setColor(prev);

        g2d.setColor(TEXT_COLOR);

        int sX,sY;

        sY = (int)(infoFace.getHeight() / 15);

        sX = (int)(infoFace.getWidth() - infoRec.getWidth()) / 2;
        sY += (int) infoRec.getHeight() * 1.1;//add 10% of String height between the two strings

        g2d.setFont(infoFont);
        g2d.drawString(INFO_TEXT,sX,sY);

        TextLayout layout = new TextLayout(howtoPlay, howtoPlayFont, frc);
        String[] outputs = howtoPlay.split("\n");
        for(int i=0; i<outputs.length; i++) {
            g2d.setFont(howtoPlayFont);
            g2d.drawString(outputs[i], 40, (int) (80 + i * layout.getBounds().getHeight() + 0.5));
        }

        backButton.setLocation(getWidth()/3,getHeight()-50);

        int x = (int)(backButton.getWidth() - infoRec.getWidth()) / 2;
        int y = (int)(backButton.getHeight() - infoRec.getHeight()) / 2;

        x += backButton.x+11;
        y += backButton.y + (layout.getBounds().getHeight() * 1.35);

        backButton.setLocation(getWidth()/3,getHeight()-50);

        if(backClicked){
            Color tmp1 = g2d.getColor();
            g2d.setColor(CLICKED_BUTTON_COLOR);
            g2d.draw(backButton);
            g2d.setColor(CLICKED_TEXT);
            g2d.drawString(backText,x,y);
            g2d.setColor(tmp1);
            infoClicked = false;
            repaint();
        }
        else{
            g2d.draw(backButton);
            g2d.drawString(backText,x,y);
        }

    }

    @Override
    public void mouseClicked(MouseEvent mouseEvent) {
        Point p = mouseEvent.getPoint();
        if(startButton.contains(p)){
           owner.enableGameBoard();

        }
        else if(infoButton.contains(p)){
            infoClicked = true;
        }
        else if(backButton.contains(p)){
            infoClicked = false;

        }
        repaint();

    }

    @Override
    public void mousePressed(MouseEvent mouseEvent) {
        Point p = mouseEvent.getPoint();
        if(startButton.contains(p)){
            startClicked = true;
            repaint(startButton.x,startButton.y,startButton.width+1,startButton.height+1);

        }
        else if(infoButton.contains(p)){
            infoClicked = true;

        }
        else if(backButton.contains(p)){
            infoClicked = false;
        }
        repaint();

    }

    @Override
    public void mouseReleased(MouseEvent mouseEvent) {
        if(startClicked){
            startClicked = false;
            repaint(startButton.x,startButton.y,startButton.width+1,startButton.height+1);
        }
        else if(infoClicked){
            infoClicked = false;
        }
        else if(backClicked){
            infoClicked = true;
        }
        repaint();
    }

    @Override
    public void mouseEntered(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseExited(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseDragged(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseMoved(MouseEvent mouseEvent) {
        Point p = mouseEvent.getPoint();
        if(startButton.contains(p) || infoButton.contains(p) || backButton.contains(p)) {
            this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
        else {
            this.setCursor(Cursor.getDefaultCursor());
        }
    }

}

Here are the images of both windows
main menu
info menu, pressing anywhere = back to home menu, pressing roughly in the middle = start game or back to main menu too

A: First read, Performing Custom Painting and Painting in AWT and Swing to get a better understanding how painting in Swing works and how you're suppose to work with it.

But I already have ...

public void paint(Graphics g){
    drawMenu((Graphics2D)g);

}

would suggest otherwise.  Seriously, go read those links so you understand all the issues that the above decision is going to create for you.
You're operating in a OO language, you need to take advantage of that and decouple your code and focus on the "single responsibility" principle.
I'm kind of tired of talking about it, so you can do some reading:

*

*https://softwareengineering.stackexchange.com/questions/244476/what-is-decoupling-and-what-development-areas-can-it-apply-to

*Cohesion and Decoupling, what do they represent?

*Single Responsibility Principle

*Single Responsibility Principle in Java with Examples

*SOLID Design Principles Explained: The Single Responsibility Principle
These are basic concepts you really need to understand as they will make your live SOOO much easier and can be applied to just about any language.
As an example, from your code...
public HomeMenu(GameFrame owner,Dimension area){
    //...
    this.setPreferredSize(area);

There is no good reason (other than laziness (IMHO)) that any caller should be telling a component what size it should be, that's not their responsibility.  It's the responsibility of the component to tell the parent container how big it would like to be and for the parent component to figure out how it's going to achieve that (or ignore it as the case may be).
The "basic" problem you're having is a simple one.  Your "God" class is simply trying to do too much (ie it's taken on too much responsibility).  Now we "could" add a dozen or more flags into the code to compensate for this, which is just going to increase the coupling and complexity, making it harder to understand and maintain, or we can take a step back, break it down into individual areas of responsibility and build the solution around those, for example...
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new HomePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class HomePane extends JPanel {

        public HomePane() {
            setLayout(new BorderLayout());
            navigateToMenu();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        protected void navigateToMenu() {
            removeAll();
            HomeMenuPane pane = new HomeMenuPane(new HomeMenuPane.NavigationListener() {
                @Override
                public void navigateToInfo(HomeMenuPane source) {
                    HomePane.this.navigateToInfo();
                }

                @Override
                public void navigateToStartGame(HomeMenuPane source) {
                    startGame();
                }
            });
            add(pane);
            revalidate();
            repaint();
        }

        protected void navigateToInfo() {
            removeAll();
            HowToPlayPane pane = new HowToPlayPane(new HowToPlayPane.NavigationListener() {
                @Override
                public void navigateBack(HowToPlayPane source) {
                    navigateToMenu();
                }
            });
            add(pane);
            revalidate();
            repaint();
        }

        protected void startGame() {
            removeAll();
            add(new JLabel("This is pretty awesome, isn't it!", JLabel.CENTER));
            revalidate();
            repaint();
        }

    }

    public abstract class AbstractBaseMenuPane extends JPanel {

        protected static final Color BORDER_COLOR = new Color(200, 8, 21); //Venetian Red
        protected static final Color DASH_BORDER_COLOR = new Color(255, 216, 0);//school bus yellow
        protected static final Color TEXT_COLOR = new Color(255, 255, 255);//white
        protected static final Color CLICKED_BUTTON_COLOR = Color.ORANGE.darker();
        protected static final Color CLICKED_TEXT = Color.ORANGE.darker();
        protected static final int BORDER_SIZE = 5;
        protected static final float[] DASHES = {12, 6};

        private Rectangle border;

        private BasicStroke borderStoke;
        private BasicStroke borderStoke_noDashes;

        private BufferedImage backgroundImage;

        public AbstractBaseMenuPane() {
            borderStoke = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, DASHES, 0);
            borderStoke_noDashes = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            border = new Rectangle(new Point(0, 0), getPreferredSize());
            // You are now responsible for filling the background
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            BufferedImage backgroundImage = getBackgroundImage();
            if (backgroundImage != null) {
                g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
            }

            Color prev = g2d.getColor();
            Stroke tmp = g2d.getStroke();

            g2d.setStroke(borderStoke_noDashes);
            g2d.setColor(DASH_BORDER_COLOR);
            g2d.draw(border);

            g2d.setStroke(borderStoke);
            g2d.setColor(BORDER_COLOR);
            g2d.draw(border);

            g2d.dispose();
        }

        public void setBackgroundImage(BufferedImage backgroundImage) {
            this.backgroundImage = backgroundImage;
            repaint();
        }

        public BufferedImage getBackgroundImage() {
            return backgroundImage;
        }

    }

    public class HomeMenuPane extends AbstractBaseMenuPane {

        public static interface NavigationListener {

            public void navigateToInfo(HomeMenuPane source);

            public void navigateToStartGame(HomeMenuPane source);
        }

        private static final String GAME_TITLE = "BRICK DESTROY";
        private static final String START_TEXT = "START";
        private static final String INFO_TEXT = "INFO";

        private Rectangle startButton;
        private Rectangle infoButton;

        private Font gameTitleFont;
        private Font buttonFont;

        // Don't do this, this just sucks (for so many reasons)
        // Use ImageIO.read instead and save yourself a load of frustration
        //private Image img =  Toolkit.getDefaultToolkit().createImage("1.jpeg");

        private Point lastClickPoint;

        private NavigationListener navigationListener;

        public HomeMenuPane(NavigationListener navigationListener) {
            this.navigationListener = navigationListener;

            try {
                setBackgroundImage(ImageIO.read(getClass().getResource("/images/BrickWall.jpg")));
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }

            this.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent mouseEvent) {
                    Point p = mouseEvent.getPoint();
                    lastClickPoint = p;
                    if (startButton.contains(p)) {
                        peformStartGameAction();
                    } else if (infoButton.contains(p)) {
                        performInfoAction();
                    }
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent mouseEvent) {
                    lastClickPoint = null;
                    repaint();
                }
            });
            this.addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent mouseEvent) {
                    Point p = mouseEvent.getPoint();
                    if (startButton.contains(p) || infoButton.contains(p)) {
                        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    } else {
                        setCursor(Cursor.getDefaultCursor());
                    }
                }
            });

            Dimension area = getPreferredSize();

            Dimension btnDim = new Dimension(area.width / 3, area.height / 12);
            startButton = new Rectangle(btnDim);
            infoButton = new Rectangle(btnDim);

            gameTitleFont = new Font("Calibri", Font.BOLD, 28);
            buttonFont = new Font("Calibri", Font.BOLD, startButton.height - 2);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            Color prevColor = g2d.getColor();
            Font prevFont = g2d.getFont();

            //methods calls
            drawText(g2d);
            drawButton(g2d);

            //end of methods calls
            g2d.setFont(prevFont);
            g2d.setColor(prevColor);
            g2d.dispose();
        }

        private void drawText(Graphics2D g2d) {
            g2d.setColor(TEXT_COLOR);

            FontRenderContext frc = g2d.getFontRenderContext();

            Rectangle2D gameTitleRect = gameTitleFont.getStringBounds(GAME_TITLE, frc);

            int sX, sY;

            sY = (int) (getHeight() / 4);

            sX = (int) (getWidth() - gameTitleRect.getWidth()) / 2;
            sY += (int) gameTitleRect.getHeight() * 1.1;//add 10% of String height between the two strings

            g2d.setFont(gameTitleFont);
            g2d.drawString(GAME_TITLE, sX, sY);

        }

        private void drawButton(Graphics2D g2d) {

            FontRenderContext frc = g2d.getFontRenderContext();

            Rectangle2D txtRect = buttonFont.getStringBounds(START_TEXT, frc);
            Rectangle2D mTxtRect = buttonFont.getStringBounds(INFO_TEXT, frc);

            g2d.setFont(buttonFont);

            int x = (getWidth() - startButton.width) / 2;
            int y = (int) ((getHeight() - startButton.height) * 0.5);

            startButton.setLocation(x, y);

            x = (int) (startButton.getWidth() - txtRect.getWidth()) / 2;
            y = (int) (startButton.getHeight() - txtRect.getHeight()) / 2;

            x += startButton.x;
            y += startButton.y + (startButton.height * 0.9);

            if (lastClickPoint != null && startButton.contains(lastClickPoint)) {
                Color tmp = g2d.getColor();
                g2d.setColor(CLICKED_BUTTON_COLOR);
                g2d.draw(startButton);
                g2d.setColor(CLICKED_TEXT);
                g2d.drawString(START_TEXT, x, y);
                g2d.setColor(tmp);
            } else {
                g2d.draw(startButton);
                g2d.drawString(START_TEXT, x, y);
            }

            x = startButton.x;
            y = startButton.y;

            y *= 1.3;

            infoButton.setLocation(x, y);

            x = (int) (infoButton.getWidth() - mTxtRect.getWidth()) / 2;
            y = (int) (infoButton.getHeight() - mTxtRect.getHeight()) / 2;

            x += infoButton.getX();
            y += infoButton.getY() + (startButton.height * 0.9);

            if (lastClickPoint != null && infoButton.contains(lastClickPoint)) {
                Color tmp = g2d.getColor();
                g2d.setColor(CLICKED_BUTTON_COLOR);
                g2d.draw(infoButton);
                g2d.setColor(CLICKED_TEXT);
                g2d.drawString(INFO_TEXT, x, y);
                g2d.setColor(tmp);
            } else {
                g2d.draw(infoButton);
                g2d.drawString(INFO_TEXT, x, y);
            }

        }

        protected void peformStartGameAction() {
            navigationListener.navigateToStartGame(this);
        }

        protected void performInfoAction() {
            navigationListener.navigateToInfo(this);
        }
    }

    public class HowToPlayPane extends AbstractBaseMenuPane {

        public static interface NavigationListener {

            public void navigateBack(HowToPlayPane source);
        }

        private static final String HOW_TO_PLAY_TEXT = """
            1- Click Start\n
            2- Choose the mode\n
            3- Each mode has 3 levels\n
            4- To play/pause press space, use 'A' and 'D' to move\n
            5- To open pause menu press 'ESC'\n
            6- To open DebugPanel press 'ALT-SHIFT-F1'""";
        private static final String BACK_TEXT = "BACK";
        private static final String INFO_TEXT = "INFO";

        private Rectangle backButton;
        private boolean backClicked = false;

        private Font infoFont;
        private Font howtoPlayFont;

        private NavigationListener navigationListener;

        public HowToPlayPane(NavigationListener navigationListener) {
            this.navigationListener = navigationListener;
            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent mouseEvent) {
                    Point p = mouseEvent.getPoint();
                    if (backButton.contains(p)) {
                        backClicked = true;
                        repaint();
                        performBackAction();
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    backClicked = false;
                }
            });

            this.addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent mouseEvent) {
                    Point p = mouseEvent.getPoint();
                    if (backButton.contains(p)) {
                        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    } else {
                        setCursor(Cursor.getDefaultCursor());
                    }
                }
            });

            Dimension btnDim = new Dimension(getPreferredSize().width / 3, getPreferredSize().height / 12);
            backButton = new Rectangle(btnDim);

            infoFont = new Font("Calibri", Font.BOLD, 24);
            howtoPlayFont = new Font("Calibri", Font.PLAIN, 14);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            g2d.setColor(BORDER_COLOR);
            g2d.fillRect(0, 0, getWidth(), getHeight());

            FontRenderContext frc = g2d.getFontRenderContext();
            Rectangle2D infoRec = infoFont.getStringBounds(INFO_TEXT, frc);
//
//            Color prev = g2d.getColor();
//
//            Stroke tmp = g2d.getStroke();
//
//            g2d.setStroke(borderStoke_noDashes);
//            g2d.setColor(DASH_BORDER_COLOR);
//            g2d.draw(infoFace);
//
//            g2d.setStroke(borderStoke);
//            g2d.setColor(BORDER_COLOR);
//            g2d.draw(infoFace);
//
//            g2d.fillRect(0, 0, infoFace.width, infoFace.height);
//
//            g2d.setStroke(tmp);
//
//            g2d.setColor(prev);
//
            g2d.setColor(TEXT_COLOR);

            int sX, sY;

            sY = (int) (getHeight() / 15);

            sX = (int) (getWidth() - infoRec.getWidth()) / 2;
            sY += (int) infoRec.getHeight() * 1.1;//add 10% of String height between the two strings

            g2d.setFont(infoFont);
            g2d.drawString(INFO_TEXT, sX, sY);

            TextLayout layout = new TextLayout(HOW_TO_PLAY_TEXT, howtoPlayFont, frc);
            String[] outputs = HOW_TO_PLAY_TEXT.split("\n");
            for (int i = 0; i < outputs.length; i++) {
                g2d.setFont(howtoPlayFont);
                g2d.drawString(outputs[i], 40, (int) (80 + i * layout.getBounds().getHeight() + 0.5));
            }

            backButton.setLocation(getWidth() / 3, getHeight() - 50);

            int x = (int) (backButton.getWidth() - infoRec.getWidth()) / 2;
            int y = (int) (backButton.getHeight() - infoRec.getHeight()) / 2;

            x += backButton.x + 11;
            y += backButton.y + (layout.getBounds().getHeight() * 1.35);

            backButton.setLocation(getWidth() / 3, getHeight() - 50);

            if (backClicked) {
                Color tmp1 = g2d.getColor();
                g2d.setColor(CLICKED_BUTTON_COLOR);
                g2d.draw(backButton);
                g2d.setColor(CLICKED_TEXT);
                g2d.drawString(BACK_TEXT, x, y);
                g2d.setColor(tmp1);
                repaint();
            } else {
                g2d.draw(backButton);
                g2d.drawString(BACK_TEXT, x, y);
            }
            g2d.dispose();
        }

        protected void performBackAction() {
            navigationListener.navigateBack(this);
        }
    }

}

Now, this example makes use of components to present different views (it even has a nice abstract implementation to allow for code re-use ), but it occurs to me, that, if you "really" wanted to, you could have a series of "painter" classes, which could be used to delegate the painting of the current state to, and mouse clicks/movements could be delegated to, meaning you could have a single component, which would simple delegate the painting (via the paintComponent method) to which ever painter is active.
And, wouldn't you know it, they have a design principle for that to, the Delegation Pattern
The above example also makes use of the observer pattern, so you might want to have a look into that as well


Q: android: how to hide bottom buttons on dialog fullscreen I'm trying to hide navigation buttons when a dialog is shown fullscreen.
I've manage to do it following this example: Android fullscreen dialog
however, whenever i touch a button they appear again.
is there any  way to hide them properly?

thanks

A: The following snippet hides the navigation bar and status bar:
window.decorView.apply {
    // Hide both the navigation bar and the status bar.
    // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
    // a general rule, you should design your app to hide the status bar whenever you
    // hide the navigation bar.
    systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}

From https://developer.android.com/training/system-ui/navigation
Nonetheless for your case you need two things to happen.

*

*First, set windowFullScreen to true to allow the dialog to paint every pixel in the screen. (i.e. Use any FullScreen theme).

*Then, on you dialog, set the systemUiVisibility to View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.
This will stop the navigationBar from ever showing until you reset the flags or dismiss the dialog.
The complete snippet:
class SomeActivity {

    fun showDialog() {
        FullScrenDialog()
            .apply {
                setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
            }
            .show(supportFragmentManager, "TAG")
    }

}

class FullScrenDialog : DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        return inflater.inflate(R.layout.dialog, container)
    }

}

A: Please try below code for dialog:
final Dialog dialog = new Dialog(this);
        dialog.setCancelable(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setContentView(R.layout.dialog_logout);
        Window window = dialog.getWindow();
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        window.getDecorView().setSystemUiVisibility(uiOptions);
        dialog.show();

Output is:

I hope it works for you.


Q: How can I use array using "row index" in python? I made code in python
There's so many arrays, what I want to do is
extract value of arrays and add it to array_matrix in row
and make a label too
and every circle row = row + 1
This is some part of my code,
I know the form of
array_matrix[row,0:3] = array1(u) and label_matrix(row,:) =[1 0]
isn't correct.
Please let me know what to change.
row = 0
array_matrix = []

for n in range(0,64,8):
  array1.append(dct_temp[0,1])
  array2.append(dct_temp[1,0])
  array3.append(dct_temp[0,2])
  array4.append(dct_temp[1,1])

  u = (index-1,index+1,1)  # index = index of max value of array
  array_matrix[row,0:3] = array1(u)
  array_matrix[row,4:7] = array2(u)
  array_matrix[row,8:11] = array3(u)
  array_matrix[row,12:15] = array4(u)

  label_matrix(row,:) =[0 1]

  row = row + 1

A: You could use a dict
dict = {"labelA",arrayVal}
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']

For your array you can use a notation like
array[FROM INDEX ROW:TOINDEX ROW, :]

The : means take all cols
FROM INDEX ROW:TOINDEX ROW means take all values from the FROM INDEX upto the TOINDEX.


Q: perl threading problem I'm writing a multithreaded website uptime checker in perl, and here is the basic code so far (includes only threading part):
#!/usr/bin/perl

use LWP::UserAgent;
use Getopt::Std;
use threads;
use threads::shared;

my $maxthreads :shared = 50;
my $threads :shared = 0;

print "Website Uptime Checker\n";
my $infilename = $ARGV[0];
chomp($infilename);
open(INFILE, $infilename);
my $outfilename = $ARGV[1];
chomp($outfilename);
open(OUTFILE, ">" . $outfilename);
OUTFILE->autoflush(1);
while ($site = <INFILE>)
{
    chomp($site);
    while (1)
    {
        if ($threads < $maxthreads)
        {
            $threads++;
            my $thr = threads->create(\&check_site, $site);
            $thr->detach();
            last;
        }
        else
        {
            sleep(1);
        }
    }
}
while ($threads > 0)
{
    sleep(1);
}

sub check_site
{
    $server = $_[0];
    print "$server\n";
    $threads--;
}

It gives an error after a while:

Can't call method "detach" on an undefined value at C:\perl\webchecker.pl line 28,  line 245.

What causes this error? I know it is at detach, but what am I doing wrong in my code? Windows shows lots of free memory, so it should not be the computer running out of memory, this error occurs even if I set $maxthreads as low as 10 or possibly even lower.

A: The specific issue is that thread->create is failing to create a thread and so it is returning undef.  You should check the value of thr before calling detach if you want your code to be more robust.


Q: How to implement email for your apps in xcode? I tried to implement 'mail composer' (sample code from dev) to my apps. They are a lot of hard coded in the sample code. For example: sent to recipient - first@example.com. I want to leave it blank like @"", however it automatically prefix comma in front of the email address. I also have other concern, based on apple DEV readme.txt, launchMailAppOnDevice will be triggered if displayComposerSheet is failed. Should I replace all hardcoded in launchMailAppOnDevice and how to do it?
Please advise.
-(IBAction)showPicker:(id)sender
{
        // This sample can run on devices running iPhone OS 2.0 or later
        // The MFMailComposeViewController class is only available in iPhone OS 3.0 or later.
        // So, we must verify the existence of the above class and provide a workaround for devices running
        // earlier versions of the iPhone OS.
        // We display an email composition interface if MFMailComposeViewController exists and the device can send emails.
        // We launch the Mail application on the device, otherwise.

        Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
        if (mailClass != nil)
        {
                // We must always check whether the current device is configured for sending emails
                if ([mailClass canSendMail])
                {
                        [self displayComposerSheet];
                }
                else
                {
                        [self launchMailAppOnDevice];
                }
        }
        else
        {
                [self launchMailAppOnDevice];
        }
}

// Displays an email composition interface inside the application. Populates all the Mail fields.

-(void)displayComposerSheet

{
        MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

picker.mailComposeDelegate = self;

        [picker setSubject:@"Visit my new apps in app store!"];

        // Set up recipients
        NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];

        [picker setToRecipients:toRecipients];

        //Replace the email body with the content from my textview

        [picker setMessageBody:TextView.text isHTML:NO];

        [self presentModalViewController:picker animated:YES];

    [picker release];
}

// Launches the Mail application on the device.

-(void)launchMailAppOnDevice
{
        NSString *recipients = @"mailto:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!";
        NSString *body = @"&body=It is raining in sunny California!";

        NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
        email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

A: Did you implement the mail class in your .h files

A: Replace your hard coded values in
"launchMailAppOnDevice".. it works for mine


Q: Searching for file using ref number I am trying to write a program that when prompted the user enters a Ref number and the program searches for the file which contains this ref number within it. Few things first:
The files all end with a .dpt extension and look like this:
PX12RUJ
PX12RUR
PX12RUV
#PX12RUU
PX12WLJ
#PX12WLL
PX12WLK
PX12RUW
WN14YGV
WN14YGY

Once I have found the file I need to read its contents into an array ignoring all lines that start with a '#'.
EDIT: Code for search but output is blank, grep within linux returns correct file test.dpt
#!/usr/bin/python

import subprocess

a = subprocess.Popen(("grep -l PX12WLK /shares/MILKLINK/PPdir/*/*.dpt"),shell=True, stdout = subprocess.PIPE)
output = a.communicate()[0]
print output

EDIT 2: Sorted it in the end for anyone interested here's how:
#!/usr/bin/python

from subprocess import Popen, PIPE, call

s_REG=raw_input('Please enter Reg number: ')

a = Popen(["grep -l %s /shares/MILKLINK/PPdir/*/*.dpt" %s_REG],shell=True, stdout = PIPE)
FILE_DIR = a.communicate()[0]
FILE_DIR=FILE_DIR.rstrip('\n')

FILE=open("%s" %FILE_DIR , 'r')
# Read File into array
LINES = FILE.read().split('\n')
# Remove Blank Lines and whitespace
LINES = filter(None, LINES)
# Ignore any lines that have been commented out
LINES = filter(lambda x: not x.startswith('#'), LINES)
FILE.close()

# Call the CrossRef Processor for each Reg to make sure for no differences
for I in range(len(LINES)):
   call(["/shares/optiload/prog/indref.sh", "%s" %LINES[I]])

A: #!/usr/bin/python

from subprocess import Popen, PIPE, call

s_REG=raw_input('Please enter Reg number: ')

a = Popen(["grep -l %s /shares/MILKLINK/PPdir/*/*.dpt" %s_REG],shell=True, stdout = PIPE)
FILE_DIR = a.communicate()[0]
FILE_DIR=FILE_DIR.rstrip('\n')

FILE=open("%s" %FILE_DIR , 'r')
# Read File into array
LINES = FILE.read().split('\n')
# Remove Blank Lines and whitespace
LINES = filter(None, LINES)
# Ignore any lines that have been commented out
LINES = filter(lambda x: not x.startswith('#'), LINES)
FILE.close()

# Call the CrossRef Processor for each Reg to make sure for no differences
for I in range(len(LINES)):
   call(["/shares/optiload/prog/indref.sh", "%s" %LINES[I]])


Q: Refit upload file from Api to Api I am trying to upload an image from one Asp net core backend to an other via refit.
await _repository.UploadImageAsync(userId,
    new StreamPart(file.OpenReadStream(), file.FileName, file.ContentType), extension);

The Api
[Put("/image/{userId}")]
Task<Guid> UploadImageAsync(Guid userId, StreamPart stream, string extension);

The receiving Controller
[HttpPut("image/{userId}")]
public async Task<IActionResult> UploadImageAsync([FromRoute] Guid userId, StreamPart stream, string extension)
{
    return await RunAsync(async () =>
    {
        var id = await _userImageManager.UploadImageAsync(userId, stream.Value, extension);

        return Ok(id);
    });
}

As soon as I run this i get the following exception:
Newtonsoft.Json.JsonSerializationException: Error getting value from 'ReadTimeout' on 'Microsoft.AspNetCore.Http.ReferenceReadStream'.
 ---> System.InvalidOperationException: Timeouts are not supported on this stream.
   at System.IO.Stream.get_ReadTimeout()
   at lambda_method(Closure , Object )
   at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, JsonSerializerSettings settings)
   at Refit.JsonContentSerializer.SerializeAsync[T](T item) in d:\a\1\s\Refit\JsonContentSerializer.cs:line 34
   at Refit.RequestBuilderImplementation.<>c__DisplayClass17_0.<<BuildRequestFactoryForMethod>b__0>d.MoveNext() in d:\a\1\s\Refit\RequestBuilderImplementation.cs:line 546
--- End of stack trace from previous location where exception was thrown ---
   at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in d:\a\1\s\Refit\RequestBuilderImplementation.cs:line 243

I tried going the way described here but had no success. Is there anything I did wrong?
EDIT
Based on @TomO answer I edited my code, but I still get null for stream:
Api 1 (the sending part to Api 2):
public async Task<Guid> UploadImageAsync(Guid userId, IFormFile file)
{
    ...
    var stream = file.OpenReadStream();

    var streamPart = new StreamPart(stream, file.FileName, file.ContentType);
    var response = await _repository.UploadImageAsync(userId,
                streamPart, extension);
    ...
}

Api 2 (The receiver):
[HttpPost("image/{userId}")]
public async Task<IActionResult> UploadImageAsync([FromRoute] Guid userId, string description, IFormFile stream, string extension)
{
    ...
}

The Refit Api:
[Multipart]
[Post("/image/{userId}")]
Task<Guid> UploadImageAsync(Guid userId, [AliasAs("Description")] string description, [AliasAs("File")] StreamPart stream, string extension);

A: I think the documentation (and the solution linked in the question) give good guidance. But here's what I got to work, anyhow:
Receiving API endpoint:
[HttpPost]
[Route("{*filePath:regex(^.*\\.[[^\\\\/]]+[[A-Za-z0-9]]$)}")]
public async Task<IActionResult> AddFile([FromRoute] AddFileRequest request,
                                         [FromForm] AddFileRequestDetails body,
                                         CancellationToken cancellationToken)

And the corresponding refit client call:
[Multipart]
[Post("/{**filePath}")]
Task AddFile(string filePath, [AliasAs("Description")] string description, [AliasAs("File")] StreamPart filepart);

The important thing here is that ALL of the member properties of the Form body(not including file) have to be decorated with the "AliasAs" attribute.
Calling on the sending side:
            System.IO.Stream FileStream = request.File.OpenReadStream();
            StreamPart sp = new StreamPart(FileStream, request.FileName);

            try
            {
                await _filesClient.AddFile(request.FilePath, request.Description, sp);
            }
            catch (ApiException ae)
            {
                ...
                throw new Exception("Refit FileClient API Exception", ae);
            }

Hope this helps the next person...


Q: ng-bind-html is not able to bind text and image url together I am trying to use some string and a image together in ng-bind-html tag in AngularJS but it is giving error so far what i did is

If only string value is coming or only image url is coming then it works fine but when string + image url both are coming it does not display anything and it thrown error(404) can not find resource.
This value is coming from DB which will assign to question variable
"This is Instruction for below question"  http://localhost:8080/OnlineExam/static/css/question_images/ tid_27-8-16_10AM_qno_25.png

A:

var app = angular.module("exApp",["ngSanitize"]);

app.controller('ctrl', function($scope, $sce){
$scope.image = $sce.trustAsHtml('');
});


Q: How to get process name in an injected dll? I have this basic internal dll:
#include "pch.h"

DWORD WINAPI HackThread(HMODULE hModule)
{
    uintptr_t moduleBase = (uintptr_t)GetModuleHandle(L"Mainmodule123.exe");

    AllocConsole();
    FILE* f;
    freopen_s(&f, "CONOUT$", "w", stdout);

    std::cout << "Injected" << std::endl;
    while (!GetAsyncKeyState(VK_END) & 1) {
        Sleep(10)
    }

    fclose(f);
    FreeConsole();
    FreeLibraryAndExitThread(hModule, 0);
    return 0;
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    {
        CloseHandle(CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr));
    }
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

I want to get a handle to the main module of the application, for example: GetModuleHandle(L"Mainmodule123.exe")
The problem, is that this application is changing the module numbers randomly.
The main module name is the same as the process name. So I need to detect the process name that I'm attached to.
How can I get the process name I'm attached to in an internal dll?

A: You can pass NULL for the lpModuleName parameter into GetModuleHandle:

If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).


Q: How to see if a .NET program is running Is it possible to determine if a Microsoft .NET program is running on a windows computer?

A: The following will return true if there is one or more processes running that have the supplied name.
    public bool IsProcessRunning(string processName)
    {
        return Process.GetProcessesByName(processName).Length != 0;
    }

A: If you are attempting to identify processes/applications that are explicit to .NET, you should look for a dependency/module within the process that is specific to the .NET framework.
Below I am using mscorlib, as it's the first that comes to mind, as my hint to identify that the process is dependent on the .NET framework. e.g.
        var processes = Process.GetProcesses();
        foreach (var process in processes)
        {
            try
            {
                foreach (var module in process.Modules)
                {
                    if (module.ToString().Contains("mscorlib"))
                    {
                        Console.WriteLine(process);
                        break;
                    }
                }
            }
            catch { // Access violations }
        }

It's not bullet proof, as some processes cannot have their modules enumerated due to access restrictions, but if you run it, you'll see that it will pull back .NET dependent processes.  Perhaps it will give you a good starting point to get you thinking in the right direction.

A: Check out CorPublishLibrary - a library that lets you interrogate all managed-code processes running on a machine.


Q: Make div appear only once after closing using useState and localstorage I have a div with a close button. Currently, what it does is when the user clicks the close button, the div disappears. But when the user refreshes the page, the div is still there. I'm thinking of using localstorage but I'm confused as to how it should be incorporated when I am using useState.
Here's my code.
const [isVisible, setIsVisible] = useState(true)
useEffect(() => {
      let hideDiv = localStorage.getItem('hideDiv ')
      if (!hideDiv ) {
        setIsVisible(true)
        localStorage.setItem('hideDiv ', 1)
      }
    }, [])
    if (!isVisible) return null

           setIsVisible(false)}>
            x

        ... some text here ...

My current idea is useEffect and localstorage, but considering how I'm completely new to React, I'm not so sure how I go about this as I've only tried hiding and showing elements using localstorage in Vanilla javascript

A: useEffect with an empty dependency array will fire once when the component mounts. This is a good place to get that value from local storage and set it to the state. Then your close function can just set the local storage to true.
I made a sandbox for you here: https://codesandbox.io/s/crazy-davinci-io03f?file=/src/App.js
You should probably initialise your state to false too. This will avoid that flicker that you see.


Q: Result does not return any data in FMDB I am using this tutorial to implement FMDB in my project. But my code does not return any value. here is the code for retrive value.
-(NSMutableArray *) getCustomers
{
    NSMutableArray *customers = [[NSMutableArray alloc] init];
    FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
    [db open];
    FMResultSet *results = [db executeQuery:@"SELECT * FROM customers"];
    NSLog(@"results %i,%@,%@",[results intForColumn:@"id"],[results stringForColumn:@"firstname"],[results stringForColumn:@"lastname"]);
    while([results next])
    {
        Customer *customer = [[Customer alloc] init];
        customer.customerId = [results intForColumn:@"id"];
        customer.firstName = [results stringForColumn:@"firstname"];
        customer.lastName = [results stringForColumn:@"lastname"];
        [customers addObject:customer];
    }
    [db close];
    return customers;
}

When i check for db than db exist at document directory here is log
CRUD[47363:f803] db /Users/pingdanehog/Library/Application Support/iPhone Simulator/5.1/Applications/D9F19E7D-A232-4C4A-8218-58BC136053A7/Documents/Customers.db

Here is my db

And it contain data

But my resulset value always be null please help this code have run before but when i create new db with same name for this project than it have stopped.
Here is the value of result.
results 0,(null),(null)

I have initialize my DB in appdelegate file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    databaseName = @"Customers.db";

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    databasePath = [documentDir stringByAppendingPathComponent:databaseName];

    [self createAndCheckDatabase];

    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

-(void) createAndCheckDatabase
{
    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:databasePath];

    if(success) return;

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

A: What happens, if you place the line

NSLog(@"results %i,%@,%@",[results intForColumn:@"id"], ....

behind the [results next], e.g. inside the while loop?
The documentation of FMDB says:
"You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one"

A: Make sure you have initialized your db into AppDelegate or any of your file where you are using FMDB.
If yes & you have initialized it somewhere, then try to run this SQL "SELECT * FROM customers" . in database itself, in SQL tab. And check whether database contains the values or not.
Before that make sure you are running SQL in databse which resides into **Application Support**

Enjoy Programming!


Q: How to Hide Body but Keep Image displaying with JavaScript I have an HTML page that I want to hide everything in the body but still show just a single image on the page.  Then, I want to hide that image that was showing and then re-enable the body.
I want to do this with JavaScript that I inject into the page.  That is, when the page launches, I can run some JavaScript that I inject to do this.  My JavaScript can inject the image. Then, I need to be able to inject some JavaScript later that will turn off the image and re-show the body tag.
I can easily turn the body tag to hidden, but then that also hides my img tag that I appended to the body and that defeats my purpose.
My page is something like this:

...

My code that has the hidden image problem is this.
document.getElementsByTagName("body")[0].style.display = "hidden";
console.log("about to create image");
n = document.createElement("img"); // create an image element
n.src =
  "https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg"; // relative path to the image
document.body.appendChild(n); // append the image to the body

A: Try this :

let newDiv = document.createElement("DIV");
newDiv.setAttribute("id", "hide");
document.body.appendChild(newDiv);
document.getElementById("hide").style.zIndex = "9";
document.getElementById("hide").style.width = "100%";
document.getElementById("hide").style.height = "100%";
document.getElementById("hide").style.backgroundImage = "url('https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg')";
document.getElementById("hide").style.backgroundRepeat = "no-repeat";
document.getElementById("hide").style.backgroundSize = "cover";
document.getElementById("hide").style.top = "0";
document.getElementById("hide").style.position = "fixed";
document.body.style.margin = "0";
document.body.style.padding = "0";

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !

This is a text under the image and will not show up because the image is covering the whole area of the body !

 I can even copy and paste this hundreds of times, but the image will still be on top of everything !