text:
Q: Getting package name or app name using a specifc intent I need some help regarding getting the package name or the application name that is using a specific intent say Camera.
I am developing an application that scans which application is using the camera in background or some other like microphone etc. But I couldn't find any way to get the such detail.
Any help would be appreciated.
Thanks

A:
Also please tell me if I can display a dialog asking some permission
  for using the camera like in marshmallow 6.0. I need such thing to do
  in device below marshmallow 23 api. Like launching the camera app
  should ask the permission in a dialog and if I click on no it should
  close the camera app

For Android Marshmallow ,  whenever you want to launch camera you should check whether you have permissions for accessing camera and if not you can request for permissions by showing the system dialog -
 if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1001); //May be any number
  } else {
       //Launch camera since you have the permission
}

Also, you have to implement onRequestPermissionsResult() callback so that you can check the user action on the permission dialog and react accordingly -
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001 : //Same request code
                if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this,"Camera permission requied", Toast.LENGTH_LONG).show();

                } else if (grantResults.length > 0 && (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
                    //Launch camera
                }
                break;
        }
    }


text:
Q: Some good books for ODE and Dynamical system. I am trying to shift my research area from Pure math to math bio for various reasons. So whatever time I invested in my algebra is not of much use plus I have to make the basics of ODE and the Dynamical system strong. I was reading Teschl's book on ODE and the Dynamical system and I felt it very hard to have a good hold on the base concept while reading the book. It is not the case that I don't understand it. Rather I can't grasp the inner concept well. I didn't read Strogatz Nonlinear Dynamics before but now I am enjoying it.

*

*Is there any other ODE-Dynamical system(if it is focused on oscillation theory that's a plus) undergraduate to graduate level bridging book and some books that give a deeper insight in an easier way and make the concept and problem-solving skills clearer?

*In pure math there are some books that state learning through problems and they try to build the conception with a series of easy problems. You can also refer to those books.

This will be of great help because I believe in making my base strong. Please don't suggest me a hard book. When I am finding Teschl hard and Strogatz good. You can get an idea.
E.g. I liked one undergraduate thesis on Floquet theory very helpful. It will be good if I get some easy to moderate to hard problems to solve with hints. What I really care for is learning about Existence,uniqueness, regularity
Sturm Liouville, Sturm comparison theorems
Linear stability, Liapunov stability, Hamiltonian, gradient systems
Poincare bendixson theorem
Some basic dynamical systems like omega limit sets
Floquet Theory
Linear ODEs etc etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AVPlayer and Progressive Video Downloads with AVURLAssets We've got an app we're working on that needs to provide playback of video files via AVPlayer. The files need to be stored on the user's device, but also must playback while downloading.
At the moment we've built a download module that uses the ASIHTTPRequest library to get the video files via PHP (we don't want the media to be linkable via public URLs) and write them to disk asynchronously.
We've then setup an AVPlayer as per the AV Foundation Programming Guide, getting the file with AVURLAsset, making an AVPlayerItem with the asset, building the AVPlayer with the item, then setting the player to an AVPlayerLayer. The player runs fine with a fully downloaded video file and will also run a progressively downloaded file perfectly well in the simulator.
Unfortunately on an actual device, the behavior of the player changes, where instead it seemingly loads the video once and doesn't attempt to grab new packets from disk. The result is that the player will play video and audio up to the point in the video that marks where the download progress was at the time the asset was loaded (e.g. if 2MB of data are buffered then the player is created, the player will only play up to the 2MB worth of data). Because it has the video's header, the player will happily continue thinking it's playing for the full duration of the video, but no other video is rendered to screen.
The last wrinkle is that if the video is inserted into an AVComposition and the AVPlayer is created with that, the progressive video will play fine. This would be a fine solution (and is necessary for our app anyway on occasion) except that the client for our app requires that the video be playable on an Apple TV via AirPlay, which AVCompositions are incapable of.
Does anyone know if there is a way to play progressively downloading video files using an AVPlayer built from AVURLAssets? Is there a way to force the player/playerItem to read from disk with an AVURLAsset the way it seems to do with an AVComposition instead of seemingly caching the video in memory?
Thanks!

A: I haven't a solution to just make it work wit AVURLAssets but I use a slightly different approach. We bundle our App with CocoaHTTPServer and play video files which aren't fully downloaded trough a HTTP request against the local server.
The server knows the total length of the file and can then decide by looking at the HTTP-Headers which part of the file is request and either loads it from disk or from remote source.
While developing this there where always 3 initial requests, one for the first two bytes of the file, one of a larger chunk from the beginning of the file and one chunk directly of the end of the file. That's why it was always needed to load at least the last part directly from the remote server since the player would need it right from the start. I would guess the same happens for local files so the player loads the last bytes from the file (which aren't the right last bytes) and won't play over that length.
You would have to subclass HTTPConnection and make your own HTTPResponse class by looking at the provided "HTTPAsyncFileResponse".
I hope this gives you an idea how to accomplish this with a different approach.


text: Q: Migrating SafetyNet to Play Integrity API for Firebase I'm developing a flutter application which uses Firebase as its framework. One of Firebase's features that we use is App Check. I've been using SafetyNet for my Android App Check, but recently I've gotten an email from Google that states that SafetyNet will be discontinued and developers are recommended to migrate to Play Integrity. The problem is, I don't know how to do so, I've tried changing it directly from Firebase Console, and now both my Play Integrity and SafetyNet option is checked, last time it was only SafetyNet. Are there any steps that I might've missed? Any help would be greatly appreciated.


text:
Q: echo $_POST['code']; error in google chrome I have one page where I submit hidden form where I store a large html code that is made in javascript and I want to send that code via form to another php file. It should work but my browser blocks it(google chrome):
<form action="napravi.php" method="post">
<input type="text" name="code" value=""/>
<input type="submit" id="forma_napravi"/>
</form>

and in javascript:
document.getElementById("forma_napravi").click();

and php page where I send the form data:
if(isset($_POST['code'])){
echo $_POST['code'];
}

and this is error that browser shows to me:

A: give your form an id and check if it is been submitted. like this-
In your html file
<form action="napravi.php" method="post" id="form">
  <input type="text" name="code" value=""/>
  <input type="submit" id="forma_napravi"/>
</form>

In your javascript
document.getElementById("form").on('submit', function(){
   // your code
});

Hope this will help

A: It will show error if you send html or javascript code this way because it is google chrome's in-built design.
I tried your code it was working. But when I put some code in place of blank, e.g. value="<script>alert('123');</script>", I got the same error

You may use htmlentities() to parse the html to string. Then the code you send will have no effect at all.


text:
Q: issue about willAnimateRotate and didRotateFrom when doing an rotation What I am having so far is
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    NSLog(@"willAnimateRotationToInterfaceOrientation");
    if(toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        NSLog(@"PortraitUpsideDown");
        // Do method A
    } else {
        [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        // Do method B
    }
}

and
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSLog(@"didRotateFromInterfaceOrientation");
    if( fromInterfaceOrientation == UIInterfaceOrientationPortrait || fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        NSLog(@"OrientationPortrait or PortraitUpsideDown");
        [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        // Do method B
    } else {
        NSLog(@"From else");
        [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        // Do method A
    }
}

My logic is after hitting the RUN from xcode, willAnimateRotationToInterfaceOrientation: is going to be called because I set Supported Device Orientation to be UpsideDown from Summary of MyApp.xcodeproj. Moreover, I also think that didRotateFromInterfaceOrientation: should not be called because we have just started the app yet. It means there are no previous states at all.
Unfortunately, this is what I got after doing the debugger

2012-02-11 12:04:08.776 MyApp[7505:10703] willAnimateRotationToInterfaceOrientation :
2012-02-11 12:04:08.776 MyApp[7505:10703] PortraitUpsideDown
2012-02-11 12:04:08.778 MyApp[7505:10703] didRotateFromInterfaceOrientation :
2012-02-11 12:04:08.779 MyApp[7505:10703] OrientationPortrait or
  PortraitUpsideDown

I am getting lost now. Does anyone have any ideas about the issue, please help. Thanks.

A: I have had some issues with rotation, similar to yours. The short version is that the will and did methods are not 100% reliable. You should try rapidly rotating back and forth and see what happens. It could be because I am pretty new, or it could be an actual bug. What I did was, in didRotateFromInterfaceOrientation:, check the current orientation and act accordingly:
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation) {
// do your portrait stuff
} else {
// do your landscape stuff
}

Before I found the UIInterfaceOrientationIsPortait test I was actually checking the frame to see if self.view.frame.size.width > self.view.frame.size.height, and that is also reliable but kind of ugly.
Either way is reliable. I have a couple apps in the store, QPalettes and QColor, that do rotation on a bunch of user-created onscreen elements. What I had to do is store the dimensions, and after didRotateFromInterfaceOrientation I check the new dimensions and if they are different, re-draw everything onscreen. Contact me if you'd like a promo code to check out the rotation in either app (they rotate the same - QColor is more complex since it also draws intersections).
Enjoy,
Damien


text:
Q: Overridden and non-overridden constructor I just wanted to ask a simple question - I have a class derived from TLabel as follows:
TMyLabel = class (TLabel)
  ...
  constructor Create(AOwner: TComponent); override;
end;

constructor TMyLabel.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  { some code }
end;

Now, Delphi lets me compile both versions with and without the override. Could you explain what the differences are? Other than being unable to request my own parameters in Create() when overridden. Thanks
Edit: What I mean is - what is the difference between a virtual and a nonvirtual base-descendant constructors? I can always call the inherited constructor by inherited Create(), so what's the point?

A: Virtual constructors allow for polymorphic instantiation of objects. The classic example of this is Delphi's .dfm streaming mechanism.
The code that reads .dfm files and instantiates forms does not know at compile time which classes to use. The decision is postponed until runtime when it can be made correctly, i.e. when the .dfm file is read. Moreover, you can get the .dfm file mechanism to create custom components that are not part of the VCL and so this .dfm mechanism must be capable of correctly instantiating classes that are not part of the VCL.
The constructor for TComponent is declared like this:
constructor Create(AOwner: TComponent); virtual;

For a component to take part in this mechanism it must declare its constructor with the override directive.
The other key to the process is class references. For example
type
  TComponentClass = class of TComponent;

The code that creates components when reading .dfm files, roughly, looks like this:
var
  ComponentClass: TComponentClass;
  Component, Owner: TComponent;
....
ComponentClass = FindComponentClass(ReadComponentClassName);
Component := ComponentClass.Create(Owner);

Now, if the mechanism did not use virtual constructors then the constructor that would be called would be TComponent.Create. And so your constructor, TMyLabel.Create would never be called.
This is why you must include the override directive on your constructors when deriving from TComponent.

A: Well, if I remember Delphi correctly (that was a while ago, though it was good time :) ) when constructor is overriden you'll be able to call it via class references (see this spec as example).


text:
Q: Generation of unique IP-port using bind(0) I need to generate port numbers for some programm. Google tells, that bind with zero-port generates binds unused port. I want to bind zero-port, remember it's number, close port. Trying to do this? but netstat doesn't see my programm's port.  Linux 2.6.27
int sfd;
struct sockaddr_in my_addr;

sfd = socket(PF_INET , SOCK_STREAM, 0);
if (sfd == -1)
{
    printf("socket error\n");
    return -1;
}

memset(&my_addr, 0, sizeof(struct sockaddr_in ));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = 0;

if (bind(sfd, (struct sockaddr_in *) &my_addr,
        sizeof(struct sockaddr_in)) == -1)
    printf("bind error\n");

if (listen(sfd, LISTEN_BACKLOG) == -1)
    printf("listen error\n");

A: bind() expects a sockaddr* not a sockaddr_in*:
bind(sfd, (struct sockaddr *) &my_addr, sizeof(my_addr))

Other than that, I don't see any other errors.  Binding to port 0 is the correct way to bind to a random available port.  If bind() and listen() do not report a failure then netstat should see an open port. Use getsockname() to find out which port bind() actually chose, eg:
int sfd = socket(PF_INET , SOCK_STREAM, 0);
if (sfd == -1)
{
    printf("socket error: %d\n", errno);
    return -1;
}

struct sockaddr_in my_addr;
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = 0;

if (bind(sfd, (struct sockaddr *) &my_addr, sizeof(my_addr)) == -1)
{
   printf("bind error: %d\n", errno);
   close(sfd);
   return -1;
}

if (listen(sfd, LISTEN_BACKLOG) == -1)
{
    printf("listen error: %d\n", errno);
    close(sfd);
    return -1;
}

memset(&my_addr, 0, sizeof(my_addr));
socklen_t my_addrlen = sizeof(my_addr);

if (getsockname(sfd, (struct sockaddr *) &my_addr, &my_addrlen ) == -1)
{
    printf("getsockname error: %d\n", errno);
    close(sfd);
    return -1;
}

printf("listening on port: %hu\n", ntohs(my_addr.sin_port));


text:
Q: How to detect deviation in path between coordinates set I have coordinate data(lat,long) of various vehicles travelling from similar source to similar destination.
There are some cases when these vehicles do not follow the regular path while going from source to destination. I am trying to find those coordinate sets where there is change from standard path.
I have latitude, longitude and time. I have to analyse the changes in path and detect the position of path change as well. I have large set of data, so i am trying to find an optimal way of doing this.
I know a bit about hausdorff distance and Jackardd Similarity. But i am trying to get more efficient way, since my data set is near to 1TB.
Also, if there is any easy way to do this with PostGis. Please suggest.

A: For specified data amount, I'm afraid, QGIS wouldn't be a proper option. If you decide to go with PostGIS, you must bear in mind GPS accuracy of your source data. I mean, even if you go exactly the same route two times you're not necessarily getting two identical footprints.
However, the very first thing I would consider upon uploading your data into PostGIS, is simplifying (st_simplify()) it to get rid of vertices that are not essential and thus to boost further calculations speed.
Next, I would employ st_buffer() to wrap routes into buffers to tolerate GPS data deviation within some acceptable range.
After that, with combination of st_intersection() and st_area() I would measure the likeliness of two routes based on the common area of two buffers.
So, for three sample routes

The very basic query
select st_area(st_intersection(st_buffer(r1.geom,0.001),st_buffer(r2.geom, 0.001)))/st_area(st_buffer(r1.geom, 0.001)) as "blue2red",
    st_area(st_intersection(st_buffer(r1.geom,0.001),st_buffer(r3.geom, 0.001)))/st_area(st_buffer(r1.geom, 0.001)) as "yellow2red",
    st_area(st_intersection(st_buffer(r2.geom,0.001),st_buffer(r3.geom, 0.001)))/st_area(st_buffer(r2.geom, 0.001)) as "blue2yellow"
from route r1
join route r2
on r2.name='blue'
join route r3
on r3.name='yellow'
where r1.name='red'

returns
blue2red    yellow2red  blue2yellow
0.495408079 0.641252527 0.688753036

I guess, that looks like something to start with.


text:
Q: Does eclipse use Java Instrumentation API for Hot Code replace I recently had a task where I had to use hot code replace functionality. So I did it using the Java Instrumentation API available in tools.jar.
Does eclipse use some different logic for hot replace of new class files or uses same Java API ?
I tried to read from some places but was not clear:

Eclipse Java debugger transmits new class files over the debugging
  channel to another JVM

This line in Eclipse Hot Code Replace was not clear.

A: I believe eclipse use the same logic, they are both relying on a native interface called JVMTI. The JVMTI provide tools to inspect the state, and to control the execution of applications running in the Java virtual machine.
There is a agent of JVMTI in the Java Instrumentation Implementation. The agent to talks to vm and perform certain tasks. it also has redefineClasses method.
Eclipse Java debugger or other tools use the JPDA (Java Platform Debugger Architecture), and the JPDA mainly have three parts (JVMTI,JDWP,JDI). JVMTI act as debuggee,JDI act as debugger,and the JDWP act as communication channel between them.
In the end, they all talk to JVMTI,and it use the same logic.

A: No, debuggers usually use JDI.
com.sun.jdi.VirtualMachine#redefineClasses
See the following link for details.
http://docs.oracle.com/javase/7/docs/technotes/guides/jpda/index.html


text: Q: Rpyc - Is it possible to get the original type back from rypc? I am using Rpyc and have setup a client server model. The server sends Python objects but I'm having trouble working with them on the client side as their types changed (eg a dict won't be a dict but a netref.something) - is it possible to get the original type back?


text:
Q: How to structure Python modules so they are accesible from different submodules This is somewhat similar to this question but I could not find a solution there.
I have a project that I've worked on over the past 4 years. I started without any Python knowledge and learned as I went along, so there is a lot of legacy code and weird things that work but could break easily. I'm redoing this project with my current knowledge hoping to get a better system.
This is an embedded project that runs on a small linux board. I have my main "core" system (with its repo) and several subfolders:

*

*main folder: queue script, worker script

*p_connections (database, sftp and ssh libs)

*p_hardware (gpio access, adc, other busses)

*p_system (file system etc)

*p_worker (measurement scripts)

*p_logging (log handlers)

*p_sensors (hw access to the sensors and processing for their raw data)

Some of these modules are used elsewhere (in other projects) as well (such as p_sensors) and I plan to incorporate them as a GIT submodule (as that seems to be the correct way to do this?).
However, some of these submodules need access to other submodules.
Some examples:

*

*The credentials modules needs to be able to read the database (p_connections module) but also log (p_logging module).

*The user needs to be able (for testing, ...) toggle gpio pins. There's script for command line control of these pins, but the pin mappings (which pins match which outputs on different boards) is inside the settings table in a database (so accessible with a script in p_connections)

I could use something like
from .../p_connections import credentials

but that doesn't seem very ...elegant.
Another option I see would be to add all my submodule paths to the python path, but that seems overkill.
How is this handled "properly"?
Most online replies that I seem to find are in line with "you're doing it wrong, that's not how you should structure a project", but that's not really helping. I've read a couple of books/articles that suggest to really think about your project structure before starting, but I can't seem to get it right...

A: If the various modules form a single project, they should be part of a common package and use relative imports (from ..foo import specific_function). For example, instead of this project layout:
my-project/
  scripts/
    ...
  p_foo/
    __init__.py
  p_bar/
    __init__.py

I would expect a layout like this, without any Git submodules or similar:
my-project/
  p/
    __init__.py
    __main__.py
    foo/
      ...
    bar/
      ...

(The __main__.py file allows the module to be used as a command line tool like python3 -m MODULE OPTIONS....)
If these modules should be installed and developed separately as their own packages, they should instead all have a setup.py so that they are PIP-installable, and declare their dependencies on the other packages. It is OK if the dependency is not resolved via PyPI but e.g. through a Git URL. With setuptools, the setup.py can declare entrypoints. These entrypoints will be installed by PIP in a way that allows them to be invoked as ordinary command line tools. By installing in development/editable mode (pip -e), this will not impede your edit–test cycle.
Approaches like setting the PYTHONPATH technically work, but that is only really suitable for self-contained applications that don't have to interact with other packages. But you should not expect that your scripts will only be invoked for a certain working directory in order to resolve imports, so setting the PYTHONPATH (or sys.path) can have merit. In my opinion, the previously suggested mechanism – to let PIP sort out the paths – is vastly superior.
A note on Git submodules: they are great for including some other repo at a local path. This is a good alternative to "vendoring" dependencies, i.e. to literally copying the source code of the dependency. However, you have to explicitly select a commit that the submodule should use – it will not automatically follow the HEAD of a repository. Thus, submodules are most appropriate for referencing stable-ish internal repositories that will be updated occasionally, but are entirely unsuitable for closely related projects that will be developed together. If you expect to regularly have changes that will span multiple projects, that can indicate that you should keep all components in a single monorepo.


text:
Q: 24 V DC solenoid coil with LED indication failing sometimes in reverse polarity I am giving power supply to a 24 V DC solenoid coil plug with an LED; positive from a PNP transistor board and negative directly from the SMPS.
When the PNP board energises the output terminal, the coil plug gets short-circuited and also it makes the transistor fail.
I think it happens when I am giving reverse polarity, but it does not happen to all the coil plugs. Some other coil plugs with LEDs are also reverse-polarised but are working well.
Can someone help me understand what makes the LED fail?

A: Usually there is surge protection on solenoid plugs with LED, but that protection could be a zener diode or a MOV.
If it is a MOV the solenoid will work in either direction but the LED will be reverse biased and will not work in the reverse direction. The LED will probably not be destroyed by this but it will typically exceed the reverse voltage rating.
If it is a Zener then the diode will be forward biased in the reverse direction and the driver will see a short circuit. This can destroy the Zener and/or the driver.


text:
Q: Passing parameters to buttons I'm dealing with a problem where I need to be able to pass particular arguments to a button's onClick method. What I want to do is something like this:
public class MainActivity extends AppCompatActivity {

    private static int clicked = 0;

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

        final ImageButton btn = findViewById(R.id.imageButton2);
        btn.setOnClickListener(new WhenClicked(btn, getApplicationContext()));
    }

    public static void incrementClicked()
    {
        clicked += 1;
    }
}

I know one way to make this work is by having our own "OnClickListener", but then I run into a problem of dealing with context since I want to spawn a new intent.
A solution like this could kind of work, but has some big problems
public class WhenClicked implements View.OnClickListener {

    private Context context; //this is obviously bad
    private ImageButton imgbtn;

    public WhenClicked(ImageButton imgbutton, Context context)
    {
        this.context = context;
        this.imgbtn = imgbutton;
    }

    @Override
    public void onClick(View view) {
        imgbtn.setColorFilter(Color.argb(150, 255, 255, 255));
        MainActivity.incrementClicked();
        //now to spawn an activity
    }
}

Edit: Since the question seems unclear, I've edited in my working solution. The problem now becomes finding a way that we don't need to store the context as an instance variable.

A: Move your button on Activity level and make it private, it will be visible inside inner class - OnClickListener. About context, you can access it inside onClick like this MainActivity.this.
public class MainActivity extends AppCompatActivity {

    private int clicked = 0;

    private ImageButton btn;

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

        btn = findViewById(R.id.imageButton2);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn.setColorFilter(Color.argb(150, 255, 255, 255));//sets a tint

                // PART YOU ARE INTERESTED IN
                clicked++;
                Intent intent = new Intent(MainActivity.this, Someclass.class);
            }
        });
    }
}

If you need this as your custom Listener Class you can do this:
public class CustomOnClickListener implements OnClickListener {
    int clicked = 0 ;

    @Override
    public void onClick(View v) {
        // here comes View, not ImageButton, so you should check if it is ImageButton and then set tint
        if (v instanceof ImageButton) {
            ((ImageButton)v).setColorFilter(Color.argb(150, 255, 255, 255));
        }

        // PART YOU ARE INTERESTED IN
        clicked++;
        Intent intent = new Intent(v.getContext(), Someclass.class);
    }
}

As you see here you have context - v.getContext() . Eveny View holds context, so it is accessible from clickListener and you don't need to pass it through constructor.

A: Actually there is no need to make anything static or pass context to another class. A simple way to do this would be to make your Activity implement OnClickListener. Set the current instance of Activity as click listener and get a callback in the onClick() method which has View as a parameter. You can easily get the image button's click here by checking the view id. This is also the best method to use when you have to deal with clicks of multiple views in your layout.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private int clicked = 0;

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

        final ImageButton btn = findViewById(R.id.imageButton2);
        //set click listener
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageButton2:
                 //Imagebutton is clicked
                 i++;
                 break;
        }
    }
}


text:
Q: How can I make the footer color match the header color? <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">

            Country
            OrderID
            Order Amount

            USA
            1000
            $1,300

            USA
            1001
            $700

            CA
            1002
            $2,000

            CA
            1003
            $1,000

                Total
                $5,000

styles.css
body {
    margin: 10px;
}

table, th, td {
    border: 1px solid #c4dcf3;
    border-left: 0;
    border-right: 0;
    border-collapse: collapse;
}

td, th {
    padding: 10px;
}

th {
    background-color: #427fef;
    color: white;
}

tr:nth-child(odd) {
    background-color: #eef7ff;
}

tfoot {
    text-align: left;
    background-color: #427fef;
}

In this example I am creating a table with several rows. I wanted the header and border to match in color while the odd rows of the table are a different color. I tried keeping the properties of the header and border the same but the didn't work. The code for the odd rows seem to override the desired color for the footer. I linked styles.css to the html document but the footer still isn't showing up like its suppose to.

A: You are using the tfoot tag incorrectly, see this: https://www.w3schools.com/tags/tag_tfoot.asp
I recommend reorganizing your html like this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">

                Country
                OrderID
                Order Amount

                USA
                1000
                $1,300

                USA
                1001
                $700

                CA
                1002
                $2,000

                CA
                1003
                $1,000

                Total
                $5,000

Now you can set styles with reference to the tfoot and tbody: tbody > tr
Refactored styles.css:
body {
    margin: 10px;
}

table, th, td {
    border: 1px solid #c4dcf3;
    border-left: 0;
    border-right: 0;
    border-collapse: collapse;
}

td, th {
    padding: 10px;
}

th {
    background-color: #427fef;
    color: white;
}

tbody > tr:nth-child(odd) {
    background-color: #eef7ff;
}

tfoot > tr {
    text-align: left;
    background-color: #427fef;
}

Now your last row is blue :)


text:
Q: css flexbox not interpreted inside iframe when I put content into iframe the header managing with flexbox has not the same render. Why iframe content different ?
https://codepen.io/lguigo/pen/JmKQEa
header {
            display: flex;
            justify-content: space-between;
            margin: 25px 10px 25px 10px;
            border-bottom: 25px solid #f2f2f2;
            padding-bottom: 25px;
        }

chrome responsive emulation OK :

this url inside iframe KO :

A: It makes no difference if its in an iframe or not. the real difference is the width of the container. The iframe is pretty small so the things in the header don't really fit. Try adding a flex-wrap: wrap; on the header. At least that will place the element under each other if they can't be next to each other.


text:
Q: Python Dataframe find the index of a second occurance of a string I have seen that similar questions have been psoted, but the solutions there do not work for me because, I believe, I am working with a column in a dataframe.
I have a column which has a string in it.  I find the first occurance of a term.  This works.  I then want to find the second occurance of that term.  This doesn't work.
My code
import pandas as pd
data = {"Text" : ["['one', 'one two']","['two one', 'three']"]}
df = pd.DataFrame(data)

#yes the data is in a list in a column but I treat it as a string

#finding if "one" is in the string - works
df["Ones"] = df.Text.str.find("one")
#finding if "one" is in the string another time as in the first row
df["NextOnes"] = df.Text.str.find("one",df.Ones +1)

The line for "NextOnes" returns NAs.  In my real code, it returns blanks.  If I replace the reference to the column with a number, such as 2, then this returns the correct value.  However this value needs to be dynamic.
I have just got this the needle haystack approach to work but building in for loops seems inefficient here,
 for i in range(len(df)):
...     df["Next"][i] = find_nth(str(df.Text[i]),"one",2)

A: You could try using the find method from str, but pass in the previous item index as starting point (as parameter to find).


text:
Q: JavaFX - How to have user draw boundary on screen overlay I am making an application that uses pixel recognition. One integral part of the application is it needs to have a general idea of where a item of interest will appear during the video game. I want to make a tool so the user can manually draw a box, my method can read the size of the box he drew, then can save that data as two Point variables.
Extremely oversimplified example below:

Let's say my program needs to now know the rough estimation of where the Princess is. The user presses the Calbirate button and then clicks and drags on the game and a red square such as below appears:

As soon as the user lets go over the mouse button, the program saves the coordinates (400, 15) and (480, 190) which is the start and end points of the box. My program then knows from what Point ranges the object we are looking for is in.
How can this be done? Note that this functionality is extremely common in many famous Screenshot programs such as ShareX or Greenshot.


text:
Q: CSS / HTML Header streches out of the screen on the right side. How to avoid that? I am trying to build a small Website but i have a problem with the header. Despite I set in the header the CSS
width:100%  position: fixed
it is alsways streching out of the screen.
I tried to  add this but it didn't work
html, body {
 margin: 0;
}

Here is the code of the Page. Any help would be appreciated.
Thank you in advance

/*-------------------
Base Style
---------------------*/

body{font-family: 'Inter', sans-serif; font-size: 16px;}

a{text-decoration: none;}

h1,h2,h3,h4,h5,p{color: #000; padding-bottom: 30px;}

.big-text{font-size: 70px; font-weight: 900;}
.medium-text{font-size: 40px;}
.normal-text{font-size: 20px;}
.small-text{font-size: 14px;}

.intro-text{text-transform: uppercase;font-size: 20px; font-weight: bold;}

.button{padding:18px 28px; background: #316bff;color:#fff;display: inline-block; border-radius: 4px;} /*sopra e sotto 18, destra sinistra 28*/

/*-------------------
Header
---------------------*/

.header{
    border: 1px solid red;
    width: 100%;
    position: fixed;
    top:0;
    left:0;
    padding: 30px;
    display: flex;
    background: #000;
}

.logo{
    border: 1px solid red;

}

.menu{
    border: 1px solid red;
    width: 100%;

}
.menu li{  display: inline-block;}
.menu li a{  color: #fff;padding:15px;display: block;}

.cta{
    border: 1px solid red;

}

/*-------------------
Hero
---------------------*/
.hero{
    background: yellow;
    height: 600px;
    display: flex; width: 100%;align-items: center;

}

.hero__content{
    border:1px solid red;
    width: 100%;
    max-width: 1350px;
    margin: 0 auto;
}

  /*Reset del padding degli elementi applicando il padding degli elementi all'interno degli elementi e non all'esterno
  Evitiamo sostanzialmente problemi di sovrapposizioni di elementi*/

  *,
  *:before,
  *after {
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
  }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" integrity="sha512-NmLkDIU1C/C88wi324HBc+S2kLhi08PN5GDeUVVVC/BVt/9Izdsc9SVeVfA1UZbY3sHUlDSyRXhCzHfr6hmPPw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;700;900&display=swap" rel="stylesheet">

Home

Single

Contact

        Contact

Intro Text

Title of the page

        Discover More


text:
Q: ASP.Net repeater control - using conditional statements I am trying to use an if statement inside of a repeater control and receiving an InvalidOperationException on the if.
What I'm trying to do is run a block of code inside the repeater only if the current item has a UserType that is set to Admin.
     <asp:Repeater ID="rptSingleValueHeaders" runat="server">
         <ItemTemplate>
             <% if (Eval("UserType").ToString() == "Admin") { %>

                     do stuff here

            <% } else { %>

                     do other stuff

            <% } %>
         </ItemTemplate>
     </asp:Repeater>

My datasource is defined on the aspx.cs and contains a property named UserType which is of type string. Let me know if I need to provide any more details. Thank you.

A: You could use server side visibility:
<ItemTemplate>
    <div runat="server" visible='<%# (Eval("UserType").ToString() == "Admin") %>'>
        I show this HTML

    <div runat="server" visible='<%# (Eval("UserType").ToString() != "Admin") %>'>
        I show this other HTML

</ItemTemplate>


text:
Q: Create MSI file from c# outlook addin in VS 2013 I have c# outlook addin created in visual studio 2013.
It has windows forms also.
I am getting mad on generating msi file, any easier solution/steps for me, please ?
Mainly tell me, after completing the process, where do I find the final MSI file (like bin/release folder) ?
I installed this - https://visualstudiogallery.msdn.microsoft.com/9abe329c-9bba-44a1-be59-0fbf6151054d
as well as installshield limited edition installer.
I was able to build it and ran the installation file(.exe) from disks folder and it is installing but not showing anything in the outlook.

A: Take a look at the Deploying an Office Solution section in MSDN. It describes two possible options for deploying your Office solution in depth:

*

*Deploying an Office Solution by Using Windows Installer

*Deploying an Office Solution by Using ClickOnce
It is up to you which way is to choose.

I was able to build it and ran the installation file(.exe) from disks folder and it is installing but not showing anything in the outlook.

There are multiple reasons why you don't see your add-in in Office applications.
First of all, make sure that you did all the steps described in the previously mentioned articles. Then I'd suggest checking the required windows registry keys for COM add-ins, see Registry Entries for Application-Level Add-Ins for more information.
Microsoft Office applications can disable add-ins that behave unexpectedly. If an application does not load your add-in, the application might have hard disabled or soft disabled your add-in.
Hard disabling can occur when an add-in causes the application to close unexpectedly. It might also occur on your development computer if you stop the debugger while the Startup event handler in your add-in is executing.
Soft disabling can occur when an add-in produces an error that does not cause the application to unexpectedly close. For example, an application might soft disable an add-in if it throws an unhandled exception while the Startup event handler is executing.
You can read more about that in the How to: Re-enable an Add-in That Has Been Disabled article in MSDN.
Finally, you may also check out the Trust Center settings in Outlook. The Macro Security settings can be applied to add-ins as well. May be it is required to sign the add-in with a digial signature and etc.


text:
Q: Jquery Queue Function I am writing a slide show. I finally have a good function for showing only one slide. It shows it exactly like I want with shoSlide wait for a time and then hide slide. No that I have this good for one slide, my problem is doing it for many.
function slideShow() {
    console.log("countdown Slide Count: " + numberOfSlides);

    console.log("Current slide number: " + jslideNumber);

    $('#slide' + jslideNumber).fadeIn(1000).delay(5000).queue(function (next) {
        console.log("Hiding Slide Number: " + jslideNumber);
        $('#slide' + jslideNumber).fadeOut(1000);
        next();
    });
}

slideShow();

I tried putting into a WHILE loop but using either loop WHILE or FOR results in an infinite counter. I was incrementing jslideNumber++ before but the problem is that the loop increments the counter faster than the queue can fire. So when Slide1 is showing, normally Slide1 should hide, but instead, Slide1 shows and then it tries to hide Slide6 by the time the delay catches up to the counter.

A: You can use "[id^=slide]" selector , $.map() , .dequeue()

var n = 150;

$.map(Array(n), function(val, index) {
  $("body").append("
"+index+"
")
})

$({}).queue("_fx", $.map($("[id^=slide]"), function(el) {
  return function(next) {
    $(el).fadeIn(1000, function() {
      $(this).delay(5000).fadeOut(1000, next)
    })
  }
})).dequeue("_fx")
[id^="slide"] {
  display:none;
}


text:
Q: What is the difference between deep and shallow history? How are they indicated? in uml What is the difference between deep and shallow history? How are they indicated?

A: deep-history is similar to shallow-history except it represents the most recent leaf-substate of the composite state.
shallow-history is shown as a circled letter H.
deep-history is shown as a circled H*.
Source: Quantum leaps


text:
Q: How to ensure that generated id does not exist in database I would like to generate unique id for entity and store the entity in Cassandra database (only if entity with generated id does not exist already).
After id generation I check in db if there is any entity with the same id. If not, then the entity is saved. Sample code from MyService class:
synchronized (MyService.class) {
    do {
        id = generateId();
    } while (myDao.find(id) != null);
    sampleObject.setId(id);
    myDao.create(sampleObject);
}

In MyDao to save entity I'm using:
cassandraOperations.insert(sampleObject);

What is the best practice to ensure that already generated id does not exist in database? I feel that this synchronize block is not the most efficient solution.
Or maybe there is any other way in which I can ensure that entity is inserted only if there is no entity with the same id in database?

A: Type 1 uuids (timeuuid) guarantees no collisions provided you create less than 10k uuids per millisecond (per host). So this is easiest solution with no impact on throughput or latency. If you use a type 4 random uuid (uuid type) the chance of a collision is less than a super volcano erupting from under your datacenter but it doesn't provide the guarantee timeuuid does.
If you want you can also use lightweight transactions with the IF NOT EXISTS clause on your query.
INSERT INTO keyspace_name.table_name
  ( identifier, column_name...)
  VALUES ( value, value ... ) IF NOT EXISTS

This will only apply the mutation if the row does not already exist. The query will return an applied field that tells you if it succeeded or not. If another inserted same thing only one would work.
https://docs.datastax.com/en/cql/3.1/cql/cql_reference/insert_r.html#reference_ds_gp2_1jp_xj__if-not-exists
This will be slower since it uses paxos, which takes multiple hops around your cluster to complete.

A: UUID is safe solution but sometimes id is not very unique.
For example SSN.
To tackle it Cassandra has support for lightweight transactions.
https://docs.datastax.com/en/cql/3.3/cql/cql_using/useInsertLWT.html
On Application side no synchronized is required.
Cassandra resultset will return applied flag true if record is written.
Function to write:
ResultSet insertIfNotExists(String Id) {
    String cql = QueryBuilder.insertInto("table_name")
            .value("id", Id)
            .ifNotExists()

    return cassandraOperations.query(cql);
}

Usage:
ResultSet rs = insertIfNotExists("abc123")
if (rs.wasApplied()) {
   log.info("success")
}


text:
Q: Ruby method arguments with just * operator: def save(*) .. end
Possible Duplicate:
naked asterisk as parameter in method definition: def f(*)
Accessing a value in a method using *

The save(*) method in Rails takes just a single asterisk as an argument.
I know that * can be used for variable length arguments as in *args, but what does the * mean in this context? How does one access the arguments here?
And more specifically, how would one pass all the arguments on to a super call?

A: In this specific case, save doesn't take any arguments. That's what happens with a naked splat. But, as you may be aware, calling save on an ActiveRecord model accepts options because this method gets overridden by ActiveRecord::Validations here:
https://github.com/rails/rails/blob/v3.1.3/activerecord/lib/active_record/validations.rb#L47
# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
  perform_validations(options) ? super : false
end


text:
Q: issue in accessing object javascript getter I am writing getter and setters dynamically. my code is buggy. I need help in correcting it.
Portion of my code looks like following:
var a = {};
var myArray = ["abc", "xyz", "bbb"];

for (var i = 0; i < myArray.length: i++) {
    var tempVar = myArray[i];
    Object.defineProperty(this, tempVar, {
        get: function () {
            var ret = $.extend(true, {}, a[tempVar]);
            return ret;
        },
        set: function (intObj) {
            a[intObj.type] = intObj;

        }
    });
}

The problem of mine is there in get function I want to access value of tempVar but I am not able to access it.
While defining it is not even going in get function.
And while using it is going in get function but the tempVar will be last value of array only.
If some body can guide me in this. It would be great.

A: Yes that link helped. Thanks. So my code will now look like following. This is a basic concept but always run away from closures. Today learnt! Thanks.
var a = {};
var myArray = ["abc", "xyz", "bbb"];

for (var i = 0; i < myArray.length: i++) {
    var tempVar = myArray[i];
    Object.defineProperty(this, tempVar, {
        get: function (newTemp) {
           return function(){
            var ret = $.extend(true, {}, a[newTemp]);
            return ret;
           }
        }(tempVar),
        set: function (intObj) {
            a[intObj.type] = intObj;

        }
    });
}


text:
Q: "Parameter "toolsPath" cannot be null." when calling MSBuildWorkspace.OpenProjectAsync() I have a Visual Studio solution with many C# projects. I'm currently trying to build a new C# project in that solution that builds and runs project 1, but I'm getting the runtime error when calling MSBuildWorkspace.OpenProjectAsync:

Parameter "toolsPath" cannot be null.'

I'm not sure what parameter this refers to. My code is below:
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.MSBuild;

namespace RunAllProjects
{
    class Program
    {
        static async Task Main()
        {
            using MSBuildWorkspace ws = MSBuildWorkspace.Create();
            var project = await ws.OpenProjectAsync("../../../../1/1.csproj");
            Console.WriteLine(project.Name);
        }
    }
}

Any idea where this error could be coming from? Thanks!

A: Before you call MSBuildWorkspace.Create(), call MSBuildLocator.RegisterDefaults(). There's instructions for how to use MSBuildLocator here.


text:
Q: Visual Studio w/Docker has exited with code 4294967295 (0xffffffff) On our new company laptops we are running into issues running containers in docker desktop from visual studio. We tried a bunch of things which were unsuccessful. Any help / thoughts would be great as we are running out of ideas.
.Net Core Version 6 / Asp.net Core (web api)
Running docker compose manually in cmd works and I'm able to hit the site.
Running docker compose debug profile from visual studio results in:

The output window shows "The program '' has exited with code 4294967295 (0xffffffff)."
Docker desktop shows the container running but I can't grab logs from it or hit it in the url.
WSL is fine and everything is working there.
My home machine works great and i'm able to launch and debug containers.

A: Faced with identical error, I was able to resolve by deleting VSDBG debugger folder:
%USERPROFILE%\vsdbg\vs2017u5

After deleting the folder start Visual Studio debugger (F5) and as a result VSDBG debugger will be recreated
Container Tools build properties https://learn.microsoft.com/en-us/visualstudio/containers/container-msbuild-properties?view=vs-2022

A: I have the same error when I'm trying to start 2 project simultaneously. And one project was cloned from another. So, they have the same GUIDs of projects in .sln files. After changing  GUIDs  all works ok.

A: Most of the time this error code does not provide any concrete information. In my case I had to go and find error details in logs folder. Log file is generally located at 'YourProject\bin\Debug\App_Data\Logs' location.
There was an issue with 3rd party service and it worked after fixing the service issue.


text:
Q: Windows 7 taskbar in Windows XP? I have been using a theme on Windows XP to make it look like Win 7 but it has some drawbacks like Blue screen dump and shutting down the system.
I want my taskbar and My Computer drive to be just like Windows 7.
Any help would be appreciated. I'm running Vista Drive Icon software to show the drive info. Even I would like to give a MAC look to my XP if there is any setup you know please help me.

A: XP has some good theming software available that will let you do this. The best that comes to mind is WindowBlinds. Once you have that installed you should be able to download themes from different places like WinCustomize.


text:
Q: How to group by subitems of a list in a List? I am new to Scala. I am curious about how to group sub-items of a list.
For example, I have data on categories of novels and their ratings. I want to get total ratings in a category.
Format of data: (Option[List(categories)], Option[rating])
var a = List(List(List("romance", "thriller"), 4), List(List("adventure", "thriller"), 3))

I want to get a mapping of Key(Category) => Value(Their ratings)
romance => (4,3)
thriller => (4,3)
adventure => (3)

I tried to do a.groupby(_._1), but it only groups when they have the exact same categories. I tried to search other posts but couldn't find any similar questions.

A: This data structure is extremely hard to work with, and that might be a cause of your problems. You have a list, which in turn contains lists, each of which in turn contains two elements, the first of which is another list, and the second element is a number.
This has many, many problems. For starters, almost none of the lists actually are lists.
The innermost list is not a list, since the order of the elements doesn't matter. It should probably be a set.
The middle list is very problematic: since it contains both a list and a number, it cannot have a useful type. The best we can do is List[Any] in Scala 2 or List[String | Integer] in Scala 3. The actual type that is inferred in Scala 3 is List[Matchable], which is essentially useless. It "pollutes" everything you try to do later. It should probably be a pair, i.e. a (Set[String], Integer).
And the outer list doesn't actually need to be a list either, it can be any sequence; we don't particularly care what specific kind of sequence it is. All we care about is that we can iterate over it. In fact, it we don't care about the order, and we don't even care about sequentiality (it would work just fine to evaluate all elements in parallel), so arguably, the correct type would be just Iterable.
So, let's fix that data structure first:
val ratings = Iterable(
  Set("romance", "thriller")   -> 4,
  Set("adventure", "thriller") -> 3
)

This data structure is both much easier to work with and more closely resembles the semantics of what you are trying to model.
In order to get the individual ratings for the genres, we need to flatten this representation out, so we get something like
Iterable(
  "romance"   -> 4,
  "thriller"  -> 4,
  "adventure" -> 3,
  "thriller"  -> 3
)

We can do this by flatMapping over ratings and mapping each genre to a pair of (genre, rating):
val individualRatings = for
  (set, rating) <- ratings
  genre <- set
yield genre -> rating

Now, we can groupBy the genre, which will give us something like
Map(
  "romance"   -> ("romance"   -> Seq(4)),
  "thriller"  -> ("thriller"  -> Seq(4, 3)),
  "adventure" -> ("adventure" -> Seq(3))
)

Which means we need to mapValues to just their second element, so we end up with something like this:
Map(
  "romance"   -> Seq(4),
  "thriller"  -> Seq(4, 3),
  "adventure" -> Seq(3)
)

And lastly, we need to reduce the list of ratings to a single rating.
There is actually the helpful method Iterable.groupMapReduce which combines these three operations in an efficient manner:
val totals = individualRatings.groupMapReduce(_._1)(_._2)(_ + _)

And the end result is this:
Map(
  "adventure" -> 3,
  "romance"   -> 4,
  "thriller"  -> 7
)

Note: even if you have no control over the data coming in, it still makes sense to "fix" the data as soon as it enters the system, and only ever work with the fixed data, instead of constantly having to deal with the broken data all the time.
You could, for example, create the data structure I outlined above from your data using something like this:
val ratings = for
  (genres: Iterable[String]) :: (rating: Int) :: Nil <- a
yield genres.toSet -> rating

Note that because of type erasure, this is actually not type-safe: at runtime, the element type of the List is erased, so it is impossible to know that the first element is a List[String] and the second element is an Integer. They are both treated as Matchables, even with the type test in the pattern.
However, this is not necessarily the best we can do. Scala is an object-oriented programming language, after all, not a list-of-lists-of-lists-of-strings-or-numbers-oriented language.
What we have done, is we have improved the data structure from a list-of-lists-of-lists-of-strings-or-numbers to an iterable-of-pairs-of-sets-of-strings-and-numbers. What we would really like to have is an iterable-of-ratings.
I will leave that as an exercise for the reader for now.

A: You first want to transform your data to a List[(Category, Rating)], and then you can use groupMap to group by category.
val a = List(
  (List("romance", "thriller"), 4),
  (List("adventure", "thriller"), 3)
)

a.flatMap{
  case (cs, r) => cs.map(_ -> r)
}
.groupMap(_._1)(_._2)


text:
Q: How to display the attributes of an XML file to a website? I want to display the data of an XML file to my website, I have a problem for displaying that, because XML file is a bit different. I have to dispaly the value of certain attributes of this XML file. the path of this XML file is stored in side the database. the data which should be displayed I marked as bold(inside double star). Thank you all so much for helping me.
I need an example please.
here the xml file:
<?xml version="1.0" encoding="UTF-8"?>
<GO2cam_to_PPU>

    <Software Version="6009" Revision="200">
        <OEM Number="10" **Name="DEMO Disk 4X"** PremilledMode="No" MountingType="None"/>
        <Protection HostId="192.168.0.203" Type="Floating"/>
    </Software>
    <Project>
        <Machine Name="SBO-GO2cam_Disk_4X.MCF" PostProcessor="F50_Fanuc" NcFile="SBO.NC"/>
        <Stock Number="1">
            <Material **Name="Zirconia.mtr"** Class="Zirconia">
                <Dimension Diameter="94" Width="93.9804412498" **Thickness="26"**/>
                <Shoulder Define="No"/>
                <Teeth Number="1">
                    <Tooth Typology="anatomicCrown">
                        <STL DirectoryName="U:\CAD Interfaces\STL\Coping - Crown\Crown Single" **FileName="0016  ADVANCED KELLY B1_0.STL"** FacetNumber="42782"/>
                        <Opelist DirectoryName="Milling Crown\Tools - Ball-D2.0-D1.0-D0.6" *FileName="2 - Zirconia - Crown - D2-D1-D0.6 - Standard.OPL"*/>
                    </Tooth>
                </Teeth>
            </Material>
        </Stock>
        <Machining Number="1">
            <Cycle Name="Roughing D2 at 0" Type="411" ToolName="Zr Ball End Mill D2.F14" ToolPosition="1"/>
        </Machining>
        <ToolList Number="1">
            <Tool Name="Zr Ball End Mill D2.F14" Type="460" Diameter="2" Radius="1"/>
        </ToolList>
    </Project>
</GO2cam_to_PPU>

A: To accomplish the goal of displaying various Attributes from some XML data using PHP the most common method would be to use DOMDocument and DOMXPath
The following uses an array to aid processing the various queries needed. This is just the way I chose to approach the issue - not necessarily how one must do it.
<?php

    $strxml='<?xml version="1.0" encoding="UTF-8"?>
    <GO2cam_to_PPU>

        <Software Version="6009" Revision="200">
            <OEM Number="10" Name="DEMO Disk 4X" PremilledMode="No" MountingType="None"/>
            <Protection HostId="192.168.0.203" Type="Floating"/>
        </Software>
        <Project>
            <Machine Name="SBO-GO2cam_Disk_4X.MCF" PostProcessor="F50_Fanuc" NcFile="SBO.NC"/>
            <Stock Number="1">
                <Material Name="Zirconia.mtr" Class="Zirconia">
                    <Dimension Diameter="94" Width="93.9804412498" Thickness="26"/>
                    <Shoulder Define="No"/>
                    <Teeth Number="1">
                        <Tooth Typology="anatomicCrown">
                            <STL DirectoryName="U:\CAD Interfaces\STL\Coping - Crown\Crown Single" FileName="0016  ADVANCED KELLY B1_0.STL" FacetNumber="42782"/>
                            <Opelist DirectoryName="Milling Crown\Tools - Ball-D2.0-D1.0-D0.6" FileName="2 - Zirconia - Crown - D2-D1-D0.6 - Standard.OPL"/>
                        </Tooth>
                    </Teeth>
                </Material>
            </Stock>
            <Machining Number="1">
                <Cycle Name="Roughing D2 at 0" Type="411" ToolName="Zr Ball End Mill D2.F14" ToolPosition="1"/>
            </Machining>
            <ToolList Number="1">
                <Tool Name="Zr Ball End Mill D2.F14" Type="460" Diameter="2" Radius="1"/>
            </ToolList>
        </Project>
    </GO2cam_to_PPU>';

    /*
        An array of Objects - each Object has the XPath expression that
        will identify a particular element in the XML and the attribute
        for which a value will be found.
    */
    $queries=array(
        (object)array('expr'=>'//Software/OEM','attr'=>'Name'),
        (object)array('expr'=>'//Project/Stock/Material','attr'=>'Name'),
        (object)array('expr'=>'//Project/Stock/Material/Dimension','attr'=>'Thickness'),
        (object)array('expr'=>'//Project/Stock/Material/Teeth/Tooth/STL','attr'=>'FileName'),
        (object)array('expr'=>'//Project/Stock/Material/Teeth/Tooth/Opelist','attr'=>'FileName')
    );

    /*
        Create the basic DOMDocument object
        and set some runtime options for libxml
    */
    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->strictErrorChecking=false;
    /*
        Load the string of XML data
        or, use `$dom->load($filepath)`
        to load a file.
    */
    $dom->loadXML($strxml);

    /*
        grab reference of any errors
    */
    $errors=libxml_get_errors();
    libxml_clear_errors();

    /*
        Create the basic XPath Object that
        will be used to query the XML data.
    */
    $xp=new DOMXPath($dom);

    /*
        Iterate through the queries array
    */
    foreach( $queries as $obj ){
        # construct the XPath query & run it.
        $col=$xp->query( $obj->expr );
        # process the results
        if( $col->length > 0 ){
            # find first item in results and find the appropriate attribute
            $node=$col->item(0);
            printf('%s: %s
', $node->tagName, $node->getAttribute( $obj->attr ) );
        }
    }

    #show any errors...
    if( !empty( $errors ) )printf('
%s
',print_r($errors,true));
?>

This will output:
OEM: DEMO Disk 4X
Material: Zirconia.mtr
Dimension: 26
STL: 0016 ADVANCED KELLY B1_0.STL
Opelist: 2 - Zirconia - Crown - D2-D1-D0.6 - Standard.OPL


text:
Q: Make simple plot nicer with Tikz Is there a way to make this figure to look nicer?
For instance, how to write the legends of the red arrows or the spacing of the dashed black lines?
At least for me, it is quite crude and can be improved..but I don't know how
\documentclass[tikz, border=20]{report}
\usepackage{tikz,enumitem,multicol}
\usetikzlibrary{arrows}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta,intersections}
\pgfplotsset{compat=1.8}

\begin{document}
\begin{figure}[h]
    \centering
    \begin{tikzpicture}[scale = 2]
        % ladder
        \draw[thick] (-1.5, 0) -- (2.5, 0);
        \draw[thick] (-1.5, .7) -- (2.5, .7);
        \draw[thick,dashed] (-2, 0) -- (-1.5, 0);
        \draw[thick,dashed] (2.5, 0) -- (3, 0);
        \draw[thick,dashed] (-2, .7) -- (-1.5, .7);
        \draw[thick, dashed] (2.5, .7) -- (3, .7);

        % hopping
        \draw [thick, dashed,  red] (0.5,0) to (.5,.7);
        \draw [thick, dashed, red] (2.05,0) to [out=40,in=-40]  (2.05,.7);
        \draw [thick, dashed, red] (1.95,.7)  to [out=-140,in=-220] (1.95,0) ;
        \draw [thick, dashed, red] (-1,0) -- (-1,.7);

        % arrow J_jos
        \draw [thick, -stealth] (0.5,-0.15) -- (0.4,0.15);
        \draw [thick, -stealth] (0.55,0.15) -- (0.65,-0.15);
        \draw [thick, red] (0.4,0.33) -- (.5,0.43);
        \draw [thick, red] (.5,0.43) -- (.6,0.33);

        % arrow t_\perp
        \draw [thick, red] (-1.1,0.33) -- (-1,0.43);
        \draw [thick, red] (-1,0.43) -- (-.9,0.33);

        % arrow J_superexchange
        \draw [thick, -stealth]  (1.95,0.15) -- (2.05,-0.15);
        \draw [thick, -stealth] (2.05,0.55) -- (1.95,0.85);
        \draw [thick, red] (2.1,0.3) -- (2.2,0.4);
        \draw [thick, red] (2.2,0.4) -- (2.3,0.3);
        \draw [thick, red] (1.7,0.4) -- (1.8,0.3);
        \draw [thick, red] (1.8,0.3) -- (1.9,0.4);

        % arrow t_perp
        \draw [thick, -stealth]  (-.95,-0.15) -- (-1.05,0.15);

        % name hoppigs
        \node[] at (-1,1.2) {a)};
        \node[] at (-0.8,0.35) {t};
        \draw [] (-0.75,0.2) -- (-0.6,0.2);
        \draw [] (-0.675,0.2) -- (-0.675,0.35);

        \node[] at (.5,1.2) {b)};
        \node[] at (0.7,.35) {t};
        \node[] at (0.9,.4) {\scriptsize pair};

        \node[] at (2,1.2) {c)};
        \node[] at (2.5,.35) {t};
        \node[] at (2.7,.4) {\scriptsize sing};

    \end{tikzpicture}
    \caption{Schematic representations of the possible instabilities. (a) Due to the transverse coupling, we can end up with a simultaneous hop of particles. (b) Two particles bound in the same site hop together in the transverse direction (Josephson hopping of pair). (c) The particles hop simultaneously by swapping their positions (super-exchange or particle-hole). }
\end{figure}

\end{document}

A: Well, it doesn't look any different, but you can minimize the code and make it more readible by using scopes and ++() notation:
\documentclass[tikz, border=20]{standalone}
\usetikzlibrary{arrows,arrows.meta}

\begin{document}
        \begin{tikzpicture}[x=2cm,y=2cm,thick]
            \draw (-0.5, 0) -- ++(3.0, 0) (-0.5, .7) -- ++(3,0);
            \draw[dashed] (-1, 0) -- ++(0.5,0) (2.5, 0) -- ++(0.5,0) (-1, .7) -- ++(0.5,0) (2.5, .7) --  ++(0.5,0);

            \begin{scope}
                \node[] at (0,1) {a)};
                \draw [dashed, red] (0,0) -- ++(0,.7);
                \draw [-stealth]  (0.05,-0.15) -- ++(-0.1,0.3);
                \draw [red] (-0.1,0.33) -- ++(0.1,0.1) -- ++(0.1,-0.1) node[anchor=south west,black] {t$_{\perp}$};
            \end{scope}

            \begin{scope}[xshift=2.25cm]
                \node[] at (0,1) {b)};
                \draw [-stealth] (0,-0.15) -- ++(-0.1,0.3);
                \draw [-stealth] (0.05,0.15) -- ++(0.1,-0.3);
                \draw [red] (-0.1,0.33) -- ++(0.1,0.1) -- ++(0.1,-0.1) node[anchor=south west,black] {{t\textsubscript{pair}}};
                \draw [dashed, red] (0,0) -- ++(0,.7);
            \end{scope}

            \begin{scope}[xshift=4.5cm]
                \node[] at (0,1) {c)};
                \draw[dashed,red] (0,.35) ellipse (.4cm and .7cm);
                \draw [red] (0.1,0.3) -- ++(0.1,0.1) -- ++(0.1,-0.1) node[anchor=south west,black] {{t\textsubscript{sing}}};
                \draw [red] (-0.3,0.4) -- ++(0.1,-0.1) -- ++(0.1,0.1);
                \draw [-stealth]  (-0.05,0.15) -- (0.05,-0.15);
                \draw [-stealth] (0.05,0.55) -- (-0.05,0.85) ;
            \end{scope}
        \end{tikzpicture}
\end{document}


text:
Q: Laptop shuts off unexpectedly while in motion Recently I've been encountering a very annoying problem during my commute in which my laptop unexpectedly powers off. I am using a Dell Inspiron 15 with a touchscreen. The laptop is just a bit over a year old. Here are some more details:

*

*Speed does not seem to matter. Today it has happened while moving in heavy traffic at approximately 5 km/h, on a road at 60 km/h, and down a rapid transit lane at nearly 100 km/h

*It happens regardless of position inside the vehicle. Whether I'm sitting 15 feet back (closer to the front of the bus) or 40-60 feet back (last row of seats) it still happens.

*It happens regardless of road quality. There's an on-ramp and some parts of the Transitway that have bad potholes but hitting those doesn't cause the power down, yet this has happened on some newly-paved roads.

*Acceleration doesn't seem to matter either. I've encountered several instances of sudden braking that did not cause the power down.

To reduce vibration, I typically set the laptop on top of a nearly-empty backpack on my lap, without any part of the laptop touching the seat or vehicle directly.
Another thing I've noticed too is that this problem does not happen only on vehicles, but also when I am walking between classes. I usually put the computer to "Sleep" instead of shutting it down before putting it in my backpack. Sometimes when I open it up the next class or at work, the power would be off and my open documents/windows would have crashed. For now, I've enabled the "Hibernate" option and use it when class is over, but it still doesn't help me when using the system in transit.
This power down phenomenon never happens when the system has not physically moved.
I've checked the Event Viewer in Windows and nothing of significance shows up:

The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly.

The battery lock is in the lock position and it appears to be fairly secure in its position.
I've also looked at some other questions that did not help my case:

*

*Is it harmful to laptop to move it when it's working?

*When the computer is suspended, would it be safe to move it around now?

*How does a laptop with HDD function when it's moving?
Can anyone suggest something to prevent this from happening?

A: Many Dell laptops have a built in accelerometer to sense when a laptop is falling and can be configured to instantly turn off the hard drive to prevent damage on impact. It sounds like your accelerometer is too sensitive. I'm guessing there's probably a setting in the BIOS that will let you disable it. I'll do some research and post if I find anything specific.
UPDATE: Apparently there is a Freefall Sensor Driver. If you go to Dell support and put in your service tag, you can download the current driver.


text:
Q: yii\base\ErrorException Cannot use a scalar value as an array 'rowOptions' =>function($dataProvider) use($isAccountingTeamOrAdmin){
        $value = 0.00;
        $results = array($dataProvider);
        $params = isset(\Yii::$app->request->queryParams) ? \Yii::$app->request->queryParams : '';
        if($results){
            $value = Yii::$app->payroll->getPayrollAmountForFloodViewHistory($results, $isAccountingTeamOrAdmin, $params);
        }
        if($value > 0){
            return false;
        }else{
            return true;
        }
    },

This line $results = array($dataProvider); how to implement ??

A: you can use the method getData() from your dataprovider
$results = $dataProvider->getData();


text:
Q: Half-integer Fourier transform Suppose we want to carry out the (generalized) Fourier transform of a function defined in the domain $\mathbb{T}\times\tfrac12\mathbb{Z}$, i.e. dependent on the arguments $\phi\in\left(-\pi,+\pi\right]$ (or other $2\pi$ length interval) and $\psi\in\tfrac12\mathbb{Z}=\pm\left\{0,\tfrac12,1,\tfrac32,\dots\right\}$. A suitable $\phi$ transform is a Fourier series, and a suitable $\psi$ transform is a Fourier sequence transform or discrete-time Fourier transform. I have doubts about the latter.
The thing is $\psi\in\tfrac12\mathbb{Z}$, not $\mathbb{Z}$ itself. I do not think it makes a big difference, but some issues may be spotted.
The first question is if it can be done just like this:
$$
\sum_{\psi\in\tfrac12\mathbb{Z}}{e^{-i\psi\psi'}f\left(\psi\right)}=\sum_{\psi\in\mathbb{Z}}{e^{-i\psi\psi'}f\left(\psi\right)}+\sum_{\psi\in\tfrac12\mathbb{Z}\backslash\mathbb{Z}}{e^{-i\psi\psi'}f\left(\psi\right)}=\sum_{\psi\in\mathbb{Z}}{e^{-i\psi\psi'}f\left(\psi\right)}+\sum_{\psi\in\mathbb{Z}}{e^{-i\left(\psi+\tfrac12\right)\psi'}f\left(\left(\psi+\tfrac12\right)\right)}
$$
The second question is how to understand this transformation with $e^{-i\left(\psi+\tfrac12\right)\psi'}$. I realize that this is not a very precise question, but I am looking forward to a bit more coverage of this issue. It certainly has something to do with the anti-periodic function. However, I have not enough imagination to determine whether $2\pi$ is an (actual) period of this function or just a "period" of its anti-periodicity (half of the actual one).
The third question concerns the inverse transformation (with respect to $\psi'$). Whether $\psi'$ will belong to $\mathbb{T}\simeq\left(-\pi,+\pi\right]$ or instead to an interval of a different length. And whether the reverse transformation should be performed with a period of $2\pi$ or some other length.
$$
\int_{\mathbb{T}}{\frac{d\psi'}{2\pi}e^{i\psi'\psi}\hat{f}\left(\psi'\right)}
$$
Generally, I look for a comprehensive introduction to harmonic analysis (Fourier-type transformations) in the case of anti-periodic functions.
I would be grateful for any answers, clarification, or expansion of these topics.
This question was originally posted on math.SE, but to date without any answer.


text:
Q: low sample size experimental design, t-test vs one way ANOVA I'm designing a biological experiment wherein the sample size is very limited, as each sample is very hard to get. Moreover, I need to have 4 independent groups, each receiving a different treatment.
I only really care about 2 comparisons: group  1 vs group 2, and g3 vs g4. My power analysis indicates my sample size is large enough to compare 1v2 with a t-test and 3v4 with a t-test. However, I worry that doing an ANOVA and post-hocs will lower the statistical power.
Question: If I know beforehand exactly what 2 groups I want to compare (and I don't care about the other comparisons), can I use t-tests instead of ANOVA?
Thanks!

A: If you reject the null hypothesis in the one-factor ANOVA, then you could do ad hoc comparisons of 1 vs 2 and 3 vs 4 using Tukey's HSD to avoid false discovery on multiple testing of the same data.
(I would not just use two 2-sample t tests.)
Without seeing your data, I can't predict whether those two HSD comparisons would lead to significant results.
HSD uses a somewhat different criterion than ANOVA, so there is no absolute guarantee any HSD comparisons will be significant. Try HSD and see what you find.


text:
Q: How to remove header on the page with big picture (or a page containing floats)? Can you help me to remove header from the page where is only one big picture? I tried \thispagestyle{empty} but it removes a header on the next or previous page. I don't know how to remove it exactly from the page only with the picture.
I put this picture in my document by using {sidewaysfigure} environment and \includegraphics in it.
Here is my MWE
\documentclass{book}

\usepackage[demo]{graphicx}

\usepackage[
 centering,
 top=12mm,
 headheight=14pt,
 headsep=11pt,
 includeheadfoot,
 papersize={160mm,235mm},
 text={125mm,190.7mm},
]{geometry}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead{}
\newcommand{\TheAuthor}{}
\newcommand{\Author}[1]{\renewcommand{\TheAuthor}{#1}}
\rhead{\small\TheAuthor}
\newcommand{\TheTitle}{}
\newcommand{\Title}[1]{\renewcommand{\TheTitle}{#1}}
\lhead{\small\normalfont\TheTitle}
\fancyfoot{}
\fancyhead[RO,LE]{\thepage}

\usepackage{lipsum}

\usepackage{rotating}

\begin{document}

\lipsum

\begin{sidewaysfigure}
   \centering
   \fbox{\includegraphics[width=190mm]{pic.jpg}}
   \caption*{\footnotesize\centering{Pic. 1}}
\end{sidewaysfigure}

\lipsum

\end{document}

A: Assuming that you use the rotating package, i.e., that sidewaysfigure is a floating environment, fancyhdr's \iffloatpage macro should do the trick.
\documentclass{book}

\usepackage{rotating}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[LO,RE]{\iffloatpage{}{(The Title)}}
\fancyhead[RO,LE]{\iffloatpage{}{\thepage}}
\fancyfoot{}
\renewcommand{\headrulewidth}{\iffloatpage{0pt}{0.4pt}}

\usepackage{blindtext}

\begin{document}

\blindtext[8]

\begin{sidewaysfigure}
\centering
\rule{1cm}{1cm}
\caption{A rotated figure}
\end{sidewaysfigure}

\end{document}

(The blindtext package is only used to add some dummy text to the example.)
EDIT: In your subsequently delivered MWE, replace
\rhead{\small\TheAuthor}

...
\lhead{\small\normalfont\TheTitle}
\fancyfoot{}
\fancyhead[RO,LE]{\thepage}

with
\rhead{\iffloatpage{}{\small\TheAuthor}}

...
\lhead{\iffloatpage{}{\small\normalfont\TheTitle}}
\fancyfoot{}
\fancyhead[RO,LE]{\iffloatpage{}{\thepage}}
\renewcommand{\headrulewidth}{\iffloatpage{0pt}{0.4pt}}

A: use package afterpage and write somewhere on the page before:
\afterpage{\thispagestyle{empty}}

A: I encountered the same problem – in my case \clearpage \thispagestyle{empty} did the trick.


text:
Q: How to decrease the size of character varying type in postgres? I need to decrease  the size of a character varying field in a postgres database table.
description | character varying(500)  | not null
i am using this command
ALTER TABLE notification ALTER COLUMN description TYPE varchar(200);

it's give me this type of error
ERROR:  value too long for type character varying(200)
So how to decrease size of character varying from 500 to 200?

A: Apparently you have values in that column that are longer than 200 characters. You first need to truncate those values:
You truncate the value as part of the ALTER TABLE statement.
ALTER TABLE notification
   ALTER COLUMN description TYPE varchar(200) USING left(description, 200);

Alternatively you can first update the table, but doing it as part of the ALTER TABLE will be faster:
update notification
  set description = left(description, 200)
where length(description) > 200;

After that you can run your ALTER TABLE statement


text:
Q: pandas: Data difference (delta) between 2 data frames I have 2 non-indexed data frames, with the exact same data structure (same columns), for the sake of simplicity here's an example:
df1
0       1       2          3    4
JoeK    Joe     Kavanagh   120  joe.kavanagh@nomail.com
BarryD  Barry   Dempsy     11   barry.dempsy@nomail.com
OrlaF   Orla    Farrel     236  ofjk@nomail.com
SethB   Seth    Black      563  sblack@nomail.com
KateW   Kate    White      254  kw12@nomail.com

and the second one:
df2
0       1       2          3    4
JoeK    Joe     Kavanagh   110  jkavanagh@nomail.com
BarryD  Barry   Dempsy     11   barry.dempsy@nomail.com
JimmyS  Jimmy   Smith      250  j.Smith@nomail.com
SethB   Seth    Blake      563  sblack@nomail.com

I would like to have a resulting dataframes representing the rows in df1 that aren't in df2:
0       1       2          3    4
JoeK    Joe     Kavanagh   120  joe.kavanagh@nomail.com
OrlaF   Orla    Farrel     236  ofjk@nomail.com
SethB   Seth    Black      563  sblack@nomail.com
KateW   Kate    White      254  kw12@nomail.com

Notice that the first row (Joek, and SethB) exist in both dataframes, but the value of column 3 for JoeK and the value of column 2 for SethB have changed, that's why they're in the final result set.
Any help is much appreciated.

A: IIUC it looks like you're just trying to match on cols 0,1,2,3, you can perform a left merge and pass param indicator=True if you're using a recent version of pandas and then filter the df:
In [197]:
merged = df1.merge(df2, how='left', on=['0','1','2','3'],indicator=True)
merged[merged['_merge'] == 'left_only']

Out[197]:
       0     1         2    3                      4_x  4_y     _merge
0   JoeK   Joe  Kavanagh  120  joe.kavanagh@nomail.com  NaN  left_only
2  OrlaF  Orla    Farrel  236          ofjk@nomail.com  NaN  left_only
3  SethB  Seth     Black  563        sblack@nomail.com  NaN  left_only
4  KateW  Kate     White  254          kw12@nomail.com  NaN  left_only


text:
Q: LinearGradient doesnt't work on chartJs canvas for Angular Here I tried to add linear gradient on ctx object of canvas as usual.
    let canvas= $("#canvas");
    let ctx=canvas[0].getContext('2d');
    var gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, 'rgba(250,174,50,1)');
    gradient.addColorStop(1, 'rgba(250,174,50,0)');

instead of using jQuery to access canvas object,I tried document.getElementbyId as well but didnt work either.
Chart is being printed just gradient is missing.I don't know why
Stackblitz:https://stackblitz.com/edit/angular-h83adp-chartjs-kfdgcy?file=app/app.component.ts

A: You correctly created the linear gradient but forgot to assign it to the backgroundColor property of the dataset.
datasets: [{
  label: 'test',
  data: [100, 200, 300],
  backgroundColor: gradient // you need to do this
}]

Please take a look at your amended StackBlitz.


text:
Q: Trigger onblur event on click of enter keypress in React js I have an input text field . When a user inputs any text and clicks enter button I need to activate the blur event to remove the focus and also to validate the textinput .
<input type="text"
    style={{marginTop:'20%', marginLeft:'40%'}}
    value={value}
    onFocus={onFocus}
    onChange={e => setValue(e.target.value)}
    onKeyPress={handleKeyPress}
/>

A: Use refs and this.inputRef.current.blur().This is working solution.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      value: ""
    };
  }
  keypressHandler = event => {
    if (event.key === "Enter") {
      this.setState({ value: this.inputRef.current.value });
      this.inputRef.current.blur();
      this.inputRef.current.value = "";
    }
  };
  render() {
    return (

      Enter Text
        <input
          type="text"
          ref={this.inputRef}
          onKeyPress={event => this.keypressHandler(event)}
        />

{this.state.value}

    );
  }
}
ReactDOM.render(<App/>, document.getElementById('root'));

A: Instead of onKeyPress, use onKeyDown which detects keyCode events.
<input type="text"
    style={{marginTop:'20%', marginLeft:'40%'}}
    value={value}
    onFocus={onFocus}
    onChange={e => setValue(e.target.value)}
    onKeyDown={(e) => this.handleKeyPress(event)}
/>

And the function will be like,
handleKeyPress(e){
   if(e.keyCode === 13){
     e.target.blur();
     //Write you validation logic here
   }
}


text:
Q: How to display the port numbers of open connections for a specific process with tcpvcon.exe (Windows 10)? I have both TCPView and Tcpvcon on my Windows 10 machine and I wonder how to get all the information (port numbers, etc.) displayed in TCPView in the output of the Tcpvcon program? TCPView has the process name, PID, protocol, remote address, remote port, etc. in its output to the GUI. Tcpvcon, on the other hand, only contains the process name, protocol, remote and local address. I would like to have all information that can be read in the TCPView GUI in the command line output of Tcpvcon (especially the port numbers). Tcpvcon seems to have only the three switches -a -c -n but no matter how I combine them, I do not reach my goal. Can anyone help me?
Below is a sample output when I use all three switches. In TCPView I see much more information about the specified process.

A: I was also very surprised that tcpvcon does not show port numbers (maybe we should ask Mark R. to add them ;-)
BUT you could use
netstat -a -o -n

or with an admin shell even
netstat -a -o -n -b

switches meaning:
-a ... Displays all active TCP connections and the TCP and UDP ports
       on which the computer is listening.

-o ... Displays active TCP connections and includes the process ID (PID)
       for each connection.

-n ... Displays active TCP connections, however, addresses and port numbers
       are expressed numerically and no attempt is made to determine names.

-b ... Displays the executable involved in creating each connection or
       listening port. (Note that this option can be time-consuming and
       will fail unless you have sufficient permissions.)

To get all available switches just use netstat -? (there are other interesting ones) or https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/netstat
swobi

A: Up until the 2011 release of TCPVCON, it used to show port info.
The newer versions don't any more.
If you could get your hand on version 2.54, you would be able to get port info.

A: Tested with tcpvcon-v2.34 (I couldn't find 2.54) and it shows the ports but it doesn't show the process, all conections appear as from System. Also TCPV6 and UDPV6 are missing.
This is an example:
C:\WINDOWS\system32>"C:\My Program Files\TCPView-v4.13\tcpvcon-v2.34.exe" -a -c
TCP,System,-1,LISTENING,WXP-OR7507156:epmap,WXP-OR7507156:0
TCP,System,-1,LISTENING,WXP-OR7507156:microsoft-ds,WXP-OR7507156:0
TCP,System,-1,LISTENING,WXP-OR7507156:sms-rcinfo,WXP-OR7507156:0
TCP,System,-1,LISTENING,WXP-OR7507156:5040,WXP-OR7507156:0
TCP,System,-1,LISTENING,WXP-OR7507156:wsd,WXP-OR7507156:0
..
UDP,System,-1,,192.168.56.1:137,*:*
UDP,System,-1,,192.168.56.1:138,*:*
UDP,System,-1,,192.168.56.1:2177,*:*
UDP,System,-1,,192.168.56.1:5353,*:*

EDIT:
I correct myself. ASB was right.
I just got TCPView v2.54 and it does indeed show the application, the ports and also TCPV6 and UDPV6.
So I confirm that the "good" version is v2.54.
Tcpvcon.exe -a -c

TCPView v2.54 - TCP/UDP endpoint viewer
Copyright (C) 1998-2009 Mark Russinovich
Sysinternals - www.sysinternals.com

TCP,dnscrypt-proxy.exe,4188,LISTENING,WXP-XXX:domain,WXP-XXX:0
TCP,[System Process],0,TIME_WAIT,WXP-XXX:domain,localhost:62240
..
UDP,Teams.exe,12632,*,WXP-XXX:58950,*:*
TCPV6,svchost.exe,1232,LISTENING,wxp-XXX:135,wxp-XXX:0
..
UDPV6,svchost.exe,19712,*,wxp-XXX:50836,*:*
UDPV6,System,4,*,wxp-XXX:56736,*:*

A: To display the port numbers (and the process names) you need the old v2.54 version of tcpvcon.exe
This SysinternalsSuite.zip Archive from the Wayback Machine contains this version:
https://web.archive.org/web/20100201154325/http://download.sysinternals.com/Files/SysinternalsSuite.zip


text:
Q: In Kneser-Ney smoothing, how are unseen words handled? From what I have seen, the (second-order) Kneser-Ney smoothing formula is in some way or another given as
$
\begin{align}
P^2_{KN}(w_n|w_{n-1})  &= \frac{\max \left\{ C\left(w_{n-1}, w_n\right) - D, 0\right\}}{\sum_{w'} C\left(w_{n-1}, w'\right)} + \lambda(w_{n-1}) \times P_{cont}(w_n)
\end{align}
$
with the normalizing factor $\lambda(w_{n-1})$ given as
$
\begin{align}
\lambda(w_{n-1}) &= \frac{D}{\sum_{w'} C\left(w_{n-1}, w'\right)} \times N_{1+}\left(w_{n-1}\bullet\right)
\end{align}
$
and the continuation probability $P_{cont}(w_n)$ of a word $w_n$
$
\begin{align}
P_{cont}(w_n) &= \frac{N_{1+}\left(\bullet w_{n}\right)}{\sum_{w'} N_{1+}\left(\bullet w'\right)}
\end{align}
$
where $N_{1+}\left(\bullet w\right)$ is the number of contexts $w$ was seen in or, simplier, the number of distinct words $\bullet$ that precede the given word $w$. From what I've understood, the formula can be applied recursively.
Now this handles known words in unknown contexts nicely for different n-gram lengths, but what it doesn't explain is what to do when there are out-of-dictionary words. I tried following this example which states that in the recursion step for unigrams, $P_{cont}(/) = P^0_{KN}(/) = \frac{1}{V}$. The document then uses this - quoting Chen and Goodman - to justify the above formula as $P^1_{KN}(w) = P_{cont}(w)$.
I fail to see how it works out in the presence of an unknown word $w = \text{unknown}$ though. In these cases $P_{cont}(\text{unknown}) = \frac{0}{\text{something}}$ since, obviously, the unknown word doesn't continue anything regarding the training set. Likewise the count of n-grams is going to be $C\left(w_{n-1}, \text{unknown}\right) = 0$.
Furthermore, the whole $\sum_{w'} C\left(w_{n-1}, w'\right)$ term might be zero if a sequence of unknown words - say, a trigram of OOD words - is encountered.
What am I missing?

A: Dan Jurafsky and Jim Martin have published a chapter on N-Gram models which talks a bit about this problem:

At the termination of the recursion, unigrams are interpolated with the uniform distribution:

$
\begin{align}
P_{KN}(w) = \frac{\max(c_{KN}(w)-d,0)}{\sum_{w'}c_{KN}(w')}+\lambda(\epsilon)\frac{1}{|V|}
\end{align}
$

If we want to include an unknown word <UNK>, it's just included as a regular vocabulary entry with count zero, and hence its probability will be:

$
\begin{align}
\frac{\lambda(\epsilon)}{|V|}
\end{align}
$

I've tried to find out what this means, but am not sure if $\epsilon$ just means $\lim_{x\rightarrow0}x$. If this is the case, and you assume that as the count goes to zero, maybe $\lambda(\epsilon)$ goes to $d$, according to:
$
\begin{align}
\lambda(w_{i-1}) = \frac{d}{c(w_{i-1})}\vert\{w:c(w_{i-1},w)>0\}\vert
\end{align}
$
then the unknown word just gets assigned a fraction of the discount, i.e.:
$
\begin{align}
\frac{\lambda(\epsilon)}{|V|} = \frac{d}{|V|}
\end{align}
$
I'm not confident about this answer at all, but wanted to get it out there in case it sparks some more thoughts.
Update:
Digging around some more, it seems like $\epsilon$ is typically used to denote the empty string (""), but it's still not clear how this affects the calculation of $\lambda$.  $\frac{d}{|V|}$ is still my best guess

A: There are many ways to train a model with <UNK> though Jurafsky suggests to choose those words that occur very few times in training and simply change them to <UNK>.
Then simply train the probabilities as you normally would.
See this video starting at 3:40 –
https://class.coursera.org/nlp/lecture/19
Another approach is to simply consider a word as <UNK> the very first time it is seen in training, though from my experience this approach assigns too much of the probability mass to <UNK>.

A: Just a few thoughts, I am far from being an expert on the matter so I do not intend to provide an answer to the question but to analyze it.
The simple thing to do would be to calculate $\lambda(\epsilon)$ by forcing the sum to be one. This is reasonable since the empty string is never seen in the training set (nothing can be predicted out of nothing) and the sum has to be one.
If this is the case, $\lambda(\epsilon)$ can be estimated by:
$$\lambda(\epsilon)=1-\frac{\sum_w{max(C_{KN}(w) - d, 0)}}{\sum_{w'}{C_{KN}(w)}}$$
Remember that here $C_{KN}(w)$ is obtained from the bigram model.
Another option would be to estimate the <unk> probability with the methods mentioned by Randy and treating it as a regular token.
I think this step is made to ensure that the formulas are consistent. Notice that
the term $\frac{\lambda(\epsilon)}{|V|}$ does not depend on the context and assigns fixed values to the probabilities of every token. If you want to predict the next word you can prescind this term, on the other hand if you want to compare the Kneser - Ney probability assigned to each token under two or more different contexts you might want to use it.


text:
Q: Lyx IEEEtran template copyright overlaps text, authors not appearing How do you make certain that the copyright and publisher id mark are correctly located at the bottom of an IEEEtran template Lyx document when rendered as PDF?
I've tried a couple of suggestions but no matter what it always appears to overlap with the text of the document at the bottom of page 1 (see first image).
Also, although it specifies in the template that your name and paper title will appear next to the name of the journal it doesn't render in the pdf even for the example that comes with a fresh install of Lyx.
How do you get the authors and paper title to appear with the journal title in the upper left corner of the pdf? (see 2nd image).
issue with copyright overlapping and author names as programmed in the Lyx example that do not show in the pdf in the upper left corner with the journal name:

Here's some suggestions I attempted but none worked:
problem having copyright notice and header at the same time in IEEEtrans template
http://www.michaelshell.org/tex/ieeetran/     (see publisher ID mark)

A: Find the overlapping paragraph in LyX, use Ctrl + L, input \IEEEpubidadjcol twice at the beginning and end of this paragraph.


text:
Q: How can I make sure exceptions during parsing lead to the same kind of response as the (custom) response returned for validation failures? I'm using Spring to create an API, but I'm having some trouble introducing custom error reporting on (a part of) the validation of the request body.
When parsing/validation errors occur, I want to give a custom response back to the user.
This works well for fields annotated with @Valid along with validators like @javax.validation.constraints.NotNull by using a custom ResponseEntityExceptionHandler annotated with @ControllerAdvice.
It does not work however if an Exception is thrown while parsing the request body (before the validations even run). In that case I get an html error page with status 500 (Server Error)
How can I make sure the exceptions during parsing lead to the same kind of response as the (custom) one I return for validation failures?

My endpoint's code looks like this:
@RequestMapping(value= "/endpoint"
    produces = { "application/json" },
    consumes = { "application/json" },
    method = RequestMethod.POST)
default ResponseEntity<Object> postSomething(@Valid @RequestBody MyRequestBody requestData){
    // ...
}

MyRequestBody class looks like this:
@Validated
public class MyRequestData {

    @JsonProperty("stringValue")
    private String stringValue = null;

    @NotNull
    @Valid
    public String getStringValue() {
        return stringValue;
    }

    // ...

    public enum EnumValueEnum {
        VALUE_1("value 1"),
        VALUE_1("value 2");

        private String value;

        EnumValueEnum(String value) {
            this.value = value;
        }

        @Override
        @JsonValue
        public String toString() {
            return String.valueOf(value);
        }

        @JsonCreator
        public static EnumValueEnum fromValue(String text) {
          if(text == null){
            return null;
          }
          for (EnumValueEnum b : EnumValueEnum.values()){
            if (String.valueOf(b.value).equals(text)) {
              return b;
            }
          }
          throw new HttpMessageNotReadableException("EnumValueEnum \"" + text + "\" does not exist");
        }

    }

    @JsonProperty("enumValue")
    private EnumValueEnum enumValue = null;
}

The custom validation error handling (and reporting) looks like this:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class MyValidationHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // return status(BAD_REQUEST).body(new ValidationResponse(ex.getBindingResult().getFieldErrors()));
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // return status(BAD_REQUEST).body(new ValidationResponse((JsonMappingException) ex.getCause()));
    }
}

In this code, if a user sends a request with an enum value that doesn't exist, an HttpMessageNotReadableException is thrown. I would like to catch that somewhere and replace it with a custom response that is consistent with the other exception handling I do. Where/How can I do that?

A: I found a solution to my own problem.
You can actually use Spring MVC's normal exception handling:
Annotating a method with @ExceptionHandler will make Spring try to use it for exception handling for the exception type specified (in the annotation's value field or the method's argument). This method can be placed in the controller or even in the ResponseEntityExceptionHandler I use for the other validation response handling.
@ExceptionHandler
public ResponseEntity handle(HttpMessageConversionException e){
    // return status(BAD_REQUEST).body(new ValidationResponse((JsonMappingException) e.getCause()));
}

Mind which type of exception you handle:
The catch here was that the exception thrown while parsing is wrapped in (some subtype of) a JsonMappingException which in turn is wrapped again in a HttpMessageConversionException.
e instanceof HttpMessageConversionException
e.getCause() instanceof JsonMappingException
e.getCause().getCause() // == your original exception

The @ExceptionHandler should therefor accept HttpMessageConversionException instead of the originally thrown exception (which in my case was HttpMessageNotReadableException)
It will not work if you write an @ExceptionHandler that only accepts your original Exception!


text:
Q: How to select the most recent date for a specific condition in another column in Postgres? I have a table with a structure like so.
id|subject|date
1 | email | june 1
1 | call  | may 29
1 | call  | may 15
2 | call  | may 17
2 | call  | may 20

I'm trying to create a column with a query called most recent call which has the most recent call date for each id. Like this:
id|most_recent_call
1 |may 29
2 |may 20

I just want to have the most recent date for each id out of all the rows where the subject column equals call

A: You can just use conditional aggregation:
select id, max(date) filter(where subject = 'call') most_recent_call
from mytable
group by id

This, of course, assumes that column date is of a date-like datatype (as it should be).