text:
Q: Why do I get: "error: assignment to expression with array type" #include <stdio.h>

int main(void) {
    int arr[10];
    arr = "Hello";
    printf("%s",arr);
    return 0;
}

The above code shows compiler error:
t.c: In function 'main':
t.c:5:9: error: assignment to expression with array type
     arr = "Hello";
         ^
t.c:6:12: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int *' [-Wformat=]
     printf("%s",arr);
            ^

Whereas the below code works fine.
#include <stdio.h>

int main(void) {
    char arr[10] = "Hello";
    printf("%s",arr);
    return 0;
}

Both look identical to me. What am I missing here?

A: They are not identical.
First of all, it makes zero sense to initialize an int array with a string literal, and in worst case, it may invoke undefined behavior, as pointer to integer conversion and the validity of the converted result thereafter is highly platform-specific behaviour. In this regard, both the snippets are invalid.
Then, correcting the data type, considering the char array is used,

*

*In the first case,
  arr = "Hello";

is an assignment, which is not allowed with an array type as LHS of assignment.

*

*OTOH,
  char arr[10] = "Hello";

is an initialization statement, which is perfectly valid statement.

A: Don't know how your second code is working (its not working in my case PLEASE TELL ME WHAT CAN BE THE REASON) it is saying: array of inappropriate type (int) initialized with string constant
Since you can't just assign a whole string to a integer variable.
but you can assign a single character to a int variable like:
int a[5]={'a','b','c','d','d'}


text:
Q: Python: How can I remove excel entries via openpyxl using a feedback loop? I am building a small app to study the vocabulary of various languages (see below the code for Mandarin). I have the basic funcions which work well. Now I want to add a button in my GUI where i can remove entries (i.e. individual words) from the database, once i have mastered the word (i.e. a button in tkinter which would remove the entry). After removing, the random function in python should then only select words from the reduced database. Do you have any idea how to do this? Any help is welcome!
from tkinter import *
import random
import sys
import os
randvalue_start = random.randint(2, 592)

window = Tk()
window.title('Mandarin Vocabulary')
window.geometry('500x400')
icon = PhotoImage(file = r'C:\Users\PycharmProjects\Mandarin\HSKlogopng.600px.png')
icon2 = icon.subsample(5 ,5)
label1 = Label(window, image = icon2, anchor="ne")

import openpyxl
path = r"\Users\PycharmProjects\Mandarin\characters.xlsx"
worbook = openpyxl.load_workbook(path, read_only=True)
sheet = worbook.active
row_count = (sheet.max_row)

def english_btn1():
    global randvalue_start
    english = f"B{randvalue_start}"
    english_value = sheet[english].value
    label_eng = Label(window, text=english_value+":", width=20, height=3, font=("TkDefaultFont",15))
    label_pin = Label(window, text="", font=30, width=15, height=3)
    label_mand = Label(window, text="", font=30, width=15, height=4)
    label_eng.grid(row=8,column=1,rowspan=2)
    label_pin.grid(row=8, column=2)
    label_mand.grid(row=9, column=2)

def pinying_btn2():
    global randvalue_start
    pinying = f"C{randvalue_start}"
    mandarin = f"D{randvalue_start}"
    pinying_value = sheet[pinying].value
    mandarin_value = sheet[mandarin].value
    combined = f"{pinying}'/'{mandarin}"
    combined_value = f"{pinying_value}'/'{mandarin_value}"
    label_pin = Label(window ,text=pinying_value,font=("TkDefaultFont",15), width=10, height=2)
    label_mand = Label(window,text=mandarin_value,font=("TkDefaultFont",30), width=8,height=2, borderwidth=5,relief="ridge")
    label_pin.grid(row=8,column=2)
    label_mand.grid(row=9,column=2)
    randvalue_start = random.randint(2, 592)

def reset():
     os.execl(sys.executable, sys.executable, *sys.argv)

frame = LabelFrame(window,text="Input",padx=5, pady=5)
frame.grid(row=0,column=1,padx=10,pady=10)

btn2 = Button(frame,text = "Show answer", fg = "green" ,width=20 ,command=pinying_btn2)
btn3 = Button(frame,text = "clear", fg= "red", width=20 ,command=reset)
btn1 = Button(frame,text = "Next character", fg = "black" ,width=20,command=english_btn1)
words_label = Label(frame,text = "# of characters: " + str(row_count))

label1.grid(row=0,column=2, columnspan=2)
Label(window, text="", width=20, height=3, font=("TkDefaultFont", 15)).grid(row=8, column=1)
label_blk1 = Label(window, text="", font=("TkDefaultFont", 15), width=10, height=3).grid(row=8, column=2)
label_blk2 = Label(window, text="", font=("TkDefaultFont", 30), width=10, height=2, padx=1, pady=1).grid(row=9, column=2)

btn1.grid(padx=5, pady=5)
btn2.grid(padx=5, pady=5)
btn3.grid(padx=5, pady=5)
words_label.grid(padx=5,pady=5)

window.mainloop()

A: This is not really a question about Pyxl or Excel. The question is really: how do you generate random numbers that skip certain numbers.
from random import randint
n = 592

numbers = list(range(n))

# To get a random number from the list
random_number = numbers[randint(0, len(numbers)-1)]

# To remove 123 from the list
numbers.remove(123)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel - VBA code breaks if i rename my excel file - is there a resolution? New-ish to VBA I guess. I wanted to make a button where once clicked it will open a dialogue box and let me attach a file onto my spreadsheet. I basically recorded a macro and edited the code with the help of google. It works. Only problem is the filename regularly gets updated when changes are made. Once renamed the code breaks.
If I understand, the code is linked to both the filename and the worksheet name. the worksheet wont change but the filename definitely will. Is there any way to make the code independent of the filename?
The excel file is on a sharedrive that others can view/edit, so it would be nice to make a file attaching button, that anyone can use
The code is pretty basic. On excel, open VisualBasic window, and on the sheet for the worksheet tab I want, I entered the below:
Sub AttachEmail()

Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With

ActiveSheet.OLEObjects.Add(Filename:=FileSelected, Link:=False, DisplayAsIcon:=False).Select
End Sub

A: From the documentation for the FileDialog object:

Each host application can only create a single instance of the
  FileDialog object. Therefore, many of the properties of the FileDialog
  object persist even when you create multiple FileDialog objects.
  Therefore, make sure that you set all of the properties appropriately
  for your purpose before you display the dialog box.

I suspect that if your Excel instance isn't closing, one of those properties is persisting (and giving your error the second time you use it).
The most likely candidate based on the message you're receiving is the InitialFileName (my emphasis):

If you specify an invalid path, the last-used path is used. A message
  warns users when an invalid path is used.

I'd add the following line of code to ensure that you always will always get a valid value:
With myFile
    .Title = "Choose File"
    .AllowMultiSelect = False
    'Add this.
    .InitialFileName = ActiveWorkbook.Path  'Or ThisWorkbook.Path

Note that if the workbook hasn't already been saved, this will default to the user's documents folder.


text:
Q: Programmatically read fMP4 using ffmpeg All of my attempts to parse fmp4 have failed with the following errors:
avcodec_send_packet returned with -10949955291 and printed the following errors:
[h264 @ 0x105001600] No start code is found.
[h264 @ 0x105001600] Error splitting the input into NAL units.

What did i do?
Downloaded a perfectly playable h.264 file and fragmented it using the following cmd
ffmpeg -i long.mp4 -an -sn -vcodec libx264 -force_key_frames "expr:gte(t,n_forced*4)" -sc_threshold 0 -r 25 -f hls -hls_time 4 -hls_list_size 99999 -start_number 1 -hls_segment_type fmp4 -hls_fmp4_init_filename init.mp4 -t 30 -threads 0 big_bunny.m3u8

and used the following AVIO read example
#include <fstream>
#include <iterator>
#include <algorithm>
#include <libavcodec/avcodec.h>

std::vector<unsigned char> b1;
std::vector<unsigned char> b2;
bool initialized = false;
int bytesread = 0;

static int read_packet(void* opaque, uint8_t* buf, int buf_size)
{
    if (b1.size() && !initialized) {
        size_t bytesToRead = std::min(buf_size, (int)b1.size());
        ::memcpy(buf, b1.data(), bytesToRead);
        bytesread += bytesToRead;
        if (bytesread >= b1.size()) {
            initialized = true;
            bytesread = 0;
        }
        return bytesToRead;
    }

    ::memcpy(buf, b2.data() + bytesread, buf_size);
    bytesread += buf_size;
    return buf_size;
}

int main(int argc, char** argv)
{
    AVFormatContext* fmt_ctx = NULL;
    AVIOContext* avio_ctx = NULL;
    uint8_t *buffer = NULL, *buffer2 = nullptr, *avio_ctx_buffer = NULL;
    size_t buffer_size, buffer_size2, avio_ctx_buffer_size = 4096;
    char* input_filename = NULL;
    int ret = 0;
    struct buffer_data bd = {0};

    std::ifstream input1("/Users/x/Downloads/fmp4/init.mp4", std::ios::binary);
    std::ifstream input2("/Users/x/Downloads/fmp4/big_bunny1.m4s", std::ios::binary);

    b1 = std::vector<unsigned char>((std::istreambuf_iterator<char>(input1)), std::istreambuf_iterator<char>());
    b2 = std::vector<unsigned char>((std::istreambuf_iterator<char>(input2)), std::istreambuf_iterator<char>());

    avio_ctx_buffer = (uint8_t*)av_malloc(avio_ctx_buffer_size);

    fmt_ctx = avformat_alloc_context();
    avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size, 0, nullptr, &read_packet, NULL, NULL);
    fmt_ctx->pb = avio_ctx;

    AVDictionary* opts = NULL;
    //   av_dict_set(&opts, "movflags", "frag_keyframe+empty_moov", 0);
    ret = avformat_open_input(&fmt_ctx, NULL, NULL, &opts);
    ret = avformat_find_stream_info(fmt_ctx, NULL);

    AVCodec* decoder = nullptr;

    decoder = avcodec_find_decoder(fmt_ctx->streams[0]->codecpar->codec_id);
    AVCodecContext* decoderCtx = avcodec_alloc_context3(decoder);

    ret = avcodec_open2(decoderCtx, decoder, nullptr);

    AVPacket pkt;
    av_init_packet(&pkt);

    AVFrame* frame = av_frame_alloc();
    while (true) {
        ret = av_read_frame(fmt_ctx, &pkt);

        ret = avcodec_send_packet(decoderCtx, &pkt);
        if (ret != 0)
            assert(false);

        for (;;) {
            ret = avcodec_receive_frame(decoderCtx, frame);
            if (ret < 0) {
                break;
            }

            int g;
            g = 0;
        }
    }

I'm not even sure that this is the right way to process fmp4 types. but for the clarity of this example, i simply loaded the init file into the first buffer, and the actual media file on the second buffer, and switch between the buffers respectfully to buf_size's value.

A: I don't think that in a case where you use avio_alloc_context demuxer get's all the needed info - see Opening a media file, but this is a wild guess since your output shows no errors from the mp4 demuxer but only from the H.264 bitstream parser, so I am leaning that the probed file format could be raw H.264, but it is hard to tell. But if I am mistaken, you have not provided a seek callback, and demuxing an mp4 would certainly require seeking to jump around the boxes and then seek to the sample data. So, I'd first try to provide a seek callback, and see if that gets called. But from the example it is not sure why you even need the I/O callbacks, since the data reside in a file not in a memory location, so I'd suggest trying to use the standard avformat_open_input way.


text:
Q: How do you enable/configure a site collection app catalog in SP 2016 on-premises? After extensive searching, I can't seem to be able to find any information online regarding how to set up a site collection app catalog on SP 2016 on-premises. All the guides are for SP Online / O365.
We have SP 2016 Feature Pack 2, which supports SPFx webparts, and I have a webpart ready to deploy, and I want to use the site collection app catalog rather than a farm-wide app catalog site, if possible.
Is it possible to set up a site collection app catalog in SP 2016?  If so, how?

A: Site Collection app catalogs are only supported in SharePoint Online. Instead, you have to use the centralized farm-wide app catalog.


text:
Q: Visual Basic (VB) Forms: wait for a user click? I'm making a simple form that is to step through a program iteratively.
How can I get it to run a method each time a user clicks a button and wait once it is finished for the next click?

A: Maybe I'm not understanding your question very well, but is it like the "Next" button on a Wizard?
You can have a State variable to store the current "state", so at starup its has the value 1. when click "Next" then do the code for State=1 and then change to State=2 and so on.
Inside you Click event you can have a case statement to proceed according

A: You want to create a method that gets called when it sees the OnClick event.
The simplest way to do this is to double-click the button in the GUI Form Designer, and it will go to the code page and start the method for you with the correct syntax.


text:
Q: graph layout using angularjs I am currently working on a GUI with AngularJS, which contains a graph given with it's nodes and connections in a javascript objects like this:
Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
Connections = [{'from': 1, 'to': 2}, {'from': 1, 'to': 3}];

What I need to do, is give the x and y values for every node. At the moment I am using a simple offset to avoid overlapping and render node-by-node, but I would like to calculate x and y values for each node to have a proper layout.
Is there an algorithm, that I give my nodes and connections to and returns with a layout (x, y values for every node), which is better looking than my simple solution?
I have tried D3, but I am already using a third party library for the graph and it's hard to integrate it, so a optimal solution would be to simply give the coordinates for the current library's data structure (Nodes and Connections).

A: From D3.js Force directed layout you can find such an algorithm. If you leave out the drawing code, you end up with the following:
var width = 100;
var height = 100;
var Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
var Connections = [{'source': 1, 'target': 2}, {'source': 1, 'target': 3}];

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

simulation
    .nodes(Nodes);

simulation.force("link")
    .links(Connections);

console.log(Nodes, Connections);

If you now open your console and inspect the Nodes variable, you will see the x and y positions are updated.


text:
Q: How do I make UIButton in a cell retain a specific state right after being tapped? So I have a list of items in a UICollectionView and there is a UIButton which has it's default and selected UIImage's set to a light grey heart and a black heart.
My aim is to allow users to add items to a list of favourites. I've added a column to the database called "favourite" and it is of type boolean.
Customer taps heart in cell of item. A method is triggered which users the object id of the item that is passed along as the titleLabel of the UIButton to grab the item from the database and update the boolean value of the favourite column to "True".
Method for favourite button:
- (void)addFavouriteButtonTapped:(UIButton *)sender
{
    NSLog(@"add to favourites button tapped %@", [[sender titleLabel] text]);

    // Set data base favaourite status to 1 (yes)
    PFQuery *query = [PFQuery queryWithClassName:@"Garments"];
    [query getObjectInBackgroundWithId:[[sender titleLabel] text] block:^(PFObject *object, NSError *error) {
        object[@"favourite"] = @YES;
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                [[[UIAlertView alloc] initWithTitle:@"Add Favouite"
                                            message:@"Item successfully added to favourites"
                                           delegate:_thisController
                                  cancelButtonTitle:@"Ok"
                                  otherButtonTitles: nil] show];
            } else {
                NSLog(@"Something went wrong");
            }
        }];
    }];
}

Then in my cellForItemAtIndexPath I have an if statement which sets the selected state of the UIButton.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{

        NSLog(@"cellForItemAtIndexPath");
        // other cell info here deleted to make things clearer

         _addFavouriteButton = [cell addFavouriteButton];

        // if database favourites status is equal to one then set highlighted to (yes)
        if ([object valueForKey:@"favourite"] ==  [NSNumber numberWithBool:YES]) {
            [_addFavouriteButton setSelected:YES];
            NSLog(@"SETTING SELECTED");
        } else if ([object valueForKey:@"favourite"] ==  [NSNumber numberWithBool:NO]) {
            [_addFavouriteButton setSelected:NO];
        }

        [[_addFavouriteButton titleLabel] setText:[object objectId]];

        [_addFavouriteButton addTarget:_thisController action:@selector(addFavouriteButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

        return cell;
}

Now when I leave the view and everything is destroyed then return back to it again, black hearts appear where ever I selected a favourite. This is fine. The problem I am having is when I actually make the selection of the item to add as a favourite the heart is updated and remains grey until I leave the UICollectionView and return.
I've tried reloadData in the main queue of the addFavouriteButtonTapped: method
I've also tried reloading just the cell.
None of this works.
I can set the UIButton's state to selected but as I scroll the selection doesn't keep position and moves to other cell UIButton's and off the cell with the button I actually selected. Only way to fix this is to leave the few so the we have a fresh UICollectionView that uses the if statement from my database to determine whether a cell is selected or not.
**My custom cell:**

@interface VAGGarmentCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet PFImageView *imageView;
@property (weak, nonatomic) IBOutlet UIButton *addFavouriteButton;

@property (weak, nonatomic) IBOutlet UITextView *title;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@end

Question:
I've done the bulk of what needs to be done and can use the favourites column later on when building the page that lists items in the customers favourite list. But how do I refresh the UICollectionView right after the button was tapped and successful update in order to display the UIButton's selected state?

A: Make sure you also set the sender (ie the button that was pressed) to selected too, or reload the collection view once after updating your model.
Update: This answer has been edited and updated after a discussion in chat.
There isn't a need for an iVar (or @property) for _addFavouriteButton in your view controller, the button variable should just be a local variable in the scope of the collectionView:cellForItemAtIndexPath:object: method - lets start by fixing that method first
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    NSLog(@"cellForItemAtIndexPath");
    // other cell info here deleted to make things clearer

    // Create a local variable for your button - this saves a bit of typing in the rest
    // of the method. You can also use dot notation as its a property
    UIButton *favouriteButton = cell.addFavouriteButton;

    BOOL objectFavourited = [object[@"favourite"] boolValue];
    NSLog(@"Setting selected? %@", objectFavourited ? @"YES" : @"NO");
    favouriteButton.selected = objectFavourited;

    // You should set the title directly on the button (as per the docs -
    // https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instp/UIButton/titleLabel),
    // you shouldn't touch titleLabel except for styling

    // However you only used the title for seeing which object the favourite button tap was for,
    // so I've commented it out
    // [favouriteButton setTitle:[object objectId] forState:UIControlStateNormal];

    [favouriteButton addTarget:_thisController action:@selector(addFavouriteButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

Now the buttons target method. Here you should be doing the following: updating your model, changing the button state and then saving the model. If the model successfully saves do your users care - no not really! If however the save fails, then the user needs to know, and the button and the model need to be reverted to their previous state.
I'm pretty sure that if the save fails, the object will be in the same state as before you attempted the save - with the favourite property set to YES. Even if it doesn't, setting it back to NO wouldn't really matter anyway.
The best way to get the indexPath of the item that the had its button pressed is to use a similar method to the one in this answer. Its the perfect way to work out the index path, no need for horrible tags!
Now we have the index path of the item, you don't need to query for that specific object - we get get it directly by using objectAtIndexPath:.
- (void)addFavouriteButtonTapped:(UIButton *)button
{
    // Method adapted for a collection view from the above answer
    CGPoint hitPoint = [button convertPoint:CGPointZero toView:self.collectionView];
    NSIndexPath *hitIndex = [self.collectionView indexPathForItemAtPoint:hitPoint];

    // Now get the object for this index
    PFObject *object = [self objectAtIndexPath:hitIndex];

    NSLog(@"add to favourites button tapped %ld - %@", (long)hitIndex.item, [object objectId]);

    // Now update the model
    object[@"favourite"] = @YES;

    // And the button state
    button.selected = YES;

    // Now save the model to parse
    [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

        if (!succeeded) {
            // Reset the object back to its previous state
            object[@"favourite"] = @NO;
            // Reload the item to reflect the changes in the model
            [self.collectionView reloadItemsAtIndexPaths:@[hitIndex]];

            // Only bother the user if something bad happened
            [[[UIAlertView alloc] initWithTitle:@"Oops!"
                                        message:@"There was a problem please try again later"
                                       delegate:self
                              cancelButtonTitle:@"Dismiss"
                              otherButtonTitles:nil] show];
        }
    }];
}

You could reload the collection view, but as you've updated the view in that method there isn't really any need.
However, you should reload the collection view if the save failed as the button might now be being used for a different item in the collection view!


text:
Q: Dropdrown button dentro de
* Este es el dropdown-button "Multimedia" y su CSS:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 15.8%;
    background-color: #e0e0e0;
    position: fixed;
    height: 600px;
    overflow: auto;
 right:1129px;
 top:47px;
 border:1px solid #939496;
 left:0px;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
 font-size:30px;

}

button:hover{
 background-color: #4dd6e2;
    color: white;
}

li a.active {
    background-color: #309ba5;
    color: white;
}

li a:hover:not(.active) {
    background-color: #4dd6e2;
    color: white;
}

.dropbtn {
    background-color: #e0e0e0;
    color: black;
    padding: 16px;
    font-size: 30px;
    border: none;
    cursor: pointer;
 width:22px;
 height:50px;
 font-family:Times New Roman;
 text-align:middle;

}

.dropdown {
    position: relative;
    display: inline-block;
 top:-88px;
 right:572px;

}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    width: 100%;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #4dd6e2;
}

  <button class="dropbtn">Multimedia</button>

    MP4
    PNG
    GIF

Y este el es menú:

Home

Contact

About

Games

Multimedia

Quiero meter el dropdown-button en el
, pero si lo meto, no funciona. Alguien sabe cómo solucionar esto?

A: El único problema que veo es que le estás dando una posición al menú que hace que se salga de la pantalla y no se vea, porque por lo demás, parece funcionar correctamente. Los estilos a los que me refiero son estos:
.dropdown {
    position: relative;
    display: inline-block;
    top:-88px;   /* <---------------- este valor   */
    right:572px; /* <---------------- y este valor */
}

De hecho, esos valores son increíblemente específicos, no me extrañaría que los tuvieses ahí por algún motivo (aunque no parecen una solución ideal), pero no tienen sentido dentro del ejemplo que pones en la pregunta.
Así, si pones tu mismo código quitando ese posicionamiento de los estilos, verás como el dropdown ya está visible y funciona (aunque parece que le falta algo de estilo a las opciones):

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 15.8%;
  background-color: #e0e0e0;
  position: fixed;
  height: 600px;
  overflow: auto;
  right:1129px;
  top:47px;
  border:1px solid #939496;
  left:0px;
}

li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
  font-size:30px;

}

button:hover{
  background-color: #4dd6e2;
  color: white;
}

li a.active {
  background-color: #309ba5;
  color: white;
}

li a:hover:not(.active) {
  background-color: #4dd6e2;
  color: white;
}

.dropbtn {
  background-color: #e0e0e0;
  color: black;
  padding: 16px;
  font-size: 30px;
  border: none;
  cursor: pointer;
  width:22px;
  height:50px;
  font-family:Times New Roman;
  text-align:middle;

}

.dropdown {
  position: relative;
  display: inline-block;
  /*top:-88px;
  right:572px;*/
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  width: 100%;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #4dd6e2;
}

Home

Contact

About

Games

      <button class="dropbtn">Multimedia</button>

        MP4
        PNG
        GIF

Para que el ancho se vea mejor, podrías quitarle el width:22px al dropbtn y hacer que la lista tenga un overflow-x:hidden para que no aparezcan las barras de scroll.


text:
Q: How to import and call a Python function in a Jinja template? I want to use a function from a python module, in my Jinja template inside a Flask application. How do I import the module or pass the function to the template so that I can use it?

A: First approach. If you want to pass function only to one template, you can pass function to template as variable. For example
render_template("index.html", func=f)

And then call it in template, {{ func(1) }}
If you want function or variable accessible in all templates (globally). You can add them during flask application initialization to app.jinja_env.globals dict, like:app.jinja_env.globals['func'] = f


text:
Q: How do I write a batch script for collecting files with the same name from several directories I have many files, different, but with the same name, in many directories. These directories are all one level deep within a single root directory.
I would like a script that goes over all these subdirectories, and copies the same-named-files to some destination. Naturally, renaming them.

A: I was having a similar requirement recently and I wrote a script to do that. It's not restricted to just files of the same name or a one level deep directory structure, but you can use it for that and I think it should fit your needs. It takes the full filename, strips the current path prefix and converts any backslashes to underscores, thereby "flattening" the directory structure into the filenames. You just need to specify a target directory and a filemask for the script to operate on (lines two and three).
@ECHO OFF
SET filemask=*.gif
SET target_path=out
SETLOCAL EnableDelayedExpansion
SET current_path=%CD%\
IF NOT EXIST "%target_path%" MKDIR "%target_path%"
FOR /F "tokens=*" %%G IN ('DIR /B /S %filemask%') DO (
    SET file=%%G
    :: strip current path
    SET file_new=!file:%current_path%=!
    :: convert backslashes to underscores
    SET file_new=!file_new:\=_!
    :: copy file
    COPY %%G %target_path%\!file_new! >nul
)
ENDLOCAL


text:
Q: Generate the same computer hardware id. (CHID) like computerhardwareids.exe from Windows SDK INTRODUCTION
This thread should be the ending chapter for this first thread from 2014 and this second one from 2017.
To cut the story short, you simply need to know that the Microsoft Windows SDK includes a program called computerhardwareids.exe, which, as its name suggests, it generates (several) hardware identifiers for the computer, and I would like to replicate the CHID algorithm using .NET to generate the same identifiers as this program generates.
The list of CHIDS that this program can generate on Windows 10, which is the O.S that I'm using, is listed here:

*HardwareID-0 Manufacturer + Family + Product Name + SKU Number +
BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release

*HardwareID-1 Manufacturer + Family + Product Name + BIOS Vendor +
BIOS Version + BIOS Major Release + BIOS Minor Release

*HardwareID-2 Manufacturer + Product Name + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release

*HardwareID-3 Manufacturer + Family + Product Name + SKU Number + Baseboard Manufacturer + Baseboard Product

*HardwareID-4 Manufacturer + Family + Product Name + SKU Number

*HardwareID-5 Manufacturer + Family + Product Name

*HardwareID-6 Manufacturer + SKU Number + Baseboard Manufacturer + Baseboard Product

*HardwareID-7 Manufacturer + SKU Number

*HardwareID-8 Manufacturer + Product Name + Baseboard Manufacturer + Baseboard Product

*HardwareID-9 Manufacturer + Product Name

*HardwareID-10 Manufacturer + Family + Baseboard Manufacturer + Baseboard Product

*HardwareID-11 Manufacturer + Family

*HardwareID-12 Manufacturer + Enclosure Type

*HardwareID-13 Manufacturer + Baseboard Manufacturer + Baseboard Product

*HardwareID-14 Manufacturer

PROBLEM
I managed to replicate all hardware ids except: 0, 1, 2 and 12
I found that these four problematic identifiers have in common that they are the only which contains numeric values to append to the string with which to generate the UUID. See the table in this link or read this list:

*

*Name | Length | Type

*System BIOS Major Release | BYTE |Varies

*System BIOS Minor Release | BYTE | Varies

*Enclosure type | BYTE | Varies
I think this is a clear sign that I don't know how to treat those numerical values when building the string with which to generate the UUID.
QUESTION
I don't know in which WMI class to find the Enclosure Type value, but it doesn't matter because I really don't care about replicating the HardwareID-12 / Enclosure Type value, but I would like to be able replicate the HardwareID-0, HardwareID-1 and HardwareID-2
I already know from which WMI class to get the BIOS major and minor release version for HardwareID-0, HardwareID-1 and HardwareID-2, but the problem is that when I append those BIOS values to the string with which to generate the UUID, I end getting a totally different UUID from what computerhardwareids.exe generates.
My questions are:

*

*What I need to do to replicate the same exact generated UUID for HardwareID-0, HardwareID-1 and HardwareID-2?.

*Maybe I need to treat those numerical values in a special way, applying some format that I don't know when appending them to the string with which to generate the UUID?.
Please note that I DON'T have experience in reverse-engineering.
CODE
This is the code I'm using, written in VB.NET. At its current state I consider it a working solution that replicates (or it should replicate) the same computer hardware ids as computerhardwareids.exe program generate, except hardware ids 0, 1, 2 and 12 for the reasons that I have explained.

*

*Computer hardware id type enumeration
 ' https://learn.microsoft.com/en-us/windows-hardware/drivers/install/specifying-hardware-ids-for-a-computer
 Public Enum ComputerHardwareIdMicrosoftType

     ''' <summary>
     ''' HardwareID-0
     ''' <para></para>
     ''' Manufacturer + Family + Product Name + SKU Number + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release
     ''' </summary>
     HardwareID_0 = 0

     ''' <summary>
     ''' HardwareID-1
     ''' <para></para>
     ''' Manufacturer + Family + Product Name + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release
     ''' </summary>
     HardwareID_1 = 1

     ''' <summary>
     ''' HardwareID-2
     ''' <para></para>
     ''' Manufacturer + Product Name + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release
     ''' </summary>
     HardwareID_2 = 2

     ''' <summary>
     ''' HardwareID-3
     ''' <para></para>
     ''' Manufacturer + Family + Product Name + SKU Number + Baseboard Manufacturer + Baseboard Product
     ''' </summary>
     HardwareID_3 = 3

     ''' <summary>
     ''' HardwareID-4
     ''' <para></para>
     ''' Manufacturer + Family + Product Name + SKU Number
     ''' </summary>
     HardwareID_4 = 4

     ''' <summary>
     ''' HardwareID-5
     ''' <para></para>
     ''' Manufacturer + Family + Product Name
     ''' </summary>
     HardwareID_5 = 5

     ''' <summary>
     ''' HardwareID-6
     ''' <para></para>
     ''' Manufacturer + SKU Number + Baseboard Manufacturer + Baseboard Product
     ''' </summary>
     HardwareID_6 = 6

     ''' <summary>
     ''' HardwareID-7
     ''' <para></para>
     ''' Manufacturer + SKU Number
     ''' </summary>
     HardwareID_7 = 7

     ''' <summary>
     ''' HardwareID-8
     ''' <para></para>
     ''' Manufacturer + Product Name + Baseboard Manufacturer + Baseboard Product
     ''' </summary>
     HardwareID_8 = 8

     ''' <summary>
     ''' HardwareID-9
     ''' <para></para>
     ''' Manufacturer + Product Name
     ''' </summary>
     HardwareID_9 = 9

     ''' <summary>
     ''' HardwareID-10
     ''' <para></para>
     ''' Manufacturer + Family + Baseboard Manufacturer + Baseboard Product
     ''' </summary>
     HardwareID_10 = 10

     ''' <summary>
     ''' HardwareID-11
     ''' <para></para>
     ''' Manufacturer + Family
     ''' </summary>
     HardwareID_11 = 11

     ''' <summary>
     ''' HardwareID-12
     ''' <para></para>
     ''' Manufacturer + Enclosure Type
     ''' </summary>
     HardwareID_12 = 12

     ''' <summary>
     ''' HardwareID-13
     ''' <para></para>
     ''' Manufacturer + Baseboard Manufacturer + Baseboard Product
     ''' </summary>
     HardwareID_13 = 13

     ''' <summary>
     ''' HardwareID-14
     ''' <para></para>
     ''' Manufacturer
     ''' </summary>
     HardwareID_14 = 14

 End Enum

*Computer hardware id generation method:
 Public Shared Function GetComputerHardwareIdFromMicrosoftHwIdType(hwidType As ComputerHardwareIdMicrosoftType) As Guid

     Select Case hwidType
         Case Is < 0, Is > 14
             Throw New InvalidEnumArgumentException(argumentName:=NameOf(hwidType), invalidValue:=hwidType, enumClass:=GetType(ComputerHardwareIdMicrosoftType))

     '' *************************************************************
     '' HARDWARE TYPE ID. 0, 1 AND 2 ARE NOT GIVING THE CORRECT GUID.
     '' *************************************************************
         Case 0, 1, 2, 12
             Throw New NotImplementedException("This hardware id type is not implemented.")
     End Select

     ' Namespace used by 'computerhardwareids.exe' program included in the Windows SDK.
     ' https://stackoverflow.com/questions/25190906/get-hardware-ids-like-microsoft-does/43619888#43619888
     ' https://blogs.gnome.org/hughsie/2017/04/25/reverse-engineering-computerhardwareids-exe-with-winedbg/
     Dim namespaceUUID As Guid = Guid.Parse("70ffd812-4c7f-4c7d-0000-000000000000")

     ' Win32_ComputerSystem fields
     Dim manufacturer, family, productName, skuNumber As String

     ' Win32_BaseBoard fields
     Dim baseBoardManufacturer, baseBoardProduct As String

     ' Win32_BIOS fields
     Dim biosVendor, biosVersion, biosMajorRelease, biosMinorRelease As String

     ' Retrieve computer info.
     Using mos As New Management.ManagementObjectSearcher()

         ' Win32_ComputerSystem
         mos.Query.QueryString = "select Manufacturer,Model,SystemFamily,SystemSKUNumber from Win32_ComputerSystem"
         Using systemInfo As Management.ManagementObject = mos.Get(0)
             manufacturer = CStr(systemInfo.Properties("Manufacturer").Value).Trim()
             productName = CStr(systemInfo.Properties("Model").Value).Trim()
             family = CStr(systemInfo.Properties("SystemFamily").Value).Trim()
             skuNumber = CStr(systemInfo.Properties("SystemSKUNumber").Value).Trim()
         End Using

         ' Win32_BaseBoard
         mos.Query.QueryString = "select Manufacturer,Product from Win32_BaseBoard"
         Using baseBoardInfo As Management.ManagementObject = mos.Get(0)
             baseBoardManufacturer = CStr(baseBoardInfo.Properties("Manufacturer").Value).Trim()
             baseBoardProduct = CStr(baseBoardInfo.Properties("Product").Value).Trim()
         End Using

         ' Win32_BIOS
         mos.Query.QueryString = "select Manufacturer,SMBIOSBIOSVersion,SystemBiosMajorVersion,SystemBiosMinorVersion from Win32_BIOS"
         Using biosInfo As Management.ManagementObject = mos.Get(0)
             biosVendor = CStr(biosInfo.Properties("Manufacturer").Value).Trim()
             biosVersion = CStr(biosInfo.Properties("SMBIOSBIOSVersion").Value).Trim()
             biosMajorRelease = CStr(biosInfo.Properties("SystemBiosMajorVersion").Value).Trim()
             biosMinorRelease = CStr(biosInfo.Properties("SystemBiosMinorVersion").Value).Trim()
         End Using

     End Using

 #If DEBUG Then
     ' Console.WriteLine($"{NameOf(manufacturer)}          = {manufacturer}")
     ' Console.WriteLine($"{NameOf(productName)}           = {productName}")
     ' Console.WriteLine($"{NameOf(family)}                = {family}")
     ' Console.WriteLine($"{NameOf(skuNumber)}             = {skuNumber}")
     ' Console.WriteLine($"{NameOf(baseBoardManufacturer)} = {baseBoardManufacturer}")
     ' Console.WriteLine($"{NameOf(baseBoardProduct)}      = {baseBoardProduct}")
     ' Console.WriteLine($"{NameOf(biosVendor)}            = {biosVendor}")
     ' Console.WriteLine($"{NameOf(biosVersion)}           = {biosVersion}")
     ' Console.WriteLine($"{NameOf(biosMajorRelease)}      = {biosMajorRelease}")
     ' Console.WriteLine($"{NameOf(biosMinorRelease)}      = {biosMinorRelease}")
 #End If

     Dim stringToHash As String = String.Empty

     Select Case hwidType

         Case ComputerHardwareIdMicrosoftType.HardwareID_0
             stringToHash = $"{manufacturer}&{family}&{productName}&{skuNumber}&{biosVendor}&{biosVersion}&{biosMajorRelease}&{biosMinorRelease}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_1
             stringToHash = $"{manufacturer}&{family}&{productName}&{biosVendor}&{biosVersion}&{biosMajorRelease}&{biosMinorRelease}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_2
             stringToHash = $"{manufacturer}&{productName}&{biosVendor}&{biosVersion}&{biosMajorRelease}&{biosMinorRelease}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_3
             stringToHash = $"{manufacturer}&{family}&{productName}&{skuNumber}&{baseBoardManufacturer}&{baseBoardProduct}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_4
             stringToHash = $"{manufacturer}&{family}&{productName}&{skuNumber}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_5
             stringToHash = $"{manufacturer}&{family}&{productName}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_6
             stringToHash = $"{manufacturer}&{skuNumber}&{baseBoardManufacturer}&{baseBoardProduct}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_7
             stringToHash = $"{manufacturer}&{skuNumber}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_8
             stringToHash = $"{manufacturer}&{productName}&{baseBoardManufacturer}&{baseBoardProduct}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_9
             stringToHash = $"{manufacturer}&{productName}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_10
             stringToHash = $"{manufacturer}&{family}&{baseBoardManufacturer}&{baseBoardProduct}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_11
             stringToHash = $"{manufacturer}&{family}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_13
             stringToHash = $"{manufacturer}&{baseBoardManufacturer}&{baseBoardProduct}"

         Case ComputerHardwareIdMicrosoftType.HardwareID_14
             stringToHash = manufacturer

     End Select

     ' Creates a name-based UUID using the algorithm from RFC 4122 §4.3.
     ' https://stackoverflow.com/questions/61267254/generating-uuid-based-on-strings
     Dim generateGuidDelegate As Func(Of Guid, String, Guid) =
         Function(namespaceId As Guid, name As String) As Guid

             ' Converts a GUID (expressed as a byte array) to/from network order (MSB-first).
             Dim swapByteOrderDelegate As New Action(Of Byte())(
                 Sub(ByVal guid() As Byte)
                     Dim temp As Byte = guid(0)
                     guid(0) = guid(3)
                     guid(3) = temp

                     temp = guid(1)
                     guid(1) = guid(2)
                     guid(2) = temp

                     temp = guid(4)
                     guid(4) = guid(5)
                     guid(5) = temp

                     temp = guid(6)
                     guid(6) = guid(7)
                     guid(7) = temp
                 End Sub)

             ' Convert the name to a sequence of octets (as defined by the standard or conventions of its namespace) (step 3).
             Dim nameBytes() As Byte = Encoding.Unicode.GetBytes(name)

             ' Convert the namespace UUID to network order (step 3).
             Dim namespaceBytes() As Byte = namespaceId.ToByteArray()
             swapByteOrderDelegate.Invoke(namespaceBytes)

             ' Compute the hash of the name space ID concatenated with the name (step 4).
             Dim hash As Byte()
             Using algorithm As HashAlgorithm = SHA1.Create()
                 algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, Nothing, 0)
                 algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length)
                 hash = algorithm.Hash
             End Using

             ' Most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12).
             Dim newGuid(15) As Byte
             Array.Copy(hash, 0, newGuid, 0, 16)

             ' Set the four most significant bits (bits 12 through 15) of the time_hi_and_version field
             ' to the appropriate 4-bit version number from Section 4.1.3 (step 8).
             newGuid(6) = CByte((newGuid(6) And &HF) Or (5 << 4))

             ' Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved
             ' to zero and one, respectively (step 10).
             newGuid(8) = CByte((newGuid(8) And &H3F) Or &H80)

             ' Convert the resulting UUID to local byte order (step 13).
             swapByteOrderDelegate.Invoke(newGuid)
             Return New Guid(newGuid)
         End Function

     Return generateGuidDelegate.Invoke(namespaceUUID, stringToHash)

 End Function

*Usage example:
 'Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(0)}}}    <- Manufacturer + Family + ProductName + SKUNumber + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release")
 'Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(1)}}}    <- Manufacturer + Family + ProductName + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release")
 'Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(2)}}}    <- Manufacturer + ProductName + BIOS Vendor + BIOS Version + BIOS Major Release + BIOS Minor Release")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(3)}}}    <- Manufacturer + Family + ProductName + SKUNumber + Baseboard Manufacturer + Baseboard Product")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(4)}}}    <- Manufacturer + Family + ProductName + SKUNumber")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(5)}}}    <- Manufacturer + Family + ProductName")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(6)}}}    <- Manufacturer + SKUNumber + Baseboard Manufacturer + Baseboard Product")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(7)}}}    <- Manufacturer + SKUNumber")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(8)}}}    <- Manufacturer + ProductName + Baseboard Manufacturer + Baseboard Product")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(9)}}}    <- Manufacturer + ProductName")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(10)}}}    <- Manufacturer + Family + Baseboard Manufacturer + Baseboard Product")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(11)}}}    <- Manufacturer + Family")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(13)}}}    <- Manufacturer + Baseboard Manufacturer + Baseboard Product")
 Console.WriteLine($"{{{GetComputerHardwareIdFromMicrosoftHwIdType(14)}}}    <- Manufacturer")

A: By trial and error trying possible formattings, I found that the numeric values (of type byte) must be converted to hexadecimal, and they must be in lower-casing.
So the only changes I need to do in the source-code that I published in the main post, and in order to replicate Hardware-Id 0, 1, 2, is this:
biosMajorRelease = CByte(biosInfo.Properties("SystemBiosMajorVersion").Value).ToString("X2").ToLower()
biosMinorRelease = CByte(biosInfo.Properties("SystemBiosMinorVersion").Value).ToString("X2").ToLower()

That and of course remove the NotImplementedException line.
Now the code works to get all hardware ids except the HardwareId-12 because I'm not aware in which WMI class to find the Enclosure Type value, which by the way is a byte type too.
But it doesn't really matter. I have 13 working CHIDS out of 14 and I consider it is a very good rate to finally say this is a complete managed solution to replicate what computerhardwareids.exe does, although I didn't tested it out of my PC.


text:
Q: Using data in an associative array as the object fo an event handler Afternoon All
I have some data -
    var searchwithin = [
{id:"clearwithin", type:"button"},
    {id:"search_radius", type:"select"},
    {id:"for_lease" ,type:"checkbox"},
{id:"for_sale", type:"checkbox"},
];

It is going to be showing and hiding informtion dependent on what is clicked (this is only a small fragment of the data.
I have already worked out how to check the type property, what I want to know is the following:
If the type is button, how do I access the id value for that items and then generate a click function so that that uses the id as the name of the button to associate the function with.
Thanks in advance
Phil

A: Concatenate '#' and the id property and use the resulting string as a selector.
$.each($.grep(searchwithin, function(i) { return i.type=='button'; }),
    function () {
        var item = this;
        $('#'+this.id).bind('click', function(e) {
            alert('clicked: ' + item.id +' '+ item.type);
        });
    });

Consider using selectors to find elements rather than ID maps.
$('input[type="button"].search').bind('click', onSearch);

A: First, fix a syntax error in your searchwithin table by removing the comma after the last item in the table.  That will cause an error in IE6/IE7.
Then, you can use this code to look through your searchwithin array to find the id for the appropriate type and then set a click event handler for that id.
var searchwithin = [
    {id:"clearwithin", type:"button"},
    {id:"search_radius", type:"select"},
    {id:"for_lease" ,type:"checkbox"},
    {id:"for_sale", type:"checkbox"}
];

function findIdByType(target) {
    for (var i = 0; i < searchwithin.length; i++) {
        if (searchwithin[i].type === target) {
            return(searchwithin[i].id);
        }
    }
}

var id = findIdByType("button");
if (id) {
    $("#" + id).click(function() {
        // do whatever you want to do on the click function here
    }
});

I notice that your table has two entries for type:checkbox.  The above code suggestion will return and operate on the first entry only.  If you want to set up click handlers for both those IDs, then either the code or table would have to be modified.  If this is all the table is used for, it could be changed to be a selector (which can contain more than one id) like this:
var searchwithin = [
    {id:"#clearwithin", type:"button"},
    {id:"#search_radius", type:"select"},
    {id:"#for_lease, #for_sale", type:"checkbox"}
];

function findSelectorByType(target) {
    for (var i = 0; i < searchwithin.length; i++) {
        if (searchwithin[i].type === target) {
            return(searchwithin[i].id);
        }
    }
}

var selector = findSelectorByType("button");
if (selector) {
    $(selector).click(function() {
        // do whatever you want to do on the click function here
    }
});


text:
Q: Autocomplete: detect no results with remote datasource Context

*

*I use jQuery UI autocomplete with a remote datasource.

*The source send data in this format: [{'label':'Bob', 'id':'03362548'}, {...}].

*I display a loader gif when the search begin.

*Data filtering is done serverside.

*I want to hide the loader gif if no results (the server send []).

Question
How to detect if the search has no results for hiding the loader gif?
Code
jquery:
$('#redir-output').autocomplete({
    source: 'php/ajax/autocomplete.php',
    search: function(event, ui) {
        $('#redir-loader').show();
    },
    open: function(event, ui) {
        $('#redir-loader').hide();
    },
    select: function(event, ui) {
        $(this).attr('name', ui.item.id);
    }
});

A: By default, when the plugin displays the results, it checks if there's data to show. In the case there isn't, it closes the menu.
_response: function(content) {
    if (!this.options.disabled && content && content.length) {
        ...
    } else {
        // it closes the menu when content.length == 0 (no data)
        this.close();
    }

Closing the menu raises the "close" event, so I though you could use it. However, the close event is only triggered when the menu is visible:
close: function(event) {
    clearTimeout(this.closing);
    // as the menu might not be visible at that moment, this is reliable
    if (this.menu.element.is(":visible")) {
        ...
        this._trigger("close", event);
    }
}

I think you will have to use the source as a callback and implement yourself the ajax request. Using the "complete" callback, you can hide the loading icon, which in any case should be hidden when the request is over, data returned or not:
$('#redir-output').autocomplete({
    source: function(request, response) {

        $.ajax({
            url: 'php/ajax/autocomplete.php',
            data: request,
            dataType: "json",
            success: function(data, status) {
                response(data);
            },
            error: function() {
                response([]);
            },
            complete: function() {
                $('#redir-loader').hide();
            }
        });

    },

    ,
    search: function(event, ui) {
        $('#redir-loader').show();
    },
    open: function(event, ui) {
        $('#redir-loader').hide();
    },
    select: function(event, ui) {
        $(this).attr('name', ui.item.id);
    }
});?


text:
Q: Win32Exception "Not enough storage is available to process this command" when creating a lot of BitmapSource-Objects In our application we are exporting a lot of images and we ran into this Win32Exception:
System.ComponentModel.Win32Exception (0x80004005): Not enough storage is available to process this command
    at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
    at System.Windows.Threading.Dispatcher..ctor()
    at System.Windows.DependencyObject..ctor()
    at System.Windows.Media.Imaging.BitmapSource..ctor(Boolean useVirtuals)
    at System.Windows.Media.Imaging.CachedBitmap..ctor(Int32 pixelWidth, Int32 pixelHeight, Double dpiX, Double dpiY, PixelFormat pixelFormat, BitmapPalette palette, Array pixels, Int32 stride)
    at System.Windows.Media.Imaging.BitmapSource.Create(Int32 pixelWidth, Int32 pixelHeight, Double dpiX, Double dpiY, PixelFormat pixelFormat, BitmapPalette palette, Array pixels, Int32 stride)

The problem is, that we create BitmapSource objects in different threads and there is a memory leak. If you execute this code, there are still a lot of objects in memory:
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 100; i++)
{
    Thread t = new Thread(new ThreadStart(() =>
    {
        BitmapSource temp = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgr24, null, new byte[3], 3);
        temp.Freeze();
    }));
    t.Start();
    threads.Add(t);
}
foreach (var thread in threads)
{
    thread.Join();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

We do this in a Windows service and after a few days the system crashes. With the "Not enough storage..."-Message. At this point a lot of other applications crash, you can't open up an editor or other Windows applications. Could it be, that the Desktop Heap is full? The memory doesn't go up much (160MB max) and the machine has 16GB of RAM.
How do we dispose the BitmapSource correctly?

A: We found a solution, where we don't see a memroy leak:
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 100; i++)
{
    Thread t = new Thread(new ThreadStart(() =>
    {
        BitmapSource temp = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgr24, null, new byte[3], 3);

        // Shutdown Dispatcher
        if (temp.Dispatcher != null)
        {
            temp.Dispatcher.InvokeShutdown();
        }

        temp.Freeze();
    }));
    t.Start();
    threads.Add(t);
}
foreach (var thread in threads)
{
    thread.Join();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

We have to see if this causes other problems, what do you think?

A: The memory leak seems related to the bitmaps not being created on the main thread and the dispatcher keeping a reference. The solution you found might work.
However, I'd like to suggest another improvement. Using an unlimited number of threads might not be a good idea. It might make sense to use a thread pool. The easiest way would be to use Task.Run to schedule the bitmap creation on the thread pool. In fact, I didn't see any memory leaks when using the thread pool.
var tasks = new List<Task>();
for (int i = 0; i < 100000; i++)
{
    var task = Task.Run(() =>
    {
        BitmapSource temp = null;
        temp = BitmapSource.Create(
            1,
            1,
            96,
            96,
            PixelFormats.Bgr24,
            null,
            new byte[3],
            3);
        temp.Freeze();
    });
    tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());

A: As you can see in .NET Reference Source,
BitmapSource.Create simply calls CachedBitmap constructor which, by default, uses BitmapCachinOptions.Default as caching options. It means that every bitmap created will be held in cache.
You need to used some other class inherited from BitmapSoure that doesn't use caching. You could try WritableBitmap if you want to create bitmap yourself.


text:
Q: Mobile Xpage dojo error, cannot find dojo version 1.9.4 My iOS and Android apps use 2 mobile Xpages. I had issues when iOS 8.0 came out, and had to install dojo 1.9.4 on our server.
Today for some reason the 2 mobile Xpages cannot find dojo.
When I open the Mobile Xpage in Chrome I get the following error:
But it appears to me that dojo is in the correct place:

When I check for my dojo version in an Xpage with
com.ibm.xsp.context.DojoLibraryFactory.getDefaultLibrary().getVersion()

in a computed field I get 1.9.4.
Our server is version 9.0.1.
Over the weekend we installed the latest version of the ExtLib (16) and the OpenNTF ODA extension and rebooted then server.
Any assistance would be greatly appreciated.


text:
Q: How to add Event Receiver for subsites I have sub sites of departments and under each department site I have sub sites of programs. I want to add an event receiver that should invoke when a sub site of department is created. so that I can add the name of that program and department is list.

A: MOSS 2007 : SharePoint does not have event handling for Site Creation.
SP 2010 : Take a look at Site WebProvisioned and WebAdding methods.

A: Do you control what kinds of sites are created?
If so you could add a feature to the sitedefinitions which can write to your list in its feature activated method of the feature receiver.


text:
Q: Connecting a USB Thermal Printer in Laravel Homestead I'm running Windows 10, my Laravel app runs inside vagrant/laravel homestead using virtual box.
I need to connect a printer to print out receipts using this package ESCPOS-PHP I tried this using XAMPP it works, but I don't know to make it work when my application is running inside vagrant/laravel homestead

A: I should warn you that the laravel homestead environment is meant only for development and not production. However if you want to connect any device to the vagrant box you can opt for enabling the gui configuration adding
config.vm.provider "virtualbox" do |vb|
    vb.gui = true
end

at the end of the file named Vagrantfile. This option will have as a result to start Homestead in a VirtualBox window allowing you to attach usb devices by right clicking on the USB connector icon at the lower right of the window.
Bear in mind that VirtualBox has support only for USB 1.1 if you haven't installed the VirtualBox Extension Pack. Downloading the Extension Pack and installing it enables USB2.x and 3.x support.
Make sure that the printer is supported in Linux as making the connection is only part of the problem. The Open Printing site has support status for most printers.


text:
Q: How did Newton find derivative of basic functions before formulating systematic Calculus? I think I read somewhere that Newton tried to find derivatives of basic functions like $x^2$ before formulating systematic calculus; how did/would he do it?

A: Here is some historical information cited from Oskar Beckers Grundlagen der Mathematik in geschichtlicher Entwicklung (say: Foundations of mathematics in historical development).
The first matured presentation of Newtons (1643 - 1727) method of fluxions which was his name of differential calculus dates from 1670/71. The title was Methodus fluxionum et serierum infinitarum and has been posthumously  published in 1736.

Newton started to think about fluxions some years before. Here is a small excerpt from one of his early notes cited from O. Becker [ch. Fluxionsmethode p.147].

*

*Newton: (from 23.11.1665)
...If two bodies $A$ and $B$ move uniformly, one of them from $A$ to $C,E$ and $G$, the other from $B$ to $D,F$ and $H$ along the same line, then the line segments $\overline{AC}$ and $\overline{BD}$, $\overline{CE}$ and $\overline{DF}$, $\overline{EG}$ and $\overline{FH}$ behave in the same manner as their velocities $p$ and $q$ and, if they do not uniformly move, then the infinite small line segments behave in each momentum as their velocities in each momentum.

If  the body $A$ with velocity $p$ describes the infinite small distance $o$ in a momentum, then the body $B$ will describe in the same momentum with velocity $q$ the distance  $\frac{op}{q}$. Since $p:q=o:\frac{oq}{p}$. So, if the line segments already described within one momentum  are $x$ and $y$, the next will be $x+o$ and $y+\frac{oq}{p}$.
Now I'm allowed, if the equation of the line is represented by
  \begin{align*}
rx+xx-yy=0
\end{align*}
  to substitute $x+o$ and $y+\frac{oq}{p}$ for $x$ and $y$ in the equation. This is valid, since they both mean in the same way as $x$ and $y$ the travelled distance described by the bodies $A$ and $B$. We obtain:
  \begin{align*}
rx+xo+xx+2xo+oo-yy-\frac{2qoy}{p}-\frac{qqoo}{pp}=0
\end{align*}
  But, according to the assumption we have:
  \begin{align*}
rx+xx-yy=0
\end{align*}
  after subtraction:
  \begin{align*}
ro+2xo+oo-\frac{2qoy}{p}-\frac{qqoo}{p}=0
\end{align*}
  and after division by $o$:
  \begin{align*}
r+2x+o-\frac{2qy}{p}-\frac{oqq}{p}=0
\end{align*}
Now, the terms which contain $o$ are infinitely smaller than the terms which do not contain $o$. So, after cancelling these terms we obtain:
  \begin{align*}
r+2x-\frac{2qy}{p}=0\qquad\text{or}\qquad pr+2px=2qy
\end{align*}
...

This is an early example how Newton treated problems of differentiation of functions like $y=x^2$.  It indicates the development of differential calculus was driven solely to solve physical problems and calculation with infinitesimals was reasoned by physical evidence.
According to O.Becker it was Newtons teacher Isaac Barrow who inspired him to develop these first ideas. On the other hand intensive studies indicate that especially Blaise Pascal inspired Leibniz in his development of differential calculus methods.

A: The earliest formulations of something that looks like calculus were not in terms of functions but of curves given by algebraic relations. So if we have
$$ y=x^2 $$
and $(y+p,x+q)$ is another point on the curve, we would also have
$$ (y+p) = (x+q)^2 $$
and if we multiply these equations out and subtract we get
$$ p = 2qx + q^2 $$
Now what happens in the earliest sources is that it is simply postulated, without any backing by theoretical definitions or limits that when $p$ and $q$ are small, we can remove their higher powers, so ignoring the $q^2$ term yields us
$$ p = 2qx \qquad\text{or, in other words,}\qquad p:q = 2x:1 $$
which can be used to draw a tangent.
The justification for this procedure was initially just that it worked in practice, but the unexplained ignoring of terms like $q^2$ drew quite a lot of contemporary criticism.
This was in the generation before Newton (chiefly Fermat and Descartes). They could produce painstaking geometric proofs in the Euclidean tradition (which was the gold standard for proofs in those days) that for each of the actual curves they considered what came out of this procedure was the right result -- but they didn't have the definitions and machinery to explain or prove rigorously why the procedure always works.
Newton brought in the new idea of a quantity $x$ that varied with time and its time rate of change $\dot x$, but he was still building on the "ignore higher powers of the increments" method. But he did it masterfully and was able to get more out of it than his predecessors did.

A: Here was how for $f(x)=x^2$:
$$\frac{f(x+o)-f(x)}{o}=2x+o.$$
Now if $o$ gets small, the quotient gets close to $2x$, so Newton declared that when $o$ "gets to" 0, the quotient "gets to" $2x$.
Note, though, that in Newton's times there was no rigorous formulation of limits. So perhaps he was drawing conclusions somewhat from intuition and experimentation. But also keep in mind that intuition was where calculus stemmed from.

A: Some of these were likely found through a combination of intuition and geometric reasoning.
Consider $y = x^2$. Notice that the square of side length $x$ has area $y$. Suppose that we change the side length by $dx$. Then what is the change in the area of the rectangle $dy$?

I apologize for the crudely drawn picture, but notice that the change in area that we get is,
$$dy = xdx+xdx+(dx)^2 = 2xdx+(dx)^2 \approx 2xdx$$
for small enough $dx$ (i.e. the little black square is insignificantly small). And thus,
$$\frac{dy}{dx} = \frac{2xdx}{dx} = 2x.$$
Similar reasoning can be used to show that $\frac{d}{dx} (x^3) = 3x^2$ by considering the change in volume of a cube.
EDIT: Figured it was worth mentioned that this same square technique can be used to intuitively see why $\frac{d}{dx}(f(x) \cdot g(x)) = f(x)g'(x)+f'(x)g(x)$.
EDIT 2: After you have the product rule, it is easy to derive the power rule (over the natural numbers) using induction. The base case $\frac{d}{dx}(x^1) = 1$ is obvious. If we assume $\frac{d}{dx}(x^k) = kx^{k-1}$, then,
$$\frac{d}{dx}(x^{k+1}) = \frac{d}{dx}(x^{k} \cdot x) = \frac{d}{dx}(x^{k})\cdot x + x^{k} \cdot \frac{d}{dx}(x)$$$$ = kx^{k-1}\cdot x+x^k\cdot 1 = kx^k+x^k = (k+1)x^k.$$

A: Surely any child with an interest in numbers will notice that in a quadratic sequence like 1, 4, 9, 16, 25, ..., the differences between successive terms form a linear sequence like 3, 5, 7, 9, ...? That doesn't need calculus; but someone with a sophisticated mathematical brain will start to recognise that there's a relationship between the function that generates the first sequence and the function that generates the second, and will develop such thinking to discover the principles of calculus.


text:
Q: Dimension of null space Consider the linear transformation $T:\mathbb{R}^2\rightarrow \mathbb{R}^3$ such that $T(x_1,x_2)=(x_1-x_2, x_2-x_1, -x_1)$. Find dimension of null space.
Now in this question, I find that the only member of the null space is the zero vector. So the dimension should be $1$. But the answer is $0$. Why is it so ?

A: The subspace consisting of only the zero vector, has dimension $0$.
Take a look at "Why $\mathbf{0}$ vector has dimension zero?" for more details, but note that in this question/title, it should be the "subspace $\left\{ {\bf 0} \right\}$" rather than only the "element ${\bf 0}$".

Now in this question, I find that the only member of the null space is the zero vector. So the dimension should be $1$. But the answer is $0$. Why is it so ?

If the dimension would be $1$, any basis for this subspace would consist of exactly one (non-zero) vector (by the definition of dimension), since a basis has to be linearly independent. But then the subspace spanned by this basis necessarily has an infinite number of elements, since all scalar multiples of the basis vector are in the subspace.


text:
Q: CURL PHP MyGate Payment gateway I am trying to post some details to mygate payment gateway.
If i use a normal form and post to the url, it generates a token id for that specific session and internally redirects the page to the details capturing page.
As i am using curl to do so, i get a success message but i am unable to get the required page.
Is it possible to load the same page in a new tab using curl, I suspect that would help me in some way.
Any other solution would also be appreciated.
Code i have tried is:
    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);

    //turning off the server and peer verification(TrustManager Concept).
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);

    $result = curl_exec($ch);

    if(!$result)
    {
        echo curl_error($ch);
    }
    else
    {
        echo $result;
    }

    //close connection
    curl_close($ch);

Thanks in Advance!

A: Since its redirecting to a page on success, You can get the location of the redirected url.
You can get the redirect URL by setting some curl options.
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
 $l = trim($r[1]);

$l would be the redirect location. You can get the url and redirect your page to the location.
$r will contain an array with location url.


text:
Q: Display 'sum' on another page I am currently having a problem displaying a calculated sum on the next page in javascript/html.
My calculation for defining the sum looks like this, where the 'sum + €' is displayed at the end.
function udregnPant() {

    let sum = 0;
    for (i = 0; i <= pantListParsed.length; i++) {

        let totalPantKr = pantListParsed[i].aPantMoney + pantListParsed[i].bPantMoney + pantListParsed[i].cPantMoney;
        sum += totalPantKr;

        console.log(sum);
        document.getElementById('sumAfPantB').innerHTML = sum + " €.";
    }

}

In the following HTML input I want to display the sum as the value instead of '10 €'
 <input type="text" name="amount" id="text1" value="10 €." readonly/>

Appreciate your help!

A: Make use of web storage.
sessionStorage - stores data for one session
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

localStorage - stores data with no expiration date
localStorage.getItem('label')
localStorage.setItem('label', 'value')

Example
function setSum(value) {
    localStorage.setItem("sum", value);
}

function getSum() {
    return localStorage.getItem("sum");
}

Live Example at JS Bin
References
Share data between html pages
HTML5 Web Storage

A: *

*After calculating your value, redirect the user to a URL with the value in the query string (See Redirections in HTTP) -- this may look something like

window.location = http://mysite/page2.html?amount=12

*On the new page, retrieve the value from the query string using the searchParams property (see URL.searchParams). Could look something like:

let params = (new URL(document.location)).searchParams;
document.getByElementId('text1').value = params.get('amount');

A: Here is a little example using local Storage, since so doesnt allow local storage try it in jsfiddle and
the code sample as well:

document.getElementById('btnSend').onclick = ()=>{
let total = document.getElementById('txtTotal').value;
if(!isNaN(total) && total > 0){
localStorage.setItem('total', total);
document.getElementById('txtTotal').value = '';
}
}
document.getElementById('btnLastTotal').onclick = ()=>{
var lastTotal = localStorage.getItem('total');
if(lastTotal !=undefined){
alert('last total is:'+lastTotal);
}else{
alert('No records found');
}
}
<input type="text" id="txtTotal">
<br>
<input type="button" id="btnSend" value="Save the total"> <input type="button" id="btnLastTotal" value="get Last Total">

Hope it helps


text:
Q: Enforce ordering without enforcing dependency I have some "phony" targets that I occasionally want to run in a specific order, but are not strictly dependent on each other. For example:
.PHONY: image-build
image-build: Dockerfile
    docker build --tag foobar --file $< .

.PHONY: image-tag
image-tag: image-build
    docker tag foobar foobar:latest

.PHONY: image-push
image-push:
    docker push foobar:latest

I don't always want to run image-tag before image-push. However, if I do happen to run them together, as in make image-tag image-push, I want to ensure that image-tag runs before image-push.
That is, whenever image-tag and image-push both appear in the dependency graph, I want image-tag to be executed first, but when image-push is in the dependency graph and image-tag is not, I do not want image-tag to be added to the dependency graph.
Is it possible to enforce this rule in GNU Make?
For now, I have created a workaround command:
.PHONY: image-deploy
image-deploy: image-tag
    $(MAKE) image-push

A: You can do this:
image-push: $(filter image-tag,$(MAKECMDGOALS))
         docker push foobar:latest

The filter will expand to nothing if image-tag is not specified as a goal target (on the command line), else it will expand to image-tag.


text:
Q: Trouble creating algorithm that modifies elements of a 2d array I am having trouble editing the values of a 2d char array.
char[,] chrRaster = new char[4, 5];

After adding values to the array and printing it to the console, I get:
// Input example:
*****
**.**
*****
****.

I am trying to make an algorithm that replaces every '*' that is beside, under or above a '.' by a '.' and then printing this to the console.
// Output after algorithm example:
**.**
*...*
**.*.
***..

I have tried converting the 2d char array to a 2d string array and then using IndexOf('*') to replace every '*' that is beside, under or above a '.', and I also tried calculating this using a number of if and for loops without any luck.
 static void Main(string[] args)
        {
            // Variablen
            int intTestgeval = 0; // Number of times you want program to repeat
            int intN = 0;         // Number of rows
            int intM = 0;         // Number of coloms
            char chrGrond;        // Used to store '*' or '.'
            char[,] chrRaster;    // 2d char array used to store all values

            // Code
            try
            {
                intTestgeval = Int32.Parse(Console.ReadLine()); // Number of times program will repeat

                if(intTestgeval > 150) // Program can not repeat more then 150 times
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Environment.Exit(0);
            }

            intN = Controle(intN);                          // Number of rows ophalen
            intM = Controle(intM);                          // Number of Coloms ophalen

            chrRaster = new char[intN, intM];               // Initializing array with user input

            for (int intR = 0; intR < intTestgeval; intR++)  // Print 2d array to console
            {
                for(int intY = 0; intY < intN; intY++)
                {
                    for(int intZ = 0; intZ < intM; intZ++)
                    {
                        chrGrond = Convert.ToChar(Console.ReadKey().KeyChar);

                        chrRaster[intY, intZ] = chrGrond;
                    }
                    Console.WriteLine();
                }

                instorten[intR] = Instorten(chrRaster, intN, intM); // Ignore this part, that's another part of my assignment not related to my question.
            }
        }

        static int Controle( int intX )
        {
            try
            {
                intX = Int32.Parse(Console.ReadLine());

                if (intX > 150 || intX < 1) // Length of row and colom can not exceed 20 and can not go lower then 1
                {
                    throw new Exception();
                }
                return intX;
            }
            catch                           // Program will off if value does not meet requirements
            {
                Environment.Exit(0);
                return intX;
            }
        }

  // It is this part of the program I need help with. This is what I tried but can't get any further
        static int Instorten(char[,] chrRaster, int intN, int intM)
        {
            for (int intY = 0; intY < intN; intY++)
            {
                for (int intZ = 0; intZ < intM; intZ++)
                {
                    if(chrRaster[intY, intZ] == '.' && chrRaster[intY, intZ + 1] == '*' || chrRaster[intY, intZ] == '*' && chrRaster[intY, intZ + 1] == '.')
                    {

                    }
                }
                Console.WriteLine();
            }
            int intm = 0;
            return intm;
        }
    }

A: Here is the algorithm that does what you want. I have tried to explain my code in the comments. The output will match what you're looking for.
    static void Main(string[] args)
    {
        char STAR = '*';
        char DOT = '.';

        var input = new char[,]
        {
            { STAR,STAR,STAR,STAR,STAR},
            { STAR,STAR,DOT,STAR,STAR},
            { STAR,STAR,STAR,STAR,STAR},
            { STAR,STAR,STAR,STAR,DOT}
        };

        var output = new char[4, 5];

        // Copy each from input to output, checking if it touches a '.'
        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 5; y ++)
            {
                if (input[x, y] == STAR)
                {
                    var isDot = false;
                    // Check left
                    if (x > 0)
                        isDot = input[x - 1, y] == DOT;

                    // Check right
                    if (x < 3)
                        isDot = isDot || (input[x + 1, y] == DOT);

                    // Check above
                    if (y > 0)
                        isDot = isDot || (input[x, y - 1] == DOT);

                    // Check below
                    if (y < 4)
                        isDot = isDot || (input[x, y + 1]) == DOT;

                    output[x, y] = isDot ? DOT : STAR;
                }
                else
                {
                    output[x, y] = input[x, y];
                }
            }
        }

        // Print output
        for (int x = 0; x < 4; x ++)
        {
            for (int y = 0; y < 5; y ++)
            {
                Console.Write(output[x, y]);
            }
            Console.WriteLine();
        }

        Console.Read();
    }

A: One way to do this would be to make a copy of the array and then iterate over it, examining each item. If the item is a '.', then update the neighbors of this item in the original array.
To determine the neighbors, we simply add one to the row to get the neighbor below, subtract one from the row to get the neighbor above, and similarly we can get the right and left neighbors by adding/subtracting from the column value. Of course we need to ensure that we're inside the bounds of the array before doing anything.
We could write a method with this logic that might look like:
private static void ExposeDotNeighbors(char[,] input)
{
    if (input == null) return;

    // Make a copy of the input array that we can iterate over
    // so that we don't analyze items that we've already changed
    var copy = (char[,]) input.Clone();

    for (var row = 0; row <= copy.GetUpperBound(0); row++)
    {
        for (var col = 0; col <= copy.GetUpperBound(1); col++)
        {
            if (copy[row, col] == '.')
            {
                // Update neighbors in original array
                // Above = [row - 1, col], Below = [row + 1, col],
                // Left = [row, col - 1], Right = [row, col + 1]
                // Before updating, make sure we're inside the array bounds
                if (row > 0) input[row - 1, col] = '.';
                if (row < input.GetUpperBound(0)) input[row + 1, col] = '.';
                if (col > 0) input[row, col - 1] = '.';
                if (col < input.GetUpperBound(1)) input[row, col + 1] = '.';
            }
        }
    }
}

We can also write some helper methods that will give us the initial array and to print an array to the console (also one that will write a header to the console):
private static char[,] GetInitialArray()
{
    var initialArray = new char[4, 5];

    for (var row = 0; row <= initialArray.GetUpperBound(0); row++)
    {
        for (var col = 0; col <= initialArray.GetUpperBound(1); col++)
        {
            if ((row == 1 && col == 2) || (row == 3 && col == 4))
            {
                initialArray[row, col] = '.';
            }
            else
            {
                initialArray[row, col] = '*';
            }
        }
    }

    return initialArray;
}

private static void PrintArrayToConsole(char[,] input)
{
    if (input == null) return;

    for (var row = 0; row <= input.GetUpperBound(0); row++)
    {
        for (var col = 0; col <= input.GetUpperBound(1); col++)
        {
            Console.Write(input[row, col]);
        }

        Console.WriteLine();
    }
}

private static void WriteHeader(string headerText)
{
    if (string.IsNullOrEmpty(headerText))
    {
        Console.Write(new string('═', Console.WindowWidth));
        return;
    }

    Console.WriteLine('╔' + new string('═', headerText.Length + 2) + '╗');
    Console.WriteLine($"║ {headerText} ║");
    Console.WriteLine('╚' + new string('═', headerText.Length + 2) + '╝');
}

With these helper methods, we can then write code like:
private static void Main()
{
    var chrRaster = GetInitialArray();

    WriteHeader("Before");
    PrintArrayToConsole(chrRaster);

    ExposeDotNeighbors(chrRaster);

    WriteHeader("After");
    PrintArrayToConsole(chrRaster);

    GetKeyFromUser("\nDone! Press any key to exit...");
}

And out output would look like:

I noticed that you also appear to be getting the values from the user, and using try/catch blocks to validate the input. A better approach might be to write a helper method that takes in a string that represents the "prompt" to the user, and a validation method that can be used to validate the input. With this, we can keep asking the user for input until they enter something valid.
Below are methods that get an integer and a character from the user, and allow the caller to pass in a function that can be used for validation. These methods will not return until the user enters valid input:
private static char GetCharFromUser(string prompt, Func<char, bool> validator = null)
{
    char result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
        result = Console.ReadKey().KeyChar;
    } while (!(validator?.Invoke(result) ?? true));

    Console.WriteLine();
    return result;
}

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
                !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}

We can then re-write our GetInitialArray method to use these methods to get the dimensions and values from the user:
private static char[,] GetInitialArray()
{
    const int maxCols = 20;
    const int maxRows = 20;

    var numCols = GetIntFromUser(
        $"How many columns do you want (1 - {maxCols}): ",
        i => i > 0 && i <= maxCols);

    var numRows = GetIntFromUser(
        $"How many rows do you want (1 - {maxRows}): ",
        i => i > 0 && i <= maxRows);

    var initialArray = new char[numRows, numCols];

    for (var row = 0; row <= initialArray.GetUpperBound(0); row++)
    {
        for (var col = 0; col <= initialArray.GetUpperBound(1); col++)
        {
            initialArray[row, col] = GetCharFromUser(
                $"Enter value for [{row}, {col}] ('.' or '*'): ",
                c => c == '.' || c == '*');
        }
    }

    return initialArray;
}

And now our output might look like this:

If you try it, notice that you cannot enter an illegal value. The program just waits for you to read the instructions and enter a valid number or character. :)

A: You can go like this :
using System;
public class chars
{
    public static void Main(string[] args)
    {
        char[,] charArray = new char[,] {{'*','*','*','*','*'},
                                         {'*','*','.','*','*'},
                                         {'*','*','*','*','*'},
                                         {'*','*','*','*','.'}};
        int[,] holdIndex = new int[4, 5];

        for(int i = 0; i<4; i++)  // get allindexes containing '.'
        {
            for(int j = 0; j<5; j++)
            {
                if(charArray[i,j] == '.')
                    holdIndex[i,j] = 1;
                else
                    holdIndex[i,j] = 0;
            }
        }

        for(int i = 0; i<4; i++)
        {
            for(int j = 0; j<5; j++)
            {
                if(holdIndex[i,j] == 1)
                {
                    if(i!=0)
                        charArray[i-1,j] = '.';  //up
                    if(j!=0)
                        charArray[i,j-1] = '.';  // left
                    if(j!=4)
                        charArray[i,j+1] = '.';  //right
                    if(i!=3)
                        charArray[i+1,j] = '.';  //down
                }
            }
        }

        for(int i = 0; i<4; i++)
        {
            for(int j = 0; j<5; j++)
            {
                Console.Write(charArray[i,j]);
            }
            Console.WriteLine();
        }
        Console.Read();
    }
}


text:
Q: Does the second order non-linear ODE $yy''=f(x)f(x)''$ have a general solution? I was working on this problem and came across an equation of the form
\begin{align}
yy''=f(x)f(x)''.
\end{align}
The equation $yy''=f(x)$ does not have a general solution (that I or WA can find), but this equation has the particular solutions $y_{0,1}=\pm f(x)$, which gives me a bit of hope. I also tried a solution of the form $y=\sqrt{f(x)^2+g(x)}$ for some $g(x)$ to be determined, but I believe only $g(x)\equiv0$ works.
Non-linear equations don't always have general solutions or transformations to simpler equations given particular solutions, but perhaps someone is aware of one for such an equation?
Edit
I've channeled my inner Claude Leibovici for this idea, taking $x$ to be the dependent variable and $y$ to be the independent variable:
\begin{align}
y''=-\frac{x''}{(x')^3},\quad\text{and}\quad
f''=-\frac{x''}{(x')^3}f'+\frac{1}{(x')^2}f''.
\end{align}
So then
\begin{align}
-y\frac{x''}{(x')^3}=-\frac{x''}{(x')^3}ff'+\frac{1}{(x')^2}ff'\quad\longrightarrow\quad
x''+\frac{ff''}{y-ff'}x'=0.
\end{align}
Using the integrating factor
\begin{align}
\ln(\mathrm E)&=\int\frac{ff''\mathrm dy}{y-ff'},\\
\left(\mathrm Ex'\right)'=0&\quad\longrightarrow\quad
x'=\frac{k_1}{\mathrm E},\\
x(y)&=k_1\int\frac{\mathrm dy}{\mathrm E}+k_2.
\end{align}
This strikes me as a solution at first, but after thinking a little I'm not so certain. Evaluating the integral for $\mathrm E$ requires knowing the first and second derivative of $f$ with respect to $y$, which I'm not sure is possible without knowing the solution to the original ODE.


text:
Q: React error boundaries not working properly with random error? I'm reading up on the official React docs concerning Error Boundaries (React Docs Error Boundaries) and did some testing of my own. To simulate an unpredictable error, an error that sometimes occur, I used Math.random(). The below sample code shows my simple example.
App.jsx
import ErrorBoundary from './components/ErrorBoundary';
import { ShakySectionFunc } from './components/ShakySection';

function App() {
    return (
        <>

Below is some section that can break...

            <ErrorBoundary>
                <ShakySectionFunc />
            </ErrorBoundary>
        </>
    );
}

export default App;

ShakySection.jsx
export function ShakySectionFunc() {
    const isFail = Math.random() < 0.5; // Simulate a random error.
    if (isFail)
        throw Error('Oh oh, something went wrong');
    return
This is stuff from the ShakySectionFunc component
;
}

ErrorBoundary.jsx
import React from 'react';

export default class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    componentDidCatch(error, errorInfo) {
        this.setState({ hasError: true });
    }

    render() {
        if (this.state.hasError) {
            return
Something went wrong
; // The UI fallback.
        }
        return this.props.children;
    }
}

Now, if isFail becomes true then the Error Boundary is not working. In the below picture one can see that the UI fallback element,
Something went wrong
, does not display, as the error was not caught by the Error Boundary.

My guess as to what's happening is that React is re-rendering the ShakySectionFunc component several times when an error does occur. Including a console.log('ShakySectionFunc rendering'); statement as the first line in the component gives us this:

ShakySectionFunc rendering is output to the console three times, and I assume this means that the line const isFail = Math.random() < 0.5; is evaluated each time, and maybe the value becomes false during the last render which "messes up" the error handling by React? Please help me out here.
If we remove the randomness of the error from ShakySectionFunc the Error Boundary does behave as expected.
React Error Boundaries cannot be used for this type of "random errors"?


text:
Q: Adding a range on an enum field I am trying to add a range (which I believe functions as a filter, right?) on an Enum field. This data source table is used in a Web Report.
This is what I do in the init method of the Web Report:
this.query().dataSourceTable(tablenum(SupplProduct)).addRange(fieldnum(SupplProduct, ShowOnReport)).value(QueryValue(NoYesCombo::Yes));

ShowOnReport is a field of type NoYesCombo Enum.
The Web Report crashes with this error:
Invalid range

I've managed to find quite a few examples on the web and this seems to be the proper way to do it so it supports all languages.
Any ideas ?
Could it be the properties of the field I'm trying to add a range on ?
Right underneath the line of code above, there is another similar line doing exactly the same, on another field:
//this is at the beginning of the init method...
AppointmentTable    activeAppoint = element.args().record().data();
;

this.query().dataSourceTable(tablenum(AppointmentTable)).addRange(fieldnum(AppointmentTable, AppointmentId)).value(queryValue(activeAppoint.AppointmentId));

This range works fine.
Thanks.

A: Oh crap. The Enterprise Portal server and its Business Connector was still at version RTM while the AOS server it connects on is RU8. After I patched the EP server to RU8, this works.
Thanks.


text:
Q: Why some module can not load maven independencies when open a project use IDEA? My project has some modules,when I open the project ,some modules can load maven independencies automatically,but some not.I have change the module sdk,java compiler target type code to 1.8,but still can not load the maven project.How to fix it?My os is windows10 and idea is 2020.3.2.I have install openjdk1.8 in my system.

A: Set JDK for importer to java 8 and after click to Reload All Maven Projects button.


text:
Q: Error in Running Maps Activity on my Samsung Galaxy S Duos in Android Studio This is the source code of MainActivity. What's wrong in this?
package io.app.hasura.imad.namanyadav123.mapsactivity;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

This is Android manifest file, I have made a Google Maps activity and try to run it but it is showing an error in my Android Studio and the app is not running.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.app.hasura.imad.namanyadav123.mapsactivity">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Error:FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

A: Seems you have com.android.dex.DexIndexOverflowException:
Try add these lines in the build.gradle:
android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

Hope it helps...