text:
Q: In Floating window not able to get listview clicks events for background apps I have created Floating button am able to keep on required position as shown in image as well access other apps as i launched settings app.
but it is blocking back key and list view item click for background apps as shown in image
if we consider wifi option am able to turn button on or off but not able to go inside wifi option.
please help solving this problem
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        show(0);
        return START_NOT_STICKY;
    }
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
            PixelFormat.TRANSLUCENT);
    private int width;
    private int height;
    public final synchronized void show(final int id) {
        width = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
        height = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight();
        final Button button = new Button(context);
        button.setText("I'm a button!");
        button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        button.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.performClick();

                if(event.getAction() == MotionEvent.ACTION_MOVE){
                    int pos[] = new int[2];
                    button.getLocationOnScreen(pos);
                    Log.i(MainActivity.TAG, "onTouch"+event.getRawX()+" :: "+width+" :: "+pos[0]);
                    Log.d(MainActivity.TAG, "onTouch"+event.getRawY()+" :: "+height+" :: "+pos[1]);
                    params = new WindowManager.LayoutParams(
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            (int)(event.getRawX())-(width/2),
                            (int)(event.getRawY())-(height/2),
                            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                            PixelFormat.TRANSLUCENT);

                    mWindowManager.updateViewLayout(button, params);
                                }
                return true;
            }
        });
        mWindowManager.addView(button, params);
    }

A: Need to add flags 0 and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE then it will work fine as bellow snippet
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.performClick();
        if(event.getAction() == MotionEvent.ACTION_MOVE){
            params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    (int)(event.getRawX())-(width/2),
                    (int)(event.getRawY())-(height/2),
                    0,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);
            mWindowManager.updateViewLayout(floatingView, params);
            return true;
        }
        return true;
    }


text:
Q: How to Retrieve list of attributes from multiple Firebase nodes My firebase DB looks like

Now I want to query the database such that I take all the users whose email id is in a query list.
For example in the above shown database structure, if I want to make a query such that find the users where username in ["allen20252482", "arne19712450"] which can give me two users.
Is it possible?
Currently I can query like https://xyz.firebaseio.com/users.json to get the complete user node data , But is it possible to filter like where I take only those users whose username is in the given query list?
I am using REST API endpoint to query the Firebase DB.
Any suggestion is very much appreciated

A: I suggest reading the documentation on filtering data.  It sounds like you want to filter by a child key:
https://xyz.firebaseio.com/users.json?orderBy="username"&equalTo="abcdef"

You will only be able to specify one username at a time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opening AngularJS Accordion on click of a button Hi I am working with an angular controller and an angular view.
In my view I have the following:

   <input type="search" class="form-control" ng-model="Filter" placeholder="Filter Search" />
    <accordion>
        <accordion-group ng-repeat="group in groups" heading="{{group.title}}">
        {{group.content}}
        </accordion-group>
    </accordion>

And then in my controller I want to be able to do two things:

*

*Open the accordion completely using 'is-open' on every group

*Somewhat related set "close-others=false"

I know how to set that two things as defaults, but my problem is that I need to do this from my controller since I basically am using an ng-model to look at changes in a search box and the moment the user start typing into this search box I want the accordion to open up completely...and eventually I'm going to user ._filter to actually do the filtering..but the first step is to trigger an open up of the accordion
Right now my controller looks like this
$scope.$watch("Filter", function (newVal, oldVal, scope) {
        console.log($scope.reportFilter);

        if ($scope.Filter)
        {
            if ($scope.Filter.length == 0){
                // close the accordion
                // show one at a time

            }

            else{

                // open the entire accordion

            }
        }

A: For the html:

   <input type="search" class="form-control" ng-model="Filter" placeholder="Filter Search" />
    <accordion close-others="showOnlyOne">
        <accordion-group ng-repeat="group in groups" heading="{{group.title}}" is-open="group.isThisOpen">
        {{group.content}}
        </accordion-group>
    </accordion>

And for the Controller:
$scope.showOnlyOne=true;
$scope.$watch("Filter", function (newVal, oldVal, scope) {
        console.log($scope.reportFilter);

        if ($scope.Filter)
        {
            if ($scope.Filter.length == 0){
                // close the accordion
                // show one at a time
                $scope.showOnlyOne=true;
                $scope.groups.forEach(function(group){
                    group.isThisOpen=false;
                });
            }

            else{
                $scope.showOnlyOne=false;
                // open the entire accordion
                $scope.groups.forEach(function(group){
                    group.isThisOpen=true;
                });
            }
        }
};

Probably that'll do the trick...


text:
Q: How to read in rows corresponding to index array? I'm fairly new to R and am working with multiple GB files with up to 100MM rows.  Instead of reading in the entire data file, I'd prefer to read in one column, subset it based on certain criterion, and use the resultant indices to read in data from another column for analysis.
I.e., I subset my column of data (let's call it ID) by which match the values in another array, as below.
rowind = which(ID[,1] %in% Zid);

Then, when I read in another column for processing, I'd like to only read in those rows that match the numbers in rowind.
I have done a lot of searching for this - I know how to skip specific columns and skip a certain number of rows at the beginning of the data frame, but I don't know how to read in say, rows [3,5,8,11,15], etc.


text:
Q: IllegalArgumentException: Bound must be positive I get an error saying that my bound must be positive.
Here is the line I get it on:
inv.setItem(i, items.get(r.nextInt(items.size())));

As far as I know, it comes from the part where I request a random integer from the list of items.
This is how I defined the list:
List<ItemStack> items = getAllItems(level);

Where the getAllItems() method looks like:
public List<ItemStack> getAllItems(int level) {
    List<ItemStack> items = new ArrayList<ItemStack>();
    for (String item : settings.getChests().getStringList("chestitems." + level)) {
        ItemStack toAdd = parseItem(item);
        items.add(toAdd);
    }
    return items;
}

I get this stacktrace:
[19:03:53 ERROR]: Error occurred while enabling KitPvP v0.5 (Is it up to date?)
java.lang.IllegalArgumentException: bound must be positive
        at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_51]
        at me.iamguus.gamegetsiepunt.kitpvp.chests.ChestsUtil.randomlyFillInv(ChestsUtil.java:101) ~[?:?]
        at me.iamguus.gamegetsiepunt.kitpvp.Main.onEnable(Main.java:40) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:335) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:356) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:316) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.reload(CraftServer.java:746) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.Bukkit.reload(Bukkit.java:534) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:25) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:646) [spigot.jar:git-Spigot-5818108-a486600]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchServerCommand(CraftServer.java:632) [spigot.jar:git-Spigot-5818108-a486600]
        at net.minecraft.server.v1_8_R3.DedicatedServer.aO(DedicatedServer.java:405) [spigot.jar:git-Spigot-5818108-a486600]
        at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:369) [spigot.jar:git-Spigot-5818108-a486600]
        at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:657) [spigot.jar:git-Spigot-5818108-a486600]
        at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:560) [spigot.jar:git-Spigot-5818108-a486600]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_51]

A: As your stack trace says,

java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_51]

The argument to nextInt() needs to be a positive integer. You will need to find out where you're passing a non-positive input to that method.

A: The issue is that you are calling Random.nextInt() with a zero and it doesn't like that. That is happening because the List from getAllItems() is empty. I would prevent this situation by checking that the list has items before performing your logic:
List<ItemStack> items = getAllItems(level);
if(!items.isEmpty()) {
    inv.setItem(i, items.get(r.nextInt(items.size())));
}


text:
Q: Past tense with modals in reported speech
— "If I could have gone to college I would have done this."

How would you report this speech? I would do it the following way. But note that nothing actually changes in the verbs and I can't think of any way to make a change.

— "He said that if he could have gone to college he would have done this."

A: You can actually change the verbs here to indicate reported speech; although you may change the meaning.

He said that had he gone to college, he would have done this.

This changes the conditional aspect of the statement slightly. It removes the implication of the lack of opportunity, so it transforms the meaning subtly. This says nothing, one way or the other, about whether this person faced barriers in obtaining an education.

He said that had he had the opportunity to go [to have gone] to college, he would
  have done this.

And while this is closer to the original statement semantically, it's a tad awkward with had had.

He said that, had he the opportunity to go [to have gone] to college, he would have done this.

Had he had the opportunity and had he the opportunity are semantically equivalent to if he could have, but they might be more awkward.
And to go is much less awkward in my examples, but to have gone is also grammatical. I included have gone in brackets because it's obviously more reflective of the speech being attributed.
By the way, I'd suggest using would have done so for the reported speech. It's just a more common usage, but it's your choice.


text:
Q: explicit constructor not allowed in initializer-list> I wanted to create a string-container type that checks if the string it contains is valid at construction. In my opinion, it should be preferable if this class has an constructor that takes a std::string as an argument (just to make sure that no implicit type conversions happen).
But when I use this string-container in an std::initializer_list (and even further in a std::unordered_multimap) I get an error, if I define the constructor as explicit.
Is there a way to define the constructor as explicit and use it at the same time in a std::multimap? (i.e. a constructor-overload of a magic type I am currently not aware of)
I prepared the following minimal example that should show the point:
#include <utility>
#include <string>
#include <stdexcept>
#include <unordered_map>

class constrained_string_container_t{
    public:
    // variant 1: works
    //constrained_string_container_t(const std::string& inst) : str{inst} {validate();}

    // variant 2: doesn't work
    explicit constrained_string_container_t(const std::string& inst) : str{inst} {validate();}
    explicit constrained_string_container_t(std::string&& inst) : str{std::move(inst)} {validate();}

    // variant 3: works
    //template<typename STR_T>
    //constrained_string_container_t(STR_T&& inst) : str{std::forward<STR_T>(inst)} {validate();}

    // variant 4: doesn't work
    //template<typename STR_T>
    //explicit constrained_string_container_t(STR_T&& inst) : str{std::forward<STR_T>(inst)} {validate();}

    void validate() {if (str == "abc") {throw std::runtime_error{"abc not allowed"};}}

    private:
    std::string str;
};

using pair_t = std::pair<std::string, constrained_string_container_t>;
using init_pair_list_t = std::initializer_list<std::pair<std::string, constrained_string_container_t>>;
using map_t = std::unordered_multimap<std::string, constrained_string_container_t>;

int main() {
    using namespace std::string_literals;

    //suceeds for all variants
    pair_t p0{std::string{"test"}, std::string{"test2"}};

    //fails to compile for variant 2 and variant 4
    init_pair_list_t p1{{std::string{"test"}, std::string{"test2"}}};

    //fails to compile for variant 2 and variant 4
    init_pair_list_t p2{{"test"s, "test2"s}};

    //fails to compile for variant 2 and variant 4
    map_t m{{"test"s, "test2"s}};
}

When I compile it, I get the following errors (with gcc-10):
explicit_shit.cpp: In function 'int main()':
explicit_shit.cpp:40:72: error: could not convert '{{std::__cxx11::basic_string<char>(((const char*)"test"), std::allocator<char>()), std::__cxx11::basic_string<char>(((const char*)"test2"), std::allocator<char>())}}' from '<brace-enclosed initializer list>' to 'init_pair_list_t' {aka 'std::initializer_list<std::pair<std::__cxx11::basic_string<char>, constrained_string_container_t> >'}
   40 |         init_pair_list_t p1{{std::string{"test"}, std::string{"test2"}}};
      |                                                                        ^
      |                                                                        |
      |                                                                        <brace-enclosed initializer list>
explicit_shit.cpp:43:48: error: could not convert '{{std::literals::string_literals::operator""s(const char*, std::size_t)(4), std::literals::string_literals::operator""s(const char*, std::size_t)(5)}}' from '<brace-enclosed initializer list>' to 'init_pair_list_t' {aka 'std::initializer_list<std::pair<std::__cxx11::basic_string<char>, constrained_string_container_t> >'}
   43 |         init_pair_list_t p2{{"test"s, "test2"s}};
      |                                                ^
      |                                                |
      |                                                <brace-enclosed initializer list>
explicit_shit.cpp:46:36: error: no matching function for call to 'std::unordered_multimap<std::__cxx11::basic_string<char>, constrained_string_container_t>::unordered_multimap(<brace-enclosed initializer list>)'
   46 |         map_t m{{"test"s, "test2"s}};
      |                                    ^

A: In order for this to compile
init_pair_list_t p1{{std::string{"test"}, std::string{"test2"}}};

your type constrained_string_container_t must be implicitly convertible from std::string, since the initialization of the elements of the std::initializer_list from the elements of the braced-init-list will use copy-initialization.
However, as I understand it, your concern is that constrained_string_container_t should not be constructed from something that the compiler might implicitly convert to std::string. So you've marked the constructors explicit. But then the previous thing doesn't work properly.
A possible fix is to have a constructor template that only participates in overload resolution if the argument type is cv std::string:
template <class T>
requires std::same_as<std::remove_cvref_t<T>, std::string>
constrained_string_container_t(T&& inst) : str{std::forward<T>(inst)} {validate();}

See the full example here: https://godbolt.org/z/W791e4rGr
(You should probably also allow classes derived from std::string. How to do this is left as an exercise for the reader.)


text:
Q: Java/Scala Swing: Make a component fill all available space in a row I'm trying to create a layout with Swing using GridBagLayout.
I want to place a ComboBox besides a Button, where the Button has a constant size, and the ComboBox fills all the available space in the row:

However, if I enlarge the window, empty space appears between the ComboBox and the Button:

How can I layout this form, so that the ComboBox fills all the space, even when the window is resized?
Layout code for the components, in Scala:
layout(button) = new Constraints() {
    gridx = 1
    gridy = 0
    anchor = GridBagPanel.Anchor.LineEnd
}

layout(comboBox) = new Constraints() {
    gridx = 0
    gridy = 0
    fill = GridBagPanel.Fill.Horizontal
}

layout(centerPanel) = new Constraints() {
    gridx = 0
    gridy = 1
    weighty = 1
    weightx = 1
    gridwidth = 2
    fill = GridBagPanel.Fill.Both
}

A: Use a BorderLayout for that section of the GUI. Put the combo. in the CENTER and the button in the LINE_END.
Like this:

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.*;

public class StretchComboLayout {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel ui = new JPanel(new BorderLayout(2, 2));
                ui.setBorder(new EmptyBorder(4, 4, 4, 4));

                JPanel controls = new JPanel(new BorderLayout(2, 2));
                ui.add(controls, BorderLayout.PAGE_START);
                String s = new String(Character.toChars(8594));
                String[] items = {"Choice: right " + s + " arrow"};
                JComboBox cb = new JComboBox(items);
                controls.add(cb, BorderLayout.CENTER);
                controls.add(new JButton("Button"), BorderLayout.LINE_END);

                JSplitPane sp = new JSplitPane(
                        JSplitPane.VERTICAL_SPLIT,
                        new JTextArea(4,40),
                        new JTextArea(4,40));

                ui.add(sp, BorderLayout.CENTER);

                JFrame f = new JFrame("Stretch Combo Layout");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setContentPane(ui);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


text:
Q: Add a toggle to collapse the hot network questions list While the hot network questions list can be entertaining, there are a few situations in which it harms the experience of using Stack Exchange sites, especially when you use Stack Exchange sites at work.
I know that variations of this have been asked before, but I think the way the Stack Exchange network changed in the meantime does merit a new discussion about this. We have far more sites that are more entertainment than professional now, and the mix of entertainment and professional topics makes the HNQ list problematic in some cases.
There are a few situations I can think of where the presence of the HNQ list has a negative effect:

*

*The appearance of pretty much random questions about all kinds of topic can be a bit annoying in a work setting. The other people looking at your screen might not see that you're only trying to solve a programming issue, when there is some inappropriate content in the sidebar.

*It exposes you to spoilers or information about recent TV series, movies, books, etc. While titles are usually written to avoid major spoilers, this is not always the case, and it's still at least a distraction.

*In any case, the hot network questions are a distraction. It's pretty much their purpose, but sometimes I don't want to be distracted.

I know this can be solved by a userscript, but that is not a real solution and has several drawbacks. It's seriously annoying when you use multiple devices, it only solves the problem for a tiny amount of users. Userscripts are a workaround, not a solution.
We don't have any control over the HNQ list, especially on work computers where the workarounds can be disallowed. We can choose which Stack Exchange site to visit, but the HNQ list is always there, mixing professional and unprofessional content.
What I'd propose is to make the HNQ sidebar collapsible, and remember the collapsed state for the user session (or forever for that user). A single click would collapse the list to only the title, and a second one would expand it again to the full list. This would make it easy to hide the HNQ list for a short time, e.g. Mondays when Game of Thrones is running, or essentially permanently as well, if you simply don't care about them at all.

A: Sometimes HNQ is really frustrating but not always. So I think this will be good if implemented.
I did a small workaround and the below code can perfectly add a toggle button to the HNQs.
var a = document.createElement('a');
a.innerHTML = "(hide)";
a.addEventListener('click',function(){
    $('#hot-network-questions ul').toggle();
    a.innerHTML = $('#hot-network-questions ul').css('display')=='none'?"(show)":"(hide)";
});
$('#hot-network-questions h4').append(a);

It will work as
When Items are visible

When you click it

But making this as a userscript is not an option because you have to install it in each and every device.
So I think the developers implement an option like this.

This is tested on Stack Overflow and some other SE sites

A: Yes, and the list should start collapsed for users who haven't recorded a preference.  This includes all the visits from people who don't have accounts (or aren't logged in).
No matter how good the HNQ algorithm is, there will always be questions on it that -- while completely appropriate questions on their sites -- are not good candidates for context-free publication to all other sites.  Sites have no way to withdraw questions, even if they did somebody would have to notice first, and it would take a lot of human power to curate the list.  On the flip side, removing individual sites just because there might be, say, questions with movie spoilers isn't fair to those sites if they want the exposure.
So if we're going to put hot network questions on every site page, we should at least (a) make it collapsible for those who don't want to see it and (b) start collapsed with some sort of indication of what's behind the toggle or invitation to explore a random slice of the rest of the network.  If we do that, then "you chose to look" becomes a completely valid response to any complaint about somebody having to see a post about poop from Parenting or gender roles from Islam or (insert position here) from Politics.

A: If you use Adblock Plus or uBlock Origin, you can hide the Hot Network Posts section by creating a filter for *.stackexchange.com###hot-network-questions


text:
Q: MYSYS2 mingw64 gcc can't link Shared Libary Hail,
I'm attempting to link to a compiled shared library to main, and it tells me it cannot find the library - despite linking to a static library of the same name in a different folder having no issues.  I am also able to make a shared library and link to it properly before trying to link to the library not in the current directory.
Perhaps I compiled it wrong or something, but here's the make files I used:
Makefile for external libraries:
all: objects libalpha.so libalpha.a

objects:
    gcc -fPIC -c file1.c file2.c

#shared lib
libalpha.so: objects
    gcc -shared -fPIC -Wl,-soname,C:\libs\libc\lib\shared\alpha.so -o C:\libs\libc\shared\libalpha.so file1.o file2.o

#static lib
libalpha.a: objects
    ar rcs C:\libs\libc\static\libalpha.a file1.o file2.o

And here's the makefile for the main / internal libraries that do work before attempting to link to external libraries:
all: libtest libtwo libgroup.so libgroup.a main.o main_static main_shared

libtest: ./sub/libtest.c ./sub/libtest.h
    gcc -fPIC -c ./sub/libtest.c -o ./sub/libtest.o

libtwo: ./sub/libtwo.c ./sub/libtwo.h
    gcc -fPIC -c ./sub/libtwo.c -o ./sub/libtwo.o

#shared - compiles and links properly
libgroup.so: ./sub/libtest.o ./sub/libtwo.o
    gcc -shared -fPIC -Wl,-soname,./sub/libtest.o ./sub/libtwo.o -o ./sub/libgroup.so

#static - compiles and links properly
libgroup.a: ./sub/libtest.o ./sub/libtwo.o
    ar rcs ./sub/libgroup.a ./sub/libtest.o ./sub/libtwo.o

#direct where the header files are located
main.o: main.c
    gcc -IC:\libs\libc\CODE\alpha -c main.c

#compiles fully and works
main_static: main.o ./sub/libgroup.a
    gcc main.o -L./sub -lgroup -LC:\libs\libc\static -lalpha -o main_static

#doesn't work man??
main_shared: main.o ./sub/libgroup.so
    gcc main.o -L./sub -lgroup -LC:\libs\libc\shared -lalpha -o main_shared

And here's the error:
ld.exe: cannot find -lalpha
collect2.exe: error: ld returned 1 exit status
make: *** [makefile:27: main_shared] Error 1

And confirming they exist:
    Directory: C:\libs\libc\shared

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         1/1/2022   4:19 AM         224820 libalpha.so

    Directory: C:\libs\libc\static

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         1/1/2022   4:19 AM           2324 libalpha.a

See anything obvious?
Thanks for your insight.

A: I see various errors;

*

*You are generating position independent machine code (-fPIC). This is only needed in UNIX machines (BSD,Linux,...) but not on Windows. (Remove it.)

*As pointed out by @ssbssa, shared libraries in Windows end with ".dll", not ".so".

*Executables in Windows end with ".exe" (last two targets).


text:
Q: $watch vs. ngChange Say that you want to do something when a property of $scope changes. And say that this property is bound to an input field. What are the advantages/disadvantages of using $watch vs. using ngChange?
html
<input ng-model="foo" ng-change="increment()">

foo: {{foo}}

fooChangeCount: {{fooChangeCount}}

js
// Option 1: $watch
$scope.$watch('foo', function() {
  $scope.fooChangeCount++;
});

// Option 2: ngChange
$scope.fooChangeCount = 0;
$scope.increment = function() {
  $scope.fooChangeCount++;
};

http://plnkr.co/edit/4xJWpU6AN9HIp0OSZjgm?p=preview
I understand that there are times when you need to use $watch (if the value you're looking to watch isn't bound to an input field). And I understand that there are times when you need to use ngChange (when you want to do something in response to a change in an input, but not necessarily in response to a scope property change).
However, in this case both accomplish the same thing.
My thoughts:

*

*ngChange seems cleaner, and easier to understand what's happening.

*$watch seems like it might be slightly faster, but probably negligible. With ngChange, I think Angular would have to do some extra work in the compile phase to set up the event listeners, and perhaps extra event listeners decrease speed a bit. Regardless of whether or not you use ngChange, the digest cycle runs on changes, so you have an opportunity to listen for something and call a function in response to changes.

A: Bottom line - You can achieve with $watch every thing you can achieve with ng-change but not vice-versa.
Purposes:

ngChange - binded to a HTML element
$watch - observing scope's model objects (HTML object models included)

My rule of thumb - if you can use ng-change use it to match your scenario, otherwise use $watch
Why you shouldnt use $watch?

*

*It's inefficient - Adding complexity to your $digest

*It's hard to test effectively

*It's not clean

A: You have it mostly right. ng-change is very DOM specific and for evaluating an expression when the change event fires on a DOM element.
$watch however, is a lower-level (and more general purpose) utility that watches your view model or $scope. So your watch function will fire every time the user types a key (in the example of an input).
So to contrast, one listens to DOM events, the other watches your data.

A: $watch adds more complexity do the $digest, making it less efficient. In your case ngChange it's a cleaner and easier solution...
Font: http://www.benlesh.com/2013/10/title.html


text:
Q: Get input from the user using ReadLine in c# code that runs as part of PowerShell script in PowerShell ISE I need to prompting users for input in C# part of the code, but it doesn't work for me (gets empty input automagically) when run from PowerShell ISE. Code works as expected when run from just regular PowerShell command prompt (asks for the name)
$id = get-random
$code = @"
using System;
using System.Linq;
namespace Application
{
    public class Program$id
    {
        public static void Main()
        {
            Console.WriteLine("Please enter your sweet name....");
            String name = Console.ReadLine();
            Console.WriteLine("Hello *"+name+" %" );
        }
   }
}
"@
Add-type -TypeDefinition $code -Language CSharp
iex "[Application.Program$id]::Main()"

When run in ISE the output is following (notice there is no chance to provide input):
       PS C:\Users\Pavithra Kathirvel\Desktop> C:\Users\Pavithra Kathirvel\Desktop\demo.ps1
       Please enter your sweet name....
       Hello * %

A: As a beginner start with the basics in C# and powershell. If you are able to use one, it will be easier for you to learn the other. Also there are parts, which are in powershell faster than in c# and less code.
If you still want to execute your C# code in powershell, have a look at this link, it will run the script from a .cs file
Run a C# .cs file from a PowerShell Script
Also here is a really good tutorial for using c# in powershell:
https://blog.adamfurmanek.pl/2016/03/19/executing-c-code-using-powershell-script/


text:
Q: Google Earth Engine: Get a Geometry object based on user's drawing In order to publish my code as a Google Earth Engine App, I need to interactively set the Area of Interest (AOI) of the analysis  based on the users's drawing (Rectangle in this case). I'm trying to use the .onDraw() method as described in the ui.Map.DrawingTools and ui.Map.GeometryLayer documentation examples but I cannot seem to make it work. I'm trying the following:
// Don't make imports that correspond to the drawn rectangles.
Map.drawingTools().setLinked(false);
// Limit the draw modes to rectangles.
Map.drawingTools().setDrawModes(['rectangle']);
// Add an empty layer to hold the drawn rectangle.
Map.drawingTools().addLayer([]);
// Set the geometry type to be rectangle.
Map.drawingTools().setShape('rectangle');
// Enter drawing mode.
var getAOI = Map.drawingTools().draw();

var getAOI = function(){
  Map.drawingTools().layers().get(0).toGeometry();
};

var AOI = Map.drawingTools().onDraw(getAOI);

Here is a link to the full script: https://code.earthengine.google.com/11a77302259a6d99c3a561a2a723fca0

A: onDraw() takes a callback function, which according to docs:

The callback to fire when a shape is drawn. The callback is passed
  three parameters: the added ee.Geometry, the GeometryLayer to which
  the geometry was added, and the ui.Map.DrawingTools widget that the
  event listener is bound to.

This means, you get a reference to the geometry like this:
Map.drawingTools().onDraw(function (geometry) {
  // Do something with the geometry
  Map.addLayer(geometry, null, 'a drawn geometry')
})


text:
Q: How do you style or override the default hover color for drop down menus? I know, someway, somehow, you can do this. I just am not sure. I would preferably like to override the default blue hover for select menus (drop downs) so that I can add a box-shadow: inset 0 0 3px 3px to my options.
So, JavaScript, JQuery, (preferably) CSS?
I don't know much about JavaScrip and JQuery... I haven't gotten that far yet, but any help with this problem would be greatly appreciated.
Thank you!
http://lrroberts0122.github.com/DWS/lab6/level-1/

A: Not every browser allows that. in fact, If you look at your website in chrome, you'll see that the selectbox itself is not even displaying the grey background. Resulting in white text on a white background.
If you really want to style the dropdown yourself, I would suggest to use javascript/jquery to replace the select/option with an ul/li, which you can style as you wish.
I'll try to find some examples to get you started. Just a second.
Edit: This should get you started: http://tutorialzine.com/2010/11/better-select-jquery-css3/
edit2: here's another one: http://bnotions.com/form-select-replacement-using-jquery-css/
And this person even created a plugin: http://forrst.com/posts/jQuery_plugin_ReplaceDropdown_to_replace_a_selec-NA2
disclaimer: I haven't tested any of the links above myself. So use at your own discretion.

A: I have found out that the properties for the drop box are in line #103 through #114. Please explain your answer more fully, as in the box BORDER itself or the text and you want NOTHING behind it?

A: use unbind() function of jquery to unbind hover then try binding again by .css() you should be able to chang


text:
Q: SFML leaves part of texture blank, if I create it from PixelPtr I have a code, which converts plain BGR data to sf::Texture. "ifs" is opened ifstream to file which contains byte triplets of BGR colors (header of source file is omitted). And Width & Height 100% valid. In my example image is 800x600.
struct h3pcx_color_bgr { uint8_t b, uint8_t g, uint8_t r };

sf::Uint8* pixels = new sf::Uint8[width * height * 4];
h3pcx_color_bgr* fileData = new h3pcx_color_bgr[width*height];
ifs.read((char*)fileData, width * height * sizeof(h3pcx_color_bgr));

for (uint32_t i = 0; i < width*height; ++i) {
    pixels[i * 4] = fileData[i].r;
    pixels[i * 4 + 1] = fileData[i].g;
    pixels[i * 4 + 2] = fileData[i].b;
    pixels[i * 4 + 3] = 255;
}

This code works good, problem comes after. Once I draw my texture:
m_tex.update(pixels); //sf::Texture
m_sprite.setTexture(m_tex); //sf::Sprite
m_window->draw(m_sprite); // m_window is sf::RenderWindow

I have this annoying grey line in image below:

What I did:

*

*Verified, that pixels contains valid value

Code snippet below (700 * 595 is inside "grey area") shows, that both pixels and fileData contains valid data (not grey color, which is appears just uninitialized memory).
auto f = fileData[700 * 595]; // 32, 31, 38
auto r = pixels[700 * 595 * 4]; // 38
auto g = pixels[700 * 595 * 4 + 1]; // 31
auto b = pixels[700 * 595 * 4 + 2]; // 32

"Grey" color is 204, 204, 204.

*

*Tried to use sf::Image

If we do something like this:
img.create(width, height, pixels); // img is sf::Image
img.setPixel(700, 595, sf::Color::Blue);

And then convert it to sf::Texture, and draw. Result will be same image with grey area, but pixel 700, 585 will be blue!
If I get color value from "grey area":
auto clr = img.getPixel(700,600); //sf::Color(204,204,204)

So, it looks like, there are some hard-limit(???) on quantity of pixels (but I doubt it, since I've looked on actual SFML code, and did not found anything suspicious) or my stupid mistake. I would be very grateful, if someone can point out - why this grey line appears.

A: In the code:
auto f = fileData[700 * 595];

You are accessing pixel 500, 520. To access the pixel 700, 595 you have to use:
auto f = fileData[700 + 595 * 800]; // x + y * width

I would write this as a comment, but I lack the necessary reputation.

A: If any1 is wondering - It's just file is wrong, with this exact grey color in the end. Code is correct.


text:
Q: Find the negation of the following quantified sentence $(∀x)(p(x)∨q(x)→¬q(x))$ I'm trying to deny a quantified sentence.
My attempt:
To negate a quantified sentence, I just need to change the quantifier and connectives.
So:
$$(∀x)(p(x)∨q(x)→¬q(x))$$
Denying:
$$(∃x) (p(x) ∧ ~q(x) ∧ q(x))$$
Notes:
$\lnot(∀)$ = $∃$
$\lnot(∨)$ = $∧$
$\lnot(→)$ = $∧$
$\lnot(¬q(x))$ = $q(x)$
I'm pretty sure that my solution is correct, the problem is that the denial of the conditional connective is causing me doubts.

A: With these types of problems you want to keep in mind logical equivalences. Also, when negating everything you want all the logical operators to be $\land$ or $\lor$. As I noted in the comments, $p\to q \equiv \lnot p \lor q$.
$1. \forall x((p(x) \lor q(x)) \to \lnot q(x)) \\
\text{Lets focus on changing the implies operator ($\to$) to its logical equivalent.} \\
(p(x) \lor q(x)) \to \lnot q(x) \equiv \lnot(p(x) \lor q(x)) \lor \lnot q(x) \equiv (\lnot p(x) \land \lnot q(x)) \lor \lnot q(x)\\
\text{Now sub this logical equivalent back into our statement.} \\
2. \forall x ((\lnot p(x) \land \lnot q(x)) \lor \lnot q(x)) \\
\text{Start the negation.} \\
3.\lnot \forall x ((\lnot p(x) \land \lnot q(x)) \lor \lnot q(x)) \\
4.\exists x \lnot ((\lnot p(x) \land \lnot q(x)) \lor \lnot q(x)) \\
5.\exists x(\lnot(\lnot p(x) \land \lnot q(x)) \land \lnot\lnot q(x)) \\
6. \exists x((\lnot\lnot p(x) \lor \lnot\lnot q(x)) \land q(x)) \\
\boxed{7. \exists x ((p(x) \lor q(x)) \land q(x)).}
$

A:
Notes:
$\lnot(∨)$ = $∧$

Not quite: the negation of $$A\lor B$$ is $$\lnot A \land\lnot B.$$ Remember, you are negating a sentence, not merely its main logical connective.

$\lnot(→)$ = $∧$

Not quite: the negation of $$A\to B$$ is $$A\land\lnot B.$$

$\lnot(∀)$ = $∃$

Not quite: the negation of  $\lnot∀x A(x)$ is $∃x\lnot A(x).$

$\lnot(¬q(x))$ = $q(x)$

Correct.

So:
$$(∀x)(p(x)∨q(x)→¬q(x))$$

Liberally inserting parentheses helps disambiguate sentences. In any case, the precedence of logical connectives dictates that this sentence ought to be read as $$∀x\Big(\big(p(x)∨q(x)\big)→¬q(x)\Big)$$ (I removed the unnecessary parentheses around the quantifier).

Denying:
$$(∃x) (p(x) ∧ ~q(x) ∧ q(x))$$

This is incorrect, as pointed out in the comments and other answers. My above corrections make clear why.

A: You are doing something weird, which is to regard the negation as an operation over operators alone, but that is not a good way to think about it. Yes, when you negate a sentence, you pay attention to what kind of sentence it is (i.e. what is the main operator), but applying the negation to that sentence does not just effect the operator, but it can also effect its operands.
For example, if you think $\neg (\land) = \lor$, then you might be inclined to say: $\neg (A \land B) = A (\neg \land) B = A \lor B$, but that is not correct: you also have to negate the operands, so you get $\neg (A \land B) = \neg A \lor \neg B$
Likewise, you should not do $\neg \forall x P(x) = (\neg \forall) x P(x) = \exists x P(x)$, because the correct answer is that $\neg \forall x P(x) =  \exists x \neg P(x)$
"Ah!", you may say: "So I have to negate the operands as well!". That is, maybe we can just stick to the $\neg (*) = *'$ schema, but we just need to make sure that something like $\neg A * B = \neg A *' \neg B$, and that (for a one-place operator) $\neg * A = *' \neg A$.
But that doesn't work either, because now you would have that $\neg \neg A = (\neg (\neg)) \neg A = \neg A$
And (as you yourself noticed) neither one works for the $\to$: there is really no 'nice' operator $*$ such that $\neg (A \to B) = A * B$ or $\neg (A \to B) =\neg A * \neg B$
Long story short: negations apply to whole statements, not just the operator!
Other answer will tell you the details for how to work out the negations involving various operators, but I just want to correct the more conceptual mistake you seem to be making.

A: I confirm the conclusion of @MauroALLEGRANZA, using the definition of $P\to Q$, which is $(\lnot P)\vee Q$.
So, since $\forall x\;(p(x)\vee q(x)\to \lnot q(x)$ is the same as $\forall x\;\lnot(p(x)\vee q(x))\vee \lnot q(x)$, its negation is
$$\exists x\:\lnot\lnot\bigl(p(x)\vee q(x)\bigr)\wedge\lnot \lnot q(x),\quad \text{i.e.}\quad \exists x\:\bigl(p(x)\vee q(x)\bigr)\wedge q(x). $$


text:
Q: Что такое конекшены с сервером, как работают, зачем нужны и как использовать? До этого знал что есть HTTP запросы, думал что хорошо их понимаю... И практически их использовал с веб сокетами, которые не очень понимал. Использую С#/.NET, c практической стороны можно говорить в контексте этого стека.
Узнал что есть некие 'соединения'... Услышал что с Http1.1 все запросы по умолчанию снабжены заголовком Connection: keep-alive  без явного добавления. То есть любой запрос порождает соединение, это ломает мое примитивное понимание запросов, а на место пустоты понимания ничего не приходит...

*

*В чем разница между просто последовательными запросами из Http1.0 и этими соединениями? Не понимаю зачем его 'держать' и что это вообще значит. Где тут выгода?
Сейчас 'держать соединение' представляю по аналогии переиспользвания инстанса HttpClient, а не создавать новый каждый раз. Только тут на клиентах в рамках браузеров/мобильных либ TCP клиенты, которые работают не явно из кода который пишут фронтендщики. Это верное понимание или тут есть некий контекст концепций из описания протокола? Как тогда на стороне сервера может быть контроль количества соединений, если их количество должно быть известно только на клиенте?

*То есть эти клиенты создавая инстансы для запросов на сервер, отслеживают появления в ответе
заголовка Connection: close для 'вызова Dispose' у инстанса, и прекращении его использования?

*Кто отправляет заголовок Connection: close? Веб сервера nginx, iis, kestrel или это делает ASP под капотом? Можно и руками добавлять используя ASP Core... но ни умения ни понимания зачем это нужно нет. Аналогично хотелось бы узнать какая часть должна отслеживать хедер Connection: keep-alive.

*Напишите, пожалуйста, что еще знаете в контексте вопроса 'Что такое конекшены с сервером, как работают, зачем нужны и как использовать?'. Любой ваш опыт или хорошие ссылки будет интересны.

A: Все очень просто.
Каждый раз, когда браузер "отрисовывает" страницу, это порождает "шквал" запросов на множество серверов. Потому что страница устроена очень сложно: это довольно много js-кода и десятки картинок с разных серверов.
Плюс к этому, этот js код начинает ajax-ом стучаться в разные методы бэкэнда.
Причем, по хорошему это должно идти не по http, а по https.
А теперь вспомним, что такое https. Это значит, что при устновлении каждого tcp-соединения происходит обмен открытыми ключами для создания зашифрованного канала - ssl handshaking.
И просто в HTTP 1.1 можно провести этот обмен ключами один раз между клиентом и конкретным сервером, а потом пользоваться уже установленным tcp соединением, не начиная всю эту возню с ключами заново при следующем обращении к тому же самому серверу.
Этот процесс абсолютно прозрачен как для сервера, так и для клиента. Более того, во многих случаях этот tcp-коннекшн существует между клиентом и энджинксом, который стоит "на входе" и служит системой распределения нагрузки, а сам nginx уже раскидывает запросы по целой ферме серверов для обслуживания бэкэнд-запросов, которые прячутся за ним.
Откровенно говоря, я не знаю, кто  отправляет заголовок Connection: close. tcp соединения имеют свойство "протухать" - ну, перешли вы через дорогу, сотовый телефон подключился к другой вышке, а трансляция потоковой музыки через спотифай продолжается. Просто на более низком уровне, чем логика клиента, tcp коннекшн порвался и установился заново, когда понадобилось протащить с сервера следующий кусочек музкального потока.
В Вашем вопросе собрано несколько вопросов, если у Вас остались сомнения по поводу тех вопросов, на которые я не ответил - уточните исходный вопрос, подумаем еще.
Кстати, только что в голову пришел простой и любопытный эксперимент. Сделем простую страницу на сервере, поддерживающем http 1.1. Посмотрим на статистику  открытых соединений на клиенте - ну,там, при помощи ss или более олдскульно - через netstat. Теперь откроем страницу в браузере.
Если я прав - то после полной загрузки страницы, когда уже всё прогрузилось и браузер ничего не ждёт, должны остаться одно или несколько открытых tcp-соединений с сервером, откуда была загружена страница. Это как раз позволило  бы, если бы клиент захотел что то еще загрузить, воспользоваться уже открытым коннектом.
Если же мои представления не верны - я буду рад, если кто то меня поправит :-) - о, пока я писал ответ, в коментариях к вопросу сказали всё то же самое , только короче!


text:
Q: this.method return undefined function Z(params) {
    for (var j in params) {
        this[j] = params[j];
    }
}

Z.prototype = {
    show: function () {
        var _this = this;
        $(window).bind('resize', this.adjust); // Return undefined? Why?
       //$(window).bind('resize',function(){
       // _this.adjust(); // This works.
       //});
    },
    adjust: function () {
        alert(this.id);
    }
}

var a = new Z({
    id: 5
});
a.show();

Hello, why this.adjust return undefined? But its working when anonymous function is being used.

A: It is because this in alert(this.id); is refering to the window object now and not to your a instance.

A: This a "this" scope issue. Try replacing the statement:
$(window).bind('resize', this.adjust);

by this:
$(window).bind('resize', _this.adjust);

A: In Javascript closures, the this keyword is late binding. Which means it is not evaluated until the function is actually called.
So when the "resize" event is fired your context is already gone.
Assigning the value to a variable then using that variable inside a function creates a closure. As long as that function is referenced somewhere it will retain the value of _this.
_this in your example uses early binding while this uses late binding. At the time that your resize event handler is called the value of this will be the window object which obviously doesn't have a method adjust
See also: http://javascript.info/tutorial/binding


text:
Q: MVD axioms and properties If X->->Y and X->->Z then does it imply X->->YZ ?
I tried few examples and found this to be true. I couldn't find this property or it's proof in any website.
Can someone please tell if the above property always holds true or not?

A: Yes, the Union Rule holds also for Multivalued Dependencies, not only for Functional Dependencies.
I think the first proof of this rule has been given in the following paper: A Complete Axiomatization for Functional and Multivalued Dependencies in Database Relations, by C.Beeri, R.Fagin, and J.H.Howard, Proc. of 1977 ACM SIGMOD Conference (bibliographic reference, pdf copy).
The proof given in the paper is the following :
1. X ->-> Z            (given)
2. X ->-> XZ           (by augmentation of 1 with X)
3. X ->-> Y            (given)
4. XZ ->-> YZ          (by augmentation of 3 with Z)
5. XZ ->-> U - X - YZ  (by complementation of 4, U are all the attributes of the relation)
6. X ->-> U - X - YZ   (by transitivity of 2 and 5, since XZ and U - X - YZ are disjoint)
7. X ->-> YZ           (by complementation of 6)


text:
Q: Does Google webrtc native implementation have support for SFU?
*

*Does Google WebRTC Native implementation has support for SFU?

*Does Google WebRTC Native implementation support for integrating custom/hardware encoder/decoder?

A: Not without alteration.
Internally WebRTC's internal audio/video pipelines are directly tied to encoder/decoders.
PeerConnectionFactory allows you to provide a video decoder/encoder factory, so you can short circuit the logic here, and grab the encoded frames, mock up a stream, and feed them directly into it as a relay, creating a new PeerConnection and setting those streams onto it.
The audio end is more difficult. There isn't a codec factory, so you will have to short circuit the logic there probably by alteration of libwebrtc.
The final question is RTCP termination, and how to override the mechanisms for quality/bandwidth control to not create a "One goes out, they all go out." situation.
Since libwebrtc will be the SFU, it will receive RTCP feedback from its remote peer for the content it is proxying, and vice versa.
For a 1-1 situation, it needs to be able to forward the RTCP feedback to the remote peer.
For multipoint, it needs to perform some logic to determine if one of the peers is problematic, and stop sending it video, switch off its video feed, or attempt to switch to a lower bitrate video stream. Basically it needs to act as a conduit that attempts to predict why/how packet loss is occurring, and keep as many audio/video feeds operating normally at at the highest possible quality for each peer.
How exactly to hijack the RTCP feedback mechanisms in libwebrtc, I think that again will likely require some customization/hooks into libwebrtc

A: I think it will be easier to try with GStreamer implementation of WebRTC. Although it is still in "Bad Plugins" it is way easier to get or provide encoded audio and video. Actually it is implemented in that in mind - to make implementation of MFU and SFU easier.


text:
Q: How to set Devise sender name for email Although this thread doesn't say much, I figured you set the sender name in the Devise intializer like this:
app/config/initializers/devise.rb

Devise.setup do |config|
  config.mailer_sender = "'MySite' <no-reply@mysite.com>"
end

But this didn't work for me.
Does anyone know the correct way to do this?

A: This is it:
config.mailer_sender = '"Example.com" <your@site.com>'

A: You can also use escaped characters like this:
config.mailer_sender = "\"Support Desk\" <support@site.com>"

A: If you need to do this for devise, heroku and mandrill: and you're setting the email address as an environment variable you'll need to do it like so (I found out the hard way when the above email format above broke our sign up process, let my pain be your gain :)
Label:  Value:
EMAIL   Example.com <no-reply@example.com>

No ' or " required.


text:
Q: pass data from one screen and retrieve data from mysql in another screen and display in android I'm new to android and I'm doing a project in which I have a grid view with Image and text. When I press any particular image, I want it to go to another page and retrieve data from database and display it in that screen.
My php code works fine. But there is some problem with the java code.If I run it, I got unfortunately DemoGridView(my app name) stopped.
This is my code:
GridViewImageTextActivity.java

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview_image_text_example);

        CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(GridViewImageTextActivity.this, gridViewString, gridViewImageId);
        androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
        androidGridView.setAdapter(adapterViewAndroid);
        androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int i, long id) {
                Intent s = new Intent(GridViewImageTextActivity.this, DisplayStateWise.class);
                s.putExtra("stateValue",gridViewString[+i]);
                startActivity(s);
            }
        });

Config.java
public class Config {

    public static final String DATA_URL = "http://demoprojects.000webhostapp.com/getData.php?State=";
    public static final String KEY_NAME = "Name";
    public static final String KEY_STATE = "State";
    public static final String KEY_C = "Catagory";
    public static final String JSON_ARRAY = "result";

}

DisplayStateWise.java
public class DisplayStateWise extends AppCompatActivity {

    private TextView textViewResult;
    private ProgressDialog loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_states);

        String data = getIntent().getExtras().getString("stateValue");

        loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

        String url = Config.DATA_URL+data;

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                showJSON(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(DisplayStateWise.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void showJSON(String response){
        String Name="";
        String State="";
        String Catagory = "";
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
            JSONObject collegeData = result.getJSONObject(0);
            Name = collegeData.getString(Config.KEY_NAME);
            State = collegeData.getString(Config.KEY_STATE);
            Catagory = collegeData.getString(Config.KEY_C);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        textViewResult.setText("Name:\t"+Name+"\nAddress:\t" +State+ "\nVice Chancellor:\t"+ Catagory);
    }
}

display_states.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".DisplayStateWise" >

<ListView
    android:id="@+id/textViewResult"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp" >
</ListView>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.swathi.demogridview">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".GridViewImageTextActivity">
            <intent-filter >
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>
        </activity>

        <activity android:name=".DisplayStateWise"/>
    </application>

</manifest>

I'm really new to android and I'm not sure what is the problem with this code. Thank you all in advance for your help.
This is what I got in logcat
09:46:29 NullPointerException: Error executing task com.android.tools.idea.uibuilder.editor.NlPreviewForm$$Lambda$193/557090381@475c7540


text:
Q: Redmine, interlan error when going to "My account" I install Redmine on Heroku host, after solving some erorrs with gems, everything seems to be working. Except one small thing, when i click "My account", there is "internal error" with code 500.
I didn't see anything interesting in logs. Redmine was installed from windows 7 machine. If you can, pleas write reply easy to understand for newbie, or even step by step instruction. It's my totally first time doing something on server, and I need everything working for tomorrow. Thanks in advance.
Logs from heroku log console. Is there any other?
    2016-07-19T17:27:28.502527+00:00 app[web.1]: Started GET "/my/account" for 81.190.76.211 at 2016-07-19 17:27:28 +0000

2016-07-19T17:27:28.511962+00:00 app[web.1]: Processing by MyController#account as HTML
2016-07-19T17:27:28.535131+00:00 heroku[router]: at=info method=GET path="/my/account" host=rgredmine.herokuapp.com request_id=b3eb89ba-2a4b-46d1-949a-b5d24f7b266f fwd="81.190.76.211" dyno=web.1 connect=1ms service=43ms status=500 bytes=968


text:
Q: How to add the custom headers to the https request curl PHP script? I am writing the following code
<?php
$ch=curl_init();
$h=array("Host:v.airtellive.com");
curl_setopt($ch,CURLOPT_URL,"https://facebook.com");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLINFO_HEADER_OUT,true);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$h);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow header redirections
curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to 4
$p=curl_getinfo($ch);
$o=curl_exec($ch);
if($o==null)
var_dump (curl_error($ch));
$headers=curl_getinfo($ch,CURLINFO_HEADER_OUT);
print_r($headers);
echo "<xmp>";
echo $o;

curl_close($ch);
?>

but it gives me error:

could not resolve the host

If I use this script with search.yahoo.com it works fine. Actually, I want to create the realhost proxy by sending the host headers.

A: Headers for CURL mus be set like this
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_HTTPHEADER , array(
                "AUTH_USERNAME: {$username}",
                "AUTH_PASSWORD: {$password}",
            ));
$curlReturn = curl_exec($curl_handle);
    curl_close($curl_handle);

Any number of custom headers can be sent as array in this.


text:
Q: What is docker node:9-stretch? I'm looking at a Dockefile we have in one of our projects that essentially builds our UI.
I see it's using FROM node:9-stretch which ships with npm 5.6.0. I want to use npm ci which requires 5.7.0 so i need to update my dockerfile node base image.
I do not see a node:9-stretch in docker hub https://hub.docker.com/_/node/
Where is this pulling node:9-stretch from and what is a -stretch version of a base image?

A: The node 9 build was dropped after this commit https://github.com/nodejs/docker-node/commit/b22fb6c84e3cac83309b083c973649b2bf6b092d. You can find Dockerfile in diff.
The node:9-stretch image you can pull build before the commit, and persisted in docker hub. The 9-stretch tag exists in Tags page, as for now https://hub.docker.com/_/node?tab=tags&page=18.


text:
Q: Science Fiction Book: historical characters are android teachers, girl pulls radio into bathtub I have the same question as was asked before:  William Shakespeare, Winston Churchill, Michael Faraday  and the like are all robots, androids, and are referred to in the book as "dry bones".  They are all used to teach children -- the goal being to repopulate the Earth
(after a war, a plague?)  There is also a "Library" -- somewhere in London (the setting.)
At one point, a girl in her bathtub calmly reaches up with her toe, and pulls the playing radio into the tub -- killing her (because the "world" is too weird???)
QUESTION:  Does anyone know the name of this book?

A: As per the answer to the question this was previously marked as a duplicate to, this may be The Overman Culture by Edmund Cooper.

"Michael had a good memory. He could remember things significant & insignificant. He remembered--if hazily--when he was young enough to be fed milk only. He remembered the odd child who disappeared from playschool & he remembered the other child who fell (or was pushed?) from the high window & lay all smashed & crumpled on the ground, but not bleeding & he remembered how he'd wanted to know about words, how you could keep them, how you could fix them--perhaps like a drawing--forever."
"Time seems to have run amok. London is governed by Queen Victoria & Winston Churchill, populated by young people called 'fragiles' & others called 'drybones' because they don't bleed. The young fragiles come to realize that they're the last of their kind--whatever kind that might be.
Thus is established the setting for a brilliant novel of adventure that speaks to the largest questions facing young people everywhere--questions of identity, of purpose in life & of responsibility for themselves & their kind."


text:
Q: How to to use SQL Server application role in my connection string My current application uses very powerful credentials to access the SQL Server back-end database. I want to improve the security in my application by using an application role created.
For example, if I created one called app-role, with a password:
EXECUTE sp_addapprole @rolename = 'app-role', @password = `right pony duracell binderclip`

I want to enable the use of this application automatically during connection by specifying it in a connection string. I don't want to risk there being any places in the software that are accidentally not re-engineered to call:
EXECUTE sp_setapprole @rolename = 'app-role', @password = `right pony duracell binderclip`, @encrypt = 'odbc'

So obviously I want this to happen automatically during connection.
Bonus Chatter
The application roles feature was first added in SQL Server 2000.
Bonus Reading

*

*How to to use SQL Server application role in my connection string


text:
Q: VSCode shortcut to cycle through changed (git) blocks in current file In Sublime Text with the GitGutter plugin you can add the following keybindings:
{ "keys": ["super+["], "command": "git_gutter_prev_change" },
{ "keys": ["super+]"], "command": "git_gutter_next_change" },

This will allow you to jump your cursor through the changed sections of the open file. Useful if you jump into a large file and just want to go to the exact section(s) you're working on.
In VSCode, I know you can use Git: Open Change command (workbench.action.git.globalOpenChange) to switch to the diff view, then the workbench.action.compareEditor.nextChange and previousChange commands to cycle. I am aware you can edit while in the diff view, but I would rather never leave the editor view.

A: Not yet, but it's tracked by this feature request: https://github.com/Microsoft/vscode/issues/18059


text:
Q: Regular Expressions: Find Names in String using Python I have never had a very hard time with regular expressions up until now. I am hoping the solution is not obvious because I have probably spent a few hours on this problem.
This is my string:
Carson Daly: Ben Schwartz, Soko, Jacob Escobedo (R 2/28/14)
'

I want to extract 'Soko', and 'Jacob Escobedo' as individual strings. If I takes two different patterns for the extractions that is okay with me.
I have tried   "\s([A-Za-z0-9]{1}.+?)," and other alterations of that regex to get the data I want but I have had no success. Any help is appreciated.
The names never follow the same tag or the same symbol. The only thing that consistently precedes the names is a space (\s).
Here is another string as an example:
Carson Daly: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh

A: An alternative approach would be to parse the string with an HTML parser, like lxml.
For example, you can use the xpath to find everything between a b tag with Carson Daly text and br tag by checking preceding and following siblings:
from lxml.html import fromstring

l = [
    """Carson Daly: Ben Schwartz, Soko, Jacob Escobedo (R 2/28/14)
'""",
    """Carson Daly: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh
"""
]

for html in l:
    tree = fromstring(html)
    results = ''
    for element in tree.xpath('//node()[preceding-sibling::b="Carson Daly" and following-sibling::br]'):
        if not isinstance(element, str):
            results += element.text.strip()
        else:
            text = element.strip(':')
            if text:
                results += text.strip()

    print results.split(', ')

It prints:
['Ben Schwartz', 'Soko', 'Jacob Escobedo (R 2/28/14)']
['Wil Wheaton', 'the Birds of Satan', 'Courtney Kemp Agboh']

A: If you want to do it in regex (and with all the disclaimers on that topic), the following regex works with your strings. However, do note that you need to retrieve your matches from capture Group 1. In the online demo, make sure you look at the Group 1 captures in the bottom right pane. :)
<[^<]*</[^>]*>|<.*?>|((?<=,\s)\w[\w ]*\w|\w[\w ]*\w(?=,))

Basically, with the left alternations (separated by |) we match everything we don't want, then the final parentheses on the right capture what we do want.
This is an application of this question about matching a pattern except in certain situations (read that for implementation details including links to Python code).


text:
Q: How to add a 360 degree panorama view to an android app? Well, I have been searching a way to add a 360 degree panoramic image for now, but for some reason, I was not able to find something useful from the internet. The only thing I found was this tutorial was this Tutorialhttps://youtu.be/gnDa-fvEyUk, which, unfortunately, is in Kotlin. So hope you guys would help me sort this.
Well, by the way I found this documentaion; however, I was not able to comprehend much from this, especially the java part. It seems the layout part is easy(all about adding VRPanorama viewGoogle VR documentation
Thanks in advance.
PS: I am gonna do it in a fragment, so if possible, please show me the way of fragments.
EDIT: In general, what I want to add is 360-degree to one of my fragments that is similar to the video I shared. I have already added the dependencies and wrote the code for the layout file(the same as the tutorial), and also, I am more interested in URL way. After some searching, again I found something which might be helpful(Still Kotlin though). Tutorial

A: To retrieve image from the URL, all you should do is add a invisible i.e gone imageview in the xml and using glide load the image in that view and from the view retrieve that image as drawable and convert it to Bitmap and then load that view in the VR's SDK method and load it.
That's it, and for the fragment part all you have to do is define the VR and Image views in the fragment and then write the required code in the fragments class.


text:
Q: Detecting middle mouse click event jQuery I want to show a jQuery-UI dialog box as a popup when user clicks on left mouse button or the middle one. It works for left click (I get the alert box and after that the popup) but doesn't work for middle (neither alert box nor popup). What am I missing?
$('a.external').live('click', function(e){
  if( e.which <= 2 ) {
    e.preventDefault();
    alert ("inside if");
  }
  popUp.start(this);
});

A: To get this working fully in Firefox (40.0.3), I had to implement .on('mouseup', fn), as follows:
$(selector).on('mouseup', function (e) {

    switch (e.which)
    {
        // Left Click.
        case 1:
            // By way of example, I've added Ctrl+Click Modifiers.
            if (e.ctrlKey) {
                // Ctrl+LeftClick behaviour.
            } else {
                // Standard LeftClick behaviour.
            }
            break;

        // Middle click.
        case 2:
            // Interrupts "Firefox Open New Tab" behaviour.
            break;

        // Default behaviour for right click.
        case 3:
            return;
    }

    // Pass control back to default handler.
    return true;
});

A: Use mousedown or mouseup instead of click. And (unless you are using a very old version of jQuery) use .on() instead of .live():
$(document).on("mousedown", "a.external", function(e) {
   if( e.which <= 2 ) {
      e.preventDefault();
      alert ("inside if");
   }
   popUp.start(this);
});

...where ideally you'd use a parent element much closer to the link than document.
Demo: http://jsfiddle.net/7S2SQ/


text:
Q: How to get axis ticks out of d3 without rendering in SVG? I'm implementing a 2d chart using canvas. I want to reuse d3's logic for generating the chart's axes. d3 does quite a lot of good work in generating axes and I'd like to take advantage of it.
(Note: For backward-compatibility reasons I'm stuck using d3v3 for the time being.)
Consider the following d3 code:
let scale = d3.time.scale()
    .range([0, width])
    .domain([lo, hi]);
let axis = d3.svg.axis()
    .scale(scale)
    .ticks(num_ticks)
    .tickSize(10)
    .orient("bottom");

I can render this into a chart div with:
svg.selectAll('.x-axis').call(axis);

I want to be able to programmatically get the tick data out of axis, including the formatted labels, by writing a function that behaves as follows:
ticks = get_axis_ticks(axis)

ticks should hold each tick position (as a Date in this particular case) and the corresponding d3-generated label.
[[Date(...), "Wed 19"],
 [Date(...), "Fri 21"],
 [Date(...), "Apr 23"],
 [Date(...), "Tue 25"],
 ...]

I could then use this data to paint an axis on my canvas.
I've dug into d3v3 source (in particular here: https://github.com/d3/d3/blob/v3.5.17/src/svg/axis.js) but I find it very difficult to tease apart the logic from the SVG manipulation.
Help would be much appreciated.

A: One idea I have is to use the scale function you have created to generate the ticks you desire and push them into an array.
As a very simple example, if you would like 10 ticks, each incrementing by a unit of 1, you could do something like this: https://jsfiddle.net/Q5Jag/3148/
//define dummy values
var lo = 1;
var hi = 10;
var width = 512
var scale = d3.time.scale()
    .range([0, width])
    .domain([lo, hi]);

//define your function
var get_x_axis = function() {
    let axisArr = [];
    for(var i = 0; i < 10; i++ ) {
    //calculate your value
    axisArr.push(scale(i))
  }
  return axisArr
}

//call it
let axisTicks = get_x_axis()

//log it
console.log(axisTicks)

I'm not sure if this is what you're looking for, but if you need further help just ask.

A: I was able to get this working. I found the time formatting strategy in the d3 docs: https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format_multi I believe this is the strategy that d3 itself uses by default when users do not provide a custom format.
I learned that simply calling scale.ticks(N) will return Nish ticks suitable for rendering on an axis. These tick values are chosen on natural boundaries. E.g., if you're working with a time axis, these ticks will be aligned on minute, hour, day boundaries.
Here's a solution:
let time_format = d3.time.format.multi([
  [".%L", d => d.getMilliseconds()],
  [":%S", d => d.getSeconds()],
  ["%I:%M", d => d.getMinutes()],
  ["%I %p", d => d.getHours()],
  ["%a %d", d => d.getDay() && d.getDate() !== 1],
  ["%b %d", d => d.getDate() !== 1],
  ["%B", d => d.getMonth()],
  ["%Y", () => true]
]);

let get_ticks = (width, lo, hi, num_ticks) => {
  let scale = d3.time.scale().range([0, width]).domain([lo, hi]);
  return scale.ticks(num_ticks).map(t => [t, time_format(t)]);
};


text:
Q: What are skeleton diagrams and what is their use in qft and many-body physics? How does one construct skeleton diagrams from specific Feynman diagrams (e.g. for the electronic Green function in QED and in many-body gases, for the polarization function, for the vertex function, for the photon Green function, for the phonon Green function)? Explanations and references for actual constructions would be greatly appreciated.
What is the use of skeleton diagrams in qft and in many-body physics?

A: Skeleton diagrams are usually used to discuss general properties of the perturbation series in field theory. They help to prove renormalizability of a theory, or to prove properties of  correlation functions.
However, they are not used in general for explicit calculation. (The main counter example is the Diagramatic Monte Carlo, that tries to compute high order of skeleton diagram series by doing Monte Carlo sampling of the diagrams.)
For example, Gavoret and Noziere (1964) used skeleton diagrams to find the exact low energy behavior of the propagator of bosonic condensates.
For a (quick) discussion of these diagrams, see for example Quantum Field Theory by Lewis H. Ryder (around p.350).


text:
Q: Mimicking WP7 Unlock Page Animation In my app, i need to create wp7 page unloak animation(ie sliding up the picture and unloak the device) how i can implement that in my app either with the help of xaml or with the help of C# code.

A: These are the steps to achieve wp7 page unlock animation
1.Create the following storyboards
 <Storyboard x:Name="LockScreenSlideAnimation">
       <DoubleAnimation Duration="0:0:1" To="-768"
       Storyboard.TargetProperty="
       (UIElement.RenderTransform).
       (CompositeTransform.TranslateY)"
       Storyboard.TargetName="LockScreenGrid" d:IsOptimized="True"/>
 </Storyboard>

    <Storyboard x:Name="CoastGrid" >
 <DoubleAnimationUsingKeyFrames
   Storyboard.TargetName="LockScreenGrid"

    Storyboard.TargetProperty="(UIElement.RenderTransform)
    .(CompositeTransform.TranslateY)">
                    <EasingDoubleKeyFrame x:Name="coastY"
            KeyTime="00:00:01" Value="0">
                    </EasingDoubleKeyFrame>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>

2.Assume that the grid name is LockScreenGrid [Image Grid which will fly up on tap]
<Grid Grid.Row="1" x:Name="LockScreenGrid" Visibility="{Binding

  LockScreenGridVisibility}"
   ManipulationDelta="lock_ManipulationDelta"
    ManipulationCompleted="lock_ManipulationCompleted" >

3.Implement lock_manipulationCompleted, lock_ManipulationDelta
 private void lock_ManipulationCompleted(object sender, ManipulationCompletedEventArgs
  e)
    {
        if (this.gridTranslate.TranslateY< 0.0)
        {
            IEasingFunction function;
            this.CoastGrid.Stop();
            this.gridTranslate.TranslateY = e.TotalManipulation.Translation.Y;
            if((e.IsInertial)&& (e.FinalVelocities.LinearVelocity.Y<-1500)  ||
            (this.gridTranslate.TranslateY<(base.ActualHeight/-2.0)))
            {

                this.coastY.Value = (-1.0 * this.LockScreenGrid.ActualHeight);
                function = new CircleEase();
                ((CircleEase)function).Ease(1.0);
            }
            else
            {
                this.coastY.Value = 0.0;
                function = new BounceEase();
                ((BounceEase)function).Ease(0);
                ((BounceEase)function).Ease(2);
                ((BounceEase)function).Ease(5.0);
            }
            this.coastY.EasingFunction=function;
            this.CoastGrid.Begin();
        }
    }
    private void lock_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
    {
        e.Handled = true;
        this.gridTranslate.TranslateY = (this.gridTranslate.TranslateY +
        e.DeltaManipulation.Translation.Y);
        if(this.gridTranslate.TranslateY>0.0)
        {
            this.gridTranslate.TranslateY = 0.0;
        }
    }


text:
Q: How to eliminate the error "XamlParseException: Set connectionId threw an exception"? I develop WPF Prism 6 MVVM multimodule application. Until today everything was OK. But this morning I decided to clean and rebuild my application. And after cleaning and rebuilding I have the following error when my application runs: System.Windows.Markup.XamlParseException" in PresentationFramework.dll. Set connectionId threw an exception: number of line is "5" position in line is "14". I've done all (clean and rebuild my application, e.t.c... in general everything that was suggested in the web to this case) but none of this helped me. You can see the error below.

What the reason of the error? How to eliminate it? Please help.

A: The "Set connectionId" is a bug in the XAML code generator. Look at this answer: https://stackoverflow.com/a/5642898/200443.
The problem can also occur if loading a Wpf related assembly fails (Xceed.Wpf.Toolkit.dll for not naming it).


text:
Q: How do I import a jQuery library into Vue.js From a HTML template i am converting to vue js application with Laravel
so like
There is function which is drag and drop table
 src="assets/js/jquery.dataTables.min.js">
 src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js">

And Table is like

                                Name
                                Lead Source
                                Value

                                lOREM IPSUM
                                Website
                                 $ 750,000.00

$(document).ready(function() {
  var $tabs = $('.t_draggable')
  $("tbody.t_sortable").sortable({
    connectWith: ".t_sortable",
    //items: "> tr:not(:first)",
    appendTo: $tabs,
    helper:"clone",
    zIndex: 999990
  }).disableSelection();

  var $tab_items = $(".nav-tabs > li", $tabs).droppable({
    accept: ".t_sortable tr",
    hoverClass: "ui-state-hover",
    drop: function( event, ui ) { return false; }
  });
});

Now When i try with vue js
i included file
require('../jquery.dataTables.min.js');
Than
mounted: function() {
        console.log('initilizede -adfg');
        var $tabs = $('.t_draggable')
        $("tbody.t_sortable").sortable({
            connectWith: ".t_sortable",
            //items: "> tr:not(:first)",
            appendTo: $tabs,
            helper:"clone",
            zIndex: 999990
        }).disableSelection();

        var $tab_items = $(".nav-tabs > li", $tabs).droppable({
            accept: ".t_sortable tr",
            hoverClass: "ui-state-hover",
            drop: function( event, ui ) { return false; }
        });

}

So nothing is happend
If someone can help with that how can we used Jquery Library in Vue js with Laravel
I am very thankful to all

A: You need to run
npm install jquery --save
Open file build/webpack.base.conf.js and add plugins:
Add:
const webpack = require('webpack')
module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
      jQuery: 'jquery'
    })
  ]
  ...
}

A: Use ProvidePlugin
Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:
plugins: [

  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]


text:
Q: How will I identify resource default url in laravel? I am running this command for model, migration, resource controller.
`php artisan make:model QuestionAnswer -mc -r` ..

Laravel give me in Resource Controller
public function show(QuestionAnswer $questionAnswer) {
        // return $questionAnswer;
 }
public function edit(QuestionAnswer $questionAnswer) {
    // return $questionAnswer;
}
public function update(Request $request, QuestionAnswer $questionAnswer){
  // return $questionAnswer;
}

if I write in web.php
Route::resource('question-answer','QuestionAnswerController'); or
Route::resource('questionAnswer','QuestionAnswerController'); or
Route::resource('question_answer','QuestionAnswerController');  laravel resolve route model binding...
that means....
Example as a
public function edit(QuestionAnswer $questionAnswer)
    {
        return $questionAnswer;
    }

$questionAnswer return object  for this url {{route('admin.question-answer.edit',$questionAnswer->id)}}
but if I write in web.php Route::resource('faq','QuestionAnswerController');
laravel can not resolve route model binding...
that means.. $questionAnswer return null for this url {{route('admin.faq.edit',$questionAnswer->id)}}
also in show and update function $questionAnswer; return null...
for working as a faq url.. i need change in  edit function variable($faq)  . or Route::resource('faq','QuestionAnswerController')->parameters(['faq' => 'questionAnswer']);I
But These  three url questionAnswer,question-answer,question_answer by default work...
I check it on "laravel/framework": "^6.0" (LTS)
Question
is there possible way to find out what exact url I will  write ? .. like question-answer.. or is there any command line ...
after running auth command .. php artisan route:list command give us all route list.. and when I make model Category laravel create table name categories and follow grammar rules

A:
How will I know I need to write question-answer this ? by default it works... when i write faq i need to change in edit function variable($faq) .
How will I know by default url (question-answer) will work ..when php
artisan route:list command give us all route list.. and when I make
model Category laravel create table name categories and follow grammar
rules

think about i will create 20 model ,migration & controller by cmd... i will not change edit,show and update function variable ...how i will know the default url for 20 model and controller ?
Laravel is an opinionated framework. It follows certain conventions

Let us understand a route parts
Route::match(
    ['PUT', 'PATCH'],
    '/question-answer/{questionAnswer}',
    [QuestionAnswerController::class, 'update']
)->name('question-answers.update')

In the above route:
1st argument: ['PUT', 'PATCH'] are the methods which the route will try to match for an incoming request
2nd argument: '/question-answer/{questionAnswer}' is the url wherein
/question-answer is say the resource name and
{questionAnswer} is the route parameter name
3rd argument: [QuestionAnswerController::class, 'update'] is the controller and the action/method which will be responsible to handle the request and provide a response
When you create a model via terminal using
php artisan make:model QuestionAnswer -mc -r
It will create a resource controller for the 7 restful actions and take the method parameter name for show, edit, update and delete routes as camel case of the model name i.e. $questionAnswer
class QuestionAnswerController extends Controller
{
    public function show(QuestionAnswer $questionAnswer){}

    public function edit(QuestionAnswer $questionAnswer){}

    public function update(Request $request, QuestionAnswer $questionAnswer){}

    public function delete(QuestionAnswer $questionAnswer){}
}

Which means if you don't intend to change the parameter name in the controller methods then you can define the routes as below to get the benefit of implicit route model binding
//Will generate routes with resource name as questionAnswer
//It would not be considered a good practice

Route::resource('questionAnswer', QuestionAnswerController::class);

//OR

Route::resource('question-answer', QuestionAnswerController::class)->parameters([
    'question-answer' => 'questionAnswer'
]);

//OR

Route::resource('foo-bar', QuestionAnswerController::class)->parameters([
    'foo-bar' => 'questionAnswer'
]);

RFC 3986 defines URLs as case-sensitive for different parts of the URL. Since URLs are case sensitive, keeping it low-key (lower cased) is always safe and considered a good standard.

As you can see, you can name the url resource anything like foo-bar or question-answer instead of questionAnswer and yet keep the route parameter name as questionAnswer to match the Laravel convention when generating controller via php artisan make:model QuestionAnswer -mc -r and without having to change the parameter name in controller methods.
Laravel is an opinionated framework which follows certain conventions:

*

*Route parameter name ('questionAnswer') must match the parameter name in controller methods ($questionAnswer) for implicit route model binding to work

*Controller generated via artisan commands, have parameter name as camelCase of the model name

*Routes generated via Route::resource('posts', PostController::class) creates routes with resource name equal to the first argument of the method and route parameter name as the singular of the first argument

*Route::resource() provides flexibility to use a different name for route resource name and route parameter name
Read more at Laravel docs:

*

*https://laravel.com/docs/8.x/controllers#restful-naming-resource-route-parameters

*https://laravel.com/docs/8.x/controllers

*https://laravel.com/docs/8.x/routing#route-model-binding
If you want to know how the php artisan make:model works you can study the code in vendor/laravel/framework/src/Illuminate/Foundation/Console/ModelMakeCommand.php and have a look at the various stubs these commands use to generate the files.
For almost all artisan commands you will find the class files with code in
vendor/laravel/framework/src/Illuminate/Foundation/Console and the stubs used by the commands to generate files in vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs folder.
If you study these command classes properly then you will get an idea of the various conventions Laravel follows when generating files via the artisan commands

A: Actually Laravel has got Naming Convection Rules In its core.
These Convictions make it to default binding database_tables to model, model to controllers ....
if you want, you can tell your custom parameters but if you dont, The Laravel uses its own default and searching for them.
for example: if you have a model named bar, laravel look for a table named plural bars . and if you dont want this behave, you can change this default by overriding the *Models* $table_name` attribute for your custom parameter.
There are some Name Convection Rules Like :

*

*tables are plural and models are singular : its not always adding s (es) in trailing.
sometimes it acts more complicate. like : model:person -> table: people

*pivot table name are seperate with underline and should be alphabetic order: pivot between fooes and bars table should be bar_foo (not foo_bar)

*table primary key for Eloquent find or other related fucntion suppose to be singular_name_id : for people table : person_id

*if there are two-words name in model attribute, all of these are Alias :
oneTwo === one_two == one-two
check this out:
class Example extends Model{

 public function getFooBarAttribute(){
    return "hello";
}
}

all of this return "hello" :
 $example = new Example();
 $example->foo_bar();
 $example->fooBar();
 // $example->foo-bar() is not working because - could be result of lexical minus

there is a page listing laravel naming conventions :
https://webdevetc.com/blog/laravel-naming-conventions/

Name Conventions : is The Language Between The Laravel and Developer
it made it easy to not to explicitly mention everything
like Natural Language we can eliminate when we think its obvious.
or we can mention if its not (like ->parameter(...)).

A: I think its becuse of dependency injection which you used in youre method.
Try this
public function edit($id)
    {
        // return $questionAnswer;
        return view('backend.faq.edit',get_defined_vars());
    }


text:
Q: Must I use ActiveXObject to open a powerpoint presentation in html I have the following code snippet which simply opens a Powerpoint presentation and calls a VBA macro.
function CallVBA()
{
    var App;
    App = new ActiveXObject("PowerPoint.Application");
    App.Visible = true;
    App.Presentations.Open("D:\\Jonathan\\PPtHymns\\b.pptm");
    App.Run("Doit");
}

While this works fine on Windows, it does not work on a Mac because of using ActiveX objects.
Is there another way of opening a Powerpoint presentation within a html page?
This may appear to be trivial, but I wish use code to add several new slides and text into the presentation and then run the presentation manually when done.

A: There appears to be no alternative at present.
As I wanted to build up slides from Excel spreadsheets, the only way to make this happen on both Mac and PC is to create a tab delimited file output from excel. Open the powerpoint app and use javascript/typescript in Script Lab.
So far this can not be done 100% as I can not see any javascript/typescript api's for inserting audio and text shapes and setting slide tansition properties. Perhaps I have missed them. Would someone please confirm?
Many thanks.


text:
Q: Dropdown can't pull number value from object (Angular 4) I'm pulling data from an API, which is going fine unless I bind my JSON option number value into the [value] tag. see example:
WORKING (data got from API is selected on the option)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.name">{{ c.name }}</option>
</select> <!-- select with c.name on value -->

NOT WORKING (data is not selected and the first option is null)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.value">{{ c.name }}</option>
</select> <!-- select with c.value on value -->

JSON object:
subdimension = [{'name': 'sub1','value': 2  },
  {'name': 'sub2','value': 4 },
  {'name': 'sub3','value': 8}]

What I want to do is to bind a number value into some selects and then sum all of them like:
data.from.api.one + data.from.api.two...
EDIT:
Component code from the data.from.api
constructor (public dataService:DataService){
    this.dataService.getData().subscribe(datas => {
      this.datas = datas;
    });
  }

getData(){
return this.http.get('https://api.url/').map(res => res.json());
              }

datas:Data[];

data = {
  from:{api:{one:'',two:'',three:''}}
}

A: Everything works. i have created plunker. You need to setUp ngModel value after request.
<select [(ngModel)]="data.from.api.one" class="form-control">
 <option *ngFor="let c of subdimension; let i = index" [ngValue]="c">{{
   c.name }}</option>
 </select>

and if you want pure number
<select [(ngModel)]="data.from.api.one" class="form-control">
 <option *ngFor="let c of subdimension; let i = index" [value]="c.value">{{
   c.name }}</option>
 </select>

In your code use this code in ngOnInit hook
return this.http.get('https://api.url/').map(res => res.json()).do((d) => {

     this.subdimension = d;
        //if you use object
        this.data.from.api.one = d[0]
        //if you use value
        this.data.from.api.one1 = d[0].value
     })

or
 this.dataService.getData().subscribe(datas => {
  this.datas = datas;
   this.data.from.api.one = datas[0]
        //if you use value
        this.data.from.api.one1 = datas[0].value
});


text:
Q: How do I tell groovy to load all of the dependencies listed in my Maven pom.xml file when running a groovy script? I have a Java application that uses Maven, so the Maven POM file (pom.xml) lists all of the dependencies needed to compile and run the application.
I'd like to use groovy during my development and testing and then plug in the code into the Java files when I'm done.   I haven't done this yet so it might not be feasible but if it is, that is what I'd like to try and do.
I would like to know if there is a function I can call that will read my pom.xml file and add all of the dependencies to my classpath so I can just import the packages that I need and goovy will already have them loaded (or at least know where to load them).
The groovy script might look like this:
addAllPomDependenciesToMyClasspath();

import my.code.pkg1;
import my.more.code.pkg2;

(new ClassInMyCode()).doCoolStuff();

Without this, I need to specify all my jars on the CLASSPATH and it would look something like this (I haven't yet done this because there are too many dependencies).
#!/bin/sh
groovy -cp "../lib1/target/MyJar1.jar:../lib2/target/MyJar2.jar:$HOME/.m2/repository/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar: KEEP LISTING THESE UNTIL ALL DEPENDENCIES ARE INCLUDED"

Perhaps a better solution would be just to create a gradle file.  Let me know if that is the preferred way (if there is no way to autoload all of the maven dependencies).
What have I tried
I've tried searching for solutions and found several ways to add your dependencies to the class path but they don't answer my question.
Some results were:

*

*How to add multiple jars to the classpath of groovyConole/groovysh?

*How do I auto load a database jar in Groovy without using the -cp switch?

*Dynamically load jar in groovy

*Including all the jars in a directory within the Java classpath
I'm guessing there is a "groovy" way to do this that approaches the problem differently and that is why I haven't found an answer to this question.
Misc Notes
(Q) How can I add multiple jar files to my groovy classpath? (A) Use "-cp jar1;jar2" (in Windows use semi-colons to separate the names of the jar files, and in Unix use colons to separate the filenames.  See https://stackoverflow.com/a/219801/3281336


text:
Q: How to do meta tag and title unit test in React for react-helmet? How to do unit test in enzyme for checking <title> and <meta /> exist and its content ?
index.test.js
describe('<Helmet />', () => {
  it('should render an <Helmet> tag', () => {
    let wrapper = mount(
      <IntlProvider locale='en'>
        <ThemeProvider theme={theme}>
          <Helmet />
        </ThemeProvider>
      </IntlProvider>
    );
    console.log(wrapper.find('title').length);
    // expect(document.title).to.equal('My page title);
  });
});

index.js
const App = ({ intl }) => {
  const domain = window.location.hostname;
  return (

      <Helmet>
        <title>My page title</title>
        <meta name="title" content="meta content" />
        <meta name="description" content="meta description" />
        <meta property="og:title" content="meta title for fb" />
        <meta property="og:description" content="meta description for fb" />
        <meta property="og:url" content={`https://${domain}/`} />
      </Helmet>

      <CookiesProvider>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route component={NotFoundPage} />
        </Switch>
      </CookiesProvider>

  );
};

A: There is always a chance in shallow testing the exact component:
export const App = ({ intl }) => {
  const domain = window.location.hostname;
  return (

      <Helmet>
        <title>My page title</title>
        <meta name="title" content="meta content" />
        <meta name="description" content="meta description" />
        <meta property="og:title" content="meta title for fb" />
        <meta property="og:description" content="meta description for fb" />
        <meta property="og:url" content={`https://${domain}/`} />
      </Helmet>

  );
};

Test code:
it("<meta> and <title> exists with proper content", () => {
  const wrapper = shallow(<App />);

  const title = "My page title";
  const metaTitleContent = "meta content";
  const metaDescriptionContent = "meta description";

  expect(wrapper.find("title").text()).toBe(title);
  expect(document.title).toBe(title);

  expect(
    wrapper.find("meta[name='title']").props().content)
  .toBe(metaTitleContent);

  expect(
    wrapper.find("meta[name='description']").props().content)
  .toBe(metaDescriptionContent);
});