Q: How to add an Internet Gateway to a VPC using AWS CDK? I am trying to produce the correct CDK scripts (TypeScript) to create an environment with a Lambda (accessed via API Gateway) that can call an RDS (Sql Server instance).
I believe I have it mostly working, but I wanted to connect to the RDS instance from my development machine to run some queries and check on a few things.
My RDS instance is in a private subnet, and so I believe in order to connect to it I need to add an Internet Gateway and security group to allow access on the appropriate ports.
For the life of me I can figure out the last piece, how to add the internet gateway using CDK.
The latest script I have tried is as follows:
const privateSubnectConfiguration = {
  cidrMask: 26,
  name: 'private-subnet',
  subnetType: SubnetType.PRIVATE,
};

const publicSubnectConfiguration = {
  cidrMask: 26,
  name: 'public-subnet',
  subnetType: SubnetType.PUBLIC,
};

const vpc = new Vpc(this, props.generateId('vpc'), {
  maxAzs: 2,
  subnetConfiguration: [privateSubnectConfiguration, publicSubnectConfiguration],
  natGateways: 1,
});

vpc.addGatewayEndpoint(props.generateId('internet-gateway'), {
  service: { name: "ig-service" }
})

Which then errors with The Vpc Endpoint Service 'ig-service' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidServiceName;
I see references to the CfnInternetGateway in the docs, but just can't figure out how to attach a new one to my VPC?
Can you please help with the syntax?

A: First of all, you cannot directly access a database in a private subnet. You have to deploy a proxy instance in your public subnet and forward the required ports to access your database.
When using CDK VPC construct, an Internet Gateway is created by default whenever you create a public subnet. The default route is also setup for the public subnet.
So you should remove addGatewayEndpoint() from your code, which adds a Gateway VPC Endpoint that you don't need.
You may also consider using SubnetType.ISOLATED to create a private subnet without a NAT GW, which may be redundant in your case. SubnetType.PRIVATE creates a NAT Gateway by default.


Q: how do i select value from dropdownlist to mode or to controller mvc Model
public class Company
{
    public int ID { get; set; }
    ....
    public int WorkZoneID { get; set;  }
    public IEnumerable<SelectListItem> WorkZones { get; set; }

Controller:
ViewBag.Workzones = cmpRep.GetWorkzoneDrop();

Repository:
public List<SelectListItem> GetWorkzoneDrop()
{
    SqlDataReader DR;
    DR = Ado.ExecDataReaderProc("WorkZoneSelectActive");
    List<SelectListItem> selectWorkZoneListItems = new     List<SelectListItem>();
    CompanyVMList C = new CompanyVMList();
    C.Companies = new List<Company>();
    while (DR.Read())
    {
        SelectListItem selectListItem = new SelectListItem
        {
            Text = Convert.ToString(DR["Name"]),
            Value = Convert.ToString(DR["ID"]),
        };
        selectWorkZoneListItems.Add(selectListItem);
    }
    return selectWorkZoneListItems;
}

View
@Html.DropDownList("Workzones")

I want to assign selected dropdownlist value to int work zone int the mode how do i select value from dropdownlist to model or to controller

A: You need to bind your dropdownlist to property WorkZoneID
@Html.DropDownListFor(m => m.WorkZoneID, Model.Workzones)

and if your wanting to preselect an option, you need to set the value in the controller before you pass the model to the view. And since your model contains a property for the SelectList, then use it (don't use ViewBag)
Company model = new Company
{
    WorkZoneID = 1 // set to a value that matches one of your options
    Workzones = cmpRep.GetWorkzoneDrop();
};
return View(model);

and when you submit to
[HttpPost]
public ActionResult Edit(Company model)

the value of model.WorkZoneID will contain the value of the selected option.


Q: How to decouple user Identity from the application data I am part of a new startup with some friends from school, and I am developing a REST API as back-end for a web application/website. I have recently gratuated and does not have much experience with large projects.
Without going in detail about the specific business idea, it will be sort of a "share economy" service, like for example uber or airbnb, where users register as either a customer or provider of a specific service. So users need to register an account and have data related to that account.
The API is developed with ASP.NET Web API. For authentication/authorization I am using ASP.NET Identity and JWT as Oauth bearer tokens with OWIN OAuth middleware.
I have used a guide for part of the setup, with some changes to fit our
project. (Just search "bitoftech Implement OAuth JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1" to find it if you are interested).
For those that don't know, the ASP.NET Identity database looks like this:
ASP.NET Identity database diagram.
So we have an AppUser table that represents the user, with roles, claims and logins attached in different tables in the Identity database.
Now, the user has much other data related to his account in our application, like messages (users can message each other), events (like a ride if this was uber), categories, reviews, files, and other data. All in separate tables.
So, since all these other tables are related to the user identity, what I did was put all these other tables in the same database with a Foreign Key to the Id in the AppUser table.
Each user has a role of either Customer or Provider (as in customer or driver in the Uber example) in the IdentityRole table.
This way I can authorize users based on role, and also query data based on role.
Now for the catch: Unexpected requirement changes. The company has decided that they (we) want to create a similar service (with customers and providers), but in a different business domain, and with the same user identity. So users that have already registered with one site should not be required to register again with a new account for the other site, but just use their existing account (and maybe sign up for the new site by clicking a button in their profile or something).
So if the first site was uber, now we want to create airbnb (not really, but as an example).
The data in the new site will be very similar to the first site. Users will have messages, events, categories, files, etc. But the events table will maybe be a little different, and maybe some new or different tables for the new site. We will try to keep the data very similar at first, so we can use much of the existing code, but we expect – if the the site(s) become popular – that they will drift apart (in terms of code and data) in time.
So first I thought: "how can I change the existing database schema so that it will fit both services?". But as I thought more about it, I think this will maybe only create problems in the future.
In the Oauth flow diagram, you have a separate resource server and authorization server. Even though I use Oauth now, my API is both a Resource Server and Authorization Server I guess, and that would probably be ok if they had not had been coupled in the way I have described?
So my question after all this is this is:
1: Should I use one (separate) database for the User Identity (IdentityDbContext),
and another database for all the other data (events, messsages etc..)?
That way Identity can run on a totally different server if need be, and not be coupled to any specific domain/site/service. Is that a good idea?
2: If so, how would I create a relationship between databases?
The only thing I can think of is to create a separate user table with only the UserId (from the Identity database) in the "Uber" database, and this will be created the first time a user registers for a site, and all the other data is related to this key. Then I would need to query data from two databases and put them together for some operations, for example, when a user queries his incoming messages, the message itself would be in one database and the name of the sender in another. Is there a better way?
3: Should I use separate databases for the first and second website/service (One for Uber and one for Airbnb, as in the example)? Or is there a better way?
4: Is there a different solution that I have not thought about that would be better?
Many people have probably faced these problems before, so I would appreciate if any experienced developers could tell me what is the best practice.
Last, it is not unprobable that even more services will be "attached" to the user Identity in the future if our current endevours are successful, so I really need a future-proof solution to this problem.
Thank you for any responses.

A: This approach seems somewhat common:

*

*Maintain a completely separate identity database.  There should be no connection at all with any of the Line-Of-Business (LOB) databases.

*Each LOB database should have its own user table, with appropriate referential integrity constraints with other LOB tables, e.g. events or messages in your case.

*When a user hits one of your LOB web sites for the first time, he should be "enrolled" in the LOB database.  A LOB user record is inserted.  Use the access token to call the identity server to get any demographic information your LOB site will need.

*When a user hits one of your LOB web sites for the Nth time, you can use the access token to call the identity server and get the most recent, up-to-date demographic information, just in case any of it has changed since his last visit. You can then store this information in the LOB user table so that it is available to you offline, e.g. if you need to push marketing emails you'll have a copy of the email address.
The advantage of this approach is separation of concerns and the ability to support more than one authentication provider (e.g. in the future you could support Facebook or Google+ logins as well).
Also you avoid any dependencies between the identity server and the LOB servers, so you can add or remove lines of business as needed, and you keep the identity server nice and lightweight.


Q: Checking if a directory exists in Linux using perl
I am programming in linux using perl. I am creating a program where a user can input a directory and a filename. The program will then check if the given directory exists or not and also searches the given filename in that directory. But my problem is verifying if the inputted directory is valid.

A: You must have specified if the path to the directory is absolute or relative. If it is absolute, you can check with -e to see if it exists and with -d if the input given it is a directory or not.
if ( -e $dir and -d $dir) {
    print "\nyour folder exists";
}

If the path is relative, then you must create the absolute path. For that you will have to use as $base your drvives (you need to do that for each drive) and after, use rel2abs to find an absolute path for the given relative path. If the folder exists, $abs_path will contain the absolute path, else it's value will be undef. Bellow as an example for searching your folder with a relative path on drive c:\:
$base = 'c:\';
$abs_path = File::Spec->rel2abs( $relative_path ) ;
$abs_path = File::Spec->rel2abs( $relative_path, $base ) ;
if ( defined $abs_path ) {
    print "\n folder exists ";
}

For more options, see perldoc -f -X


Q: Python - filtering in Django I'm new in python/django and i have a problem, i'm trying to use checkbox filtering in my html table and i don't really know how to do it.
This is what i have now
I want to add these
models.py
class Tags(models.Model):
    tag_frequency = models.CharField(max_length=250)

views.py
@login_required(login_url='/login/')
def index(request):
    title = 'Tags'
    all_tags = Tags.objects.all()
    return render(request, 'tag/index.html' ,{'all_tags':all_tags, 'title':title})

How do i use filter with these, i tried something like this but doesn't work:
LF = 125 - 134.2 KHz
HF = 13.56 MHz
UHF = 860 - 960 MHz

LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2)

A: In order to make your query works, you have to change your field to FloatField:
class Tags(models.Model):
    tag_frequency = models.FloatField(default=0.00, null=True, blank=True)

Set null, blank and default values based on your needs.
Then, put your checkboxes (or radio inputs) in your html form like this:
<form action="" method="post">

<input type="checkbox" name="is_lf" id="input_lf"> LF

<input type="checkbox" name="is_hf" id="input_hf"> HF

<input type="checkbox" name="is_uhf" id="input_uhf"> UHF

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

Then in your view, you can try something like this:
def form_view(request):
    if request.method == 'POST':
        # these strings come from HTML Elements' name attributes
        is_lf = request.POST.get('is_lf', None)
        is_hf = request.POST.get('is_hf', None)
        is_uhf = request.POST.get('is_uhf', None)

        # Now make your queries according to the request data
        if is_lf:
            LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2)

        if is_hf:
            # another query here

        # and rest of your view


Q: How to have MySQL return multiple column of values based on a different benchmark? I have a MySQL database table (sales) consisting of sales data with their dates.
| Sales ID |    Date     | Values |
|---------------------------------|
| 1        | 01/01/2020  |  1,500 |
| 2        | 02/01/2020  |  2,000 |
| 3        | 07/02/2020  |  1,000 |
| 4        | 12/03/2020  |  2,000 |
| 5        | 21/06/2020  |  1,000 |
| 6        | 11/08/2020  |  4,200 |

I have a SQL query that relies on a specific date benchmark.
```
SET @benchmark = "31/01/2020";

SELECT SUM(Values) FROM sales
WHERE (date < @benchmark);
```

This query supposedly returns only one numeric value. Now I set the condition to be dependant on the benchmark. The problem is, I don't want this benchmark to stay constant. I need the query to return 14 values for each end of month benchmark from January 2020 to February 2021.
So the result would probably be something like this,
|              SUM(Values)            |
|-------------------------------------|
|(result for benchmark = "31/01/2020")|
|(result for benchmark = "29/02/2020")|
|(result for benchmark = "31/03/2020")|
                   ⋮
|(result for benchmark = "31/01/2021")|
|(result for benchmark = "28/02/2021")|

Which sets the benchmark for every end of the month. Note that I do not have access to CREATE anything.
I was thinking of a while loop or a temporary table, but those require me to CREATE something which always returns "Error Code: 1142. CREATE command denied to the user ...." or "Error Code: 1044. Access denied for the user ....".
Thanks for any help or feedback.

A: You can list the dates you want and aggregate:
select m.eom, sum(s.sales)
from (select '2020-01-31' as eom union all
      select '2020-02-29' union all
      . . .
     ) m left join
     sales s
     on s.date < m.eom
group by m.eom;

Note that you can also generate the dates using a recursive CTE or calendar table.
For this particular query, you could also use a cumulative sum:
select last_day(date) as eom, sum(sales),
       sum(sum(sales)) over (order by last_day(date))
from sales
group by eom;

That works for your particular example, but might not work for other logic.


Q: do a task for each server from a specific group I have a host file with:
[synology]
192.168.1.111 ansible_sudo_pass='dfg78G67'

[web]
139.59.xx:8682 server_name=do1 sql_server_id=1 sql_auto_increment_increment=1
139.59.xx:8682 server_name=do2 sql_server_id=2 sql_auto_increment_increment=2

For each server I have his ssh public key
I would like to add it to my synology
- name: "Add ssh key"
   authorized_key: user=admin key="{{ lookup('file', 'ssh_keys/id_rsa_{{ item.server_name }}.pub') }}"
   with_items: "{{ groups['web'] }}"

but Ansible responds
TASK [synology_init : Add ssh key] **********************
fatal: [192.168.1.111]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'server_name'"}

Thx

A: - name: "Add ssh keys"
  authorized_key: user=admin key="{{ lookup('file', 'ssh_keys/id_rsa_{{ hostvars[item].server_name }}.pub') }}"
  with_items: "{{ groups['web'] }}"


Q: Best way to support large dropdowns Say I have a report that can be restricted by specifying some value in a dropdown. This dropdown list references a table with > 30,000 records. I don't think this would be feasible to populate a dropdown with! So, what is the best way to provide the user the ability to select a value given this situation? These values do not really have categories and even if I subdivided (by having some nesting dropdown situation) by the first letter of the value, that may still leave a few thousand entries.
What's the best way to deal with this?

A: Search, don't categorise.
You can display the control as a simple text box, and when the user types in a few characters, you could pop up an autocomplete-like dropdown to select the final value. Here's a link to the jQuery plugin for autocomplete.

A: I really wouldn't have a 30,000 element drop-down. The GUI is supposed to make it easier on the user rather than harder.
If you have no other way to categorise the data other than alphabetically, you're not restricted to using a two-stage approach with just the first character. Make it reliant on the first two characters.
This would give you at most 676 (assuming alphas only) in the first drop-down and (on average) 44 in the second.
We've actually taken two approaches to this problem. BIRT (which we use) allows for cascading parameters which can easily run that second-level query whenever you change the first drop-down box.
However, some of our customers care absolutely zero for nice GUI stuff (other than the output of nice 9-point Verdana and beautiful charts to placate management, of course). They prefer a free-form text entry field where they can just type in "SYS_PAX_%" to change their queries.
Of course, these are the customers that know exactly what data is in their database and use values which lend themselves to categorisation with SQL LIKE clauses. Others prefer the ability to search.

A: I had this same question about 2 years ago concerning a asp.net dropdown box.
Trust me, don't even try it. Use the auto complete suggestions above. I've found that displaying anything above 5000 records tends to crash the browser.
Just my 2 cents.

A: +1 @pax.  Still i'd like to see a 30K dropdown!  :)
@JustAProgrammer, perhaps you could do a text box where people can type in the beginning of what they are looking for and you can filter as they type in.

A: If you're asking from a performance perspective rather than a usability perspective I would consider using a live-list approach that loads only a subset of the list items on demand as you scroll up or down.  If the user clicks down the list quickly, to say the middle, it will load another 10 elements corresponding to that position.  Both render time and load time will be much faster.
Like paging, but 'fluid'.

A: Auto complete drop down as suggested above is best to have. But it will require the users to have some idea about the type of entries to start with. If the users are familiar with data, go for it.
Alternatively, if you can categorize your data, then you can start with the categories first and then based on the selection you can populate the dependent drop down with actual values which will be a subset of original values.


Q: adding/embedding youtube videos in asp.net page I want to add youtube videos thumbnails to my asp.net website like the videos section in http://jtsplatmaster.com/. On this website, If you click the right thumbnails, video will start playing in the main section without page refresh. Which control so I need to use. I know that object tag can be used to embed youtube videos in asp.net page.
Please suggest.

A: I found this API http://youtube.codeplex.com/. May be helpful for someone in future.
Regards,
Asif Hameed


Q: Python Matrix Cyberpunk Solver I have input data like this:
4              #length of way
BD 1C BD 55    #way
5              #matrix size (5x5 now)
1C BD 1C 55 55 #matrix
55 55 55 1C 1C
E9 1C 55 55 E9
BD 1C 1C 1C BD
55 BD E9 55 1C

I need to print the right way to solving matrix. The rules of solving are this:

*

*At this input i have a BD 1C BD 55 code to find. I take the first line (1C BD 1C 55 55) and find BDin it. It is the 2nd element

*Now I take the 2nd vertical (BD 55 1C 1C BD) and find 1C in it. It can be 3rd and 4th. And that's my problem for now. The program should check the 3rd way and the 4th. As you can see, there is no BD element in the third line (E9 1C 55 55 E9), but there is a BD element at the fourth line (BD 1C 1C 1C BD). So it is the first element.

*Now i continue doing finding this untill i get all way. So i print the way and the answer for this input is 2 4 1 2. If there is more than one answer, I can choose any one.
Here is the visualisating
Here is my code.
arrway = []
waylen = int(input())
wayin = list(map(str, input().split()))
for i in range(waylen):
    arrway.append(wayin[i])
k = int(input())
array = [[0 for j in range(k)] for i in range(k)]

for i in range(k):
    a = list(map(str, input().split()))
    for j in range(k):
        array[i][j] = a[j]
ANS = []
##############
print(array)
# The array for the example is [['1C', 'BD', '1C', '55', '55'], ['55', '55', '55', '1C', '1C'], ['E9', '1C', '55', '55', 'E9'], ['BD', '1C', '1C', '1C', 'BD'], ['55', 'BD', 'E9', '55', '1C']]
#############
currentNum = 0
currentPos = 0
for i in range(waylen):
    currentElement = arrway[currentNum]
    if i % 2 == 0:
        for jk in range(k):  # horizontal
            if array[currentPos][jk] == currentElement:
                ANS.append(jk + 1)

                currentPos = jk
                currentNum += 1
    else:
        for jkl in range(k):  # vertical
            if array[jkl][currentPos] == currentElement:
                ANS.append(jkl + 1)

                currentPos = jkl
                currentNum += 1
##########
print(ANS)
# the ANS for example is [2, 3, 4, 1, 2] but no [2, 4, 1, 2].
##########

So, as you can see, the problem is about checking the right way of the several elements. Now my code have the two-dimensional array of matrix.
Hope you can help me. Thank you.

A: If your input is reasonably small, then you can try using recursion (however if the input is big, you might fail with a stack overflow).
You first call find_on_row giving it the whole list of way elements, the whole array, and also indices of the current way element we find (in the beginning it's 0) and the index of a row you want to search over (in the beginning it's 0, as you said).
find_on_row goes over all elements in the specified row, and for each elements that is equal to the needed way element it calls find_on_col function (since you have BD only once on the first row, the function find_on_col is called once with this column.
find_on_col does the similar thing - it goes over all elements in the specified column, looks for the next way elements and calls find_on_row for each match (2 times in this case, since 1C can be found twice on the first column.
These two calls now search the answer separately, one from the 3rd row, the other from the 4th row. They go until either the whole way is found (i.e. way_index is the maximum possible), or if there's no match for the current way elements (so no answer from this search path).
def find_on_row(way, array, way_index, row_index):
    if way_index == len(way): # found answer
        return []
    for col_index in range(len(array[0])):
        if array[row_index][col_index]== way[way_index]:
            candidate_answer = find_on_col(way, array, way_index + 1, col_index)
            if not candidate_answer is None: # unwind answer
                return [col_index] + candidate_answer
    return None

def find_on_col(way, array, way_index, col_index):
    if way_index == len(way): # found answer
        return []
    for row_index in range(len(array)):
        if array[row_index][col_index] == way[way_index]:
            candidate_answer = find_on_row(way, array, way_index + 1, row_index)
            if not candidate_answer is None: # unwind answer
                return [row_index] + candidate_answer
    return None

way = ['BD', '1C', 'BD', '55']

array = [['1C', 'BD', '1C', '55', '55'], ['55', '55', '55', '1C', '1C'], ['E9', '1C', '55', '55', 'E9'], ['BD', '1C', '1C', '1C', 'BD'], ['55', 'BD', 'E9', '55', '1C']]

print(f'Starting from first row the answer is {find_on_row(way, array, 0, 0)}')
# Starting from first row the answer is [1, 3, 0, 1]

It prints indices starting from 0, so to get your desired output you can increment each value by 1 (I don't do that, because it's more convenient to work with indices starting from 0)


Q: replace/fill columns base on agg of multiple columns I have a DF as follows:
|   feat1 | feat2   | feat3    | feat4   | label |
|--------:|---------|----------|---------|-------|
|  0.1856 | -0.186  | 1.681    | 0.56781 |   0   |
| 0.78671 | 0.1761  | -0.671   | 0.176   |   0   |
|  -1.681 | 0.15689 | -0.18689 | 0.681   |   0   |

I want to replace the label column where the mean of all feat features is > 0. I tried this:
feat = [f for f in df.columns if "feat" in f]
df.loc[df[feat].mean() > 0, "label"] = 1

But it does not seem to work right.

A: You can use df.filter to filter all columns containing feat and calculate mean across axis=1 , and convert to int after comparison.
df['label'] = df.filter(like='feat').mean(1).gt(0).astype(int)
print(df)

     feat1    feat2    feat3    feat4  label
0  0.18560 -0.18600  1.68100  0.56781      1
1  0.78671  0.17610 -0.67100  0.17600      1
2 -1.68100  0.15689 -0.18689  0.68100      0


Q: U-Boot SPL Debug Messages I've been trying to get U-Boot SPL to print debug messages.  I've noticed plenty of debug() functions that aren't printing to the serial console, however when I define the DEBUG preprocessor macro, I still don't see those messages.
Is this something the SPL can even do?  Especially since the serial console is initialized in preloader_console_init() can any messages be sent before that function is executed?

A: Assuming that your UART is configured correctly, you should see messages once preloader_console_init has been run.  Prior to that, you can (depending on your platform) see about getting DEBUG_UART to function in your environment.


Q: How do I make sections with different sizes in a rectangle/box? I was inspired by how HAL is shown in this picture and would like to make something that is more or less the same in latex.

This is my current code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfgantt}
\usepackage{float}

\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{darkgray}{rgb}{0.66,0.66,0.66}
\definecolor{black}{rgb}{0,0,0}
\definecolor{white}{rgb}{1, 1, 1}

\tikzset{block/.style={rectangle, draw, fill=gray!50,
text width=10em, text centered, rounded corners=0pt, minimum height=0em}}

\title{boxes}
\date{February 2020}

\begin{document}

\maketitle

\begin{figure}[H]
        \centering
        \begin{tikzpicture}
        \node[block, minimum height=2cm, xshift=2cm] (task) {Tasks};
        \node[block, minimum height=2cm, fill=darkgray!150, below=of task, yshift=1cm] (executive) {Executive};
        \node[block, minimum height=3cm, yshift=1cm, below=of executive] (driver) {Drivers};
        \node[block, minimum height=1cm, below of=driver, xshift=0.53cm, text width=7em] (hal) {Hardware abstraction layer};
        \node[block, minimum height=2cm, below=of driver, yshift=1cm](hardware) {Hardware};

        \end{tikzpicture}

        \caption{\label{fig:Fig1_ecosystem}HALs place in the hierarchy of the executionpath}

    \end{figure}

\end{document}

This is the output:

A:
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{array}
\begin{document}
\renewcommand\arraystretch{2}
\begin{tabular}{m{2cm}p{2cm}}
\rowcolor{gray!20}\multicolumn{2}{c}{bla bla bla} \\
\rowcolor{gray}\multicolumn{2}{c}{bla bla bla} \\
\rowcolor{gray!20}\multicolumn{2}{c}{bla bla bla} \\
\rowcolor{gray!20}            & \cellcolor{gray!40}   bla bla bla bla bla bla     \\
\rowcolor{black}\multicolumn{2}{c}{\color{white} bla bla bla} \\
\end{tabular}
\end{document}


Q: Scroll to div with some px in less I find here in Stack Overflow a simple script written in jQuery which allows to have a smooth scroll to a specific div id, clicking a button:
$("#button").click(function() {
$('html, body').animate({
    scrollTop: $("#myDiv").offset().top
}, 2000);
});

Everything works perfectly, but I have a little problem: in the site I have a fixed menu, that clutters this script. When I click the button for scroll to a specific div, the menu takes a part of the div that I want to see (overwrap the div), so the div is not visible to 100%.
I want to ask if there is a manner to scroll to a specific div removing some px, equivalent to the height in px of the menu.
Example:
Page:

I click the button, and I get this effect:

But I want this effect:

A: Just get the height of the menu bar and subtract it from the offset like for example if the menu is 60px

$("#button").click(function() {
$('html, body').animate({
    scrollTop: $("#myDiv").offset().top-60
}, 2000);
});


Q: Attempting to access the member of a struct through a property on an enclosing class I get an error when trying to run this code. I can't seem to find the root cause.
    public class MyClass
    {
        public MyClass()
        {
            ListView listView;
            listView = new ListView();
            listView.Size.Width = 5;

        }
    }

A: Try
listView.Width = 5;

or
listView.Size = new Size(5, listView.Height);

Size is a struct, so accessing its property will get a copy of it; hence modifying it is not actually modifying the original struct. You're modifying the copy of it. So compiler complains that this is not what you intended.

A: Try the following lines instead.
ListView lvi = new ListView();
MyStruct ms;
ms.Width = 5;
lvi.Size = ms;


Q: homepage olderposts link showing page not found I am using WordPress 3.5.1 version, now I had a problem with olderposts link present at bottom of homepage. it is ok with rest of the category pages.
I am working on this problem since last two days, please somebody help me
i changed the settings > reading, changed htaccess but the problem was not solved.
I deactivated all the plugins and it didn't solve the problem.
i need somebody to help me.
my permalink structure is: http://www.orclage.com/sample-post/
my website name:
http://www.orclage.com
when i click olderposts the page is moving to
http://www.orclage.com/page/


Q: Log vscode command execution for shortcuts mapped to multiple commands Is there a way to find what vscode command was executed. For example, 'tab' is a keyboard shortcut for a lot of commands (depending on the context). Now I wish to find a way to display which specific command was pressed (insertSnippet or insertNextSuggestion or something else...) in the console or anywhere


Q: Insert "element" among other "elements" of the array (loop) php my code causes the images to appear randomly within the page.
But how to insert an "element" (in my case would be a div) between these images?
<?php
$myImagesList = array (
    'image1.png',
    'image2.png',
    'image3.png',
    'image4.png'
);

shuffle ($myImagesList);
for ($i=0; $i<4; $i++) {

echo '';
}
?>

Example:
The original code displays the images as follows:
image3.png image4.png image2.png image1.png
F5 refresh page
image2.png image1.png image4.png image3.png
F5 refresh page
image4.png image2.png image3.png image1.png

I needed it this way:
image2.png image1.png
 content
image4.png image3.png
F5 refresh page
image4.png image2.png
 content
image1.png image3.png
F5 refresh page
image2.png image3.png
 content
image4.png image1.png

A: You would want something like this...
 $myImagesList = array (
    'image1.png',
    'image2.png',
    'image3.png',
    'image4.png'
 );
 shuffle ($myImagesList);

 $i = 0;
 foreach ($myImagesList as $img) {

    $i++;

    if ($i % 3 === 0) { /* show content */ }

    echo '';

 }

This will give you the content section every third iteration, no matter the size of the list.

A: If you want to add a div(content) between those two pairs of images - add additional condition into your loop:
...
for ($i=0; $i<4; $i++) {
    if ($i == 1) echo '
some content ...
';
    echo '';
}

A: Go with the most readable solution - the one that doesn't make you fall and debug later when changing something.
$splitAtNumber = 2; // or dynamically use count($myImagesList) / 2 or ....

// output first part of the array
for ($i = 0; $i < $splitAtNumber; $i++) {
    echo '';
}

// Output your content
echo 'content';

// Output second part of the array
for ($i = splitAtNumber; $i < count($myImagesList); $i++) {
    echo '';
}


Q: Convert first order ODE system into a complex ODE Consider the first-order ODE system for the vector $X = (x,y) \in \mathbb{R}^2$ ,
$$
\frac{d}{dt} X(t) = (r + R_{\pi/2}) \nabla U = r  \nabla U + R_{\pi/2} \nabla U
$$
where $R_{\pi/2}$ is the $2\times 2$ rotation matrix of $\pi/2$ in the anti-clockwise direction, i.e.
$$ R_{\pi/2}(a,b)=(-b,a) \, ,$$
$r$ is a real number and $U(x,y)$ is a potential in the plane.
Hence, $R_{\pi/2}\nabla U$ is just the gradient of $U$ rotated by 90-degrees (since the gradient is orthogonal to the level sets of $U$, if $r=0$ this means that $X$ moves along the level sets of constant $U$).
I wonder if it is possible to see this equation as an ODE for the complex variable $\Phi(t) = x(t)+i y(t)$. If we represent everything in the complex plane, then $R_{\pi/2} \sim i$ because both perform a rotation by 90-degrees, and we should have
$$
\frac{d}{dt} \Phi(t) = (r + i) F(\Phi)
$$
where $F=f( x,y)+i g(x,y)$ is an appropriate complex function (say that $\nabla U = (f,g)$). However, it is not clear to me if this can always be safely done, or I am missing some subtleties...
If the answer is "yes, it can be always done", does $F$ have some nice property since it stems from the gradient of a real function?
(Feel free to assume all the nicest properties for $U$.)


Q: OpenCV Surf and Outliers detection I know there are already several questions with the same subject asked here, but I couldn't find any help.
So I want to compare 2 images in order to see how similar they are and I'm using the well known find_obj.cpp demo to extract surf descriptors and then for the matching I use the flannFindPairs.
But as you know this method doesn't discard the outliers and I'd like to know the number of true positive matches so I can figure how similar those two images are.
I have already seen this question: Detecting outliers in SURF or SIFT algorithm with OpenCV and the guy there suggests to use the findFundamentalMat but once you get the fundamental matrix how can I get the number of outliers/true positive from that matrix? Thank you.

A: Here is a snippet from the descriptor_extractor_matcher.cpp sample available from OpenCV:
if( !isWarpPerspective && ransacReprojThreshold >= 0 )
    {
        cout << "< Computing homography (RANSAC)..." << endl;
        vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
        vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
        H12 = findHomography( Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold );
        cout << ">" << endl;
    }

    Mat drawImg;
    if( !H12.empty() ) // filter outliers
    {
        vector<char> matchesMask( filteredMatches.size(), 0 );
        vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
        vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
        Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);

        double maxInlierDist = ransacReprojThreshold < 0 ? 3 : ransacReprojThreshold;
        for( size_t i1 = 0; i1 < points1.size(); i1++ )
        {
            if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier
                matchesMask[i1] = 1;
        }
        // draw inliers
        drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask
#if DRAW_RICH_KEYPOINTS_MODE
                     , DrawMatchesFlags::DRAW_RICH_KEYPOINTS
#endif
                   );

#if DRAW_OUTLIERS_MODE
        // draw outliers
        for( size_t i1 = 0; i1 < matchesMask.size(); i1++ )
            matchesMask[i1] = !matchesMask[i1];
        drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), matchesMask,
                     DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
#endif
    }
    else
        drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );

The key lines for the filtering are performed here:
if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier
                matchesMask[i1] = 1;

Which is measuring the L2-norm distance between the points (either 3 pixels if nothing was specified, or user-defined number of pixels reprojection error).
Hope that helps!

A: you can use the size of the vector named "ptpairs" in order to decide how similiar the pictures are.
this vector contains the matching keypoints, so his size/2 is the number of matches.
i think you can use the size of ptpairs divided by the total number of keypoints in order to set an appropriate threshold.
this will probably give you an estimation to the similiarty between them.


Q: Terminate a process and close all its opened listening ports On my Qt application, I run an external executable on a separate process like this:
QProcess *server = new QProcess();
server->start("./server.exe");

External executable starts a server on 127.0.0.1 listening on port 18383.
Then at some point, I terminate the process like this:
server->terminate();

The problem is that by terminating the server process, many times its used port i.e. 18383 remains open. Consequently, when I try to start the server again, I receive these errors:

"Server -2 Could not setup server. listen tcp :18383: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

How can I terminate the process and close all its opened listening ports?

A:
sometimes I receive these errors while terminating the process:
  QProcess: Destroyed while process (" ... server.exe ...") is still
  running

It seems you are not waiting for the process to gracefully terminate.
Here is a generic way to terminate a process you launched :
server->terminate();
server->waitForFinished(timeoutMS);
if (server->state() == QProcess::Running) {
     server->kill();
}

Terminate will send a polite "can you please stop" signal, kill will abruptly stop the target process. How much time does it take for the server to shut down (it may be several seconds)? so you should have a generous timeout period which take this in account.


Q: Función distinta cuando hago click en un div Tengo el siguiente ejercicio de jQuery, he estado  buscando funciones y no he encontrado nada, el ejercicio es el siguiente.
Crea un div de 800x70 con background gris, que al hacer click se ponga 250x250 y al hacer click de nuevo, vuelva a su tamaño original.
Hasta ahora he conseguido que al hacer el primer click si que se cambie al tamaño pedido en el ejercicio (mediante cambio de clases en CSS) pero no consigo encontrar la forma de que cuando haga el segundo click me vuelva estar por defecto.

A: Puedes poner y quitar la clase con los estilos que necesitas usando toggleClass, por ejemplo

 $('#myDiv').on('click', function(e){
    $(this).toggleClass('mutedDiv');
  });
#myDiv{
  width: 800px;
  height: 700px;
  background-color:gray;
}

.mutedDiv{
  width: 250px!important;
  height: 250px!important;
}

Asi cada vez que le des click al div o contenedor que selecciones pondrá o quitara la clase respectivamente si ya la posee o no

A: Cuando haga click, cambiale o añadele una nueva.
Luego a traves de jquery cuando haga click, comprueba si lleva una clase u otra y en funcion de la clase que lleve haces lo que tengas que hacer.
$( "#id_que_buscas" ).on( "click", function() {
  if ($(this).hasClass("pepito")){
     $(this).addClass("juanito");
  }else{
     $(this).removeClass("pepito");
  }
});


Q: BSOD при работе программы под .NET 4.6.2 Есть программа ("Электронной очереди") написанная на C# под фреймворк .NET 4.6.2
Программа должна постоянно крутится на сервере, но стали поступать жалобы, что компьютер перезагружается несколько раз в день, снял дамп, там присутствует постоянно 1 ошибка
SYSTEM_SERVICE_EXCEPTION 0x0000003b. driver ntoskrnl.exe

Погуглив данную ошибку я нашел, что в причина скорее всего в железе (видео карты, память, HDD).
Моя программа также использует железо.
Я хотел спросить, может ли данный BSOD быть из за ошибок в коде, или это исключено и в любом случае будет только Exception уровня приложения.
1.
Программа использует сетевую карту.
4 терминала по выдаче билетов, подключены по TCP/IP
2.
Программа использует 2 USB порта:
Конверторы RS-485 в USB, к ним подключены кассовые планшеты
3.
Карта передающая видеобуфер.
Через эту карту подключены табло, через спец программу (Mars)
происходит захват видео буффера с областей экрана, эти области и идут на табло.
Карта вставлена в PCI слот и подключается как монитор по DVI.
4.
Вывод звука через встроенную звуковую карту.
Из низкоуровневых библиотек я использую Naudio.dll (Подтягивал через Nuget).
Объект важный, хотелось бы услышать ваши мнения.

A: Исключение SYSTEM_SERVICE_EXCEPTION означает проблему при переходе из кода уровня пользователя в код уровня ядра. Она может возникать например, из-за того, что данные, переданные модулю ядра, были каким-то образом повреждены и не было предусмотрено проверки их корректности. Parameter 1 у BSOD - код исключения, 0xC0000005 соответствует STATUS_ACCESS_VIOLATION, т.е. произошла попытка обратиться к защищенной области памяти.
Причиной может быть как дефект железа, так и ошибка в коде драйвера (ошибка в коде .Net приложений напрямую обычно не вызывает такое исключение). Поскольку драйвера видеоадаптеров в Windows разделены на модули уровня ядра и уровня пользователя, наибольшее подозрение падает именно на них.
Для диагностики проблемы можно попробовать следующее:

*

*Настроить windbg на правильные символы и попытаться получить стек вызовов и список загруженных модулей. Это поможет выявить, какие именно драйвера вызывают проблему.

*Обновить драйвера до последних версий.

*Те драйвера, которые уже были недавно обновлены, наоборот попробовать откатить на предыдущую версию (т.к. в новой версии могла появится ошибка). Если проблема не исчезнет, вернуть новую версию.

*Заменять компоненты железа на заведомо исправные, и смотреть, на каком исчезнет ошибка.


Q: Charge Conjugation to Analyze CPT Invariance Source: http://hyperphysics.phy-astr.gsu.edu/hbase/Particles/cpt.html#:~:text=Charge%20conjugation(C)%3A%20reversing,like%20momentum%20and%20angular%20momentum.
In the image below, reaction (1) shows CP conservation whereas reaction (2) does not. Does this have to do with the fact that the charge conjugation of the RHS of the reaction 1 is $(-1)(-1)=1$ whereas the charge conjugation of the RHS of reaction 2 is $(-1)(-1)(-1)=-1$, which is not equivalent to the RHS Conservation of Charge C or $(1)(1)(1)=1$?
Is this how one would check for charge conjugation?

A: Yes. More precisely, the neutral pion $\pi_0$ is an eigenstate of the charge conjugation operator $\mathcal{C}$, with eigenvaue $+1$. A photon is also an eigenstate of this operator but with eigenvalue $-1$.
The eigenvalue for a multiparticle state is given by the product of the eigenvalues of each individual particle (given that those particles are eigenstates themselves). So for an even number ($2n$) of photons, the C-parity of the system would be $(-1)^{2n}=+1$. Conversely, for an odd number ($2n+1$) of photons we have that the C-parity is $(-1)^{2n+1}=-1$.
To check whether Charge conjugation allows a certain transition you can then compare the C-parity of the initial an final states, as you have done. The transition is allowed by the Charge conjugation symmetry if and only if both eigenvalues are the same.


Q: Rails: Convert future meeting time in one time zone to another time zone Using flatpickr, I allow the user to specify the time and date of a future meeting that includes their time zone.
The result is the following value:
Mon May 25 2020 12:00:00 GMT-0600 (Mountain Daylight Time)
They can choose a team member to meet with and that time member will have set their current time zone and I'm storing that value using ActiveSupport::TimeZone (https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html)
I am trying to figure out how to take the date result above and display to the user who is scheduling the meeting, "It will be 7pm for X."
I send the attendeeZone and meetingTime to a Rails endpoint:
  def time_for_attendee

    attendeeZone = params["attendeeZone"]
    # => "Tokyo"

    meetingTime = params["meetingTime"]
    # => "Mon May 25 2020 12:00:00 GMT-0600 (Mountain Daylight Time)"

    attendeeTime = ???

    render json: {
      attendeeZone: attendeeZone,
      meetingTime: meetingTime,
      attendeeTime: attendeeTime
     }

  end

How would I convert that meetingTime to the attendeeTime based on their time zone?
I got close with Time.zone.now.in_time_zone(attendeeZone) but I'm not sure how to convert the format of meetingTime to replace now.

A: It's .parse()
Time.zone.parse(params["meetingTime"]).in_time_zone(attendeeZone)

Alternatively, if you assign it to a model, then it will be parsed automatically already.


Q: java.util.MissingResourceException I am getting below exception while running an application. This application read abc.properties file,

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name abc, locale en_US
    at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:853)
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:822)
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:566)
    at com.ibm.dst.DailyExtract.getResourceBundle(DailyExtract.java:104)
    at com.ibm.dst.DailyExtract.main(DailyExtract.java:131)

abc.properties file reside at the workspace.
I am using RSA7 as IDE, is there any setting problem?
any suggestions are welcome.....
Thanks a lot in advance

A: You just need to add the package name while getting the file
For example if your properties name is "ABC.properties" in package a.b.c then the below code will work perfectly
ResourceBundle labels = ResourceBundle.getBundle("a.b.c.ABC");

A: Just copy the resource file over to where your class files are.
In my case my directory was:
bin
  - com
     - brookf
        - all my packages here.

copy your resource file to the bin folder.

A: Follow the hints in this post and see if you made one of those mistakes, which could be (copy pasted from the link):

*

*These resource properties files are loaded by classloader, similar to java classes.  So you need to include them in your runtime classpath.

*These resources have fully-qualified-resource-name, similar to a fully-qualified-class-name, excerpt you can't import a resource into your java source file.  Why? because its name takes the form of a string.

*ResourceBundle.getBundle("config") tells the classloader to load a resource named "config" with default package (that is, no package).  It does NOT mean a resource in the current package that has the referencing class.

*ResourceBundle.getBundle("com.cheng.scrap.config") tells the classloader to load a resource named "config" with package "com.cheng.scrap."  Its fully-qualified-resource-name is "com.cheng.scrap.config"

A: Loading the Properties file for localization stuff is also affected by the package naming. If you put your Properties file in a package like org.example.com.foobar and load it just by its name abc you have to add the prefix org.example.com.foobar, too. If you have the properties at a different location (like in the root directory or in another subdir) you have to change either the name to load or the classpath.
I run fine in placing the properties file in the same location where the .java file is and using something like
private static ResourceBundle RES = ResourceBundle.getBundle(NameOfTheCurrentClass.class.getCanonicalName());

A: I had the same issue today and it took me a while until I figured out a fix (I'm using Eclipse as an IDE). My project folder contains the *.properties-Files in the following path:
project/src/strings

Since strings is a sub-folder of src and src is already in the build path of the project (see Property Window), all I needed was to add an Inclusion-Pattern for the *.properties-Files:
**/*.properties

There should be already an Inclusion-Pattern for *.java-Files (**/*.java)
Maybe there is something similar for your IDE

A: Is the file in your classpath? If it is, try renaming it to abc_en_US.properties


Q: Signal handlers reset every time I'm writing a C program that does the following:
Monitors which signals are sent to it. Counts how many times SIGUSR1 and SIGUSR2 have been sent. Terminates when SIGTERM has been sent but first prints out how many times SIGUSR1 and SIGUSR2 have been sent.
Please note that this is a problem from class, so it's not supposed to really have any usage, just to test us. Also, no other signals except for the mentioned three will be sent.
This is what I got:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int sigUsr1Count = 0;
int sigUsr2Count = 0;

static void sighandler(int signum){
    switch(signum){
        case SIGUSR1:
            sigUsr1Count++;
            break;
        case SIGUSR2:
            sigUsr2Count++;
            break;
        case SIGTERM:
            printf("%d %d\n", sigUsr1Count, sigUsr2Count);
            exit(0);
    }
}

int main(int argc, char ** argv){
    pid_t mypid = getpid();
    fprintf(stderr, "My PID is %d\n", mypid);

    struct sigaction sa;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sa.sa_handler = sighandler;
    iAssert(-1 != sigaction(SIGUSR1, &sa, NULL), "sigaction1 failed");
    iAssert(-1 != sigaction(SIGUSR2, &sa, NULL), "sigaction1 failed");
    iAssert(-1 != sigaction(SIGTERM, &sa, NULL), "sigaction1 failed");

    while(true){
        fprintf(stderr, "Waiting...\n");
        sleep(3);
    }

    return 0;
}

I've read on a forum somewhere that, when using sigaction, signal handlers will NOT be reset to default unless the sa_flags field is set to SA_RESETHAND. However, that does not seem to be the case with me. (The man page describes the SA_RESETHAND flag but is not explicit about the action in the situation where it's omitted.)
When I run the program, it will only go to my handlers the first time SIGUSR1 or SIGUSR2 are sent, after that the program terminates with the message:
User defined signal 1 (or 2)

In that sense, the program only outputs the correct values if either: SIGUSR1 and SIGUSR2 haven't been sent at all, or each of them has been sent at most once.
The iAssert macro & function:
#define iAssert(cond, msg) crash(cond, msg, __LINE__)
void crash(bool cond, char * msg, int line){
    if(!cond){
        perror(msg);
        fprintf(stderr, "at line %d\n", line);
        exit(EXIT_FAILURE);
    }
}

Compilation methods that I've already tried (same with each of them):
gcc 1.c
gcc -std=c99 1.c
gcc -std=c11 1.c

Any ideas?
Thanks.

A: Well since all the comments turned out to be equally useless (no offence), I've decided to take a different approach.
Instead of sigaction I've used the signal system call. I've also modified a few other things. Since printf is not a signal-safe function I've introduced a global variable named shouldStop which is by default set to false and then changed to true with SIGTERM handler. The printing is then done inside the main function.
Here's the code:
int sigUsr1Count = 0;
int sigUsr2Count = 0;

bool shouldStop = false;

static void sighandler(int signum){
    switch(signum){
        case SIGUSR1:
            sigUsr1Count++;
            break;
        case SIGUSR2:
            sigUsr2Count++;
            break;
    }
}

static void termhandler(int signum){
    shouldStop = true;
}

int main(int argc, char ** argv){
    pid_t mypid = getpid();
    fprintf(stderr, "My PID is %d\n", mypid);

    iAssert(SIG_ERR != signal(SIGUSR1, sighandler), "signal1 failed");
    iAssert(SIG_ERR != signal(SIGUSR2, sighandler), "signal2 failed");
    iAssert(SIG_ERR != signal(SIGTERM, termhandler), "signal3 failed");

    do{

    }while(!shouldStop);
    printf("%d %d\n", sigUsr1Count, sigUsr2Count);

    return 0;
}

And it works fine the way I wanted it.
Thanks anyway.


Q: Mysql throwing query error yet finishing query just fine-why? I am getting
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result
resource in *filename* on line 81

While running a query to build a chart.  The query gets data from the mysql db and uses it to build the chart.
Usually, I get this error and go to the code and find where I've screwed up, fix it, and move on.  The tricky part about this problem is that the query is actually running and the chart is being built and displayed accurately.  Why is my server (localhost on xampp) telling me that the query result is bad when it can utilize the resource just fine?
Here is the full query:
$chart=array();
    $roll=array();
    //select used terms
    $rosh=mysql_query("select distinct term from search_terms");

    while($roshrow=mysql_fetch_assoc($rosh)){
        extract($roshrow);
            $roll[]=$term;
        }

        //select term_number for each term
        foreach($roll as $sterm){
            $termarray=array();
                  **//following is line 81**
            $bashq="select term_number from search_terms where term ='$sterm'";
            $bash=mysql_query($bashq);
            while($brow=mysql_fetch_assoc($bash)){
                extract($brow);
                //put results into array to sum
                $termarray[]=$term_number;
            }
            $termsum=array_sum($termarray);

        //put term=>number array for chart script
            $chart[$sterm]=$termsum;

        }
        //sort array so high numbers at beginning
        arsort($chart);

        //slice top 10 terms
        $chart=array_slice($chart,0,10);

A: Do this:
$rosh=mysql_query("select distinct term from search_terms")
  or die("Error with query: " . mysql_error());

and this:
$bash=mysql_query($bashq)
  or die("Error with query: " . mysql_error();

That will tell you when it fails. You are correct though, you're getting that message because mysql_query has returned "false" and isn't a valid result resource.

A: Because your querying within a loop, one of the terms isn't processed (probably because search_terms is missing rows for that specific turn. Which is odd, since you're querying the same table.
However, since it's a Warning, and not a fatal Error, it will still continue.
Either way, it's seems like wrong way to pulling your data, you can probably do taht with one query, adequate sorting (ORDER BY) directly in the SQL server, GROUP BY and SUM() for getting the sum of your terms.
You should read up on your SQL instead :)

SELECT term, SUM(term_number) as term_sum
FROM search_terms
GROUP BY terms
ORDER BY term_sum DESC
LIMIT 10

then just copy it to your hashtable and it should already be sorted, aswell as limited to 10 entries.


Q: How to redirect a URL without a query string to a URL with a query string? I've looked around for the answer to my question but only to be confused even more. I'm hoping somebody can help me...
I need to redirect this URL:
http://www.testsite.co.uk/ecommerce/cabinets/aluminium_cabinets

To:
http://www.testsite.co.uk/products/cabinets/?types[]=illuminated-aluminium-cabinets&types[]=non-illuminated-aluminium-cabinets

Please help :)

A: Try :
 RedirectMatch ^/ecommerce/cabinets/aluminium_cabinets/?$ http://www.testsite.co.uk/products/cabinets/?types[]=illuminated-aluminium-cabinets&types[]=non-illuminated-aluminium-cabinets


Q: Android alert dialog blank space when setting a view I have a question. I made an alert dialog that is showing an message and view with a "do not show again" check-box. When i'm running this app on android KK it is displaying fine, however when I run it on android JB it is showing me a blank space like on this image(i also get this blank space when the view contains only a linear layout with a height of 0dp):
http://foto.modelbouwforum.nl/images/2014/08/15/Screenshot2014-08-15-14-33-40.png
My code of the alert dialog:
final SharedPreferences sharedPreferences=getSharedPreferences("appPrefs", Context.MODE_PRIVATE);
        if(!sharedPreferences.getBoolean("isTutorialMainScreenChecked", false)){
            View checkBoxView = View.inflate(MainScreenHandler.this, R.layout.checkbox_alert_dialog,null);
            checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setMessage(getString(R.string.alertDialog_main_screen_tutorial));
            builder.setCancelable(false);
            builder.setView(checkBoxView);
            builder.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if(checkBox.isChecked()){
                                SharedPreferences.Editor editor=sharedPreferences.edit();
                                editor.putBoolean("isTutorialMainScreenChecked", true);
                                editor.commit();
                            }
                            dialogInterface.dismiss();
                        }
                    });
            builder.setNegativeButton(getString(R.string.alertDialog_cancel),
                    new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialogInterface, int i){
                            dialogInterface.cancel();
                        }
                    });
            alertDialog = builder.create();
            alertDialog.show();

And here is my checkbox layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:orientation="vertical"
             android:baselineAligned="false">
    <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#ffff3bb2"/>

    <CheckBox
            style="@android:style/TextAppearance.Small"
            android:textColor="#ff000000"
            android:text="@string/alertDialog_checkbox_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkbox"/>
</LinearLayout>

Thanks in advance
P.s:
This is how it looks on android KK:
http://foto.modelbouwforum.nl/images/2014/08/15/QuickMemo2014-08-15-14-42-41.png

A: I looked through sources of alert_dialog.xml layout in API 19 and found the following layout for inserting a custom view:
<FrameLayout android:id="@+id/customPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1">
    <FrameLayout android:id="@+android:id/custom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dip"
        android:paddingBottom="5dip" />
</FrameLayout>

Then I tried to set background to see which view takes the space. customPanel was colored in red, custom view was colored in green.
AlertDialog d = builder.create();
d.show();

View v = (View)d.getWindow().findViewById(android.R.id.custom).getParent();
v.setBackgroundColor(Color.RED);

This picture means that customPanel should have some paddings, or custom should have non-zero layout params or something else. After checking those attributes which were equal to zero I tried to test minimumHeight of the customPanel and got 192 on xxhdpi or 64dp. This setting cause the frame to be larger than a nested custom view.
I haven't figured out where this setting is applied, but here is the workaround:
AlertDialog d = builder.create();
d.show();

View v = (View)d.getWindow().findViewById(android.R.id.custom).getParent();
v.setMinimumHeight(0);

Tested on API 18,19.

A: In addition to vokilam's answer:
If you're using android.support.v7.app.AlertDialog.
Tested on API 27 (pretty sure this works on API 28 too)
The layout:
<FrameLayout
    android:id="@+id/contentPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="48dp">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Space
                android:id="@+id/textSpacerNoTitle"
                android:visibility="gone"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dialog_padding_top_material" />

            <TextView
                android:id="@+id/message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingEnd="?attr/dialogPreferredPadding"
                android:paddingStart="?attr/dialogPreferredPadding"
                style="@style/TextAppearance.Material.Subhead" />

            <Space
                android:id="@+id/textSpacerNoButtons"
                android:visibility="gone"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dialog_padding_top_material" />
        </LinearLayout>
    </ScrollView>
</FrameLayout>

<FrameLayout
    android:id="@+id/customPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="48dp">

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

The android:minHeight="48dp" for contentPanel and customPanel are causing the unwanted blank space.
Unwanted space dialog
What I did is:
alertDialog.SetView(view);
alertDialog.show();
...
View customPanel = (View) view.getParent().getParent();
if (customPanel != null)
    customPanel.setMinimumHeight(0);
View contentPanel = (View) alertDialog.findViewById(android.R.id.message).getParent().getParent().getParent();
if (contentPanel != null)
    contentPanel.setMinimumHeight(contentPanel.getMinimumHeight() * 2 / 3);

Result:
Blank space removed

A: Did you try playing around with paddings and margins?
You could copy your layout in res/layout-vXX and set a specific (negative) margin.


Q: QueryDSL DateTime field formatted projection I trying to do a query that returns the date and time part of a Datetime field using QueryDSL.
The query in plain SQL looks like this:
select convert(varchar, FELectura, 103) as sDate,
       convert(varchar, FELectura, 108) as sTime
from dbo.T2_LecturaEstacionClima;

Where FELectura is a DateTime field and the Database is SQL Server 2012.
This query gives the following output:
sDate                          sTime
------------------------------ ------------------------------
02/01/2012                     00:00:00
02/01/2012                     01:00:00
02/01/2012                     02:00:00
02/01/2012                     03:00:00
02/01/2012                     08:00:00
02/01/2012                     09:00:00
02/01/2012                     10:00:00

How can i achieve this same output using QueryDSL?

A: If you use Querydsl SQL this should work
Expression<String> dateExpr = Expressions.stringTemplate("convert(varchar, {0}, 103)", table.feLecutra);
Expression<String> timeExpr = Expressions.stringTemplate("convert(varchar, {0}, 108)", table.feLectura);
List<Tuple> results = query.from(table).list(dateExpr, timeExpr);

And to access the columns from a Tuple instance
String date = tuple.get(dateExpr);
String time = tuple.get(timeExpr);


Q: No content after smarty gzip filter I tried smarty gzip plugin smarty gzip plugin.
    $stpl->loadFilter('output','gzip');
$stpl->display('file:'.$cnf->site_root.$cnf->client_tpl_path.$slang.'/main.tpl');

After this, my site look like that:

I don't know why my browser not decoded gzip.


Q: Encountering lag when updating a CardView item in a RecycleView i'm having an issue working with CardViews . I`ve created a CardView containing 1 TextView and 2 ImageViews , which gets displayed in an RecycleView . When i try to update the contents of one of the CardViews (created 5 cards for testing) the interface starts to lag when scrolling over the updated card, but goes back to normal when i pass the item. It only happens when ImageViews are present , when substituting the ImageViews for say, TextViews with some random text in them, it works normally.
Now, here's my code , after that i'll add some more information that could be causing it.
First , the Adapter class, which also contains the items class and List :
public class MovieDetailsAdapter extends RecyclerView.Adapter<MovieDetailsAdapter.MovieViewHolder> {

public List<MovieDetails> movieList;
private static final String TAG = "MyAdapter";

public MovieDetailsAdapter() {

    movieList = new ArrayList< MovieDetails>();
}

public void setItemCount(int count ,String title, Bitmap poster,Bitmap fanart ) {
    movieList.clear();
    movieList.addAll(generateDummyData(count, title, poster , fanart));

    notifyDataSetChanged();
}

@Override
public int getItemCount() {

    return movieList.size();
}

public void addItem(int position,String title, Bitmap poster, Bitmap fanart) {
   if (position > movieList.size()) return;

    movieList.add(position, generateDummyItem(title, poster, fanart));
   // notifyDataSetChanged();
    notifyItemInserted(position);
}

public void updateItem(int position, String title, Bitmap poster, Bitmap fanart) {
    if (position > movieList.size()) return;

    movieList.add(position, generateDummyItem(title, poster, fanart));
     notifyItemChanged(position);
  //  notifyDataSetChanged();
}

@Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.
            from(viewGroup.getContext()).
            inflate(R.layout.card_layout_movies, viewGroup, false);
    Log.d(TAG, "create header view holder");
    return new MovieViewHolder(itemView);
}

@Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {

    Log.d(TAG, "bind header view holder");
    MovieDetails mdet = movieList.get(i);

    movieViewHolder.vTitle.setText(mdet.Title);
    movieViewHolder.vPoster.setImageBitmap(mdet.imageViewPoster);
    movieViewHolder.vFanart.setImageBitmap(mdet.imageViewFanart);

    Log.d(TAG, "position: " + i + " holder: " + movieViewHolder + " text: " + movieViewHolder.vTitle);

}

public static class MovieViewHolder extends RecyclerView.ViewHolder {

    protected TextView vTitle;
    protected ImageView vPoster;
    protected ImageView vFanart;

    public MovieViewHolder(View v)
    {
        super(v);
        vTitle  = (TextView)  v.findViewById(R.id.title);
        vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
        vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);

    }

}

public static class MovieDetails {

    protected String title;
    protected Bitmap imageViewPoster;
    protected Bitmap imageViewFanart;

    public MovieDetails(String title, Bitmap imageViewPoster,Bitmap imageViewFanart )
    {
        this.title = title;
        this.imageViewPoster = imageViewPoster;
        this.imageViewFanart = imageViewFanart;
    }
}

public static MovieDetails generateDummyItem(String title, Bitmap poster, Bitmap fanart) {

    MovieDetails mov = new MovieDetails(title, poster, fanart);
    return  mov;
}

public static List< MovieDetailsAdapter.MovieDetails> generateDummyData(int count, String title , Bitmap imageViewPoster, Bitmap imageviewFanart) {

    ArrayList<MovieDetailsAdapter.MovieDetails> items = new ArrayList<MovieDetailsAdapter.MovieDetails>();

    for (int i=0; i < count; i++) {

        items.add(new MovieDetailsAdapter.MovieDetails(title, imageViewPoster, imageviewFanart));
    }

    return items;
}

}
Now, here is my main class , the activity class
public class MoviesListActivity extends AppCompatActivity {

public MovieDetailsAdapter ca = new MovieDetailsAdapter();
public RecyclerView recList;
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movies_list);
    RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recList.setLayoutManager(llm);
    button = (Button) findViewById(R.id.button);
    MyOnClickListener Listener = new MyOnClickListener();
    button.setOnClickListener(Listener);

    recList.setItemAnimator(null);

    Bitmap bittest1 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster_example, 640, 955);
    Bitmap bittest2 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart_example, 800, 450);

    ca.setItemCount(5, "TestingTitle", bittest1, bittest2);
    recList.setAdapter(ca);
}

public class MyOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:

                Bitmap bittest12 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster2, 640, 955);
                Bitmap bittest22 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart2, 800, 450);

                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();

                ca.updateItem(1, "test", bittest12, bittest22);
               // ca.addItem(1,"test",bittest12,bittest22);
                break;
            default:
                break;
        }
    }
}

//------methods used for resizing the images down to smaller ones before loading into memory---//

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
  }

And finally, not that i probably matters, my CardView XML.
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="@color/bkg_card"
        android:text="Movie Title"
        android:gravity="center_vertical"
        android:textColor="@android:color/white"
        android:textSize="14dp"/>

    <ImageView
        android:elevation="5dp"
        android:scaleType="fitCenter"
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:id="@+id/imageViewPoster"
        android:text="Poster"
        android:gravity="center_vertical"
        android:layout_below="@id/title"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"/>

    <ImageView
        android:id="@+id/imageViewFanart"
        android:scaleType="fitCenter"
        android:layout_alignBottom="@+id/imageViewPoster"
        android:layout_toEndOf="@+id/imageViewPoster"
        android:layout_width= "235dp"
        android:layout_height="122dp"
        android:layout_marginRight="5dp"/>

</RelativeLayout>

Now , somebody in another discussion showed me this as a possible cause : Why RecyclerView.notifyItemChanged() will create a new ViewHolder and use both the old ViewHolder and new one?
So i added the Log items inside the onBind and onCreate methods of the Adapter to see if that could be causing it, and indeed, it`s not just creatind one additional ViewHolders, but 3 of them, and each time i scroll over the newly updated card, it seems to be re-binding, the onBind method seems to be called each time.
Setting the animation to 'null' as per the solution in the thread doesn't seem to have any effect in my case, so maybe that`s not what is causing it.
Any ideas ?

A: Well, i solved it. It seems to happen only when i'm loading the images via the XML method, if i load them with a 3rd party library like Picasso, the lag seems to dissapear. Something like :
Picasso.with(context).load(MovieDetails.getPoster())
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(movieViewHolder.imageViewPoster);

inside the onBindViewHolder
and instead of passing around bitmaps, just pass a String for the URL or location of the image. And pass the Context to the Adapter class.


Q: Coloring the faces of a hypercube I will restate the 3-D version of the problem. In how many ways can you color a regular cube with 2 colors up to a rotational isometry. The answer is of course a special case of Burnsides Lemma which can be used to show that the number of distinct face permutations is $\frac{1}{24}(N^6 + 3N^4 + 12N^3 + 8N^2)$ where $N$ is the number of colors used, $2$ in this case, which gives us an answer of $10$ distinct permutations.
My question is how can you expand this to a tesseract, and then more generally, to any hypercube. The rotational isometries of a cube are somewhat simple to comprehend, but the rotational isometries o hypercube are difficult to grasp (even after an hour of playing with the 4d rubiks cube app)
My initial thought was to consider the expansion of a tesseract as 8 interconnected cubelets. For the two color case each one of these cubelets has 10 distinct states. Which gives us $10^8$ non-distinct permutations of the hypercube. Or more generally, this reduces to how many distinct ways one can color a 8 faced 3-dimensional figure using 10 colors. So the complicated question of 4-dimensional isometries reduces to 3 dimensional rotational isometries of a octahedron.
But I'm a physicist so what the hell do I know :D

A: First let's state the special case of Burnside's lemma that is relevant here.
Lemma:  Let $G$ be a finite group acting on a finite set $X$.  The number of ways to color the elements of $X$ with $z$ different colors, up to the action of $G$, is
$$\frac{1}{|G|} \sum_{g \in G} z^{c(g)}$$
where $c(g)$ is the number of cycles in the cycle decomposition of $g$ acting on $X$.  (Proof.)
Here $X$ is the set of faces of a hypercube.  In $n$ dimensions there are $2n$ such faces.  $G$ is the subgroup of index $2$ in the hyperoctahedral group with determinant $1$, also known as the Coxeter group $D_n$.  So our job now is to count, for each $k$, the number of elements of $D_n$ with $k$ cycles in the action on $X$.
Now, note that to analyze the action of $D_n$ on the faces it suffices to analyze the action of $D_n$ on the midpoints of the faces.  But these are precisely the $2n$ points $(0, 0, ... \pm 1, ..., 0, 0)$, so writing the elements of $D_n$ as signed permutation matrices is very well-suited to analyzing their action on these points; in particular, it suffices to figure out the answer for a single signed cycle.  But this turns out to be very simple: there are either one or two cycles depending on whether the product of the signs is $-1$ or $+1$.
(It might be helpful here to play with a specific example.  Consider $\left[ \begin{array}{cc} 0 & 1 & 0 \\ 0 & 0 & -1 \\ -1 & 0 & 0 \end{array} \right]$ acting on the six points $(\pm 1, 0, 0), (0, \pm 1, 0), (0, 0, \pm 1)$ to get a feel for what's going on in the general case.)
From here I think it's easiest to work with generating functions because the combinatorics get a little messy.  Begin with the identity
$$\sum_{m \ge 0} Z(S_n) t^n = \exp \left( z_1 t + \frac{z_2 t^2}{2} + \frac{z_3 t^3}{3} + ... \right)$$
where $Z(S_n)$ is the cycle index polynomial for the action of $S_n$ on $\{ 1, 2, ... n \}$.  Each $z_i$ is the term that controls cycles of length $i$.  We want to modify this generating function so that it tells us how the cycles in $D_n$ work.  There are $2^i$ signed cycles of length $i$ which come in two flavors: half of them have positive sign product (two unsigned cycles) and half of them have negative sign product (one unsigned cycle), so to keep track of the total number of unsigned cycles we should replace $z_i$ with $2^{i-1} z^2 + 2^{i-1} z$.  We also have to keep in mind that the determinant of a signed cycle is its sign product multiplied by $(-1)^{i+1}$, and we only want permutations with determinant $1$.  So the generating function we want is
$$\sum_{n \ge 0} f_n(z) \frac{t^n}{n!} = \frac{1}{2} \left( \exp \left( \sum_{i \ge 1} \frac{2^{i-1} z^2 + 2^{i-1} z) t^i}{i} \right) + \exp \left( \sum_{i \ge 1} (-1)^{i+1} \frac{2^{i-1} z^2 - 2^{i-1} z) t^i}{i} \right) \right)$$
where $f_n(z) = \sum_{g \in D_n} z^{c(g)}$.  After some simplification the above becomes
$$\sum_{n \ge 0} \frac{1}{|D_n|} f_n(z) t^n = \frac{1}{(1 - t)^{(z^2+z)/2}} + (1+t)^{(z^2-z)/2}.$$
Substituting $z = 2$ gives, at last, the answer
$$\sum_{n \ge 0} \frac{1}{|D_n|} f_n(2) t^n = \frac{1}{(1 - t)^3} + 1 + t.$$
In other words, for $n \ge 2$ we simply have $\frac{1}{|D_n|} f_n(2) = {n+2 \choose 2}$.  This is such a simple answer that there should be a direct proof of it.  I'll keep working on it.  (There is a rather straightforward proof of the corresponding result with "hypercube" replaced by "simplex," so my guess is something along those lines is possible here.)

A: Once someone else has done the hard work and come up with the answer,
as Qiaochu has done, then it's easy to prove it on an ad hoc
basis as this interloper (me) will do.
Consider an $n$-cube with faces coloured red and blue. Consider a set
of $n$ balls. Colour the $j$-th ball red, blue or green according to the
colours of the $j$-th pair of faces in the cube, that is if they both have
the same colour give the ball that colour, else if they have different
colours colour the ball green. Now a symmetry operation on the cube
will shuffle the balls so the number of each colour of balls will be the same.
Conversely given the $n$ coloured balls there will be various coloured
cubes giving rise to the colour distribution of the balls, but these
will all be equivalent under the full symmetry group of the cube.
However for $n\ge 2$ each $2$-coloured cube has a non-rotational symmetry,
so any two coloured cubes giving rise to the same colour distribution
of balls are related by a rotation. Hence the number of $2$-coloured $n$-cubes
up rotation is the same as the number of triples $(r,b,g)$ of nonnegative
integers adding to $n$ and there are ${n+2\choose 2}$ of these.
One can repeat this with $k$-colours for the cube. This time one needs
${k+1\choose 2}$ colours for the balls, and the argument ensuring that
rotations and the full symmetry group give the same answer requires
$n>{k\choose 2}$ (why?).
Added (30/9/2010)
One can get the general result using these considerations. For
$n>{k\choose 2}$ one gets
$${n+(k^2+k)/2-1\choose (k^2+k)/2-1}$$
colourings up to rotations. For $n\le {k\choose 2}$ there are $k$-colourings
having no improper (determinant $-1$) symmetries. But any such colouring
has no nontrivial symmetries at all. If two opposite faces have
the same colour, one can reflect through a hyperplane parallel to them.
So assume that no colour is opposite itself. Then if two pairs of opposite
faces have the same two colours between them, one can reflect in a plane
$x_i=x_j$or $x_i=-x_j$. Hence in these "special" colourings each pair
of opposite faces has a distinct pair of distinct colours. Up to symmetry
there are
$${(k^2-k)/2\choose n}$$
of these special colourings. So for $n\le{k\choose 2}$ there are
$${(k^2-k)/2\choose n}+{n+(k^2+k)/2-1\choose (k^2+k)/2-1}$$
up to rotational symmetries.

A: I presume you want to colour the faces of the cube?
If so there are $2^6$ colourings as there are six faces.
But do you want two colourings which are equivalent under
rotations (or rotations and reflections) to count as as the same?
If so then this is a classic application of
Burnside's lemma.
Added
If you want to do the same in higher dimensions then you need a good
handle on the symmetries of an $n$-cube. Its convenient to centre the
cube at the origin and take its vertices to be all points $(\pm1,\ldots,\pm1)$.
Then all symmetries of the cube fix the origin and their matrices
are "signed" permutation matrices: each row and column is all zero save for
one entry which is $\pm1$. The rotations correspond to signed permutation
matrices of determinant 1. The faces are the sets defined by $x_i=1$ and
$x_i=-1$. Again use Burnside's lemma but the book-keeping gets fiddlier.

A: Here is a contribution that treats the full symmetry group of the hypercube, not just rigid motions. This group can be obtained by labelling the vertices of the cube with the $2^n$ bit strings of length $n$ where adjacency is equivalent to having one bit different between two vertices. Then we obtain the full vertex permutation group of the hypercube by combining bit flips with bit position permutations e.g. combine a particular bit flip with a particular permutation of the bits and the result is an automorphism. Once we have these permutations we can use them to compute the induced permutation group on the two-faces.
This gives the following cycle indices for the face permutation groups containing rotations and reflections: for $n=2,$ $$a_{{1}},$$
for $n=3$,
$$1/48\,{a_{{1}}}^{6}+3/16\,{a_{{2}}}^{2}{a_{{1}}}^{2}+1/6\,{a_{{3}}}^{2}+1/16\,{a_{{1
}}}^{4}a_{{2}}\\+{\frac {7}{48}}\,{a_{{2}}}^{3}+1/8\,{a_{{1}}}^{2}a_{{4}}+1/6\,a_{{6}}
+1/8\,a_{{4}}a_{{2}},$$
for $n=4$,
$${\frac {1}{384}}\,{a_{{1}}}^{24}+1/32\,{a_{{1}}}^{6}{a_{{2}}}^{9}+1/12\,{a_{{3}}}^{8
}+{\frac {3}{64}}\,{a_{{1}}}^{4}{a_{{2}}}^{10}+{\frac {7}{32}}\,{a_{{4}}}^{5}{a_{{2}
}}^{2}+{\frac {1}{96}}\,{a_{{1}}}^{12}{a_{{2}}}^{6}\\+{\frac {3}{32}}\,{a_{{1}}}^{2}{a
_{{2}}}^{11}+1/12\,{a_{{3}}}^{4}{a_{{6}}}^{2}+1/32\,{a_{{1}}}^{4}{a_{{4}}}^{5}\\+1/16
\,{a_{{1}}}^{2}a_{{2}}{a_{{4}}}^{5}+1/6\,{a_{{6}}}^{4}+1/8\,{a_{{8}}}^{3}+1/32\,{a_{
{4}}}^{6}+{\frac {5}{384}}\,{a_{{2}}}^{12},$$
and for $n=5$,
$${\frac {1}{3840}}\,{a_{{1}}}^{80}+{\frac {1}{192}}\,{a_{{1}}}^{20}{a_{{2}}}^{30}+1/
48\,{a_{{1}}}^{2}{a_{{3}}}^{26}+{\frac {13}{384}}\,{a_{{2}}}^{36}{a_{{1}}}^{8}\\+{
\frac {37}{192}}\,{a_{{4}}}^{18}{a_{{2}}}^{4}+1/24\,{a_{{1}}}^{2}{a_{{3}}}^{6}{a_{{6
}}}^{10}+1/10\,{a_{{5}}}^{16}+{\frac {1}{768}}\,{a_{{1}}}^{32}{a_{{2}}}^{24}+1/24\,{
a_{{1}}}^{2}{a_{{3}}}^{10}{a_{{6}}}^{8}\\+1/40\,{a_{{2}}}^{40}+{\frac {1}{192}}\,{a_{{
1}}}^{8}{a_{{4}}}^{18}+1/32\,{a_{{1}}}^{4}{a_{{2}}}^{2}{a_{{4}}}^{18}+1/24\,{a_{{1}}
}^{2}{a_{{3}}}^{2}{a_{{12}}}^{6}\\+1/8\,{a_{{6}}}^{13}a_{{2}}+1/8\,{a_{{8}}}^{10}+1/10
\,{a_{{10}}}^{8}+{\frac {1}{64}}\,{a_{{1}}}^{4}{a_{{2}}}^{38}\\+1/48\,{a_{{1}}}^{2}{a_
{{3}}}^{2}{a_{{6}}}^{12}+1/32\,{a_{{4}}}^{20}+1/24\,{a_{{12}}}^{6}a_{{6}}a_{{2}} .$$
These directly produce the following formulas for the number of colorings with at most $N$ colors. For $n=2$, we get $$N.$$ For $n=3$ we get
$$1/48\,{N}^{6}+1/16\,{N}^{5}+3/16\,{N}^{4}+{\frac {13}{48}}\,{N}^{3}+{\frac {7}{24}}
\,{N}^{2}+1/6\,N, $$
for $n=4$ we get
$${\frac {1}{384}}\,{N}^{24}+{\frac {1}{96}}\,{N}^{18}+1/32\,{N}^{15}+{\frac {3}{64}}
\,{N}^{14}+{\frac {3}{32}}\,{N}^{13}+{\frac {5}{384}}\,{N}^{12}+1/32\,{N}^{9}+{
\frac {7}{48}}\,{N}^{8}\\+{\frac {7}{32}}\,{N}^{7}+{\frac {11}{96}}\,{N}^{6}+1/6\,{N}^
{4}+1/8\,{N}^{3},$$
and for $n=5$ we have
$${\frac {1}{3840}}\,{N}^{80}+{\frac {1}{768}}\,{N}^{56}+{\frac {1}{192}}\,{N}^{50}+{
\frac {13}{384}}\,{N}^{44}+{\frac {1}{64}}\,{N}^{42}+1/40\,{N}^{40}+1/48\,{N}^{28}+{
\frac {1}{192}}\,{N}^{26}+1/32\,{N}^{24}+{\frac {37}{192}}\,{N}^{22}+{\frac {7}{96}}
\,{N}^{20}+1/24\,{N}^{18}+{\frac {29}{240}}\,{N}^{16}+1/8\,{N}^{14}+1/6\,{N}^{10}+{
\frac {17}{120}}\,{N}^{8} .$$
Note that the case for $n=3$ is OEIS A198833.
These cycle indices were computed with the following Maple program.

with(combinat, permute);
with(combinat, choose);

pet_autom2cycles :=
proc(src, aut)
        local numa, numsubs;
        local marks, pos, cycs, cpos, clen;

        numsubs := [seq(src[k]=k, k=1..nops(src))];
        numa := subs(numsubs, aut);

        marks := [seq(true, pos=1..nops(aut))];

        cycs := []; pos := 1;

        while pos <= nops(aut) do
              if marks[pos] then
                 clen := 0; cpos := pos;

                 while marks[cpos] do
                       marks[cpos] := false;
                       cpos := numa[cpos];
                       clen := clen+1;
                 od;

                 cycs := [op(cycs), clen];
              fi;

              pos := pos+1;
        od;

        return mul(a[cycs[k]], k=1..nops(cycs));
end;

hypercube_face_cind :=
proc(dim)
        option remember;

        local verts, v1, v2, faces, f, ff, fv, k, m, b,
        d2, pos, fpos, perm, fperm, act, s;

        if dim=1 then return FAIL fi;

        verts := [];
        for k from 2^dim to 2^(dim+1)-1 do
            b := convert(k, base, 2);

            verts := [op(verts), [seq(b[m], m=1..dim)]];
        od;

        faces := [];

        for d2 in choose(dim, 2) do
            for k from 2^(dim-2) to 2^(dim-1)-1 do
                b := convert(k, base, 2);

                f := [];
                for ff in [[0,0], [0,1], [1,0], [1,1]] do
                    fv := [seq(-1, pos=1..dim)];
                    fv[d2[1]] := ff[1];
                    fv[d2[2]] := ff[2];

                    fpos := 1;
                    for pos to dim do
                        if fv[pos] = -1 then
                           fv[pos] := b[fpos];
                           fpos := fpos+1;
                        fi;
                    od;

                    f := [op(f), fv];
                od;

                faces := [op(faces), convert(f, set)];
            od;
        od;

        s := 0;
        for k from 2^dim to 2^(dim+1)-1 do
            b := convert(k, base, 2);

            for perm in permute(dim) do
                act :=
                proc(v)
                      local w, m;
                      w := [seq(v[m], m=1..dim)];
                      for m to dim do
                          if b[m]=1 then
                             w[m] := 1-w[m];
                          fi;
                      od;
                      w := [seq(w[perm[m]], m=1..dim)];
                end;

                fperm := map(x -> map(act, x), faces);
                s := s + pet_autom2cycles(faces, fperm);
            od;
        od;

        s/2^dim/dim!;
end;

bs_Ninto_cind :=
proc(vN, ind)
           local subs1, indvars, v, pot, res;

           res := ind;

           indvars := indets(ind);
           subs1 := [seq(indvars[k]=vN, k=1..nops(indvars))];

           subs(subs1, res);
end;

v :=
proc(dim)
        option remember;

        bs_Ninto_cind(dim, hypercube_face_cind(dim));
end;

This MSE link computes another cube-related cycle index.


Q: Next.JS build with websocket connection I'm trying to build a next.js application which uses signalr for to talk to webservices. However, during the build it tries to connect to the websocket which is not available at build-time and therefore the build fails with the following error:
FailedToNegotiateWithServerError: Failed to complete negotiation with the server: FetchError: request to https://localhost:7021/hubs/hub/negotiate?negotiateVersion=1 failed, reason: connect ECONNREFUSED 127.0.0.1:7021

How can we use websockets which are not available runtime. This is how we create the websocket connection in the app:
const socketInstance = new HubConnectionBuilder()
    .configureLogging(LogLevel.None)
    .withUrl(`${process.env.NEXT_PUBLIC_SOCKET_URL}`)
    .withAutomaticReconnect()
    .build();

socketInstance.start().then(() => {});


Q: How do you find the index of an accordion tab containing a specific element within a jQuery UI Accordion? I have an accordion (an archive) of links/dates. When a user clicks one I am trying to have the accordion expand to the current selected link. To do this, I search the accordion for the link which matches the current URL and would like to then expand the accordion to that link.
JSFiddle
HTML

Archive

2016

November (0)

October (5)

September (11)

August (8)

                ....

2015

November (0)

October (5)

September (11)

August (8)

July (9)

                ....

2014

November (0)

October (5)

September (11)

                ....

Javascript
// Accordionize the above structure.
$(function() {
    $("#blog-archive-accordion").accordion({ header: "h3" });
    $("#blog-archive-accordion-year").accordion({ header: "h4"  });
});

// Find the current url in the accordion links (obv. doesn't work like this in JSFiddle)
//var selectedArchiveLink = $('#blog-archive-accordion').find("a[href='" + location.pathname + location.search +"']").parent();
var selectedArchiveLink = $('#blog-archive-accordion').find(".current-archive-link").parent();
if(selectedArchiveLink.length > 0){
    selectedArchiveLink.addClass("current-archive-link"); // Style the current link

    // How do I know where the found link was?
    $('#blog-archive-accordion-year').accordion('option', 'active', 1);
}

In the above example I'm forcing the accordion ope with .accordion('option', 'active', 1); but I would like to know how to find the index of the found link. Considering the index in accordions is based on heading tags and not the actual index in the accordion.
IE:

would accordion on the two
 tags and the index of the second one is 3 not 1 like you would need for this .accordion() function.

A: You can use the index function to get the index/place of the current element inside the parent (and you can use it also based on the tagname)
selectedArchiveLink.parent().index('ul')

Check the example:
http://jsfiddle.net/tg4hc9zr/

A: you might be looking for this. Just add this function to your accordion function call and it will give you the index of h4 tag. Hope this helps.
  activate: function(evt, widget ) {
        var index = $(this).find("h4").index(widget.newHeader[0]);
    }

$("#blog-archive-accordion-year").accordion({
       header: "h4",
       activate: function(evt, widget ) {
            var index = $(this).find("h4").index(widget.newHeader[0]);
        }
    });