text:
Q: QWebEngine not working on my old laptop again. Since the last time I messed with my old laptop, reconfiguring it for my daughter, she eventually got a new one and the poor old thing landed on my desktop. I don't want to throw it away because, in spite of showing its age (made in 2009), the laptop is still perfectly useable, running faster than even my desktop machine, which is two years and a half younger and has more RAM and a supposedly better processor (Pentium Dual E5700 versus Intel Celeron 900). So I formatted it and installed Arch Linux. The whole process was an ordeal, because of incompatible hardware (b43 wireles and sis671/771 graphics card), but I sorted out most of the hassles. Now I've got 1280x800@75Hz, no display glitches and the wirelss card works normally, thought it takes about 1 minute to fully start. I can help anyone with a similar setup, if asked.
I am only left with one quite small issue: QtWebEngine isn't working properly. AFAIK it could be related to GLX issues (but glxgears working correctly and I even compiled an opengl app, wxglterm, which works OK.
When I start ANY QtWebEngine browser it loads the page (cursor changes, links are clickable, text is copied to the clipboard) but everything inside the window is black.
I have confirmed the problem with QupZilla, Qutebrowser, Otter-Browser and the Qt example apps "markdownviwer" and "simplebrowser" (which I compiled as tests).
The problem does not affect Chrome or Opera (though they use the same rendering engine, they might be bundling their own version).
Sis driver apart (which cannot be discusses for now, because the whole compiling process was too complicated), are there any non-hardware related causes for such glitch?
Is there any Xorg.conf thing I should blacklist, block, load or configure?
Here is my current Xorg.conf (the meaning of some entries I still don't know, this is mostly guesswork).
Section "ServerFlags"
        Option "DontZap" "0"
        Option "IgnoreABI" "0"
EndSection

Section "Device"
        Identifier "device0"
        Driver "sisimedia"
        BusID "PCI:1:0:0"
        Option "EnableSiSCtrl" "1"
        Option "UseFBDev" "1"
        Option "ForceCRT1Type" "NONE"
        Option "ForceCRT2Type" "LCD"
        Option "CenterLCD" "1"
        Option "CRT2Detection" "1"
        Option "Brightness" "0.000 0.000 0.000"
        Option "Contrast" "0.000 0.000 0.000"
        Option "XvOnCRT2" "1"
        Option "UseTiming1366" "0"
        Option "XvGamma" "0"
        Option "UseSSE" "1"
        Option "NoAccel" "0"
        Option "NoYV12" "0"
        Option "Xinerama" "0"
        Option "AGPSize" "256"
        Option "RenderAcceleration" "1"
        Option "AccellMethod" "exa"
        Option "TurboQueue" "1"
        Option "SwapbuffersWait" "1"
        Option "pci_burst_on" "1"
EndSection

Section "Monitor"
    Identifier  "monitor0"
        Option "DPMS"
        HorizSync 30 - 65
        VertRefresh 50 - 75
    Gamma 1.000 1.000 1.000
EndSection

Section "Screen"
    Identifier  "screen0"
    Monitor     "monitor0"
        DefaultDepth    16
SubSection "Display"
        Depth   16
                Modes           "1280x800" "1024x768" "800x600" "640x480"
        EndSubSection
    Device      "device0"
EndSection

Section "Module"
     Load "i2c"
     Load "freetype"
     Load "modesetting"
     Load "bitmap"
     Load "ddc"
#     Load "int10"
#     Load "vbe"
EndSection

Section "DRI"
     Mode 0666
EndSection

I am not entirely sure whether not loading int10 and vbe is useful or if loading "modesetting" helps at all. Probably not.
Here's the screenshot, showing two qtwebenging browsers with the same problem.


text:
Q: C read multiple words followed by an integer I want to read the following text using fscanf. However, I have tried using "fscanf(ifp, "%[^d\n] %d", title, &stock)" to read it. But it does not work. The integer is always included in the string and I could not seperate the string part and the integer part.
Logan 1
Star Wars: Rogue One 5
Monster Trucks 6
Power Rangers 5
The Fate of the Furious 6
Transformers 4
Thor 2
The Smurfs 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress стили не подключаются в тег head Я новичок вордпресс, недавно столкнулся с неприятным багом. Мне нужно, что бы показ странички был ограничен до полной загрузки 3 стилей (я пометил их в коде комментами со знаками "!"), иначе перед показом сайта на 100-500 милисекунд выскакивает некрасивая версия сайта без стилей (Показано ниже на скрине). Стандартные хуки наподобие wp_head не работают и все равно подключают стили уже после тега head. Вот мой functions.php
add_action('wp_head', 'chesmo_styles');
add_action('wp_enqueue_scripts', 'chesmo_scripts');
add_action('after_setup_theme', 'chesmo_setup');
add_action('after_setup_theme', 'true_load_theme_textdomain');
add_filter('show_admin_bar', '__return_false');

function chesmo_setup()
{
    load_theme_textdomain('chesmo');
    add_theme_support('menus');
}
function chesmo_scripts () {
    wp_register_script( 'fancybox-js', 'https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js');
   wp_enqueue_script( 'custom_jquery', get_stylesheet_directory_uri() . '/js/jquery-2.2.0.min.js');
    wp_enqueue_script( 'fancybox-js');
    wp_enqueue_script( 'custom_jquery_ui', get_stylesheet_directory_uri() . '/js/jquery-ui.min.js');
    wp_enqueue_script( 'aos', get_stylesheet_directory_uri() . '/js/aos.js');
    wp_enqueue_script( 'slick_slider', get_stylesheet_directory_uri() . '/js/slick.min.js');
    wp_enqueue_script( 'custom_sliders', get_stylesheet_directory_uri() . '/js/sliders.js');
    wp_enqueue_script( 'common_js', get_stylesheet_directory_uri() . '/js/common.js');
    wp_enqueue_script('newscript', get_template_directory_uri() . '/js/custom_script.js');
    wp_enqueue_script('contacts_window', get_template_directory_uri() . '/js/contacts.js');
}
function chesmo_styles() {
    wp_register_style('header-css', get_template_directory_uri() . '/css/header.css');
    wp_register_style('index-css', get_template_directory_uri() . '/css/index.css');
    wp_register_style('bulma-css', get_template_directory_uri() . '/css/bulma.min.css');
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    wp_enqueue_style('header-css');
    wp_enqueue_style('bulma-css');
    wp_enqueue_style('index-css');
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    wp_enqueue_style('common-css', get_template_directory_uri() . '/css/common.css');
    wp_enqueue_style('main-css', get_template_directory_uri() . '/css/style.css');
    wp_enqueue_style('animate-css', get_template_directory_uri() . '/css/aos.css');
    wp_enqueue_style('slick-css', get_template_directory_uri() . '/css/slick.css');
    wp_enqueue_style('footer-css', get_template_directory_uri() . '/css/footer.css' );
    wp_enqueue_style('fonts-css', get_template_directory_uri() . '/css/fonts.css' );
    wp_enqueue_style( 'fancybox-css', 'https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css' );
    if(is_page_template('tpl_promotions.php')){
        wp_enqueue_style('non-main-header-css', get_template_directory_uri() . '/css/non-main-header.css' );
        wp_enqueue_style('promotions-css', get_template_directory_uri() . '/css/promotions.css' );
    }
    if(is_page_template('tpl_service.php')){
        wp_enqueue_style('service-css', get_template_directory_uri() . '/css/service.css' );
    }
    if(is_page_template('tpl_all_services.php')){
        wp_enqueue_style('non-main-header-css', get_template_directory_uri() . '/css/non-main-header.css' );
    }
    if(is_page_template('tpl_calculator.php')){
        wp_enqueue_style('non-main-header-css', get_template_directory_uri() . '/css/non-main-header.css' );
        wp_enqueue_style('calculator-css', get_template_directory_uri() . '/css/calculator.css' );
        wp_enqueue_script( 'calculator_js', get_stylesheet_directory_uri() . '/js/calculator.js');
    }
    if(is_page_template('tpl_contacts.php')){
        wp_enqueue_style('non-main-header-css', get_template_directory_uri() . '/css/non-main-header.css' );
        wp_enqueue_style('contacts-css', get_template_directory_uri() . '/css/contacts.css' );
    }
    if(is_page_template('tpl_equipment.php')){
        wp_enqueue_style('non-main-header-css', get_template_directory_uri() . '/css/non-main-header.css' );
        wp_enqueue_style('equipment-css', get_template_directory_uri() . '/css/equipment.css' );
    }
    if(is_page_template('tpl_about.php')){
        wp_enqueue_style('about-css', get_template_directory_uri() . '/css/about.css' );
    }
}

function true_load_theme_textdomain(){
    load_theme_textdomain( 'chesmo', get_template_directory() . '/languages' );
}

function chesmo_the_breadcrumb(){
    global $post;
    if(!is_home()){
        if (pll_current_language() == "ru")
            echo 'Главная';
        else if (pll_current_language() == "uk")
            echo 'Головна';

        if(is_single()){ // posts
            the_category(', ');
            echo "
 /
 ";
            echo '
';
            the_title();
            echo '
';
        }
        elseif (is_page()) { // pages
            if ($post->post_parent ) {
                $parent_id  = $post->post_parent;
                $breadcrumbs = array();
                while ($parent_id) {
                    $page = get_post($parent_id);
                    $breadcrumbs[] = 'ID) . '">' . get_the_title($page->ID) . '';
                    $parent_id  = $page->post_parent;
                }
                $breadcrumbs = array_reverse($breadcrumbs);
                foreach ($breadcrumbs as $crumb) echo $crumb;
            }
            echo ''; echo the_title(); echo '';
        }
        elseif (is_category()) { // category
            global $wp_query;
            $obj_cat = $wp_query->get_queried_object();
            $current_cat = $obj_cat->term_id;
            $current_cat = get_category($current_cat);
            $parent_cat = get_category($current_cat->parent);
            if ($current_cat->parent != 0)
                echo(get_category_parents($parent_cat, TRUE, '
 /
 '));
            single_cat_title();
        }
        elseif (is_search()) { // search pages
            echo 'Search results "' . get_search_query() . '"';
        }
        elseif (is_tag()) { // tags
            echo single_tag_title('', false);
        }
        elseif (is_day()) { // archive (days)
            echo '' . get_the_time('Y') . '';
            echo '' . get_the_time('F') . '';
            echo get_the_time('d');
        }
        elseif (is_month()) { // archive (months)
            echo '' . get_the_time('Y') . '';
            echo get_the_time('F');
        }
        elseif (is_year()) { // archive (years)
            echo get_the_time('Y');
        }
        elseif (is_author()) { // authors
            global $author;
            $userdata = get_userdata($author);
            echo 'Posted ' . $userdata->display_name . '';
        } elseif (is_404()) { // if page not found
            echo 'Error 404';
        }

        if (get_query_var('paged')) // number of page
            echo ' (' . get_query_var('paged').'- page)';

    } else { // home
        $pageNum=(get_query_var('paged')) ? get_query_var('paged') : 1;
        if($pageNum>1)
        {
            if (pll_current_language() == "ru")
                echo 'Главная ' . $pageNum . '- page';
            else if (pll_current_language() == "uk")
                echo 'Головна ' . $pageNum . '- page';

        }
        else
        {
            if (pll_current_language() == "ru")
                echo 'Главная';
            else if (pll_current_language() == "uk")
                echo 'Головна';

        }
    }
}

A: TLDR
Используйте правильный хук для постановки стилей в очередь - wp_enqueue_scripts. Обычно функции wp_enqueue_script() и wp_enqueue_style() используют внутри одной функции, в вашем случае - chesmo_scripts().
Объяснение
Надо понимать, что функции wp_enqueue_script() и wp_enqueue_style() не делают ничего, лишь ставят скрипты в очередь (заносят их в массив в ядре). Вывод стилей и скриптов производится на хуке wp_print_scripts, который срабатывает после wp_enqueue_scripts, но ДО wp_head. Поэтому ваши скрипты в хедер уже не попадают, остаются в очереди (массиве) и выводятся ядром уже в футере. Вот почему вы видите некоторое время сайт без нужных вам стилей.


text:
Q: Given a Dictionary of Words Determine the Order of the Letters The exact problem statement is this: given a dictionary of words sorted according to some unknown ordering of letters, determine the total order of the letters. It is guaranteed that any inputs provided have a total order and that the order can be found.
From what I have read about this type of problem, it would seem that the correct approach to solving this problem is to build a directed acyclic graph and then perform a topological sort on the graph. Furthermore, there are two ways to implement topological sort (that I am aware of). One of these uses a depth-first search, and this is how I chose to implement my algorithm.
My program works for the small number of test cases provided (and any that I can come up with), but fails for the test cases that are used to verify the correctness of my program. Unfortunately, I cannot access these test cases, or I would have an easier time debugging my program.
Would anybody be willing to suggest some refinements to my code? Is there some other approach to this problem? Also, does anybody know of a way to generate good test cases? The test cases that I have come up with have been inadequate to finding where my program is incorrect. An ideal test case would be a dictionary of words on which a total ordering is guaranteed to exist and be obtainable.
I think the problem is in the way I build my directed acyclic graph.
from sets import Set
from copy import copy

#Hash table representation of directed acyclic graph.
DAG = {}
#Set of all vertices with no incoming edges
noIncomingEdges = Set()
#Any array (initially empty) which will contain the total order
#of the letters used to sort the dictionary
sortedLetters = []

class VertexList:
    def __init__(self):
        self.outgoing = Set()
    def addOutgoingEdge(self, edge):
        self.outgoing.add(edge)
    def removeOutgoingEdge(self, edge):
        self.outgoing.remove(edge)

def buildDAG(words):
    numWords = len(words)
    for i in range(numWords - 1):
        #Get two consecutive words from the dictionary
        w1 = words[i]
        w2 = words[i + 1]
        lenw1 = len(w1)
        lenw2 = len(w2)
        #If the first word is longer than the second, pad the first words
        #by taking the last letter in the first words and appending it   until
        #both words are of equal length.
        #As an example:
        #       a       -->     aa
        #       ab      -->     ab
        #The algorithm for building the DAG should now be able to see that
        #a comes before b.
        if lenw1 < lenw2:
            while len(w1) < lenw2:
                w1 = w1 + w1[lenw1 - 1]
        n = lenw2
        for j in range(n):
            #If the DAG doesn't have a vertex for a given letter, add it.
            #Also, add it to the list of nodes with no incoming edges.
            if not DAG.has_key(w1[j]):
                DAG[w1[j]] = VertexList()
                noIncomingEdges.add(w1[j])
            if not DAG.has_key(w2[j]):
                DAG[w2[j]] = VertexList()
                noIncomingEdges.add(w2[j])
            #Compare corresponding letters in the two consecutive words. If
            #The letter in the first word is different from the letter in the
            #second word, create an edge between the vertex represent the letter
            #from the first word and the vertex for the letter in the second
            #word.
            if w1[j] != w2[j] and w2[j] not in DAG[w1[j]].outgoing:
                DAG[w1[j]].addOutgoingEdge(w2[j])
                #Remove the vertex for the second letter from the list of
                #vertices with no incoming edges.
                if w2[j] in noIncomingEdges:
                    noIncomingEdges.remove(w2[j])
                break

def visit(v):
    visited = Set()
    if v not in visited:
        visited.add(v)
        vertices = copy.deepcopy(DAG[v])
        for vertex in vertices.outgoing:
            visit(vertex)
        sortedLetters.insert(0, v)

def topologicalSort():
    for vertex in noIncomingEdges:
        visit(vertex)

def answer(words):
    buildDAG(words)
    topologicalSort()
    return ''.join(sortedLetters)

A: I found the problem.  It's in the line
if word1[j] != word2[j] and word2[j] not in DAG[word1[j]].outgoing:

You need to separate these clauses, because you have to break out of the loop when the two letters differ, even if the second letter is in the DAG.  Otherwise, you go on to the next pair of letters, when you should be done comparing these words.
The result is that you get a spurious DAG edge farther down this pair of words.  I started my data set with
a
ab
bad

The first comparison went fine, adding a->b to the DAG.
In the second comparison, ab vs bad, we hit the first difference at the fist letter.  However, since b is already in the outgoing list of a, your logic says to go on to the next letter pair.  This adds the edge b->a from the second letters.
This introduces a cycle to the DAG, killing the algorithm.  The code should read
if word1[j] != word2[j]:
    if word2[j] not in DAG[word1[j]].outgoing:
        <add edge>
    break


text:
Q: Cannot access laravel debugging I'm having a hard time connecting to the development webserver inside the container (from safari on my host machine).
Since I am using network_mode: host I did not expect there to be any errors.
In my .env APP_URL is set to localhost.com - I added an entry to /etc/hosts accordingly.
Ping localhost.com referes to 127.0.0.1 so that should not be the issue.
version: '3'
services:
  setup:
    image: mariadb:latest
    command:
      - mysql -u root -proot -e "CREATE DATABASE central;"
  web:
    image: waryor/laravel-8.0:latest
    volumes:
      - '..:/var/www/html'
    depends_on:
            - mariadb
            - redis
    stdin_open: true
    tty: true
    network_mode: host
  mariadb:
    image: mariadb:latest
    environment:
        MYSQL_ROOT_PASSWORD: 'root'
        MYSQL_DATABASE: 'central'
        MYSQL_USER: 'root'
        MYSQL_PASSWORD: 'root'
    network_mode: host
    restart: always
  redis:
    image: arm64v8/redis:alpine
    restart: always
    healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            retries: 3
            timeout: 5s
    network_mode: host

Starting the webserver works without any errors
root@docker-desktop:/var/www/html# php artisan serve
Starting Laravel development server: http://127.0.0.1:8000
[Wed Oct  6 00:20:54 2021] PHP 8.0.11 Development Server (http://127.0.0.1:8000) started

I've even tried using the --host 0.0.0.0 option without any success.

A: You need to expose the ports. You don't have to use network_mode. Change your file to:
web:
    image: waryor/laravel-8.0:latest
    volumes:
      - '..:/var/www/html'
    ports:
      - 80:8000
    depends_on:
      - mariadb
      - redis
    stdin_open: true
    tty: true
    network_mode: host

By doing - 80:8000, you are exposing internal 8000 to external 80, so you can go to localhost and done.


text:
Q: How do I set "snapshot on delete" for an AWS EBS Volume created via a LaunchTemplate In the Amazon Web Services cloud (AWS), I want to create a launch template that launches an AMI with a root EBS volume and a separate EBS data volume. When the instance is deleted, I want both volumes deleted, but first I want the data volume to have a snapshot taken using a DeletionPolicy of Snapshot rather than Delete or Retain. I would like to create this launch template with the AWS CDK in Python, but as a last resort it would be helpful if I could configure the EBS volumes this way by any means, including a script run after the instance launches.
Currently, I have the launch template configured to create the EBS volumes and delete them when the AMI terminates. So far, so good. What I cannot find is a say to have the "data" volume take a snapshot before it deletes. The closest I can come is to trigger a script to respond to the instance termination signal by initiating a snapshot, but I worry that that is unreliable.
The AWS CloudFormation documentation claims you can set a DeletionPolicy of Snapshot on an AWS::EC2::Volume. I mostly cannot figure out how to get that to work for a random EBS volume attached to an EC2 instance as a data volume (not root or AMI volume).

*

*I do not see any place in the AWS Console to set the DeletionPolicy

*I do not see any place in the aws CLI to read the DeletionPolicy

*Looking at the LaunchTemplate, I do not see any place to set this policy

So possibly I am thinking about this the wrong way, or possibly the documentation is just misleading. After pouring over the documentation for several hours, I am left to believe that this is not a real option, but rather a hack to enable "snapshot on delete" for RDS clusters.
How can I get this to work for a normal EC2 instance?

A: You can try to use terraform also if you are comfortable using that.
Example:
    resource "aws_ebs_volume" "example" {
  availability_zone = "us-west-2a"
  size              = 40

  tags = {
    Name = "HelloWorld"
  }
}

resource "aws_ebs_snapshot" "example_snapshot" {
  volume_id = "${aws_ebs_volume.example.id}"

  tags = {
    Name = "HelloWorld_snap"
  }
}

So when the volume will be deleted, snapshot will be there and you can restore data anytime from that.
you can set the parameter DeleteOnTermination true  or false.
When an instance is terminated, Amazon Elastic Compute Cloud (Amazon EC2) uses the value of the DeleteOnTermination attribute for each attached EBS volume to determine whether to preserve or delete the volume when the instance is terminated. By default, the DeleteOnTermination attribute for the root volume of an instance is set to true, but it is set to false for all other volume types.


text:
Q: How to put an alert box using javascript and asp.net? I just want to know how to put an alert box using javascript and asp.net. Basically I have created a webpage where the admin will fill up a form, and then after clicking the submit button, there should be an alert box that will popup with a message that says upload successful or upload failed.
I tried doing it with this code(I only included the javascript code and the asp submit button):
<script>
    function UploadStatusSuccessful()
    {
        alert("Upload Successful!");
    }
</script>

<script>
    function UploadStatusFail()
    {
        alert("Upload Failed!");
    }
</script>

<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click"/>

and here is the code-behind:
protected void Button1_Click(object sender, EventArgs e)
{

    try
    {
        int item_brandId =
        ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
        string item_model = itemModel.Text;
        double item_price = Convert.ToDouble(itemPrice.Text);
        string item_image1 = Session["PicturePath1"].ToString();
        string item_image2 = Session["PicturePath2"].ToString();
        string item_description = itemDescription.Text;
        string item_necktype = itemNeckType.Text;
        string item_body = itemBody.Text;
        string item_fretboard = itemFretboard.Text;
        string item_fret = itemFret.Text;
        string item_bridge = itemBridge.Text;
        string item_neckpickup = itemNeckPickup.Text;
        string item_bridgepickup = itemBridgePickup.Text;
        string item_hardwarecolor = itemHardwareColor.Text;

        if (itemType1.Checked)
        {
            int item_type =
            ConnectionClassBrands.GetIdByType(itemType1.Text);
            ItemType = item_type;
        }
        else if (itemType2.Checked)
        {
            int item_type =
            ConnectionClassBrands.GetIdByType(itemType2.Text);
            ItemType = item_type;
        }

        var item = new instrumentItem
        {
            typeId = ItemType,
            brandId = item_brandId,
            model = item_model,
            price = item_price,
            itemimage1 = item_image1,
            itemimage2 = item_image2,
            description = item_description,
            necktype = item_necktype,
            body = item_body,
            fretboard = item_fretboard,
            fret = item_fret,
            bridge = item_bridge,
            neckpickup = item_neckpickup,
            bridgepickup = item_bridgepickup,
            hardwarecolor = item_hardwarecolor
        };

        ConnectionClassGuitarItems.AddStringInstrumentItems(item);

        Button1.Attributes.Add("onclick", "JavaScript:return
        UploadStatusSuccessful()");

        ClearTextFields2();

    }
    catch (Exception)
    {
        Button1.Attributes.Add("onclick", "JavaScript:return
        UploadStatusFail()");
    }

}

I tried doing the Button1.Attrbute.Add but no alert box is showing. Please provide solutions or actual examples on how to achieve this. Also kindly inform me if there are wrong syntax that i missed so that i can correct it immediately.

A: You can use ScriptManager.RegisterStartupScript in code behind to show alert message like below . You need to Scriptmanager control to your aspx page . This is the recommended way
 ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
          "err_msg",
          "alert('Upload failed!');",
          true);

Otherwise you can simple do like below
Response.Write("<script>alert('Upload failed!');</script>");
Link for scriptmanager control
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

A: ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>UploadStatusSuccessful();</script>", false);


text:
Q: How do I prevent VS 2022 to display typescript errors with d.ts files in esproj I created a project (.esproj) for my SPA under visual studio 2022.
It build well but visual studio is showing a lot of errors (only on .dt.ts files from node_modules of the project and also from the one of Typescript locally installed in AppData).
The errors are not showing up on VS Code but ideally I would use visual studio 2022 for this.
Here my esproj
<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/0.5.0-alpha">
    <PropertyGroup Label="Globals">
        <ProjectGuid>6b86a87b-eb34-43fe-9cbb-99a2e3db4e41</ProjectGuid>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <StartupCommand>set BROWSER=none&&npm start</StartupCommand>
        <JavaScriptTestRoot>src\</JavaScriptTestRoot>
        <JavaScriptTestFramework>Jest</JavaScriptTestFramework>
    </PropertyGroup>
    <ItemGroup>
        <Script Include="**" Exclude="*.esproj;**\node_modules\**" />
    </ItemGroup>

    <!-- This target is copied from the ASP.NET SPA template in order to ensure node_modules are in place. -->
    <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
        <!-- Ensure Node.js is installed -->
        <Exec Command="node --version" ContinueOnError="true">
            <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
        </Exec>
        <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
        <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install --legacy-peer-deps" />
    </Target>
</Project>

here my tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "ESNext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}

Any idea how I can configure visual studio 2022 to not run analyzer on .d.ts ?
Thanks in advance

A: *

*In Visual Studio, Right click the node_modules folder and select 'Exclude From Project' if not already set.

*Close your solution in VS.

*Using File Explorer, set the properties of the node_modules folder to Hidden (do not apply to sub folders).

*Open your solution.

Faster solution load, no more intellisense errors, NPM still works even though the folder is hidden.

A: This worked for me change .csproj to include this setting inside PropertyGroup:
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

A: Replacing the payload part
 <ItemGroup>
        <Script Include="**" Exclude="*.esproj;**\node_modules\**" />
    </ItemGroup>

by
  <ItemGroup>
    <Script Include="**"/>
    <Script Remove="**.d.ts"/>
  </ItemGroup>

seems to solve my issue

A: My colleague suggested this fix and its seems to have removed all the typescript errors from the visual studio error list.

*

*Go to the folder where your project is located and look for a folder called "node_modules".

*Right click that folder and select "properties."

*Click the "Hidden" checkbox.

*Click "OK" and a popup menu will appear that asks you if you want to "Apply changes to this folder, subfolders, and files". Select "OK".
All 778 typescript errors disappeared on Visual Studio 2022.


text:
Q: How to generate an individual adjacency matrix from a group adjacency matrix, in r I have an adjacency matrix representing species by species interactions (a tri-trophic chain):
mat = matrix(c(0,1,0,
               0,0,1,
               0,0,0), nrow=3, byrow = T,
             dimnames = list(c("sp1","sp2","sp3"),
                             c("sp1","sp2","sp3")))

and a dataframe that contains the species' abundances:
comm = t(data.frame(sp1=100,
                    sp2=20,
                    sp3=5))

Using the above, is there an efficient way to create an individual based adjacency matrix?
in.mat = matrix(0, nrow = sum(comm),
               ncol = sum(comm),
            byrow = T,
            dimnames = list(c(rep("sp1",100),rep("sp2",20),rep("sp3",5)),
                            c(rep("sp1",100),rep("sp2",20),rep("sp3",5))))

So that all individuals of sp3 are connected with all individuals from sp2 and those with all individuals of sp1.
I would appreciate any pointers, I have not managed to find similar questions, perhaps because I am not using the appropriate terms.

A: To illustrate we will use a smaller example shown in the Note at the end but the same code would work with the example in the question.  No packages are used except as indicated.
1)  Expand the names into nms and then use subscripting.
nms <- rep(rownames(comm), comm)
mat[nms, nms]
##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
##  [1,]    0    0    1    1    1    0    0    0    0
##  [2,]    0    0    1    1    1    0    0    0    0
##  [3,]    0    0    0    0    0    1    1    1    1
##  [4,]    0    0    0    0    0    1    1    1    1
##  [5,]    0    0    0    0    0    1    1    1    1
##  [6,]    0    0    0    0    0    0    0    0    0
##  [7,]    0    0    0    0    0    0    0    0    0
##  [8,]    0    0    0    0    0    0    0    0    0
##  [9,]    0    0    0    0    0    0    0    0    0

2) Another approach using nms as above is to use one of these:
outer(nms, nms, function(x, y) mat[cbind(x, y)])

outer(nms, nms, Vectorize(function(x, y) mat[x, y]))

sapply(nms, function(y) sapply(nms, function(x) mat[x, y]))

library(listcompr)
gen.matrix(mat[x, y], x = nms, y = nms)

The eList or comprehenr packages could also be used.
Note
# input
sp <- paste0("sp", 1:3)
mat <- matrix(c(0,0,0,1,0,0,0,1,0), 3, dimnames = list(sp, sp))
comm <- matrix(2:4, 3, dimnames = list(sp, NULL))

mat
##     sp1 sp2 sp3
## sp1   0   1   0
## sp2   0   0   1
## sp3   0   0   0

comm
##     [,1]
## sp1    2
## sp2    3
## sp3    4


text:
Q: Show $\int_{\mathbb{R}^n}|f(x)|^3 dx =3 \int_{0}^\infty t^2 |\left\{x : f(x)>t \right\}| dt$ I am studying for a measure theory exam, and I came across the following problem that I am stuck on.
Show $\int_{\mathbb{R}^n}|f(x)|^3 dx =3 \int_{0}^\infty t^2 |\left\{x : f(x)>t \right\}| dt$.
My idea:
$|f(x)|^3=3 \int_{0}^{|f(x)|}t^2dt$.
$\implies \int_{\mathbb{R}^n}|f(x)|^3 dx= 3\int_{\mathbb{R}^n} \int_{0}^{|f(x)|}t^2dt$.
I am stuck after this. I think that I should Fubini's theorem.
Any help would be appreciated.

A: $\int_{\mathbb{R}^n}|f(x)|^3dx=3\int_{\mathbb{R}^n}\int_0^{|f(x)|}t^2 dt dx=3\int_{\{(t,x)\in\mathbb{R}^{n+1}:0\leq t\leq |f(x)|\}}t^2 d(t,x)=3\int_{\mathbb{R}}\int_{\{x:|f(x)|\ge t\}}t^2dxdt=3\int_{\mathbb{R}}t^2\int_{\{x:|f(x)|\ge t\}}dxdt$
Here I used several times Fubini's (or "just" Tonelli's) theorem (check!).
The desired result with $>$ instead of $\ge$ should follow if the graph of $|f|$ has Lebesgue measure $0$ in $\mathbb{R}^{n+1}$. (Continuity of $f$ should be sufficient for that.)


text:
Q: flatten json nested array (lodash/deepdash) I have a nested json array that I need to flatten it and remove the keys(onSale,newComing).
Below is the 2 jsons: what I have and what I want it to be.
(Javascript-lodash-deepdash)
what I have:
[
  {
    "id": 1,
    "model": "Google Pixel 3",
    "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "price": 799,
    "quantity": 2
  },
  {
    "id": 2,
    "model": "Samsung Note 9",
    "image": "/src/assets/images/samsung-1283938__340.jpg",
    "price": 999,
    "quantity": 2
  },
  {
    "newComing": [
      {
        "id": 10,
        "model": "Samsung Galaxy A7 (2020)",
        "image": "/src/assets/images/Samsung S7.jpg",
        "price": 533,
        "quantity": 2
      },
      {
        "id": 12,
        "model": "Samsung Galaxy A7 (2018)",
        "path": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=",
        "image": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=",
        "price": 630,
        "quantity": 2
      }
    ]
  },
  {
    "onSale": [
      {
        "id": 14,
        "model": "Samsung Galaxy A7 (2018)",
        "path": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg",
        "image": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg",
        "price": 533,
        "quantity": 2
      },
      {
        "id": 15,
        "model": "Samsung Galaxy A7 (2018)",
        "path": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg",
        "image": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg",
        "price": 533,
        "quantity": 2
      }
    ]
  }
]

what i want:
[
  {
    "id": 1,
    "model": "Google Pixel 3",
    "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "price": 799,
    "quantity": 2
  },
  {
    "id": 2,
    "model": "Samsung Note 9",
    "image": "/src/assets/images/samsung-1283938__340.jpg",
    "price": 999,
    "quantity": 2
  },
  {
    "id": 10,
    "model": "Samsung Galaxy A7 (2020)",
    "image": "/src/assets/images/Samsung S7.jpg",
    "price": 533,
    "quantity": 2
  },
  {
    "id": 12,
    "model": "Samsung Galaxy A7 (2018)",
    "path": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=",
    "image": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=",
    "price": 630,
    "quantity": 2
  },
  {
    "id": 14,
    "model": "Samsung Galaxy A7 (2018)",
    "path": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg",
    "image": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg",
    "price": 533,
    "quantity": 2
  },
  {
    "id": 15,
    "model": "Samsung Galaxy A7 (2018)",
    "path": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg",
    "image": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg",
    "price": 533,
    "quantity": 2
  }
]

I have been playing with _.reduce, _.flatmap and been unable to get anything close.
Thanks for help.

A: flatMap will do.

const array = [ { "id": 1, "model": "Google Pixel 3", "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg", "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg", "price": 799, "quantity": 2 }, { "id": 2, "model": "Samsung Note 9", "image": "/src/assets/images/samsung-1283938__340.jpg", "price": 999, "quantity": 2 }, { "newComing": [ { "id": 10, "model": "Samsung Galaxy A7 (2020)", "image": "/src/assets/images/Samsung S7.jpg", "price": 533, "quantity": 2 }, { "id": 12, "model": "Samsung Galaxy A7 (2018)", "path": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=", "image": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozkCQ3zE6KZOde8=", "price": 630, "quantity": 2 } ] }, { "onSale": [ { "id": 14, "model": "Samsung Galaxy A7 (2018)", "path": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg", "image": "https://fdn.gsmarena.com/imgroot/reviews/20/samsung-galaxy-s20-plus/lifestyle/-1024w2/gsmarena_002.jpg", "price": 533, "quantity": 2 }, { "id": 15, "model": "Samsung Galaxy A7 (2018)", "path": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg", "image": "https://www.phonefinity.net/wp-content/uploads/camon-17-blue.jpg", "price": 533, "quantity": 2 } ] } ];

const flatten = array.flatMap(({newComing, onSale, ...item}) => newComing || onSale || [item]);
console.log(flatten);

const lodash = _.flatMap(array, ({newComing, onSale, ...item}) => newComing || onSale || [item]);
console.log(lodash);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>


text:
Q: Change Popup Menu Position In MpAndroid Bar Chart On Value Selected I want to Change position of popup menu on value selected event in Bar chart. The popup menu always displays on top. I want that popup menu to display near the item selected in bar chart .
Barchart.java
package com.example.saravanakumars.spinnerchart;

/**
 * Created by saravanakumars on 9/18/2017.
 */
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class barchart extends AppCompatActivity  {
    BarChart chart ;
    ArrayList<BarEntry> BARENTRY ;
    ArrayList<String> BarEntryLabels ;
    BarDataSet Bardataset ;
    BarData BARDATA ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bar_chart);
        chart = (BarChart) findViewById(R.id.barchart);

        BARENTRY = new ArrayList<>();

        BarEntryLabels = new ArrayList<String>();

        AddValuesToBARENTRY();

        AddValuesToBarEntryLabels();

        Bardataset = new BarDataSet(BARENTRY, "Projects");

        BARDATA = new BarData(BarEntryLabels, Bardataset);

        Bardataset.setColors(ColorTemplate.COLORFUL_COLORS);

        chart.setData(BARDATA);

        chart.animateY(3000);

//        chart.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View view) {
//
//
//            }
//
//        });

        chart.setOnChartValueSelectedListener( new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

                PopupMenu popup = new PopupMenu(barchart.this,chart);

                popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());

                popup.show();

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(barchart.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
                        return true;
                    }
                });

            }

            @Override
            public void onNothingSelected() {

            }
        });

    }

    public void AddValuesToBARENTRY(){

        BARENTRY.add(new BarEntry(2f, 0));
        BARENTRY.add(new BarEntry(4f, 1));
        BARENTRY.add(new BarEntry(6f, 2));
        BARENTRY.add(new BarEntry(8f, 3));
        BARENTRY.add(new BarEntry(7f, 4));
        BARENTRY.add(new BarEntry(3f, 5));

    }

    public void AddValuesToBarEntryLabels(){

        BarEntryLabels.add("January");
        BarEntryLabels.add("February");
        BarEntryLabels.add("March");
        BarEntryLabels.add("April");
        BarEntryLabels.add("May");
        BarEntryLabels.add("June");

    }

}

i tried Show at location property but it wont work. i google it. but cant find the answer. help me out with this .


text:
Q: How to create a multi project template in visual studio 2013? I followed the How to: Create Multi-Project Templates article to create a template that will generate a solution containing 4 projects. My Root.vstemplate file contains the following
<VSTemplate Version="2.0.0" Type="ProjectGroup"
xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
    <Name>Yugasat BeyondAdmin</Name>
    <Description>The Yugasat BeyondAdmin Project Template</Description>
    <Icon>Icon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
</TemplateData>
<TemplateContent>
    <ProjectCollection>
        <ProjectTemplateLink ProjectName="PresentationLayer">
            PresentationLayer\MyTemplate.vstemplate
        </ProjectTemplateLink>
        <ProjectTemplateLink ProjectName="BusinessLogicLayer">
            BusinessLogicLayer\MyTemplate.vstemplate
        </ProjectTemplateLink>
        <ProjectTemplateLink ProjectName="BusinessLogicLayerAPI">
            BusinessLogicLayerAPI\MyTemplate.vstemplate
        </ProjectTemplateLink>
        <ProjectTemplateLink ProjectName="DataAccessLayer">
            DataAccessLayer\MyTemplate.vstemplate
        </ProjectTemplateLink>
    </ProjectCollection>
</TemplateContent>

I copied the template to the [drive]:\Users\[user]\Documents\Visual Studio 2013\Templates\ProjectTemplates\ folder. The problem is that the template is not listed as a multi project template

So I can create the individual projects, but not a solution containing all 4 my projects. The content of my template folder looks like

A: Ensure that the ".vstemplate" file (for each project) has the same name as the project that it resides in.
i.e Presentation Layer should have a PresentationLayer.vstemplate
Its not necessary to create a VSIX Installer for this but the link has a visual representation of what is expected in the "root.vstemplate".
Also, once this has been completed and your template folder has been copied to ~/My Documents/Visual Studio 2013\Templates\ProjectTemplates\, the option should be found in the "Visual C#" section of Create New Project.


text:
Q: How can I match Word Boundary "or" [@#]? I can't seem to get a regex that matches either a hashtag #, an @, or a word-boundary. The goal is to break a string into Twitter-like entities and topics so:
input = "Hello @world, #ruby anotherString"
input.scan(entitiesRegex)
# => ["Hello", "@world", "#ruby", "anotherString"]

To get just the words, excluding "anotherString" which is too large, is simple:
/\b\w{3,12}\b/

will return ["Hello", "world", "ruby"]. Unfortunately this doesn't include the hashtags and @s. It seems like it should work simply with:
/[\b@#]\w{3,12}\b/

but that returns ["@world", "#ruby"]. This made me realize that word boundaries are not by definition a character, so they don't fall into the category of "A single character" and, so, won't match. A few more attempts:
/\b|[@#]\w{3,12}\b/

returns ["", "", "@world", "", "#ruby", "", "", ""].
/((\b|[@#])\w{3,12}\b)/

matches the right things, but returns [[""], ["@"], ["#"], [""]] as expected, because the braces also mean capture everything enclosed.
/((\b|[@#])\w{3,12}\b)/

kind of works. It returns [["Hello", ""], ["@world", "@"], ["#ruby", "#"]]. So now all the correct items are there, they're just located at the first element of each of the subarrays. The following snippet technically works:
input.scan(/((\b|[@#])\w{3,12}\b)/).collect(&:first)

Is it possible to simplify this to match and return the correct substrings with just the regular expression not requiring the collect post-processing?

A: You can just use the regular expression /[@#]?\b\w+\b/. That is, optionally match a @ or #, followed by a word boundary (in #ruby, that boundary would be between # and ruby, in a normal word it would also match at the start of the word) and a bunch of word characters.
p "Hello @world, #ruby anotherString".scan(/[@#]?\b\w+\b/)
# => ["Hello", "@world", "#ruby", "anotherString"]

Furthermore, you can adjust the number of characters a matching word should have with quantifiers. You gave an example in a comment to a deleted answer to match only #ruby by using {3,4}:
p "Hello @world, #ruby anotherString".scan(/[@#]?\b\w{3,4}\b/)
# => ["#ruby"]


text:
Q: Number as the sum of digits of some degree
We will say that the measure of a number is equal to the maximum degree in which it is possible to represent a number in the form of a sum of digits copied (You can not rearrange the numbers). For example, for $55$ this will be $5$, because $$ 55^1 = 55, \quad 55 = 55$$ $$ 55^2 = 3025, \quad 30+25 = 55 $$ $$ 55^3 = 166375, \quad 1+6+6+37+5 = 55$$ $$ 55^4 = 9150625, \quad 9+15+0+6+25 = 55 $$$$55 ^ 5 = 503284375, \quad 5 + 0 + 3 + 28 + 4 + 3 + 7 + 5 = 55.$$
  Let $a_n$ be a sequence of numbers such that all smaller ones have a measure less than. What is the asymptotics of this sequence? Is it possible to somehow build numbers with a given measure? If not, what measures can not be built?

The task was put in a Russian forum, I put it a little different question, I will be glad to any help in its solution :)


text:
Q: How to make the view inside the flexbox layout in android take the remiaing space How to make the view inside the flexbox layout in android take the remiaing space.
I have dynamic views inside flexboxlayout ,the views inside the flexboxlayout should be of 2 rows and should take the width based on the screen and if odd number of views present then the odd one should take the full width


text:
Q: how to get the jquery append method to start counting at index 0 during each execution of a each loop? how to get the jquery append method to start counting at index 0 during each execution of a each loop?
An unordered list gets external data appended() to it during the execution of a each loop.
Then it gets cleared out using either .html('') or .empty(); and then goes through the each loop again appending data to the unordere list again but during the second time, the index increases and does not start at 0 index during the second time of each loop. How do I get the append() to always start at index 0 during the execution of the each loop after clearing it out using either empty(); or .html(''); methods?


text:
Q: How to return and access an object from a Javascript on a button post submitted? I am working on a Javascript that aims to return then manipulate an object from a clicked button. I am now stuck how can i get its object then process it on a post method. On my button I have this:
<button type="submit" name="submit" form="form-add" id="export-btn" class="btn btn-small"  style="border-radius: 0;">Save</button>

and i have this javascript method:

and on top of my page I have this:
if(isset($_POST['submit'])){
   echo "Test";
   // Process here the object
}

but How can i access those data, since $EXPORT.text(JSON.stringify(data)); output a JSON, that looks like this [{"id":"1","Val":"Sample","data":"Sample Date"}] on my paragraph tag.

A: You can't post data from paragraph.
Create hidden input in the form and assign the data to it.
$(this).append($("<input />", { name : "foo", value : data,  type : "hidden" }))


text:
Q: What's going on with this method overloading? I have a question about method overloading in C#.  I have a parent class and a child class.
class Parent
{
    public virtual string GetMyClassName()
    {
        return "I'm a Parent";
    }
}

class Child : Parent
{
    public override string GetMyClassName()
    {
        return "I'm a Child";
    }
}

I have two static methods declared outside of those two classes that act on objects of either type:
static string MyClassName(Parent parent)
{
    return "That's a Parent";
}

static string MyClassName(Child child)
{
    return "That's a Child";
}

When I test out how these methods are all called, I get what I think is a strange result:
Parent p = new Child();
var str1 = MyClassName(p); // = "That's a Parent"
var str2 = p.GetMyClassName(); // = "I'm a Child"

Why does str1 get set to "That's a Parent"?  I am probably misunderstanding method overloading in C#.  Is there a way to force the code use the Child call (setting str1 to "That's a Child")?

A:
Why does str1 get set to "That's a Parent"?

Because overloading is (usually) determined at compile-time, not execution time. It's based purely on the compile-time types of the target and arguments, with the exception of calls using dynamic values.
In your case, the argument type is Parent, so it calls MyClassName(Parent)

Is there a way to force the code use the Child call (setting str1 to "That's a Child")?

Two options:

*

*Declare p as being of type Child, not Parent

*Declare p as being of type dynamic, which will force the overload resolution to be performed at execution time

A: Method overload resolution happens at compile time, while virtual method override resolution happens at run time.
Your call to MyClassName() is being resolved at compile time to the Parent overload because the type of p is Parent.  Since the Child object is actually an instance of Parent too (due to inheritance) this is not a problem.  (Note that p instanceof Parent is true, even if p references a Child object.)


text:
Q: How can I pull any cells with a value greater than a number? I asked a similar question to this here but I realized the >=1400 can be either before or after my "x".
I'm trying to look at the number of users who are on screens larger than 1400. I have my Excel sheet, and tried doing an IF statement, but because of the "x" in the middle, it's not working properly and is instead just pulling all of the cells, even the ones with screen sizes less than 1400. I want to be able to pull all cells with Screen Resolution values larger than 1400 on either the first or second number.
All of the numbers highlighted in yellow would be the ones pulled.
I've tried doing slight variations of the =IF(--LEFT(A2,SEARCH("x",A2&"x")-1)>1400,A2,"No") but I can't find the right format to narrate that I want the formula to look at both numbers on either side of the "x".

A: You can try this:
=IFERROR(IF(OR(VALUE(LEFT(A2,SEARCH("X",A2)-1))>=1400,VALUE(RIGHT(A2,LEN(A2)-SEARCH("X",A2)))>=1400),A2,"No"),"")

A: Another option with array formula:
=IF(OR(FILTERXML(""&SUBSTITUTE(A2,"x","")&"","//b[1 or 2]")>1400),A2,"No")

Array formula after editing is confirmed by pressing ctrl + shift + enter

A: As you are using Excel365 then try below formula.
=FILTER(A2:A10,(--TRIM(LEFT(SUBSTITUTE(A2:A10,"x",REPT(" ",100)),100))>=1400)+(--TRIM(RIGHT(SUBSTITUTE(A2:A10,"x",REPT(" ",100)),100))>=1400))

Or use-
=FILTER(A2:A10,(FILTERXML("<t><s>"&SUBSTITUTE(A2:A10,"x","</s><s>")&"</s></t>","//s[1]")>=1400)+(FILTERXML("<t><s>"&SUBSTITUTE(A2:A10,"x","</s><s>")&"</s></t>","//s[2]")>=1400))

A: As an alternative to using a complicated formula, you could just split the data up.
Create two new columns next to column A. Then use text to columns and delimit on the "x".
In the E column use a simple formula of
IF(OR(B2>=1400,C2>=1400),"True","False")


text:
Q: Mann Whitney U test with normal distribution approximation: null hypothesis rejected? I'm new with U test and I have some doubts about the rejection of the null hypothesis with the U test with normal distribution approximation.
In my example I used this data for a 1 tailed test:
$$
H_0: median_1 = median_2
$$
$$
H_1: median_1 < median_2
$$
$$
\alpha = 0.05
$$
$$
Z_\alpha = 1.645
$$
I obtained $$Z = 1,0313$$
Do I reject the null hypothesis if
$$Z < Z_\alpha$$ or if
$$Z > Z_\alpha$$?
Thanks in advance for your answers.

A:
I'm new with the U test and I have some doubts about the rejection of the null hypothesis with the U test with normal distribution approximation.
H0:median1=median2
  H1:median1$<$median2

The Mann-Whitney U test is not of itself a test of the hypothesis of equality of population medians -- at least no more than it is a test of equality of population means. If accompanied by additional assumptions (that would make what it does test equivalent to a test of equality of populations) then it can function as such a test.

I obtained Z=1,0313
Do I reject the null hypothesis if
   $Z<Z_α$
  or if
   $Z>Z_α$

Possibly neither of those -- it depends on exactly what the statistic you have is computing. Note, however, that it would be very unusual indeed to have a test where the rejection region included a Z-score of 0 and this is not one of those rare cases.
If your $U$ is the number of times an observation from sample 1 exceeds an observation from sample 2 (what I'd expect to be the most likely definition of $U$) then you'd reject for unusually small values of the statistic, so most likely you'd actually reject for $Z\leq -Z_α$.
However, you should double check how $U$ has actually been defined for your situation (and strictly speaking, you should also double check how $Z$ is defined in terms of that $U$ as well). That would then confirm which direction the comparison should go (i.e. whether the rejection region is $Z\leq -Z_α$ or $Z\geq Z_α$).

A: U test can be explained with Area Under ROC see this post. It is a non-parametric test, not necessary to tell if mean or median is different but two distributions are different.
Do not know how if you like to try following code to see how the numbers are calculated.


text:
Q: tablelayout tablerow layout alignment I am totally out of idea why test,test1,test2,test3 is not proper align with first row. First row is refer to test,2012,test,test. I want the following row follow the first row in the table.
xml:
 <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/tl"
        android:weightSum="5"
        >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#27160e" >

       <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textStyle="bold"
            android:textSize="18sp"
            android:gravity="center"
            android:textColor="#fad06e"
            android:layout_weight="1"
            android:text="Project" />

       <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textStyle="bold"
            android:textSize="18sp"
            android:gravity="center"
            android:textColor="#fad06e"
            android:layout_weight="1"
            android:text="Project2" />

         <TableLayout
             android:layout_weight="3"
        android:layout_marginRight="4dp"
       android:stretchColumns="*"
       >

       <TableRow>
       <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="#fad06e"
            android:text="Cost"
            android:gravity="center"
            android:layout_span="2" />
   </TableRow>
        <TableRow
            >

       <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="#fad06e"
            android:text="2011" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="#fad06e"
            android:text="2012" />
                  </TableRow>
                  </TableLayout>
    </TableRow>

  <TableRow>
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="1"
            android:text="test" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"

            android:layout_weight="1"

            android:text="test" />
      <TableLayout android:stretchColumns="*"
          android:layout_weight="3">
          <TableRow>
                <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"

            android:text="test" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"

            android:text="test" />

          </TableRow>

      </TableLayout>

  </TableRow>

</TableLayout>

Code:
TableLayout tl;

        tl = (TableLayout) findViewById(R.id.tl);

        for(int x = 0; x < 3; x++) {

            // Create the table row
            TableRow tr = new TableRow(this);
            tr.setId(100+x);

            TextView lblrecID = new TextView(this);
            lblrecID.setId(200+x);
            lblrecID.setText("test");
            lblrecID.setGravity(Gravity.CENTER);
            LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
            lblrecID.setLayoutParams(params);
            tr.addView(lblrecID);// add the column to the table row here

            TextView lblrecName = new TextView(this);
            lblrecName.setId(200+x);// define id that must be unique
            lblrecName.setText("test1");
            lblrecName.setGravity(Gravity.CENTER);
            lblrecName.setLayoutParams(params);
            tr.addView(lblrecName); // add the column to the table row here

            TableLayout tl1 = new TableLayout(this);
            LayoutParams params1 = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 3f);
            tl1.setStretchAllColumns(true);
            tl1.setLayoutParams(params1);
            TableRow tr2 = new TableRow(this);

            TextView lblrecID1 = new TextView(this);
            lblrecID1.setId(200+x);
            lblrecID1.setText("test2");
            lblrecID1.setGravity(Gravity.CENTER);
            tr2.addView(lblrecID1);// add the column to the table row here

            TextView lblrecName1 = new TextView(this);
            lblrecName1.setId(200+x);// define id that must be unique
            lblrecName1.setText("test3");
            lblrecName1.setGravity(Gravity.CENTER);
            tr2.addView(lblrecName1); // add the column to the table row here
            tl1.addView(tr2);
            // finally add this to the table row

            tr.addView(tl1);
            //tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
            tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

        }

Result

A: Ok. I don't get what you want. Is it like this layout maybe?
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tl"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="*">

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#27160e" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Project"
        android:textColor="#fad06e"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Project2"
        android:textColor="#fad06e"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Cost"
        android:textColor="#fad06e"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="2011"
        android:textColor="#fad06e"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="2012"
        android:textColor="#fad06e"
        android:textSize="18sp"
        android:textStyle="bold" />
</TableRow>

<TableRow>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />
</TableRow>

 <TableRow>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="test" />
</TableRow>


text:
Q: How to know group and artifact ID's while adding to maven Trying to add JNA dependency to my java project, but don't know Group and Artifact ID's and version number. What is the logic of getting such kind of information in general? Is it possible somehow browse for this information? For example I don't know what JNA versions are available.

A: I usually check Maven Coordinates here: http://search.maven.org/
You can even search for a specific class: http://search.maven.org/#advancedsearch|gav

A: I don't know of reverse index to get maven id from class, but you can :

*

*type the root package or emblematic class in google and find a jar that contains it (grepcode.com usually does that, or you will find the github page of the project)

*search with jar name on maven central


text:
Q: Why do my posts look like they are in "admin editing mode"? I have created a wordpress blog. But when I on my created website and click on a link that leads to one of my posts, I do get to that post, but with the following problem:
At the top I see this grey "wordpress option bar" with the wordpress simbol, "Costumize", "Howdy Admin" etc.  Like I would go on the post as an admin.  But I just want to visit the post "normally" like a normal user. How do I make the post look "normal"?  (how do you call this "Not normal" mode?
It seems to me it has something to do that the link to the post is also really weird: http://box5466.temp.domains/~eternbf8/the-prospect-of-an-eternal-blissful-life/
Shouldn't that link be something like https://my-domain-name/the-prospect-of-an-eternal-blissful-life ?
Does this have something to do with the "WordPress Address (URL)" or "Site Adress (URL)" in the general settings? (right now they are both set to http://box5466.temp.domains/~eternbf8 ) I think that wasn't always the case.
Any buzz words that help me google this problem (or just links where the problem is descirbed) are already helpful to me! I don't really know how to proceed in solving this. I am a newbie to wordpress.
Thanks!

A: The grey bar at the top of your site is the WordPress Toolbar or Admin Bar. This is displayed, by default, for logged in users and is completely normal behaviour.
If your "WordPress Address (URL)" or "Site Adress (URL)" is set to http://box5466.temp.domains/~eternbf8 then this is the URL that will be used for all pages and links on your site - it's a temporary URL/domain name from your web hosting. You'll need to change the "WordPress Address (URL)" or "Site Adress (URL)" to your real domain name if you want the site to work from there.
As per the link that Dave provided above in his comment, you can read more about changing the site URL there - https://codex.wordpress.org/Changing_The_Site_URL
Note Both settings should include the http:// part and should not have a slash "/" at the end.


text:
Q: how to add numeric value to for loop i have pass numeric value to javascript function.i want to check it in for loop.val is amount of checkboxes.in this thime there is two checkboxes.then val is 2
function cal(val, id){ // val =2
    var sum = 0;
    var gn, elem;
    var l = 1 * val; //l=1*2
    var b = parseInt(l) + 1; // b=2+1
    for (i = 1; i < b; i++) { //this is not working.but b to replace 3,it's working
        alert(i);
        gn = 'testw' + i; //checkboxes ids
        elem = document.getElementById(gn);
        if (elem.checked == true) {
            sum += Number(elem.value); //calculate checkboxes values
        }
    }
    document.getElementById("rp").value = sum.toFixed(2);
    // display total in textfield
}


text:
Q: Keep running an app in lock screen I am new at Ubuntu, and I have an app running with tomcat, to broadcast images.
I need this app keep running even if I lock th system (ctrl+alt+l).
Is there any way to do it?
Ubuntu 14.04 LTS

A: Locking the system does not affect running processes if they expect any interaction.


text:
Q: Unable to Scroll to UI object using Python-UIAutomator I was wondering if I can scroll to an element on default android web browser where in the Web view is converted into a native XML tree.
I was trying to scroll to a UI element which in almost bottom of the page. I had used the following code fragment.
from uiautomator import device as d
from uiautomator import Device

d = Device('XXXXXXXXXXXXXX')
d(scrollable=True).scroll.to(text="XYZ")

But, I was not able to scroll to this object.
Any suggestions for alternate solutions on this problem?


text:
Q: How to know if a comment on a page post is hidden in Graph API We are looking for a way to find out, if a comment is hidden on a story on a page feed. We are using the Graph API to get the comments: [story_id]/comments with an Admin Access Token. Facebook tells us if we can delete the comment. However, there is no "is_hidden" flag or something.
Is there any other way to find out if the comment is hidden/marked as spam?
Thanks!

A: I'm PHP Developer, we have also used Facebook Graph API many times.
As per my expertise, I think we cannot fetch/identify only hidden/spam comments.
But yes you can get the comments for only particular user if you want.
For example:
1.) Get id of a fanpage with public graph data: http://graph.facebook.com/cocacola - thumsup has 507267189335315.
2.) Get ThumsUp's "like plugin" iframe display directly with some modified params: http://www.facebook.com/plugins/fan.php?connections=100&id=40796308305
3.) Now check the page sources, there are a lot of fans with links to their profiles, where you can find their profile ids or nicknames
4.) If you are interested only in profile ids use the graph api again - it will give you profile id directly
I hope you will find my answer appropriate.
If you are getting some other solution, please share
Thanks,
Shreyas

A: By now, finding out if a comment is hidden can be achieved via the is_hidden flag.
More detailed answer on a similar question
Facbook API docs for comment endpoint


text:
Q: C# program crash (.ico file) The program crashes if there's no .ico file inside the same folder. I have:

*

*Added the MyIcon.ico file in the Application section, also 'embed manifest with default settings' is checked.

*Made the .ico file as Embedded Resource (Build Action) in the .ico file properties.

*Added this.Icon = new Icon("plat.ico"); in the Public form.

So... why is the application not booting? What gives?

A: The constructor for Icon you are using tries to read "plat.ico" as a filename, not from embedded resources.
If you want to load the Icon from resources, you will need to explicitly get a Stream from the resource, then pass that into the Icon's constructor.
This will likely be something similar to:
// Add using System.Reflection; at the top of your file...

this.Icon = new Icon(
    Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.plat.ico")
  );

Alternatively, you can use the constructor overload that pulls directly from a resource, by name, instead of a filename:
this.Icon = new Icon(this.GetType(), "plat.ico");

A: I had the same problem in a windows form, where the icon could not be found even though it was in the same directory as the form.
notifyIcon1.Icon = new Icon("enabled.ico");

I looked at the .ico file's properties in VS2010 and saw that Copy to Output Directory was set to Do not copy. I changed it to Copy always and that did the trick.
Sometimes the simplest solution is the best solution.

A: You need to set the icon file's "Copy to Output" to "Copy Always" or "Copy if Newer".

A: You are invoking wrong constructor. Just use this:
this.Icon = new Icon(this.GetType(), "plat.ico");


text:
Q: Prefix matching search in multiple words in dart Let's consider a list:
List<String> recipeNamesList = [
  'Burger',
  'French Fries',
  'Pizza',
  'Bengali Lamb Curry',
  'Chingri Malai Curry',
];

What my search needs to do:

*

*Only match using prefix so if the user types in ger it shouldn't return burger. It should return burger only when someone types in bur.

*If someone types in Bengali Curry it should return Bengali Lamb Curry.

*If someone types in Curry it should return Bengali Lamb Curry & 'Chingri Malai Curry',

What I've tried so far(got help from another question I asked):
  Future<List<String>> getSuggestions(String search) async {
    List<String> results = [];
    List<String> searchSplit = search.toLowerCase().split(" "); // split the search query

    for (int i = 0; i < searchSplit.length; i++) { // iterate over search query
      for (int j = 0; j < recipeNamesList.length; j++) { // iterate over the recipe names list
        List<String> recipeNamesListSplit = recipeNamesList[j].split(" "); // split the recipe names
        for (int k = 0; k < recipeNamesListSplit.length; k++) { // iterate over the list of splitted name
          if (recipeNamesListSplit[k]
              .toLowerCase()
              .startsWith(searchSplit[i])) { // convert to lower case and check if the query is present in splitted name
            results.add(recipeNamesList[j]); // if contains == true add to results
          }
        }
      }
    }

    // Avoid repeated values
    results = results.toSet().toList();
    return results;
  }

Issues with code:

*

*If I provide a space(anywhere in text field) it loads everything.

*If I type Bengali Curry it returns both Bengali Lamb Curry & 'Chingri Malai Curry'.

Can any one point out what I did wrong in this code?
N.B: any pointer for an even optimized code will be appreciated. Although it's not a must right now

A:

*

*If I provide a space(anywhere in text field) it loads everything.

I don't observe that when trying your code.  It will happen if your search string contains multiple consecutive spaces because String.split unfortunately does not collapse consecutive instances of the search pattern.  For example, 'fooxxxbar'.split('x') will return ['foo', '', '', 'bar'].  You later check if any of the tokens from recipeNamesList start with any of those elements, but ''.startsWith(string) is always true.
An easy way to fix that is to essentially collapse whitespace yourself by making the search pattern match one-or-more whitespace characters.  That is, replace string.split(' ') with string.split(RegExp(r'\s+')).
Another easy way to fix it is to just continue if encountering an empty token to ignore it.

*If I type Bengali Curry it returns both Bengali Lamb Curry & 'Chingri Malai Curry'.

Your current algorithm always adds the results list whenever it finds any match.  It searches for 'bengali', finds one item, adds it to results, searches for 'curry', finds both of those results, and adds both of them.
Instead of iterating over search tokens in the outer loop and iterating over the recipeNamesList tokens in the inner loop, it would make more sense to iterate over recipeNamesList, and on each iteration, check if all of the search tokens match the tokens of the search string.  If so, then add that recipe name to the list of results1.  That also would prevent the same recipe name from being added multiple times without needing to use a Set.
1 Or if you want fuzzier matching, record a score for each recipe name (e.g. the number of search tokens that were matched), sort the results by the scores, and discard any below a certain threshold.


text:
Q: Cambio automático de enlaces de páginas Me explico...
No se si se puede hacer o no, por eso hablo desde el desconocimiento.
Tengo una web de trabajo temporal.
Esta web tiene un enlace de "Inscripción" para que nuevas empresas se registren y comiencen a publicar sus ofertas.
Generalmente, esta deshabilitado y al darle a "Inscripción" aparece que no hay plazo de inscripción abierto.
Durante una semana o dos al año abrimos ese periodo de inscripción para las empresas y luego volvemos a cerrar la inscripción.
En cuanto a la parte técnica, cuando esta cerrado el enlace redirige a la pagina "inscripcioncerrada.php" y cuando nos establecen el periodo para abrir la inscripción lo que hacemos es cambiar la redirección a "inscripcionabierta.php". Cuando se cierra hacemos a la inversa, cambiamos "inscripcionabierta.php" por "inscripcioncerrada.php".
Esto realmente es tedioso y bastante largo ya que tenemos muchas paginas donde se hace referencia al enlace "Inscripción" y hay que cambiarlo cada vez que se abre o cierra la inscripcion en unas 20 páginas individualmente.
Por eso, pregunto (como he dicho bajo el desconocimiento) si existe alguna manera de hacer una funcion o script que cuando quiera abrir el periodo de inscripcion me cambie los enlaces de las 20 paginas que quiero a "inscripcionabierta.php".
Esto seria mucho mas rapido y eficiente para mi.
P.D: La web esta hecha en PHP como podeis ver por las extensiones.
P.D2: Las fechas de inscripcion cambian todos los años, es decir, no se abre y se cierra el periodo de inscripción el mismo dia todos los año.
Gracias de antemano

A: inscripciones.php
$enlaceInscripcion = 'inscripcionabierta.php'

En TODOS los ficheros php que tengas enlaces a esa url, al inicio, cargas un
include_once("ruta/hasta/el/fichero/inscripciones.php");

(o incluso mejor, si ya tienes un fichero "header" o similar que ya cargas con include o require en todas las páginas, puedes definir ahí mismo la variable)
con esto tienes en TODOS los ficheros, definida una variable llamada $enlaceInscripcion que vale lo que le pongas tú en el fichero "inscripciones.php".
Ahora modificas en TODAS las páginas el enlace que tenías a "inscripcionabierta.php" o "inscripcioncerrada.php" y lo sustituyes por
<?= $enlaceInscripcion; ?>

de modo que según cambies el contenido en el fichero del include, automáticamente en todos los enlaces pondrá la url que quieres.
Esto lo haces una vez, y ya está, a partir de ahí solo necesitas cambiar el contenido del "inscripciones.php" para llevar al visitante donde necesites, en vez de cambiar a mano los 20 enlaces.


text:
Q: How to fix "iff" error for pine-script version 5 for customizing Cyclic Smoothed RSI I am trying to upgrade a customized version of "Cyclic Smoothed RSI" an open community script available on TradingView. But encountering the following error -

line 43: Could not find function or function reference 'iff'.

The code is as follows -
//@version=5
indicator(title="csRSI-EMA", shorttitle="csRSI-EMA")
src = close
domcycle = input.int(20, minval=10, title="Dominant Cycle Length")
crsi = 0.0
cyclelen = domcycle / 2
vibration = 10
leveling = 10.0
cyclicmemory = domcycle * 2
//set min/max ranges?

h1 = hline(30, color=color.silver, linestyle=hline.style_dashed)
h2 = hline(70, color=color.silver, linestyle=hline.style_dashed)

torque = 2.0 / (vibration + 1)
phasingLag = (vibration - 1) / 2.0

up = ta.rma(math.max(ta.change(src), 0), cyclelen)
down = ta.rma(-math.min(ta.change(src), 0), cyclelen)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1])

lmax = -999999.0
lmin = 999999.0
for i = 0 to cyclicmemory - 1 by 1
    if nz(crsi[i], -999999.0) > lmax
        lmax := nz(crsi[i])
        lmax
    else
        if nz(crsi[i], 999999.0) < lmin
            lmin := nz(crsi[i])
            lmin

mstep = (lmax - lmin) / 100
aperc = leveling / 100

db = 0.0
for steps = 0 to 100 by 1
    testvalue = lmin + mstep * steps
    above = 0
    below = 0
    for m = 0 to cyclicmemory - 1 by 1
        below := below + iff(crsi[m] < testvalue, 1, 0)
        below

    ratio = below / cyclicmemory
    if ratio >= aperc
        db := testvalue
        break
    else
        continue

ub = 0.0
for steps = 0 to 100 by 1
    testvalue = lmax - mstep * steps
    above = 0
    for m = 0 to cyclicmemory - 1 by 1
        above := above + iff(crsi[m] >= testvalue, 1, 0)
        above

    ratio = above / cyclicmemory
    if ratio >= aperc
        ub := testvalue
        break
    else
        continue

//EMA with Signal
//Inputs
len = input(9, minval=1, title="Length")
srcema = crsi
smoothingLength = input(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
offset = input(title="Offset", defval=0, minval=-500, maxval=500)
//Calculation
ma = ta.ema(srcema, len)
sigline = ta.sma(ma, smoothingLength)
hist = ma - sigline + 50

//Histogram Color
col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")

//Plotting
plot(hist, histbase=50, title="Histogram", style=plot.style_columns, color=(hist>=50 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(ma, title="EMA", color=color.green, offset=offset)
hline(50, "Median", color=color.new(#787B86, 50))
plot(sigline, title="Smoothing Line", color=color.red, offset=offset, display=display.none)
lowband = plot(db, "LowBand", color.aqua)
highband = plot(ub, "HighBand", color.aqua)
fill(h1, h2, color=color.silver, transp=90)
fill(lowband, highband, color=color.gray, transp=90)
plot(crsi, "CRSI", color.fuchsia)

Please help me to fix this issue. Thanks for your time and effort. Regards.

A: You can find a good explanation here: Pine Script: IF vs IFF
"iff(crsi[m] >= testvalue, 1, 0)" should be "(crsi[m] >= testvalue ? 1 : 0)"


text:
Q: background-position won't work in Firefox/IE I am using background-position and it works fine in Chrome but on Firefox and IE it doesn't work as it should.
.badge {
background: url(badge.png) no-repeat;
background-position: 0px 1px;
display: inline-block;
color: #9e988e;
font-size: 12px;
padding-left: 15px;

What shall I use to make it same in all browsers?
JSFIDDLE

A: Internet Explorer does this with background-position-x or background-position-y. Firefox doesn't support that..

A: just came across a similar issue today.
This can get a little weird, but try adding this to your style.
Example
background-position-x: 54%;
background-position-y: 10%;
You may have to mess around with the exact position, but most browsers accept it.


text:
Q: Is using DirectoryServices.NativeObject slow/bad? In an ASP.NET 4 application, I have existing code to access a user's Active Directory information (potentially under Windows Authentication or FBA) like this:
// authType taken from run-time config file, default below
AuthenticationTypes authType = AuthenticationTypes.Secure;
string path = "LDAP://" + domain;
DirectoryEntry entry = new DirectoryEntry(path);
entry.AuthenticationType = authType;

// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;

DirectorySearcher search = new DirectorySearcher(entry);
// set search Filter/Properties etc. ..., nice and correctly
SearchResult result = search.FindOne();

It has always worked fine for me, on my LAN.  But I get no feedback from customer sites (other than it works).  I now note a post like http://www.justskins.com/forums/directoryentry-nativeobject-slow-with-203410.html, implying this COM way of going via DirectoryEntry.NativeObject might be inefficient or ill-advised? On the other hand, I see here LDAP search using DirectoryServices.Protocols slow, implying it is OK?
This code probably dates from .NET 1/2, when perhaps System.DirectoryServices had less in it; it came from some MS example for using ADSI somewhere.
In a word: I don't want to change the code just for the sake of it, but will if faster.  Is there actually nowadays any superior method(s) in DirectoryServices which I should be using?


text:
Q: How prevent to create a .exe.config in a Windows Forms Application build (Visual Studio Community 2019 - C#) I'm working in a legacy project (Windows Forms Application), with target framework .NET 2.0. The goal is to build a single .exe file that does not depend in any configuration file (in particular that does not depend on the .exe.config because the application doesn't need anything from this configuration file).
The characteristics of the project:
Application:
Targe framework: .NET Framework 2.0
Output type: Windows Application
Auto-generate binding redirecs: Not enabled

Build:
Platform target: Any CPU

Visual Studio Community 2019, version 16.1.3

The solution has a app.config file that I've tried to remove but for some reason It seems that remains in the project. When I say seems to remains in the project is because I follow this steps:

*

*In the Solution Explorer, right-click on the App.config, and then click on Exclude From Project.

*Rebuild the project, and still the .exe.config in generated.

*Again in the Solution Explorer > Add > New Item, and when I try to add an Application Configuration File with the name App.config VS show this message: A file with the name 'App.config' already exists. Do you want to replace it?.

(I've also tried with the right-click on the App.config, and then click Delete option)
This seems to indicate that the configuration file is not effectively removed from the project, and therefore the .exe.config is still generated.
Also, I've checked this post, and tried changing the files properties (Build Action, Copy to Output Directory, etc) but the .exe.config file remains in the build.
Finally, I've tried (probably more as a desperate attempt) with uncheck the Auto-generate binding redirects which prevents the generation of the .exe.config but the .exe is not running properly.
Just as an additional information, the content of the .exe.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Company.Afis.ImageContainer" publicKeyToken="97cac07b8409e999" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.5.0.1827" newVersion="2.5.0.1827" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Other post that I've checked:

*

*How to make work 'do not copy' app.config to output directory?

*appname.exe.config not created on windows application

*Release build without config file

*How to not copy app.config file to output directory
If any other information is needed, please let me know to update it.

A: Disable auto generation of assembly binding redirects and instead, handle  AssemblyResolve event of the current AppDomain.CurrentDomain and load the requested assembly in the event handler.

*

*Disable Auto-generate assembly binding redirects
Right click on project, choose Properties and in the project properties page, in the first tab (Application tab), uncheck Auto-generate binding redirects. You can do the same by editing project file and setting <AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>.

*

*Handle AssemblyResolve Event
You should add the event handler before the run-time tries to load the assembly. For example, in the static constructor of Program class. For example, in the following code, I suppose the application is looking for MyAssembly which I have it as MyAssembly2.dll in application's folder.
static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private static Assembly CurrentDomain_AssemblyResolve(object sender,
    ResolveEventArgs args)
{
    if (new AssemblyName(args.Name).Name == "MyAssembly")
        return Assembly.LoadFrom(
            Path.Combine(Application.StartupPath, "MyAssembly2.dll"));
    throw new Exception();
}


text:
Q: How do I display and assign foreign keys on an object in MVC Core? I have a World object and I have a Kingdom object with a WorldId. I've been trying to find any documentation that will tell me how to, on my create page for my Kingdom object, choose from a list of World objects and based on that bind the FK to the World object's Id.
My world model
    public class World
{
    public int Id { get; set; }
    public string Name { get; set; }
    public long Age { get; set; }
}

My Kingdom model
    public class Kingdom
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? WorldId { get; set; }
}

For now, this is my Index Action
        public async Task<IActionResult> Index()
    {
        var model = await _context.Kingdom.ToListAsync();

        return View(model);
    }

I don't know what methods to use, what are the best practices for achieving this? I have looked at ViewModels, but no good explanations on how to achieve it.

A: *

*add a World property to your Kingdom class so that Kingdom becomes -

public class Kingdom
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? WorldId { get; set; }

    public World World { get; set; }
}

*right click on your Controllers folder, then select "Add", then select "Controller"

*then from the dialog box select "MVC controller with views, using Entity Framework"

*select Kingdom from Model class dropdown, and also select your DbContext

*click Add

This process is called Scaffolding, and it will generate a KingdomsController in your Controller folder and all the views you need in the Kingdoms folder under Views.
Now open the Create.cshtml under Kingdoms in Views. You'll find it has generated a dropdown (html select) for you to select a World.
Once you select a World from that dropdown, its Id will be added to your Kingdom model as the foreign key.
Go the Create action method (the GET one, not the POST one) in your KingdomsController and you'll find where the data for that World select dropdown is coming from.
Run the application, explore the generated code.
You can go through this tutorial for details. Happy coding.


text:
Q: How to iterate attributes in custom direction's link method in AngularJS I use AngularJS custom directive which creates HTML element and want to add attributes, entered from HTML page, in 'link' method but i cannot iterate attributes. My code:
 link: function (scope, element, attrs) {
     // iterate attrs
 }

Is there way to iterate all attributes?

A: angular.forEach(attrs, function(value, key) {
    ...some code here
}


text:
Q: What keyboard shortcuts are available in Xfce4? Note this is all apropos of Xubuntu, in spite of a mention of Mint Xfce.  I actually use 3 OS types, and all three have this issue in one form or another.
I'm looking at Xfce4 documentation here of the Settings->Keyboard app, and I'm a bit puzzled about the keyboard shortcuts, even the ones in the illustration.  Things like Super-P are clear enough once I understand that the Super key bears an MS Windows logo on my keyboard.  But what are the ones that look like plain text:
Mail
WWW
Display
Print

and looking on my own machine running Xfce Linux Mint
Messenger
Calculator
Home Page
Music

Are there keyboards with keys bearing such names, or is something else going on?

A:
Are there keyboards with keys bearing such names?

Yes. Normally they have icons on them, instead of names.
Sometimes those are separate keys, and sometimes they're combined with F1..12. In the latter case you have to press FnF1-12 to trigger such shortcut.