text:
Q: xcopy batch file pst backup I'm trying to build a batch file script, which will copy the outlook.pst file, from the user's My Documents folder and move it to the server, which I've mapped as a drive, "B:\"
This is the code I have so far:
@echo on
xcopy "c:\Documents and Settings\%username%\My Documents\outlook.pst" "B:\PST\%username%\" -c -d -i -y
exit

The script is designed for Windows XP.
However, when I run this code on the client machine, it doesn't copy the .pst file across, it just runs the command over and over again, until I Ctrl + C it...
Thanks

A: If I recall correctly, the default location for PST files is in %localappdata%\Microsoft\Outlook\.  And if the user has PST files in multiple locations, it's possible that he has more than one with the same name, just in different folders.  Good times.
If it's possible that your users might have PST files in locations other than My Documents, I recommend modifying your script with just a couple of very minor changes.
@echo off
setlocal enabledelayedexpansion
for /r "%userprofile%" %%I in (*.pst) do (

    rem avoid overwriting in case "outlook.pst" exists in two locations, for instance
    if exist "B:\PST\%username%\%%~nxI" (
        set cnt=000

        rem get count of files matching b:\pst\username\filename*.pst
        for /f %%a in ('dir "B:\PST\%username%\%%~nI*%%~xI" 2^>NUL ^| find " File(s) "') do (
            set "cnt=!cnt!%%a"
        )

        rem file of the same name will become filename001.pst, filename002.pst, etc.
        set "dest=%%~nI!cnt:~-3!%%~xI"

    rem otherwise leave the filename alone
    ) else set "dest=%%~nxI"
    set /P "=Copying !dest!... "<NUL
    copy "%%~fI" "B:\PST\%username%\!dest!"
    echo Done.
)

A: I wished to copy outlook.pst from its Microsoft default location to a memory stick using a batch file in Windows XP
I found that xcopy failed to copy Outlook.pst to the memory stick or to My Documents
I now xcopy it in 2 steps, firstly to C:\ then to the Memory Stick
It has worked reliably


text:
Q: what are best practices for deploying new features for spring boot application? i have a spring boot application with too many users, and there are many incoming requests to my application, what should i do for deploying a new feature to the application without losing incoming user request and actually interrupting the application's availability to clients ? i wanna know about best practices for my issue.

A: Please note deployment strategies depends on the nature of your application.
For cases like you mentioned Blue/Green or Canary would be useful.
Various ways Deployment strategies classified, below is one such categorization.

*

*Recreate: Version A is terminated then version B is rolled out.

*Ramped (also known as rolling-update or incremental): Version B is
slowly rolled out and replacing version A.

*Blue/Green: Version B is released alongside version A, then the traffic is
switched to version B.

*Canary: Version B is released to a subset of users, then proceed to a full rollout. A/B testing: Version B is released to a subset of users under specific condition.

*Shadow: Version B receives real-world traffic alongside version A and doesn't impact the response.
reference link - https://thenewstack.io/deployment-strategies/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove a WordPress page from a path? I have a site that was made in WordPress and I need to remake it just with HTML and php.
The problem is
I have a page at the url www.mydomain.com/create
I created a new file with same name, www.mydomain.com/create.php
Now on the host I removed the extension .php, but the problem is i will still hit the word press page.
Where can I find the file with the url set for this page? I don't know much about word press besides where plugins are.

A: WordPress does not use one file per page / post. WordPress instead has a template system inside themes that defines how pages and lists of posts are turned into HTML. The content of those pages and posts resides within the database and can be viewed in wp-admin. Further, WordPress extensions and themes can define hook functions and filters to modify content and style of the page and execute code upon certain events.
You cannot find a file for this "/create/" page. It has some content in the database but the content itself won't render into what you see in the browser.
Sorry to say this, but if you like to recreate the site, you will have to find a new way of constructing and rendering it (and also reusing code). You might also want to look for a proper framework like Laravel and have some proper routing in place (instead of renaming PHP files).
Edit:
You can change the permalink for create like so:
UPDATE PREFIX_posts SET post_name = 'create_old' WHERE post_name = 'create';

You have to adapt the MySQL table name to the WP posts table by replacing PREFIX with whatever prefix your WP posts table has.


text:
Q: Calculate Percentage of RowTotal instead of GrandTotal in Power BI I am new in Power BI, I am trying to calculate the percentage based on the rowTotal instead of GrandTotal. for example - with my dataset in excel -
RAW Data is like -
from these raw data I want the calculation like -

A: Very simple problem to be solved and accept the solution if helping:

*

*From the original table, create the Total measure:
Total = SUM(Sheet2[Compliant]) + SUM(Sheet2[Non-Compliant])

*Create the Percentage measure
 Percentage = SUM(Sheet2[Compliant]) / (SUM(Sheet2[Compliant]) + SUM(Sheet2[Non-Compliant]))
The outcome using table report


text:
Q: Installing centos, error - failed to find suitable stage1 device On my machine i already have windows. On free space of 100gb, I created 3 partitions for new centos installation - /boot 500mb, swap 8gb, and / of remaining 90gb. All are of type standard partition, and file system type ext4(except swap which is of type swap)
Its giving me error checking storage configuration - failed to find suitable stage1 device:Efi system partition must be mounted on one of /boot/efi
Whats the reason for this? Also will it interfere in dual boot?

A: First a caveat - I don't really know how this works.
But from what I've read, you need a separate partition (of type vfat) that's mounted in /boot/efi. It should be about 200Mb.


text:
Q: JPQL - How can I get an extra param inside my entity? I am new to JPQL and I am trying to get an extra parameter that is not in the entity, but I am not finding how to do it.
Through searched here in the forum I found out that some uses a DTO for it, but I am not knowing how to apply that.
Here is my entity:
@Entity
@Table(name = "person")
public class Person implements Serializable {

    private int id;
    private String name;
    private String email;
    private int age;

...
}

And my JPQL:
SELECT COUNT(a.name) as countOfNames, a FROM Person a WHERE a.name like :name

How can I get the countOfNames result inside of myentity object since it is not a column?

A: The simplest way is to use a constructor expression
package com.entites

public class PersonDto {

    private Person person;

    private Integer countOfNames;

    public PersonDto(Person person, Integer countOfNames) {
        this.person = person;
        this.countOfNames = countOfNames;
    }

}

select new com.entites.PesronDto(a, count(a.name))
  from Person a
  where a.name like :name


text:
Q: Determine highest precision type for corresponding floating point and complex types To deduce the highest precision type for floating point and complex types, i.e.

*

*float/double/long double results in  long double,

*std::complex<T> results in std::complex<long double>,

my attempt ( live example on Wandbox ) feels very clumsy:
#include <complex>
#include <type_traits>

template <typename T>
struct is_complex : std::false_type {};

template <std::floating_point T>
struct is_complex<std::complex<T>> : std::true_type {};

template <typename T>
inline constexpr bool is_complex_v = is_complex<T>::value;

template <typename T>
struct highest_precision_type
{
    // none for arbitrary type
};

template <typename T>
    requires std::is_floating_point_v<T>
struct highest_precision_type<T>
{
    typedef long double type;
};

template <typename T>
    requires is_complex_v<T>
struct highest_precision_type<T>
{
    typedef std::complex<long double> type;
};

int main()
{
    auto f  = highest_precision_type<float>::type{1};
    auto cf = highest_precision_type<std::complex<float>>::type{0, 1};

    static_assert(std::is_same_v<decltype(f), long double> );
    static_assert(std::is_same_v<decltype(cf), std::complex<long double>> );
}

Is there a more concise way to achieve the desired result?

A: Using std::conditional<> and @KamilCuk's comment reduces code to:
template <typename T>
struct highest_precision_type
    : std::conditional<std::is_floating_point_v<T>, long double, T>
{
};

template <typename T>
struct highest_precision_type<std::complex<T>>
{
    typedef std::complex<long double> type;
};

see live example.

A: I think your code is fine but if you'd like a more compact alternative, this could be done using std::conditional:
template <typename T>
struct highest_precision_type
{
    static_assert(std::is_arithmetic_v<T>);

    using type =
        std::conditional_t<
            std::is_unsigned_v<T>,
            std::uintmax_t,
            std::conditional_t<
                std::is_integral_v<T>,
                std::intmax_t,
                long double>
        >;
};

For types instantiated from templates, what Barry had in his now deleted answer looks good. This is my take on that:
template <template <typename...> class C, typename... Ts>
struct highest_precision_type<C<Ts...>>
{
    using type = C<typename highest_precision_type<Ts>::type...>;
};

template <typename T>
using highest_precision_type_t = typename highest_precision_type<T>::type;

Demo
Note the part in the demo that does:
highest_precision_type_t<std::string> s;
static_assert(std::is_same_v<decltype(s), std::basic_string<std::intmax_t>>);


text:
Q: refer .js in AngularJS service In my angular environment I have below files.
app/scripts/constants.js
myApp.constant('constants', {
    errorMessages: {
        serverUnavailable: 'The server is not available at the moment, please try again later.'
    },
.
.
.

app/scripts/services/user.js
myApp.factory('MyHttpInterceptor', ['$q', '$injector', '$location', '$rootScope'
    function($q, $injector, $location, $rootScope) {
        .
        .
        .
    }
]);

I want to refer the 'serverUnavailable' defined in constants.js into user.js, for that, I have added constants.js as 'constants' at the end as shown below but it results in an error 'Uncaught SyntaxError: Unexpected token function'.
app/scripts/services/user.js
myApp.factory('MyHttpInterceptor', ['$q', '$injector', '$location', '$rootScope', 'constants'
    function($q, $injector, $location, $rootScope, constants) {
        var v = constants.errorMessages.serverUnavailable;

What is the correct way of doing this?

A: Add a comma after 'constants' and before function.


text:
Q: Oracle - adding foreign constraint in disabled state? I need to add a foreign key constraint but initially it should be disabled. I can add it in create table sentence or in an alter table  sentence, it does not matter. I do not know the reason behind this request (it may be ORA-02298: cannot validate (BLA.BLA_FK) - parent keys not found ) but I was asked to do it this way. So what is the correct sentence for this in Oracle database?

A: You'd want to do something like
ALTER TABLE YOUR_TABLE
  ADD CONSTRAINT YOUR_TABLE_FK1
    FOREIGN KEY (COLUMN1, COLUMN2) REFERENCES SOME_OTHER_TABLE (COLUMN1, COLUMN2)
      DISABLE
      NOVALIDATE;


text:
Q: Wordpress default audio playlist - how to add custom caption? The wordpress default audio playlist shows the caption of the media file in the list. Is there any way I can add custom title while creating playlist?
I am using the same audio file in 2 playlists, and I need the playlists to display different captions for it. What can I do?

A: If I'm not mistaken, then you can't do that with the playlist shortcode by default.
How often does this case happen? If it rarely happens, it might be easiest to upload the file a second time, and change the caption, information as needed.
Create your own playlist shortcode code based on the default one found in wp-includes/media.php. As for the approach, for example, if custom shortcode attribute is present, then replace caption (title or whatever), secondary information can be saved in custom fields, else keep the default. You can deregister the default shortcode and then register your custom code to [playlist].


text:
Q: Android: searchview to search specific strings variables I am developing an android app where I use a SearchView widget to search in a custom ListView of users data (image + Name and several textfields). The problem is that when I type a query it only searches through the names. Is there any way to tell the SearchView widget to search through the other strings in the ListView cells?
Thank you in advance.
The code below is what I currently have in the activity with search in actionbar:
public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.redirect_user, menu);
        MenuItem menuitem = menu.findItem(R.id.action_search);
        searchItem = (SearchView) menuitem.getActionView();

        int id = searchItem.getContext().getResources()
                .getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchItem.findViewById(id);
        textView.setTextColor(Color.WHITE);
        searchItem.setBackgroundColor(color.white);

        searchItem.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                FiltreActivity.getAdapter().getFilter().filter(newText);

                return false;
            }
        });

A: try this
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;

/**
 * Shows a list that can be filtered in-place with a SearchView in non-iconified mode.
 */
public class SearchViewFilterMode extends Activity implements SearchView.OnQueryTextListener {

    SearchView mSearchView;
    private ListView mListView;

    private final String[] mStrings = Cheeses.sCheeseStrings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.searchview_filter);

        mSearchView = (SearchView) findViewById(R.id.search_view);
        mListView = (ListView) findViewById(R.id.list_view);
        mListView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                mStrings));
        mListView.setTextFilterEnabled(true);
        setupSearchView();
    }

    private void setupSearchView() {
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(true);
        mSearchView.setQueryHint("Search Here");
    }

    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
        } else {
            mListView.setFilterText(newText.toString());
        }
        return true;
    }

    public boolean onQueryTextSubmit(String query) {
        return false;
    }
}


text:
Q: How can I disable the Windows UAC popup specifically for Teamspeak 3 client? Everytime I start up Teamspeak 3 client, I get Windows UAC pop up and to be honest it's finally annoyed me to the point I'm going to try and do something about it!
After reading up on teamspeak it might have something to do with installing the program for all users, which will then use each user's virtualstore to actually run the program and I'm thinking that is why I get the UAC notification.
Can anyone confirm this is/isn't the case? If this isn't the case, how can I make it so that I don't get UAC notifications for the launch of this specific program?
OS: Windows 10 x64
Installed on OS/main drive, in Program Files.

A: The general approach to get rid of the UAC is using the Microsoft Application Compatibility Toolkit.

*

*Download and install the Microsoft Application Compatibility Toolkit.

*Start the appropriate version 32bit or 64bit - depending on the application to modify.

*Select the "New database" (or reopen an existing database, if you are adding another application tweak) and right click -> "Create New" -> "Application Fix".

*Enter name, vendor and select the executable [continue]

*Skip the compatibility modes [continue]

*Select the single compatibility fix: "ForceAdminAccess" [continue]

*uncheck all boxes but keep "COMPANY_NAME" and "PRODUCT_NAME" (otherwise you have to create a new patch for every version) [continue]

*select the database and save it

*right click on the database and install it.

If this does not work, you may also try adding the compatibility mode "RunAsAdmin".

A: If a Windows program is installed in the default Windows program directory and UAC is enabled, it is write-protected. The virtualstore was made to support legacy apps that must put their data into the program directory. If a program attempts to write something into it's program directory, Windows redirects the write operation and the files are written to the virtualstore directory instead. Windows then merges the two directories, so the user doesn't notice that and thinks it is all one directory
To fix this I reinstalled Teamspeak and installed it outside of the Program Files directory, this eliminates the problem of needing access to edit files in the virtualspace and therefore stops the UAC notification!


text:
Q: Method will be shown automatically with the try catch block in android studio In Eclipse there is the option to set a method will be created along with try catch block or not.
What will i do get the same thing in android studio.
How i did the thing in eclipse will explained below,

help me to do the above thing in android studio.
Thanks in advance.

A: *

*Highlight the code

*Press "Code-> Surround With"

*In the list, type "try"

There's also a keyboard shortcut, You can get it from your menu.


text:
Q: Prevent disk reordering on boot I have 3 physical drives in my Mac Pro with OSX 10.6.4. Occasionally after rebooting the machine, the disk numbering changes such that the /dev/disk# does not reference the same drive as it did before the reboot.
Example
/dev/disk0 -> 64GB SSD drive
/dev/disk1 -> 640GB Hitachi
/dev/disk2 -> 160GB WD (BootCamp)

After rebooting the mapping might be
/dev/disk0 -> 160GB WD (BootCamp)
/dev/disk1 -> 640GB Hitachi
/dev/disk2 -> 64GB SSD drive

Even more confusing is that the remapping is not consistent. For most stuff this is irrelevant. However I also have Parallels installed to allow access to the BootCamp partition from within OSX. Parallels uses the /dev/disk# path in it's configuration file so, after rebooting OSX I launch Parallels and it tells me that the disk is no longer present.
Is there a way to tell OSX to always assign a given drive to /dev/disk0?

A: There does not seem to be a way to specify a device for a given drive. Your best bet might be to not auto-mount, then use a LaunchAgent to mount them in the order you want with a pause between each mount, and see if it works that way. This method might get messed up if you have a USB key or something else that auto-mounts available to the system when you boot.

A: One trick I've used to solve your Parallels use case is to have the config file point to a symbolic link file, and then update the symlink to point to the correct device before starting the vm.
If you're comfortable writing scripts, you could use a shell script like this to determine the device name and update the symlink based on the volume name:
 BOOTCAMP_DEVICE=`mount | grep BOOTCAMP | cut -f 1 -d ' '`
 ln -f -s $BOOTCAMP_DEVICE path_to_symlink


text:
Q: Set title of UIButton that's located in a UICell I don't understand why I can't set the title of my UIButton. It crashes here:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if(section == 0) {
        let view = UIView()
        view.alpha = 0
        return kTableHeaderShouldStickToTop ? view : carouselViewController.view
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier("NewsFeedSectionHeaderCell") as! NewsFeedSectionHeaderCell
        cell.delegate = self
        cell.dataSource = self

        cell.followingButton.setTitle("test", forState: .Normal)
        return cell
    }
}

It is connected in my .xib file:

A: Please check whether we can take cell object in viewForHeaderInSection: method because as per my knowledge viewForHeaderInSection: is called before cellForRowAtIndexPath. Put a breakpoint at
let cell = tableView.dequeueReusableCellWithIdentifier("NewsFeedSectionHeaderCell") as! NewsFeedSectionHeaderCell

And check from the variable View (left to console where we see logs) or hover over this object to see whether this object is nil or not. It will be nil so it raising the exception.


text:
Q: Is there a way to retry restarting a docker container if its port binding fails? I am trying to find a way so that a container with host port binding will restart if port mapping fails, just like it does based on healthchecks.
I am using docker-compose to manage multiple docker containers in the same docker network. One of them needs to map a port range with the host. However, sometimes one of the host ports in that range might become temporarily unavailable (e.g., when the host instance is initialized) causing the container to exit. The container remains at Exited state and visible through docker ps -a. docker inspect <container_id> displays the following error:
        "Error": "driver failed programming external connectivity on endpoint <container_name> (<container_id>): Error starting userland proxy: listen tcp4 0.0.0.0:<port>: bind: address already in use",
        "StartedAt": "2022-01-11T15:00:58.90581688Z",
        "FinishedAt": "2022-01-11T15:02:58.00504584Z",
        "Health": {
            "Status": "unhealthy",
            "FailingStreak": 0,
            "Log": [
                {
                    "Start": "2022-01-11T15:01:18.906002309Z",
                    "End": "2022-01-11T15:01:19.193144266Z",
                    "ExitCode": 0,
                    "Output": "7\n"
                },
                {
                    "Start": "2022-01-11T15:01:39.215216028Z",
                    "End": "2022-01-11T15:01:39.269082647Z",
                    "ExitCode": 0,
                    "Output": "7\n"
                },
                {
                    "Start": "2022-01-11T15:01:59.29146919Z",
                    "End": "2022-01-11T15:01:59.355386838Z",
                    "ExitCode": 0,
                    "Output": "7\n"
                },
                {
                    "Start": "2022-01-11T15:02:19.375357304Z",
                    "End": "2022-01-11T15:02:19.420589614Z",
                    "ExitCode": 0,
                    "Output": "7\n"
                },
                {
                    "Start": "2022-01-11T15:02:39.440870926Z",
                    "End": "2022-01-11T15:02:39.502808386Z",
                    "ExitCode": 0,
                    "Output": "7\n"
                }
            ]
        }
    },

, container_name, container_id and port being self-explanatory.
The issue appears to be temporary and the port is available shortly after the service exits, however there is no retry for it to start. Is there such an option through docker-compose, healthchecks or any other ideas?

*

*There is a restart: always entry on the service's docker-compose.yml service entry that works when the container exits during, e.g, a runtime error. This, however, does not seem to apply during this stage of port binding.

*The port range essentially describes a set of suggested ports for the containerized service and not all of them need to be available for it to work, so I could do also with ignoring any non-binded ports.

*Unfortunately, I cannot let docker do the assignment of the host ports.

I am aware that docker does not handle port ranges very good but changing the container network to host (although it might be the best solution overall) would require refactoring in other services and configurations as well, which I am trying to avoid. I would like first to exhaust all options while maintaining the container in its isolated docker network.


text:
Q: python list elements start with and end with same character Very new and beginner to python, got a small assignment to do this
Suppose that you have a list of strings named samples.
Write a Python loop that goes through the list and counts the number of strings where the string length is 2 or more and
the first and last characters of the strings are the same.
Test your code on the following three versions of the list samples:
samples = ['aba', 'xyz', 'aa', 'x', 'bbb']

samples = ['', 'x', 'xy', 'xyx', 'xx']

samples = ['aaa', 'be', 'abc', 'hello']

What I tried did not work it returned nothing for me:
samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
 if ( len(elem) >=2 and str.startswith('"') and str.endswith('"')):
  print(elem)

A: Here is a one line answer, hope it helps:
results = [x for x in samples if len(x)>=2 and x[0]==x[-1]]

Basically results is a new list created from filtering samples with 2 conditions.

A: The quotation marks are not part of the string; they will not match for you.  Rather, you want an innermost comparison such as
elem.endswith(elem[0])

Note that str is the documentation's way of saying "put your string here".  Let's update the program so far:
samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
    if (len(elem) >=2 and elem.endswith(elem[0])):
        print(elem)

Output:
aba
aa
bbb


text:
Q: React router Link changes URL, but doesn't render the component I have a simple routing system using hash router in my react app. I have a MainDisplay that Links to the route /assets/id. I also have a component called Trending that Links to the same route /assets/id. The link in MainDisplay works perfectly, but the link in Trending does not. The link for Trending changes the URL when I click on it but doesn't send me to the proper page until I refresh.
The trending component is being rendered by another component called CryptoInfo, which holds information based on the id I got from MainDisplay. Can someone help me understand why my routing isn't working in the Trending component?
// MainDisplay.js

      <Link key={index} to={`/assets/${id}`}>
          {name}
          ${current_price}
      </Link>

// CryptoInfo

import React, { useState, useEffect } from 'react'
import { useParams } from "react-router-dom"
import '../../styles/CryptoInfo.css'
import MainNav from '../nav/MainNav'
import Chart from './Chart'
import Description from './Description'
import Footer from '../main/Footer'
import Exchanges from './Exchanges'
import News from './News'
import Trending from './Trending'

export default function CryptoInfo() {
    const [currentData, setCurrentData] = useState([])
    const [image, setImage] = useState("")
    const [currentPrice, setCurrentPrice] = useState("")
    const [marketCap, setMarketCap] = useState("")
    const [marketData, setMarketData] = useState([])
    const [days, setDays] = useState(1)
    const [usd, setUsd] = useState('')
    const [currency, setCurrency] = useState('')

    const { id } = useParams()
    const api = `https://api.coingecko.com/api/v3/coins/${id}`

    async function fetchApi() {
        const data = await fetch(api)
        const response = await data.json()
        setCurrentData(response)
        setImage(response.image.small)
        setCurrentPrice(response.market_data.current_price.usd)
        setMarketData(response.market_data)
        setMarketCap(response.market_data.market_cap.usd)
    }

    useEffect(() => {
        fetchApi()
    }, [days])

    const currentDataDisplay = (
        <>

                    Rank: {market_cap_rank}

                    {name}
                    {SYMBOL}

            {/*

                    <progress className='progress-bar' min="0" max="0.14" value="0.1"></progress>

                    {todayLow}

                        -

                     {todayHigh}

 */}

                ${current_price}
                 0 ? 'green' : 'red' }} >  {priceChange24h}  %

        </>
    )

    return (
        <>
            <MainNav />

                        {currentDataDisplay}

                    <Chart />

                        <Description symbol={SYMBOL} />
                        <Exchanges />

                    <News />

                <Trending />

        </>
    )
}

// Trending.js

import React, { useEffect, useState } from 'react'
import { Paper } from '@mui/material'
import { Link } from 'react-router-dom'

export default function Trending() {
    const [trendingData, setTrendingData] = useState([])
    const [trendingStats, setTrendingStats] = useState([])

    const api = 'https://api.coingecko.com/api/v3/search/trending'

    useEffect(() => {
        fetchData()
    }, [])

    const fetchData = async () => {
        const data = await fetch(api)
        const response = await data.json()
        setTrendingData(response.coins)
    }

    const fetchMarketData = async () => {
        const data = await fetch(fetchAll)
        const response = await data.json()
        setTrendingStats(response)
    }

    let coinsArray = []
    trendingData && trendingData.forEach((item) => {
        const { id } = item.item
        coinsArray.push(id + '%2C%20')
    })

    const allIds = coinsArray.join('').replace(',', '').slice(0, -6)

    const fetchAll = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=${allIds}&order=market_cap_desc&per_page=100&page=1&sparkline=true`

    useEffect(() => {
        fetchMarketData()
    }, [allIds, trendingStats])

    const trendingDivv1 = (
        trendingStats && trendingStats.slice(0, 4).map((coin, index) => {
            const { name, price_change_percentage_24h, image, id, current_price } = coin
            const sparkline = coin.sparkline_in_7d.price
            let borderColor
            let changePercent = price_change_percentage_24h.toFixed(2)

            return (
                <Link key={index} to={`/assets/${id}`}>
                    <Paper className="trending-box" elevation={3}>

                                {name}
                                ${current_price}

                            {changePercent}%

                            <Sparklines data={sparkline}>
                                <SparklinesLine color={borderColor} />
                            </Sparklines>

                    </Paper >
                </Link>
            )
        })

    const trendingDivv2 = (
        trendingStats && trendingStats.slice(4, 8).map((coin, index) => {
            const { name, price_change_percentage_24h, image, id, current_price } = coin
            const sparkline = coin.sparkline_in_7d.price
            let borderColor
            let changePercent = price_change_percentage_24h.toFixed(2)

            return (
                 <Link to={`/assets/${id}`}>
                    <Paper className="trending-box" elevation={3}>

                                 {name}
                                ${current_price}

                            {changePercent}%

                            <Sparklines data={sparkline}>
                                <SparklinesLine color={borderColor} />
                            </Sparklines>

                    </Paper >
                </Link >

            )
        })
    )

    return (
        <>

Trending Coins

                                {trendingDivv1}

                                {trendingDivv2}

See More Coins

        </>
    )
}

//App.js

     <>
      <Router>
        <Switch>

          <Route exact path="/" >

              <MainNav />
              <InfoNav />
              <MainDisplay />

          </Route>

          <Route path="/assets/:id">
            <CryptoInfo />
          </Route>

          <Route path="/categories">
            <CategoryList />
          </Route>

        </Switch>
      </Router>
    </>

A: So it turns out the link in Trending is working. The issue is that the  CryptoInfo component doesn't respond to the id route param updating to fetch any new data.
export default function CryptoInfo() {
  ...
  const [days, setDays] = useState(1); // <-- (3) setDays never called, days never updates
  ...

  const { id } = useParams(); // <-- (1) id param updates
  const api = `https://api.coingecko.com/api/v3/coins/${id}`; // <-- (2) api value updated

  async function fetchApi() {
    ...
  }

  useEffect(() => {
    fetchApi(); // <-- (5) no refetch
  }, [days]); // <-- (4) dependency doesn't update

  ...

  return (....);
}

To resolve, move the api and fetchApi function into the useEffect and use the correct dependencies, just id in this case. You should also surround any asynchronous code in a try/catch to handle any rejected promises or any other thrown exceptions.
Example:
function CryptoInfo() {
  ...

  const { id } = useParams();

  useEffect(() => {
    const api = `https://api.coingecko.com/api/v3/coins/${id}`;

    async function fetchApi() {
      try {
        const data = await fetch(api);
        const response = await data.json();
        setCurrentData(response);
        setImage(response.image.small);
        setCurrentPrice(response.market_data.current_price.usd);
        setMarketData(response.market_data);
        setMarketCap(response.market_data.market_cap.usd);
      } catch (error) {
        // handle error
        console.log(error);
      }
    }

    fetchApi();
  }, [id]);

  ...

  return (...);
}


text:
Q: RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: 3214336 im trying to do a Discord Dashboard, but im getting a weird error: Invalid bitfield flag or number 3214336. This happens when im trying to get the guilds that user have MANAGE_GUILDS, my code is:
<%- include("../Includes/header", { bot, path, user, Discord, title: 'Dashboard' }) %>

SELECT A SERVER

<% user.guilds.forEach(guild => {
 const permsOnGuild = new Discord.Permissions(guild);
 if(!permsOnGuild.has("MANAGE_GUILD")) {
 return
 }

   if (!bot.guilds.cache.get(guild.id)) {
    return
   }
 if (guild.icon) {
 iconurl = "https://cdn.discordapp.com/icons/" + guild.id + "/" + guild.icon + ".png??size=512";
} else {
 iconurl = "https://cdn.glitch.com/82fe990a-7942-42e3-9790-39807ccdb9f6%2Ficon-404-dark.png?v=1602427904949";
}
%>

<img class="server-icon" src="<%= iconurl %>" alt="<% guild.name %>"/>

<%= guild.name %>

  <% if (bot.guilds.cache.get(guild.id)) { %>
    <a class="edit button" href="/redeem/<%= guild.id %>">Redeem
  <% } %>

  <% }); %>

Idk why this happening, if I log "guild" I can get access to id, name, icon, owner, permissions, features and permissions_new

A: Try doing
let permsOnGuild = new Discord.Permissions(BigInt(guild.permissions));
if (! permsOnGuild.has(Discord.Permissions.FLAGS.MANAGE_GUILD)) return;


text:
Q: PayPal for PhoneGap - Error in PaymentActivity.ENVIRONMENT_LIVE Im working on PayPal integration in Android with Phonegap Framework.
I have taken the code given in GitHub. Im getting an error in this line

private String environemnt = PaymentActivity.ENVIRONMENT_LIVE;

I have checked out with many codes online but always ending up with an error in this line.
Were those data members have been removed in the latest update of the code or have I missed out anything which solves this problem.
I see many people also dealing with the same problem. Can anyone help me with this?

A: Not sure about the version of PhoneGap plugin you are using, but the environment constants changed in the underlying mobile SDK in version 2.x.  Try PaymentActivity.ENVIRONMENT_PRODUCTION.


text:
Q: Throwing a cube for $20$ times and counting the amount of possibilities We throw a regular cube with $6$ faces $20$ times. Consider $A_i$ to be the case where we got the number $i$ exactly $i$ times. I'm trying to calculate $P(A_i\cap A_j)$ where $i\neq j$.
The probability to get $i$ is $\frac{1}{6}$. The probability to get $j$ is $\frac{1}{6}$. The probability to get a number that is different than $i$ and $j$ is $\frac{2}{3}$.
Consider a vector that contains exactly $i$ times the number $i$ and $j$ times the number $j$. Ther other $20-i-j$ places can contain any number $x\in\{1,...,6\}\backslash\{i,j\}$. The number of possible vectors that contain $i$ times $i$ and $j$ times $j$ is ${20 \choose i}{20-i \choose j}$. So we get:
$$P(A_{i}\cap A_{j})={20 \choose i}{20-i \choose j}\left(\frac{1}{6}\right)^{i}\left(\frac{1}{6}\right)^{j}\left(\frac{2}{3}\right)^{20-i-j}$$
The only thing I don't understand in this solution is why we ignore the number of possibilities to arrange the other four numbers in the other $20-i-j$ places. I think the solution should be:
$$P(A_{i}\cap A_{j})=4^{20-i-j}{20 \choose i}{20-i \choose j}\left(\frac{1}{6}\right)^{i}\left(\frac{1}{6}\right)^{j}\left(\frac{2}{3}\right)^{20-i-j}$$
But I don't understand why my book says otherwise. Will be glad for explanation.

A: Consider an outcome i.e. a specific sequence of twenty dice tosses, $(x_1,\dotsc, x_{20})$ where we got $i$ exactly $i$ times, and $j$ exactly $j$ times where $i\neq j$. By independence of the dice tosses the probability of observing a specific outcome is
$$
\left(\frac{1}{6}\right)^i\left(\frac{1}{6}\right)^j\left(\frac{4}{6}\right)^{20-i-j}\tag{0}
$$
The event $A_{i}\cap A_{j}$ is the union of all these (disjoint) posssible outcomes and hence $P(A_i\cap A_j)$ is the sum of the probabilities of all these outcomes. Since each outcome has equal probabilty we only need to multiply (0) by the number of possible outcomes to determine $P(A_i\cap A_j)$. The number of possible outcomes equals
$$
\binom{20}{i}\binom{20-i}{j}\binom{20-i-j}{20-i-j}=\binom{20}{i}\binom{20-i}{j}
$$
(choose $i$ dice tosses to correspond to rolling $i$, then choose $j$ dice tosses among the remaining $20-i$ dice tosses to correspond to rolling j). Hence
$$
P(A_i\cap A_j)=\binom{20}{i}\binom{20-i}{j}\left(\frac{1}{6}\right)^i\left(\frac{1}{6}\right)^j\left(\frac{4}{6}\right)^{20-i-j}
$$

A: Suppose, our die has $n$ sides, and we rolled it $k$ times. Suppose, that $i$ is rolled $a$ times and $j$ is rolled $b$ times. Suppose, if we determined the exact $a$ rolls with $i$ and the exact $b$ rolls with $j$ we would have had the probability being $(\frac{1}{n})^{a + b}(\frac{n - 2}{n})^{k - a - b}$. Then there are $\frac{k!}{a!b!(k - a - b)!)}$ distinct ways of choosing those two sets. Thus the final probability will be:
$$\frac{k!}{a!b!(k - a - b)!}(\frac{1}{n})^{a + b}(\frac{n - 2}{n})^{k - a - b}$$
Now in your specific case $n = 6$, $k = 20$, $a = i$ and $b = j$. Thus your answer is:
$$\frac{20!}{i!j!(20 - a - b)!}(\frac{1}{6})^{i + j}(\frac{2}{3})^{20 - a - b}$$
And we are ignoring the number of possibilities to arrange the other four numbers, because there is no need for us to know them. If it were an unfair die with three sides: "i" with probability $\frac{1}{n}$, "j" with probability $\frac{1}{n}$ and "other" with probability $\frac{n - 2}{n}$, the problem would have been exactly the same.


text:
Q: System.NullReferenceException' occurred in WindowsApplication1.exe Additional information: Object reference not set to an instance of an object I am writing a very basic database input form for a sql database using vb.net
upon executing the code
dsnewrow = ds.Tables("Car Details").NewRow()

i am declaring dsnewrow just before this in the same sub here:
 Dim dsnewrow As DataRow

and ds is being declared here:
Dim ds As DataSet

in the public class of the form.
I understand that there is a problem with my ds variable, but I don't understand what it is,can anyone help?
full program:
Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class Form1
    Dim inc As Integer
    Dim ds As New DataSet
    Dim da As SqlDataAdapter
    Dim maxrows As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)

        If MessageBox.Show("Are you sure that you want to delete this record?", _
                           "Delete", MessageBoxButtons.YesNo, _
                           MessageBoxIcon.Warning) = Windows.Forms.DialogResult.No Then
            MsgBox("Operation Cancelled")
        Else
            ds.Tables("Car Details").Rows(inc).Delete()
            maxrows = maxrows - 1
            inc = 0
            NavigateRecords()
            da.Update(ds, "authors2")
        End If

    End Sub

    Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Car_DetailsTableAdapter.Fill(Me.CourseworkDataSet.Car_Details)
        Dim sqlstring As String
        Dim conn As SqlConnection
        Dim connstring As String

        connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Daniel\Documents\Coursework.mdf;Integrated Security=True;Connect Timeout=30"

        conn = New SqlConnection(connstring)
        conn.Open()
        MsgBox("successful")

        sqlstring = "SELECT * FROM Car Details"
        da = New SqlDataAdapter(sqlstring, conn)
        ds = New DataSet
        da.Fill(ds, "Car Details")

        conn.Close()
        conn = Nothing

        maxrows = ds.Tables("Car Details").Rows.Count
        inc = 0
        navigaterecords()
    End Sub

    Private Sub Car_DetailsBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Car_DetailsBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.Car_DetailsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.CourseworkDataSet)

    End Sub

    Private Sub NavigateRecords()
        MakeTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(0)
        ModelTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(1)
        Engine_SizeTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(2)
        ColourTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(3)
        DoorsTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(4)
        Buy_PriceTextBox.Text = ds.Tables("Car Details").Rows(inc).Item(5)
        Sell_PriceTextBox = ds.Tables("Car Details").Rows(inc).Item(6)

    End Sub

    Private Sub btnFwd_Click(sender As Object, e As EventArgs) Handles btnFwd.Click
        If inc <> maxrows - 1 Then
            inc = inc + 1
            NavigateRecords()
        Else
            MsgBox("No More Records")

        End If
    End Sub

    Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        If inc > 0 Then
            inc = inc - 1
            NavigateRecords()
        Else
            MsgBox("First Record")
        End If
    End Sub

    Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
        If inc <> 0 Then
            inc = 0
            NavigateRecords()
        End If

    End Sub

    Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
        If inc <> maxrows - 1 Then
            inc = maxrows - 1
            NavigateRecords()

        End If
    End Sub

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
        ds.Tables("Car Details").Rows(inc).Item(0) = MakeTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(1) = ModelTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(2) = Engine_SizeTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(3) = ColourTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(4) = DoorsTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(5) = Buy_PriceTextBox.Text
        ds.Tables("Car Details").Rows(inc).Item(6) = Sell_PriceTextBox.Text

    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        btnUpdate.Enabled = False
        btnAdd.Enabled = False
        btnConfirm.Enabled = True
        btnDelete.Enabled = False

        ModelTextBox.Clear()
        MakeTextBox.Clear()
        Engine_SizeTextBox.Clear()
        ColourTextBox.Clear()
        DoorsTextBox.Clear()
        Buy_PriceTextBox.Clear()
        Sell_PriceTextBox.Clear()
    End Sub

    Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
        If inc <> -1 Then
            Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
            Dim dsnewrow As DataRow

            dsnewrow = ds.Tables("Car Details").NewRow()

            dsnewrow.Item("Make") = MakeTextBox.Text
            dsnewrow.Item("Model") = ModelTextBox.Text
            dsnewrow.Item("Engine Size") = Engine_SizeTextBox.Text
            dsnewrow.Item("Colour") = ColourTextBox.Text
            dsnewrow.Item("Doors") = DoorsTextBox.Text
            dsnewrow.Item("Buy Price") = Buy_PriceTextBox.Text
            dsnewrow.Item("Sell Price") = Sell_PriceTextBox.Text

            btnConfirm.Enabled = False
            btnAdd.Enabled = True
            btnUpdate.Enabled = True
            btnDelete.Enabled = True

        End If
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        btnUpdate.Enabled = True
        btnAdd.Enabled = True
        btnConfirm.Enabled = True
        btnDelete.Enabled = True
        inc = 0
        NavigateRecords()
    End Sub
    End Class

A: You are only declaring the variable ds. You should create an instance, before you can use the methods.
Dim ds As DataSet

should be
Dim ds As New DataSet

or
Dim ds As DataSet
ds = New DataSet

A: This line in Form_Load is wrong
sqlstring = "SELECT * FROM Car Details"

A table name when contains spaces should be enclosed in square brackets
sqlstring = "SELECT * FROM [Car Details]"

when you execute the query it doesn't work and your dataset is never initialized with new. Then when you try to use it you get the NULL Reference Exception. I suppose that you run this code on a 64bit system where the exceptions in a Form_Load event are ignored


text:
Q: How can I put two forms on the same page We would like to have a website search bar form and a Google Driving Directions form on the same page.
Today we added a search bar to every page on MinnesotaSeasons.com, over 5,000 pages. It works on every page except 480 "Destination" pages that already have a driving directions form. Adding CSS positioning for "form" puts one form on top of the other. The Website does NOT use PHP - at least, those three letters do not appear together anywhere in the code.
The search bar is a must, but we would hate to lose the driving directions. The problem results can be seen here on the top right corner of the page:
http://www.minnesotaseasons.com/Destinations/Afton_State_Park.html
Here is the code on "Destinations" pages - no CSS used:
<form action="http://maps.google.com/maps" method="get" target="_blank">

Get driving directions from Google Maps to this destination from any address, and send those directions to your phone.

Your Address (street address and either city and state or ZIP code)

<input type="text" class="text" name="saddr" id="mapsUsSaddr" value="" placeholder="Your Address" />

<input type="submit" class="clickDirections" value="Click Here for Directions" />
<input type="hidden" name="daddr" value="N45 2.898, W93 10.384" />
<input type="hidden" name="hl" value="en" />

</form>

Here is the search bar code on all pages:
<form role="search" id="form">
    <input type="search" id="query" name="q" placeholder="Search..." aria-label="Search through site content">
    <button>
        <svg viewBox="0 0 1024 1024"><path class="path1" d="M848.471 928l-263.059-263.059c-48.941 36.706-110.118 55.059-177.412 55.059-171.294 0-312-140.706-312-312s140.706-312 312-312c171.294 0 312 140.706 312 312 0 67.294-24.471 128.471-55.059 177.412l263.059 263.059-79.529 79.529zM189.623 408.078c0 121.364 97.091 218.455 218.455 218.455s218.455-97.091 218.455-218.455c0-121.364-103.159-218.455-218.455-218.455-121.364 0-218.455 97.091-218.455 218.455z"></path></svg>
    </button>
</form>

Here is the CSS for the search bar:
form {
    position: absolute;
    top: 75px;
    left: 680px;
    z-index: 200;
    background-color: #4654e1;
    width: 250px;
    height: 30px;
    display:flex;
    flex-direction:row;
    align-items:center;
}

      input {
        all: unset;
        font: 16px system-ui;
        color: #fff;
        height: 100%;
        width: 100%;
        padding: 6px 10px;
      }

      ::placeholder {
        color: #fff;
        opacity: 0.7;
      }

      svg {
        color: #fff;
        fill: currentColor;
        width: 24px;
        height: 24px;
        padding: 10px;
      }

      button {
        all: unset;
        cursor: pointer;
        width: 44px;
        height: 44px;
      }


text:
Q: Upload files to S3 from form I'm new with s3 and trying to upload some files but the I'm getting The system cannot find the file specified: <hashed_file_name>.jpg I understand the issue. When the file is saved at the root, everything is fine. But I don't want to save the file. I want to upload it directly after the action at the form.
def upload_to_s3(file_to_upload, s3_upload_folder):
    s3 = boto3.resource('s3',
                    aws_access_key_id=app.config['ACCESS_KEY_ID'],
                    aws_secret_access_key=app.config['SECRET_ACCESS_KEY'])

    s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)

def _user_img_folder(form, file_name):
    username = session['name']
    vacation_name = slugify(form.test_name.data)
    directory = os.path.join(username, test_name)
    directory = os.path.join(UPLOAD_FOLDER, directory)
    return directory + '/' + file_name

@app.route('/post', methods=['GET', 'POST'])
def test():
    if _is_image():
        uploaded_images = request.files.getlist('photo')
        for image in uploaded_images:
            processed_image_name = _hash_image_name(image) # Returns hashed filename with extension
            directory = _user_img_folder(form, processed_image_name)
            upload_to_s3(str(processed_image_name), str(directory))
    return render_template('test.html', form=form, error=error)

Thank you for your help.
EDIT 1:
{# Heavily edited #}
{% extends '_base.html' %}
{% block content %}
    <form class="logVacation" enctype=multipart/form-data role="form" method="post" action="/post">
        {{ form.csrf_token }}
        {{ form.vacation_name(placeholder="Name Your Vacation")}}

        {{ form.location(placeholder="Where was it?") }}

        {{ form.with_who(placeholder='Who was with you') }}

        {{ form.description(placeholder="Tell us about your vacation... or not.") }}

        {{ form.when(class="datepicker", placeholder="when?") }}

        {{ form.photo(multiple="multiple") }}

        <button class="btn btn-sm btn-success" value="upload" type="submit">Done</button>
    </form>
{% endblock %}

A: Found the answer:
I've changed the
s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)

to:
s3.Object(app.config['BUCKET_NAME'], s3_upload_folder).put(Body=image)

so the trick is, you must either have the file on disk and provide filepath with file_to_upload OR provide the file itself as I demonstrated in this answer.


text:
Q: how to bind the adapter list content of click event friend's
   i have listview with 10 records parsed initially from internet and i have footer at bottom of my listview by using for click more to view,the view getting ok but the problem here is during my click event i have to call the same adapter class with different url it getting parsed well,the problem is click event adapter data are not binded with listview,i'm getting error has like this..
09-02 21:02:15.042: ERROR/AndroidRuntime(424): java.lang.IndexOutOfBoundsException: Invalid location 58, size is 1
09-02 21:02:15.042: ERROR/AndroidRuntime(424):     at java.util.ArrayList.get(ArrayList.java:353)
here my java code initially executing....
LayoutInflater inflater2 = this.getLayoutInflater();
        View footerView = inflater2.inflate(R.layout.footer, null);
        footerView.findViewById(R.id.text1);

//      ((ListView) adapter).

    //  setListAdapter(adapter);

        adapter = new Adapter(Expand.this,url);
        getListView().addFooterView(footerView);
        setListAdapter(adapter);

code at my footer click event ...
footerView.findViewById(R.id.text1).setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

//
int  a = adapter.count;
                    len =100;
//                  Log.v("Count",Integer.toString(a));
                    url = "http://www.artistdirect.com/nad/rss/top100/0,,,00.xml";
                    adapter = new Adapter(Expand.this,url);
    adapter.notifyDataSetChanged();
}

how can i resolve it,is there any otherway to place link to view more and bind it on listview.
Thanks in advance.

A: I think that url is invalid...or it will return null values,
check your url...

A: Call  getListView().addFooterView(footerView); before calling setAdapter. This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.


text:
Q: SQL: Column B entries of column A are also in column A --> Match column C attribute of A's B entry in A to original A in a SQL server database SQLBASE I have a table article with three columns:
artnr (Article number)
succesor (Successor article number)
color (Color of article number)
Not every article number must have a successor number, but every successor number is always also listed somewhere in column A, like below:
Input
Article1   |   Article3    |   green

Article2   |    empty      |   blue

Article3   |   Article2    |   red

Article4   |    empty      |   yellow

For any article number of column A I need the color of the corresponding successor number (if there is any successor, otherwise leave blank).
Output:
Article1   |   red

Article2   |   empty

Article3   |   blue

Article4   |   empty

Please, I would appreciate any help on how to link the successor material's color to the predecessor material using an SQL query.
Thanks!

A: You can use a self join:
select a1.artnr, a2.color
from Articles a1 left join Articles a2
on a1.succesor = a2.artnr


text:
Q: My table in xslt doesn't work I have XML file which looks like that :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet href="test.xsl" type="text/xsl"?>

<root text="Récapitulatif des bug MD 360">
<list day="2016-11-15">
<item text="3988 (K2) : [MozillaMD] Plantage vidéo de localisation prise OBD" severite="K2" importance="Anomalie" status="RESOLVED" etat=" WORKSFORME" date="20Thu Nov 17 10:52:52 2016"></item>
<item text="4853 (K2) : Profil Midas : Menu de configuration du serveur atelier" severite="K2" importance="Evolution" status="ASSIGNED" etat=" FIXED" date="20Thu Nov 17 10:52:52 2016"></item>
<item text="4991 (K3) : ECU screen affiché au lieu de ECU Fault screen" severite="K3" importance="Evolution" status="RESOLVED" etat=" FIXED" date="20Thu Nov 17 10:52:52 2016"></item>
<item text="4992 (K3) : Bouton "Voir tous les calculateurs" à supprimer dans Express Diag view" severite="K3" importance="Evolution" status="RESOLVED" etat=" WONTFIX" date="20Thu Nov 17 10:52:52 2016"></item>
<item text="4993 (K3) : Zone clickable buton trop grande sur ECU fault screen" severite="K3" importance="Evolution" status="NEW" etat=" FIXED" date="20Thu Nov 17 10:52:52 2016"></item>
<item text="4994 (K3) : Mauvaises résolutions des icones du portail 0" severite="K3" importance="Evolution" status="RESOLVED" etat=" FIXED" date="20Thu Nov 17 10:52:52 2016"></item>
</list>
</root>

My .xsl is like that:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes" method="html"/>

<xsl:template match="list">

  K1
  K2
  K3
  K4

<xsl:value-of select="count(item[@severite='K1'])"/>
<xsl:value-of select="count(item[@severite='K2'])"/>
<xsl:value-of select="count(item[@severite='K3'])"/>
<xsl:value-of select="count(item[@severite='K4'])"/>

</xsl:template>
</xsl:stylesheet>

My output is just a line : K1 K2 K3 K4  57 126 103 13
I have correct values, but I don't have my table and I can't understand why.


text:
Q: Headline next to page number overtaken to next chapter I have one chapter for my listings
%%% Document Class
\documentclass[ngerman,bt]{dbvdoc}

\phantomsection
\addcontentsline{toc}{chapter}{Listings}
\lstlistoflistings
\cleardoublepage

and the next one for the acronyms
\chapter*{Acronyms}
\addcontentsline{toc}{chapter}{Acronyms}
\begin{acronym}
    ....
\end{acronym}

The problem is that the headline which reads next to the page number (I don't know how to call it) on the second page of the acronyms chapter is still "Listings", I dont know how to change it. I'm using pdfLaTeX.

A: The headlines can be set manually with
\chapter*{Acronyms}
\markboth{Acronyms}{Acronyms}
\addcontentsline{toc}{chapter}{Acronyms}

possibly with some formatting to make them agree with the other headlines.
If the class is book or is based on book, one could simply say
\chapter{Acronyms}

provided this is between the \frontmatter and \mainmatter declarations.


text:
Q: ADB installation failures I have developed an APK which I would like to install on a Samsung phone. I have downloaded and installed
the Samsung USB driver and I have my phone (a Galaxy Note 9) connected to my Windows 10 computer. I used Android
Studio to develop the software and generate the APK. I am using adb to do the install.
Despite all this, when I attempt to run adb  to do the installation:
 adb install -r app.debug.apk

I get the following failure:
Performing Push Install
adb: error: failed to get feature set: no devices/emulators found

Am I missing something here? How do I get my apk installed onto my phone?

A: This occurs when your device is not connected to your pc.
Check these things -

*

*Enable USB debugging by going into developer options.
https://www.greenbot.com/article/2457986/how-to-enable-developer-options-on-your-android-phone-or-tablet.html

*On your phone, tap the "Charging this device via USB" notification. Under "Use USB for," select File Transfer. (Optional, in case the first one, don't work)


text:
Q: Microsoft Add-in Store Submission - Sign in with office 365 credential I published my Word Add-in to store and got rejected by the validation team.
My Add-in have sign-in function that only a user in our tenant - Thread can login and use the add-in.
When the add-in work on Word Online, when sign-in to office 365 it will automatically get credential that stored in cookie to perform an authentication.
But the validation team reject my add-in by this reason

*

*Insert your add-in.

*Click on "Sign in with office 365" and click "Allow" to permit the authentication window to open.

*Notice we are not given a chance to enter any credentials and does not progress beyond the loading process, as shown above.

I have specified it in the description when i submited the manifest file.

To use this add-in, you must be a Thread subscription customer as it requires your Thread web application credentials to sign in. For example, if you are using the add-in with Word Online documents, it will automatically use your Thread web application credentials to sign in.

As i understand, when we login by Azure AD if we already have credential it will not show the pop-up to enter username and password.
Anyone know how to by pass this. Please help
Many Thanks

A: Since this add-in is only applicable for user's in your own tenant, I wouldn't recommend leveraging the Office Store. The Store isn't designed to handle internal deployments of add-ins. Instead, take a look at Use centralized deployment to publish Office Add-ins. This allows you to publish your add-in to all users on your tenant.


text:
Q: What does ">" in this jQuery selector mean? What difference does the greater than symbol (>) make here?
Is $('#someElement').find(">[someAttribute]") the same as $('#someElement').find("[someAttribute]")?

A: No : it only selects an element if it's a direct child of #someElement.
It's semantically based on the CSS direct child selector.
See child selector's documentation


text:
Q: Add totals row from 2 different subform and display in textbox I have two subforms that are each from different queries and both have a totals row. I am trying to sum the field 'Total' from both subformA and subformB together but how would I go about doing that? Is there a way to reference just the totals row?
Any guideline would be appreciated


text:
Q: Is there a shortcut to type a symbol from a different keyboard layout? I use two keyboard layouts (English and Lithuanian) and have to switch between them constantly.
Windows had the shortcut Ctrl+Shift+Alt+[symbol] that would let me type an English keyboard symbol without fully switching the keyboard layout.
E.g.:
I use the 1 key to print ą. If I want to type !, on windows I could use Ctrl+Shift+Alt+1. Or Ctrl+Alt+1 to type 1.
Is there a similar shortcut I could use in Ubuntu?

A: Well, you can't type symbols from other layouts, but there is indeed an equivalent to access symbols which are actually part of the Lithuanian layout.
To type 1 with the Lithuanian keyboard layout:
AltGr+1
To better understand how the Lithuanian layout on Linux works: When Lithuanian is selected, click the layout indicator at the top right of the screen and select the Show keyboard layout option. That will show an image of the Lithuanian layout. Let's take the 1 key as an example:

That tells us:

*

*1 -> ą

*Shift+1 -> Ą

*AltGr+1 -> 1

*Shift+AltGr+1 -> !

HTH


text:
Q: Using LINQ and EF, how to remove values from database where not in list of items I have an existing set of items in a database where a MultiSelectList of Id's allows Shifts to be added to an Operator.
Currently, an Operator has 3 Shifts assigned. This is now edited on the View to remove 1 Shift from the 3.
What is the best way to go through the existing set of items and determine which of the 3 to remove that isn't found in the list of selected items.
I know the easiest method would be to remove all items in the database for the Operator and then insert the values from the MultiSelectList but thought there might be a way to use LINQ to select from existing where not in the list of Id's
var existing = (from os in db.OperatorShifts
                where os.OperatorId == model.Id
                select os);

public List<Guid?> Shifts { get; set; }
public MultiSelectList AvailableShifts { get; set; }

model.Shifts

A: //asuming your db has these fields: db.Shifts, db.OperatorShifts
//and model is the current Operator

var existingShifts = (from os in db.OperatorShifts
                where os.OperatorId == model.Id
                select os).ToList();

IEnumerable<Guid> newShiftIds = ?; //don't now how your selected shift ids got post back, figure it out yourself

var shiftsToRemove = existingShifts.Where(e => newShiftIds.All(id => e.Id != id)).ToList();
var shiftIdsToAppend = newShiftIds.Where(id => exising.All(e => e.Id != id)).ToList();

foreach(var shift in shiftsToRemove)
{
    db.OperatorShifts.Remove(shift);
}

foreach(var shiftId in shiftIdsToAppend)
{
    db.OperatorShifts.Add(new OperatorShift{
        OperatorId = model.Id,
        ShiftId = shiftId
    });
}

A: I have found the simplest way to do tasks like this is to delete all the items from the database and then insert the ones I want back in.


text:
Q: Teams notifications are not received when using Graph's sendActivityNotification I've created a Teams app using the Teams App Visual Studio template, and configured it with a single personal tab. I've set set up ngrok so that this can be debugged locally. I've sideloaded the app, and all looks fine - Teams can load the tab, and it displays as it should.
I'm now trying to send an activity notification to this tab. Graph accepts the post activity just fine - I'm returned a 204 - but the activity is never delivered to my Teams client.
My test teams user and the Azure AD app are configured in the same tenant. The Azure AD app has the TeamsActivity.Send permission.
All URLs in my manifest are configured with the ngrok endpoint. I have a valid activityType defined, and my webApplicationInfo section is configured with the AAD App ID and redirect URI as outlined here. I've also added TeamsActivity.Send to the applicationPermissions section of webApplicationInfo
I'm posting the following json to Graph:
{
    'topic': {
        'source': 'entityUrl',
        'value': 'https://graph.microsoft.com/beta/users/<my user id>/teamwork/installedApps/<my app id>'
    },
    'activityType': 'testActivity',
    'previewText': {
        'content': 'Something happened'
    },
    'templateParameters': [
        {
            'name': 'teammember',
            'value': 'Bobby muffin'
        }
    ]
}

This all ties up correctly with the manifest, and as I mentioned, Graph accepts the POST just fine. I've also tried adding the "recipient" section to the json, but get the same result.
I have no idea why I'm not seeing notifications. After I post the notification, I don't see any traffic to ngrok (although I'm not sure whether the notification would come in that way, or via the Teams client).
It feels like I'm missing some config somewhere.

A: My bad... while I was testing this, I was trying to send a notification to myself, which is explicitly not supported - https://learn.microsoft.com/en-us/graph/teams-send-activityfeednotifications#faqs


text:
Q: PaintComponent() being called but JComponent not being painted Bascially I'm having an issue with painting a custom component I made. Whenever repaint() is called the paintComponent() of my Button class is called but nothing shows up in my frame. I also know the component is the right size and is in the right location because I set up a border to check this.
The following is my custom component class:
public class Button extends JComponent {

protected static final Color BUTTON_COLOR = Color.black;
protected Point position;
protected Dimension size;

public Button(int posX, int posY, int width, int height) {
    super();
    position = new Point(posX, posY);
    size = new Dimension(width, height);
    setBounds(position.x, position.y, size.width, size.height);
    setBorder(BorderFactory.createTitledBorder("Test"));
    setOpaque(true);
}

@Override
protected void paintComponent(Graphics g) {
    setBounds(position.x, position.y, size.width, size.height);
    drawButton(g);
    super.paintComponent(g);
}

@Override
public Dimension getPreferredSize() {
    return size;
}

public void drawButton(Graphics g) {

    selectColor(g, BUTTON_COLOR);
    g.fillRect(position.x, position.y, size.width, size.height);
    g.setColor(Color.black);
    g.drawRect(position.x, position.y, size.width, size.height);

}}

This is the JPanel that my custom component is being added to:
public class MainMenu extends JPanel {
public MainMenu() {
    setBackground(Color.BLACK);
    setLocation(0,0);
    setPreferredSize(new Dimension(800,600));
    setDoubleBuffered(true);
    setVisible(true);
    this.setFocusable(true);
    this.requestFocus();
}}

Finally, I add the following components into a MainMenu JPanel:
    main_menu.add(new Button(200, 200, 150, 50));
    dropdown = new JComboBox<File>() {
        @Override
        public void paintComponent(Graphics g) {
            dropdown.setLocation(new Point(400, 200));
            super.paintComponent(g);
        }
    };

    main_menu.add(dropdown);

What's strange is when the repaint() is called on main_menu, the JComboBox is painted but not the Button even though the Button's paintComponent() is called.

A: Several problems:

*

*You should never call setBounds(...) within a painting method such as paintComponent. This method is for painting and painting only.

*Your bounds and your painting region are the same -- but they represent two very different things. The bounds are the component's position relative to its container, the painting x, y are relative to the JComponent itself. So you're painting out of your bounds.

*So in the same vein, your drawButton method should be drawing at 0, 0: g.drawRect(0, 0, size.width, size.height);

*setBounds shouldn't be called regardless. That is the layout managers job. By doing this, you add a whole layer of potential and hard to find bugs.

*I would override getPreferredSize() to help set the component's best size (edit -- which you already do, albeit in a very simple fashion).

*You should not set the location of the button inside the button -- again, that's the job of its container's layout manager.

*The super.paintComponent(g) should probably be called first in the paintComponent override.

*I would avoid giving my class a name that clashes with a common core class.


text:
Q: Prevent empty lines in ejs for loops I have the following simple ejs template:
<% for (var i =0; i < 10; ++i) { %>
    - <%- i %>
<% } %>

This renders the following:
- 0

- 1

- 2

- 3

- 4

- 5

- 6

- 7

- 8

- 9

How can I prevent ejs to create empty lines like these?
If possible I don't want to modify the result string but to tell ejs to not render these empty lines. How can I do that?

A: Trim-mode ('newline slurp') tag, trims following newline.
 <% i -%> or <% -%> or <%= i -%> or <%- i -%>

All you need is the hypen.
In the Features section, there you can see this option:

*

*Newline-trim mode ('newline slurping') with -%> ending tag

Note that the new version of ejs is maintained at mde/ejs (not tj/ejs anymore).

A: If you add a '-' before the "%>", it will make line break
<% for (var i =0; i < 10; ++i) { %>
     - <%- i -%>
<% } %>

But I found it quite tricky to use, because it not always work as expected.
This issue has more details on it.


text:
Q: How do I make a callback for startActivityForResult() if I don't can't change the Activity? I'm making a Cordova plugin and I'm using startActivityForResult() to make Bluetooth discoverable. I want to run a method in my plugin when Intent finishes. I can't modify the Activity directly, how else can I make a callback?
Here's what I have:
    if(bt.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
        if(bt.isEnabled())
            bt.disable();

        Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);
        cordova.getActivity().startActivityForResult(intent,Leo.BT_DISCOVERABLE_INTENT);
    }

A: In your plugin class, you have to implement the onActivityResult function to deal with the intent's result and then call either callbackContext.success in case of success or callbackContext.error in case of failute :
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode == android.app.Activity.RESULT_OK) {
        this.callbackContext.success(intent.getStringExtra("result"));
    } else {
        String message = intent == null ? "null intent!" : intent.getStringExtra("result");
        this.callbackContext.error(message);
    }
}

A: In the activity:
setResult(RESULT_CANCELED);
finish();


text:
Q: Strassen's Laser Method Technique AND Tensors in matrix multiplication algorithms
*

*I understand the first algorithm presented by Strassen in 1968, for fast matrix multiplication. This was the first improvement to the naive approach of multiplying matrices. Thereafter, he went on to introduce the 'Laser Method' technique. What is this technique exactly?  How do we really go about using this approach?

I have been referring to a lot of papers for this. But, no paper exactly describes the technique appropriately. Some of the papers are referred to are:
http://www.maths.ed.ac.uk/assets/files/pgrexternalfiles/theses/probability/stothers.pdf

*I also don't well understand the use of Border rank in the matrix multiplication algorithms (both Strassen's and Winograd's via Arithmetic progressions) Can anyone help me with this as well?

http://www.cs.umd.edu/~gasarch/TOPICS/ramsey/matrixmult.pdf
Thanks!

A: Maybe try this paper?
Fast Matrix Multiplication: Limitations of the Laser Method
It goes into enough detail for me to think I understand what's going on.  I think the laser method is figuring out answers for N values with less rounding errors than what occurs using Strassen's method using some differential equation or numerical method.  In recent years computers have advanced enough for the task to be automated which has resulted in higher order (of precision) solutions.
That pdf has a link to some code for their results - maybe that could help?  If you get an answer or already have, then please post back.
You can also check the book "Introduct to algorithms" from the MIT press, chapter 4 - divide-and-conquer.  The end notes to the chapter proved insightful for me at least.

A: The laser method (introduced in Strassen, Crelle 1987) and border rank and its uses (introduced in Bini, Capovani, Lotti, & Romani, Inform. Proc. Lett. 1979) are very nicely explained in Bläser's graduate survey.


text:
Q: Limits of the wave equation with piecewise constant propagation speed Consider a wave equation
$$\frac{\partial^2 u}{\partial t^2} = c(x)^2 \frac{\partial^2 u}{\partial x^2} \tag{1}$$
In frequency domain this becomes an ODE:
$$-\omega^2 u = c(x)^2 \frac{\partial^2 u}{\partial x^2} \tag{2}$$
We can solve (2) analytically when $c(x)$ is constant, then the solution is $\exp\left(\pm\frac{i \omega}{c} x\right)$. We can also solve it analytically if $c(x)$ is piecewise constant: write in every region-of-constant-$c$ a linear combination of leftward and rightward propagating waves, impose the appropriate continuity conditions on the interfaces between regions with different values of $c$, solve for the coefficients of the linear combinations.
Suppose now that $c(x)$ is some arbitrary function. We can still write it as a limit of piecewise constant functions:
$$c(x)=\lim_{\Delta\rightarrow 0^+} \sum_{i=-\infty}^{\infty} \left\{\begin{matrix}c(i\Delta) & x\in [i\Delta,(i+1)\Delta[ \\ 0 & \text{otherwise}\end{matrix}\right.$$
Let us call these piecewise constant approximations to $c$, $c_{\Delta}$
$$c_{\Delta}(x)=\sum_{i=-\infty}^{\infty} \left\{\begin{matrix}c(i\Delta) & x\in [i\Delta,(i+1)\Delta[ \\ 0 & \text{otherwise}\end{matrix}\right.$$
We can analytically solve, for any strictly positive $\Delta$,
$$-\omega^2 u_{\Delta}= c_{\Delta}(x)^2 \frac{\partial^2 u_{\Delta}}{\partial x^2}$$

Question
Is $\lim_{\Delta\rightarrow 0^+} u_{\Delta} = u$?
In other words, can we approximate general solutions of (2) by substituting in a piecewise constant approximation of $c(x)$, and then solving analytically?

I expect the answer to be "no".

*

*because $\lim_{\Delta\rightarrow 0^+} c_{\Delta} = c$, but $\lim_{\Delta\rightarrow 0^+} \frac{\partial}{\partial x}c_{\Delta} \neq \frac{\partial}{\partial x} c$, in fact the limit doesn't even exist

*In literature on numerical solutions of PDEs, I have never seen this suggested as a viable way of approximating solutions of wave equations.

A: New:
For the initial conditions of $u_\Delta$ choose $u_\Delta(0) = u(0)$ and $u'_\Delta(0) = u'(0)$. Define $v = u - u_\Delta$ and $\delta c = c - c_\Delta$. So $v(0) = v'(0) = 0$. Suppose $c$ is sufficiently well behaved so $u$ is also. $u_\Delta$ should be well behaved excluding a discontinuous second derivative and if ever $c_\Delta = 0$ then $u_\Delta$ and $u''_\Delta$ jumps to zero.
Define $v = u - u_\Delta$ and $\delta c = c - c_\Delta$. Subtracting
$$ -\omega^2 v = c_\Delta^2 v'' - (2c\delta c - \delta c^2) u''
$$
Suppose for some $x_0 \geq 0$ we want to know $v(x_0)$. Note if $\Delta \rightarrow 0$ then the sup norm $||\delta c||_{\infty, [0,x_0]} \rightarrow 0$. Since $u''$ and $c$ are well behaved we're arguing $||(2c\delta c - \delta c^2) u''||_{\infty,[0,x_0]} \rightarrow 0$. If this term on the RHS were zero, by the uniqueness theorem $v(x)=0$ on $[0,x_0]$. The fact it approaches zero simply means it perturbs $v(x)$ from $0$ an arbitrarily small amount.
So $u_\Delta \rightarrow u$ as $\Delta \rightarrow 0$ if $c$ is sufficiently nice. I haven't tried to address what a necessary and sufficient condition may be.

Original:
It's hard for me to picture the limit does not hold for a large class of well behaved functions. On the other hand surely we can contrive functions which will break the limit. By work such as Lebesgue's I feel finding a necessary and sufficient condition on functions for the limit to hold may not be easy.
Thoughts for proof: If we can prove the limit holds when $c(x)$ is a polynomial perhaps we can take a limit on the degree to argue the limit holds for many Taylor series.
For convenience scale $c(x)$ by $\omega$. Suppose $c(x)$ is a polynomial and denote $c(x)^2 = c_0 + c_1 x + \cdots + c_n x^{2n}$. If we were able to solve for $u$ and $u_\Delta$ we'd be able to take the limit and see if they match. Applying the Laplace transform which is generally a simplification
\begin{align} \mathcal{L}\{-u\} = -U(s) =& \sum_{0\leq k \leq 2n} \mathcal{L}\{c_k x^k u''\} \\ =& \sum_{0\leq k \leq 2n}  (-1)^k c_k \frac{d^k}{ds^k}\bigg[s^2U-su(0)-u'(0)\bigg] \\ =& -c_0 (su(0)+ u'(0)) + c_1 u(0) + \sum_{0\leq k\leq 2n} (-1)^k (c_k s^2-2c_{k+1}s+2c_{k+2}) U^{(k)}
\end{align}
where $c_{2n+1},c_{2n+2} = 0$.
\begin{align} \mathcal{L}\{-u_\Delta\}=-U_\Delta(s)= & \sum_{0\leq k} \mathcal{L}\Big\{\big(H(x-k\Delta)-H(x-(k+1)\Delta)\big)c(k\Delta)^2 u_\Delta''(x)\Big\} \\ =& \sum_{0\leq k} c(k\Delta)^2 e^{-sk\Delta}\Big[\mathcal{L}\{u''_\Delta(x+k\Delta)\} - e^{-s\Delta}\mathcal{L}\{u''_\Delta(x+(k+1)\Delta)\}\Big]
\end{align}
using $\mathcal{L}\{H(x-k\Delta)u''_\Delta(x)\}=\int_0^\infty e^{-sx}H(x-k\Delta)u''_\Delta(x) dx = e^{-sk\Delta}\mathcal{L}\{u''_\Delta(x+k\Delta)\}$ where $H$ is the heaviside function. Unfortunately $u''_\Delta(x)$ is not of the right form. Yet going back and directly solving the original equations for any $\Delta$ seems recursive without a generating formula. Perhaps there's less explicit theorems which can be used.


text:
Q: DidDeselect cells off screen I am trying to show the selected cell in my UICollectionView by changing its border and shadow color. my issue is that my DidDeselect function causes a crash if I select a cell then scroll the selected cell of screen and select another cell, I understand that is because my DidDeselect is trying to deselect a cell that has been reused so my question is:
How do I remove the border from a cell that is no longer visible once it has scrolled off the screen
My DidSelect:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath as IndexPath) as! PresentationCell
    cell.layer.borderColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
    cell.layer.borderWidth = 3
    cell.layer.shadowColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
}

My DidDeSelect:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cellItem = collectionView.cellForItem(at: indexPath) as! PresentationCell
    cellItem.layer.borderColor = UIColor.clear.cgColor
    cellItem.layer.borderWidth = 3
    cellItem.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
 }

It crashes on this line:
let cellItem = collectionView.cellForItem(at: indexPath) as! PresentationCell

Error is : Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Which I understand is because the cell I selected first is no longer displayed because I've scrolled it out of view and then selected a cell at the bottom of the collectionView
How do I get around this?

A: Elevate you not doing proper way to achieve your requirements
below i suggest to way achieving your requirement.
put your border colour and width in your cell method
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
      "id_PresentationCell", for: indexPath) as! PresentationCell
   if arrYourData[IndexPath.row].isSelected == true {
        cell.layer.borderColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
        cell.layer.borderWidth = 3
        cell.layer.shadowColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
  }

}

When tap on didSelected Make isSelected true on tap like beolow :
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        self.arrYourData[IndexPath.row].isSelected = !self.arrYourData[IndexPath.row].isSelected

**Reload your collection here**
     }

A: It is a correct behavior. When you use the dequeueReusableCell cell are reused and memory gets allocated to visible cells only. So, if you try to pull a cell which is already deallocated then it will gives you nil.
In your case, you need to have some custom implementation where you can hold the selection and apply the logic.
Following is the working code...
Declare the variable at top
var mySelection = -1

Use this code block for rest of logic
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
 {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    cell.backgroundColor = .blue
    if mySelection == indexPath.row {
      applySelection(cell: cell, index: indexPath.row)
    } else {
      removeSelection(cell: cell, index: indexPath.row)
    }
    return cell
 }

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
 {
    mySelection = indexPath.row
    if let cell = collectionView.cellForItem(at: indexPath as IndexPath)
    {
      applySelection(cell: cell, index: indexPath.row)
    }
 }

override func collectionView(_ collectionView: UICollectionView,
 didDeselectItemAt indexPath: IndexPath)
 {
    if let cellItem = collectionView.cellForItem(at: indexPath)
    {
      removeSelection(cell: cellItem, index: indexPath.row)
    }
 }

func applySelection(cell: UICollectionViewCell, index: Int) {
      cell.layer.borderColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
      cell.layer.borderWidth = 3
      cell.layer.shadowColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
 }

func removeSelection(cell: UICollectionViewCell, index: Int) {
    cell.layer.borderColor = UIColor.clear.cgColor
    cell.layer.borderWidth = 3
    cell.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
 }


text:
Q: How can I specify the auto-increment value of a primay key column? How can I specify the auto-increment value of a primay key column?  I would like to initialize it to 18.

A: You can change the value of AUTO_INCREMENT:
ALTER TABLE tbl AUTO_INCREMENT = 18;

It can also be set to an initial value in the table create statement.
CREATE TABLE test1
(
    x INT PRIMARY KEY AUTO_INCREMENT,
    y VARCHAR(100)
)
AUTO_INCREMENT = 18;

See the documentation for CREATE TABLE and ALTER TABLE.

A: I'm assuming your PK is an auto-number...
ALTER TABLE tblSomething AUTO_INCREMENT=18;


text:
Q: plus sign in solr query is not correctly treated All:
I am new to Solr, when I play with solr example with importing some random document,  I use a search query in q like:
fund+report

There is no space between fund and +, and I thought it will search a word "fund+report" in the document, which rarely happen in document, but a lot results return, thequery url is:
http://localhost:8983/solr/collection1/select?q=fund%2Breport&fl=id+filename+%5Bexplain%5D&wt=xml&indent=true

I thought Solr treat my query just like:
fund report

or
fund OR report

Could anyone tell me why solr treat my query like that? And how can I make solr treat fund+report as a single word?
Thanks

A: The HTTP call will simply translate the + to a space . If you need an actual + sign then you need to use the URL-encoded value for + (which I think is %2B). If you are looking for the phrase fund report then you want to put double quotes around the phrase, e.g., "fund report". These should also be URL-encoded (I think the value for that is %22).
Keep in mind that if you're using stemming then a search for "fund report" will find results for "funds reports", "funding reports", etc. But maybe that is what you want.
So after all is said and done, your URL might look like the following:
http://localhost:8983/solr/collection1/select?q=%22fund%20report%22&fl=id,filename,%5Bexplain%5D&wt=xml&indent=true

Note that the fields listed for the fl parameter should be comma-delimited. I am not sure why you have the square brackets around the explain field.


text:
Q: In this "putting a price /pʊtɪŋ-ə- prʌɪs/", is there /g/ in between?
"Putting a price on carbon emissions has taken a heavy political toll in Australia."
  (here the presenter's voice is linked; this is originally from Aussie ABC)

I hear, or I may be bewitched to hear, /g/ sound between /ŋ/ and /ə/ (schwa), in 'putting a price'. Is there really /g/ or am I bewitched? If there is, can it be a certain pronouncing pattern concerning the /ŋ/ sound?

A: You are not completely off; I do hear a bit of a velar stop in that clip. Whether it's voiced or unvoiced, I can't say for certain, but since both /ŋ/ and the following vowel would be voiced, I would imagine it is probably also voiced--that's what I'm hearing, but it might just be what I expect to hear.
Is there a general pronunciation rule here? I'm not really sure. I don't think the speaker intends to make that sound, but rather it's an effect of speaking rapidly with his accent (and also trying to enunciate clearly; he is a newscaster after all). I am looking for an American example, but haven't found one readily. In my own accent, I would probably (as Snailplane suggests) just drop the G, so /ŋ/ -> /n/. Unless trying to make the vowel separation very clear, I would never consciously pronounce a hard stop on a word ending in -ing.
Do you want to sound like this Australian newscaster? If you like his accent, this is one of many features of his speech you could probably try to imitate. But it wouldn't invalidate your use of English (or render it markedly non-native) to not do so.
In my opinion, it will mark your speech as non-native most if you are inconsistent about which accent features you emulate. But if your ear is good enough to catch this sound, I think you are probably going to be just fine.


text:
Q: Finding the smallest integer that can not be represented as an IEEE-754 32 bit float
Possible Duplicate:
Which is the first integer that an IEEE 754 float is incapable of representing exactly?

Firstly, this IS a homework question, just to clear this up immediately. I'm not looking for a spoon fed solution of course, just maybe a little pointer to the right direction.
So, my task is to find the smallest positive integer that can not be represented as an IEEE-754 float (32 bit). I know that testing for equality on something like "5 == 5.00000000001" will fail, so I thought I'd simply loop over all the numbers and test for that in this fashion:
int main(int argc, char **argv)
{
    unsigned int i; /* Loop counter. No need to inizialize here. */

    /* Header output */
    printf("IEEE floating point rounding failure detection\n\n");

    /* Main program processing */
    /* Loop over every integer number */
    for (i = 0;; ++i)
    {
        float result = (float)i;

        /* TODO: Break condition for integer wrapping */

        /* Test integer representation against the IEEE-754 representation */
        if (result != i)
            break; /* Break the loop here */
    }

    /* Result output */
    printf("The smallest integer that can not be precisely represented as IEEE-754"
           " is:\n\t%d", i);

    return 0;
}

This failed. Then I tried to subtract the integer "i" from the floating point "result" that is "i" hoping to achieve something of a "0.000000002" that I could try and detect, which failed, too.
Can someone point me out a property of floating points that I can rely on to get the desired break condition?
-------------------- Update below ---------------
Thanks for help on this one! I learned multiple things here:

*

*My original thought was indeed correct and determined the result on the machine it was intended to be run on (Solaris 10, 32 bit), yet failed to work on my Linux systems (64 bit and 32 bit).

*The changes that Hans Passant added made the program also work with my systems, there seem to be some platform differences going on here that I didn't expect,
Thanks to everyone!

A: The problem is that your equality test is a float point test.  The i variable will be converted to float first and that of course produces the same float.  Convert the float back to int to get an integer equality test:
float result = (float)i;
int truncated = (int)result;
if (truncated != i) break;

If it starts with the digits 16 then you found the right one.  Convert it to hex and explain why that was the one that failed for a grade bonus.

A: I think you should reason on the representation of the floating numbers as (base, sign,significand,exponent)
Here it is an excerpt from Wikipedia that can give you a clue:

A given format comprises:
* Finite numbers, which may be either base 2 (binary) or base 10

(decimal). Each finite number is most
  simply described by three integers: s=
  a sign (zero or one), c= a significand
  (or 'coefficient'), q= an exponent.
  The numerical value of a finite number
  is
          (−1)s × c × bq
        where b is the base (2 or 10). For example, if the sign is 1
  (indicating negative), the significand
  is 12345, the exponent is −3, and the
  base is 10, then the value of the
  number is −12.345.

A: That would be FLT_MAX+1. See float.h.
Edit: or actually not. Check the modf() function in math.h


text:
Q: Java swing. How to change color intensity from black to white? I don't see  the how to change color only from black to white. Grayscale.
My example. I have values that goes from 0 to 100.
Their representation is like this:
0 - Black
100 - White
I am painting JComponent and whenever I have to change color I have to call
g.setColor(Color);

But how to tell it to change color only from Black to White, depending of my number (the larger the number, color is whiter)?
How to manipulate over RGB?

A: The Color API has HSB values which you may find easier to use.
You can also use the HSL Colors. Check out the "luminance" tab when you start with a black or white color.

A: There is, of course, no color change from black to white, per se, except through gradually lighter shades of gray.
So, just use equal values of RGB, treating 0 - 100 as a percentage of 255.
For example, 50% is RGB of 128,128,128 (though depending on rounding you might arrive at 127,127,127).
The expression for going from a percentage value to a 0-255 is:
rgb=(pct*255)/100;

A: As long as values are equal in rgb you have a grey.
so
g.setColor(new Color(0, 0, 0);

is white.
g.setColor(new Color(255,255,255);

is black
g.setColor(new Color(128,128,128);

is an equal blend of white and black.


text:
Q: How to protect powershell file, and call single function I'm having this problem for a while now and google have its limits.
I'm writing a powershell file that contain several generic function.
I use the function in vary scripts and now I want to let other personal in my work to use them as well.
the problem is, do to sensitive operation, I want to lock and protect the script (compile to a dll, exe etc').
how do I create powershell library like C# DLL?
one option I try but did not find out how to continue is to compile the script using powerGUI to executable file ( .exe) but then I canot access the function in it let alone pass on parameters to that function.
hope you understood me :)
thank you.

A: You don't. Rather than trying to obscure this information (if you compile them, they can be decompiled and your "protected" resources will no longer be), remove them entirely and make those parameters for your functions. This both protects your "sensitive" data and makes the code much more reusable.
You can then package your functions into a module


text:
Q: how to fix my implementation of Auto-complete feature using Trie Tree? Hi so i've been trying to implement Auto-complete/suggestion using trie tree
but the suggestion part only suggests 1 or 2 first similar words to it and i can't find out what causing this.
This is my Trie structre
 struct TrieNode {
        struct TrieNode* children[ALPHABET_SIZE];

        bool isEndOfWord;
};

struct TrieNode* getNode(void) {
       struct TrieNode* pNode = new TrieNode;

       pNode->isEndOfWord = false;

       for (int i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;

       return pNode;
}

bool isLeafNode(struct TrieNode* root) { return root->isEndOfWord != false; }

and this is the suggestion/Auto-complete part
void suggestionsRec(struct TrieNode* root, string currPrefix) {
     if (root->isEndOfWord) {
         cout << currPrefix;
         cout << endl;
     }

     if (isLeafNode(root))
         return;

    for (int i = 0; i < ALPHABET_SIZE; i++)
    {
        if (root->children[i])
        {
            currPrefix.push_back(97 + i);
            suggestionsRec(root->children[i], currPrefix);
            currPrefix.pop_back();
        }
    }
}

int spellchecker(TrieNode* root, const string query) {
    struct TrieNode* pCrawl = root;
    int level;
    int n = query.length();

    for (level = 0; level < n; level++) {
         int index = CHAR_TO_INDEX(query[level]);
         if (!pCrawl->children[index])
             return 0;
         pCrawl = pCrawl->children[index];
    }

    bool isWord = (pCrawl->isEndOfWord == true);
    bool isLast = isLeafNode(pCrawl);

    if (isWord && isLast) {
        cout << query << endl;
        return -1;
    }

    if (!isLast) {
        string prefix = query;
        suggestionsRec(pCrawl, prefix);
        return 1;
    }
}

for example when i try words like : [ the , there , these ] and input is "t" all it suggests is "the" .
this is the whole code https://pastebin.com/VPd94rny
also any suggestion to improve my code is much appreciated


text:
Q: How can I display numbers in status bar in Android? I am working on an application where I need to show the download speed in status bar. I have tried using notificationBuilder.setSmallIcon() but it takes a constant drawable as parameter. I want the number to change after every 3 seconds. I have seen many apps that show some number in status bar e.g temperature, download percentage etc. So, there is a way for sure. But I can't figure it out.

A: You can achieve that by converting text string to bitmap drawable.
Use below method to convert your text to bitmap. And use return bitmap as smallIcon in notification builder.
public Bitmap textAsBitmap(String text, float textSize, int textColor) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(textSize);
    paint.setColor(textColor);
    paint.setTextAlign(Paint.Align.LEFT);
    float baseline = -paint.ascent(); // ascent() is negative
    int width = (int) (paint.measureText(text) + 0.5f); // round
    int height = (int) (baseline + paint.descent() + 0.5f);
    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(image);
    canvas.drawText(text, 0, baseline, paint);
    return image;
}


text:
Q: Methods/approach to simplify $k^2(k+1)^2 + 4(k+1)^3$ Hi guys are there any other Methods/approach to simplify $k^2(k+1)^2 + 4(k+1)^3$ instead of expanding everything out and getting a quartic and cubic?? I expanded the entire thing out and got a quartic and cubic which both i have used factor theorem and long division. In the end i have got $(k+1)^2 \cdot (k+2)^2$ which is the answer, but this approach took too long to solve. So my question is are there any more simpler approach so can i do this quicker?

A: Do you really mean $k^2(k+1)^2\cdot 4(k+1)^3=4k^2(k+1)^5$ which should not be simplyfied further, because it does not get simpler then that.
It always depends on what you want to do with your term.
If you mean $k^2(k+1)^2+4(k+1)^3$ you can factor out $(k+1)^2$ and get:
$(k+1)^2(k^2+4k+4)=(k+1)^2(k+2)^2$
Where we used the binomial formula, to see $k^2+4k+4=(k+2)^2$


text:
Q: No data found in oracle I have a procedure in oracle that looks like this
create or replace procedure check_display_stock as

id_brg number(20);
rowcount number (20);

begin

  -- 1. insert datas from display into temp_display
  insert into temp_display
  select id_barang,stok,min_stok
  from display
  where stok <= min_stok;

  --2. select the number of datas in temp_display
  select count(rownum)
  into rowcount
  from temp_display;

  while(rowcount != 0)
  loop

      -- Error: no data found
      select id_barang
      into id_brg
      from temp_display
      where rownum = 1;

      --just another procedure to do other things
      insert_spb(id_brg);
      delete from temp_display where rownum = 1;

      end if;

  end loop;

end check_display_stock;

An error occurs when I tried to select into that says no data found.
I don't understand why this happened.

A: You never decrement rowcount so you will end up deleting the rows in temp_display one-by-one and then keep going (potentially forever) and on the next iteration after you have already emptied the table you will try to select id_barang into id_brg ... and it will fail as you have already emptied the table.
Instead, you could use BULK COLLECT INTO or a CURSOR to bypass the temporary table:
create or replace procedure check_display_stock
as
begin
  FOR cur IN ( select id_barang,
                      stok,
                      min_stok
               from   display
               where  stok <= min_stok
             )
  LOOP
    insert_spb(cur.id_barang);
  END LOOP;
END;
/

db<>fiddle here