text:
Q: adding a VARCHAR to DATE as MINUTES I'm pretty sure this is an easy one for you guys but it's driving me crazy.
I have a column with dates in a "YYYY-MM-DD" format and a column with small intergers values between 0 and 29. So I want to add the 2 columns together and get something like this:
Date        | INT |  NEW timestamp
2016-01-01  |  2  |  2016-01-01  00:02:00
2016-10-15  | 21  |  2015-10-15  00:21:00

so I tried the obvious like:
"Date" + "INT" as "NEW timestamp"

and stuff like
VARCHAR_FORMAT("INT",'MI')

or even
VARCHAR_FORMAT("Date",'YYYY-MM-DD HH24:MI:SS')  + VARCHAR_FORMAT("INT",'MI')

but keep getting errors. I am doing this in dashDB

A: One option is to use:
select add_minutes(cast("date" as timestamp),"int") from yourTable

Another simple version is:
select cast("date" as timestamp) + "int" minutes from yourTable

A: On db2 iseries
 select TIMESTAMP_FORMAT(Date , 'YYYY-MM-DD') + INT minute as Newtimestamp from yourtable

or
 select cast(cast(Date as date) as timestamp) + int minute from yourtable

A: you can try this
Date_add(cast(`Date` as date),interval Int minute)


text:
Q: norm induced by inner product and triangle inequality Let $\langle\cdot,\cdot\rangle$ be a scalar product on a space $X$, and let $\lVert \cdot\rVert$ denote the norm induced by this scalar product. I need to show that for $x,y\in X$, $\lVert x+y\rVert=\lVert x\rVert+\lVert y\rVert $ holds $\Longleftrightarrow$ $x$ and $y$ are linear transformations of each other, i.e. $\exists \alpha\geq 0$ with $x = \alpha y$. While one direction is clear ($\Longleftarrow$) I am struggling with $\Longrightarrow$. How can I construct such an $\alpha$?

A: Do you know that the Cauchy-Schwarz inequality
$$\lvert \langle x, y \rangle \rvert \leq \lVert x \rVert \lVert y \rVert$$
is an equality if and only if $x = \alpha y$ for some $\alpha$? (If not, here's a proof.)
With that, you can prove the other direction by noting that
$$\lVert x \rVert^2 +\lVert y \rVert^2 + 2\lVert x \rVert \lVert y \rVert = (\lVert x \rVert + \lVert y \rVert)^2 = \lVert x + y \rVert^2 =\langle x+y , x+y \rangle \\
= \langle x , x \rangle + \langle y , y \rangle + 2\langle x, y \rangle = \lVert x \rVert^2 + \lVert y \rVert^2 + 2 \langle x , y \rangle.$$
This implies that $\langle x , y \rangle = \lVert x \rVert \lVert y \rVert$, which by the first claim means that $x = \alpha y$ for some $\alpha$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding limit of a 2 variable function (or show a lack of) $$ \lim_{x,y\to -1,0} \frac{πx^4 - 3xy^3}{ln(x^4+y^4)} $$
How do i find the following limit, or explain that it does not exist?

A: Let $r(x,y) = πx^4 - 3xy^2$ be the nominator and $s(x,y) = \log (x^4 + y^4)$ be the denominator.
Now find a sequence $(p_n)_n ∈ ℕ$ in $ℝ^2$ such that

*

*$p_n \overset{n → ∞}\longrightarrow (-1,0)$,

*$r(p_n)\overset{n → ∞}\longrightarrow π$, and

*$s(p_n) \overset{n → ∞}\longrightarrow 0$.

Then conclude.


text:
Q: How to use JS Form Validator API I am trying to use this form validator: https://via-profit.github.io/js-form-validator/
And at the bottom there is some API functions i'd like to use but I don't understand how they are used.
So basically created a form and have a submit button like this:
var validator = new Validator(formHandle, function (err, res) {
    return res;
}, options);

$(".submitMyForm").click(function(event) {
    validator.validate();
});

So I want to run the validator myself on click of the submit button but I know that that validate() function isn't how it works. Can someone explain how this API is used? There are no examples.
Thanks

A: Use
$(".submitMyForm").click(function(event) {
    new Validator(document.querySelector('.submitMyForm'), function (err, res) {
        return res;
    });
});

The res is a boolean and is always present
 If the form has a validation error, the argument err will be the Object, and if there are no errors - null.
In addition to this your input fields must have a data-rule attribute:
<input type="text" name="email" data-rule="required|email"/>

The vertical bar (|) is used the use multiple rules. The list of rules can be found the docs page of api
I have not tried the code so let me know what happens


text:
Q: Array inside a Java Class? public class Playlist
{
    String title;
    String genre;
    Boolean privatePlaylist = true;
    Song[] listOfSongs;

    public Playlist(String tl, String gn, Boolean priv)
    {
        tl = title;
        gn = genre;
        priv = privatePlaylist;
    }

    Song[] mostPlayedSongs()
   {
       return listOfSongs;
   }

}

Above is my code. I am trying to create a java class that returns a playlist. I want it to return a title, genre, whether the playlist is private or public. All three of these things are already constructed above. However, to that list, as a fourth property I would like to add an array that lists all the song in the playlist. The array is already a property I created above(Song[]listOfSongs). However, I do not know how to join this array to the other three properties and how to put the songs in this array. Any suggestions?

A: if you don't want to change the songs, you could just place it in the constructor:
public PlayList(String title, String genre, Boolean privatePlaylist, Song[] songs) {
    this.title = title;
    this.genre = genre;
    this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
    this.listOfSongs = listOfSongs;
  }

if the list of songs shouldn't be added in the constructor (i.e, it needs to be updated) I would use an ArrayList so you can change the size:
    // Field:
private ArrayList<Song> listOfSongs;

// Constructor
public PlayList(String title, String genre, Boolean privatePlaylist) {
        this.title = title;
        this.genre = genre;
        this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
        this.listOfSongs = new ArrayList<>();
}

// To edit the songs:
public void setListOfSongs (ArrayList<Song> listOfSongs) {
     this.listOfSongs = listOfSongs;
}

A: import java.util.ArrayList;

public class Playlist {
    public final String title;
    public final String genre;
    public final Boolean privatePlaylist;
    public final ArrayList<Song> listOfSongs;

    public Playlist(String tl, String gn, Boolean priv) {
        title = tl;
        genre = gn;
        privatePlaylist = priv;
        listOfSongs = new ArrayList<>();
    }
}

Example usage:
public class Main {
    public static void main(String[] args) {
        Playlist pl = new Playlist("title", "genre", false);
        pl.listOfSongs.add(...);
        System.out.println(pl.title);
    }
}


text:
Q: Checking if all true and reset a Boolean[] array using one-liner lambda expression of Java 8 Suppose I have a huge Boolean array flags:
Boolean[] flags = { true, false, true };    // 3 means "many"

I want to do two things on flags:

*

*check whether all the elements are true and return an indicator;

*reset all the elements to false.

Using lambda expression of Java 8, I can do them as follows:
indicator = Arrays.stream(flags).allMatch(flag -> flag);
Arrays.stream(flags).forEach(flag -> flag = false);
return indicator;

However this implementation scans flags twice. Since flags is huge, I don't want this. In addition, I do prefer the lambda way. Is there any way of implementing this checkIfAllTrueAndReset semantics with (one-liner) lambda expression which scans flags only once?

Related but not the same: What is the most elegant way to check if all values in a boolean array are true?

Note: I learn a lot from comments and answers. Thank you all!

*

*Stream is cool, but it is not for this.

*BitSet (and its bit-wisely atomic counterpart AtomicBitSet) is more suitable for this (so accepted as the answer; thank others).

*Side-effects in map (Stream or generally functional programming) are discouraged.

*Arrays.stream(flags).forEach(flag -> flag = false) (in my code) does not set anything!

A: This is a bad match for streams and lambdas and there is no really nice way to do it.
The problem is that steams work with the elements of a collection, but you need to modify the actual collection.
I think you are best of using an old-school for-loop for this.

One not-so-nice solution is to get a stream over the indices of the array and use a forEach of that to loop over the array. An AtomicBoolean could be used to store if all elements are true. This can be run in parallel, but I think an ordinary for-loop is better.
Example:
Boolean[] flags = { true, true, true };

AtomicBoolean allTrue = new AtomicBoolean(true);
IntStream.range(0, flags.length)
    .forEach(ix -> {
        if (!flags[ix]) allTrue.set(false);
        flags[ix] = false;
    });

Solution with atomic boolean
In in the comments of the question it was mentioned that it might be interesting with a solution for AtomicBoolean. In that case a solution with streams is possible, since an element can be reset without modifying the original collection.
The solution is really questionably however, so it's probably best to not use it. The problem is that map is used both for a side effect (resetting the value) and a mapping operation (extracting the old value). I think it is possible to run it in parallel but it's probably slower than a normal for-loop since the operation on each element is so tiny.
Also note that allMatch cannot be used since that operation is short-circuiting and if it finds a false it will terminate and subsequent elements will not be reset.
AtomicBoolean[] flags = { new AtomicBoolean(true), new AtomicBoolean(false), new AtomicBoolean(true) };

boolean allTrue = Stream.of(flags)
    .map(b -> b.getAndSet(false))
    .reduce(true, (a, b) -> a && b);

A: If you really want to do this with streams in one line, then you can do something like this
boolean allTrue = IntStream.range(0, flags.length).reduce(0,
    (result, i) -> flags[i] ^ (flags[i] = false) ? result : 1) == 0;

However this does not look like a good idea, and I would lean towards using a BitSet as suggested by @MarounMaroun

A: Classic example for using the BitSet class:

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value.

In complexity terms, BitSet uses ~1 bit for each boolean value, which is way better than using big array of Boolean objects.
Regarding checking of all bits are set or not (true or false), the API provides many useful methods - and they're really efficient.

A: If you know the size of the array in advance, you can check in O(1) time if all the flags are true. Store the size of the array in a variable arraySize and set an additional variable indexCount to 0. Instead of changing the flags within the array to true/false, increment/decrement the indexCount variable. If you want to know whether all flags are true, simply check arraySize == indexCount. If you do not need to know the current flag of specific items, you can completely dispense with the array.
This is also applicable, if you have to check whether a specific amount of flags is true.


text:
Q: pass file stream for model processing in Sails.js I have custom Create method I am trying to add for my Founder model in my Sails.js Application. The Application includes files and normal form fields. Following the advice of this tutorial.
I am trying to offload a lot of controller code into the Founder model for processing. This makes something a little awkward and results in the following error.
TypeError: Cannot read property 'stream' of undefined

This is the result of this line in my model function:
createFromForm: function(opts, cb){
  var id = opts.id;
  var params = opts.params;
  var newFilename = opts.avatartwo._files[0].stream.filename;

In the fourth line. Now in the controller the analogous code would be, following Sails syntax:
var newFilename = opts.req.file('avatartwo')_files[0].stream.filename;
I tred simply writing the result of req.file('avatartwo') into an option I passed into the model function via:
var opts = {
    params: params,
    id: id,
    avatartwo: req.file('avatartwo')
  };

Although this seems problematic, but because I am not the most informed on the subject, I do not know why. I could appreciate some elucidation here. Thanks!

A: To handle file upload in sailsjs use following code.
   var uploadedFile = req.file('some_file').upload({
    dirname: 'path to store the file',/* optional. defaults to assets/uploads I guess*/
    saveAs: 'new file name', /* optional. default file name */
    maxBytes: 5 * 1024 * 1024 //5 MB
}, function(err, uploadedFiles) {
    if (err) {
        return res.json(500, err);
    } else if (uploadedFiles.length === 0) {
        // handle if no files were uploaded
    } else {
        // do processing with file descriptor available at  uploadedFiles[0].fd
        //  pass to model in your case
        var opts = {
                params: params,
                id: id,
                avatartwo: uploadedFiles[0].fd
        };

    }
});


text:
Q: Cordova App 8.1 Caching HTTP request I'm working on an app using Visual Studio 2015 Cordova tools on Windows 8.1. Target is also Windows 8.1.
The app is caching HTTP GET request. So the second GET request to the same resource returns a cached response. I have tested after disabling the network adapter and I still get a response with the cached results.
I am using jsforce libray to connect to salesforce.com. I know I can add a timestamp on the url but I would like to find fix not a work around.
Any ideas?
[UPDATE]
Issue is not related to jsforce as it works well on Android. The error is specific to Windows 8.1 and cordova.

A: As suggested in the question, timestamping the url helps: I used:
var url = "https://api.myurl.com/" + param1 + "?" + new Date().getTime()

A: I wrote a simple library to add caching to REST requests for Cordova: https://github.com/glauber-md/mobile-simple-web-call#using-this-library .
The library will use a local database (sqlite) to fetch server data and cache it locally where applicable (e.g. HTTP GET requests with cache-related headers).
Once it receives a 304 Response, it will use the cached data.
To send a GET request, you'd use:
wscall.get(
    'http://myserver.org/users/1234',
    // (Optional) query strings
    null,
    function(responseData) {
        // Do something when the response is successful
    },
    function(error) {
        // Do something when an error happens
    }
);

Then the data would come from remote server or local cache depending of the HTTP server response.
Maybe it will help you.


text:
Q: The widget displaying over htmlelementview is not detecting gestures in flutter? I have placed a dropdown button in appbar which shows a dropdown list. In the body of my page, i am displaying a iframewidget using htmlelementview . When i click the dropdown button,the dropdown list is displaying over the iframe widget(which is the body of the page) and if i select the option from my dropdown list,there is no gesture detection(because it is displaying over the iframe) .
How to solve this?

A: You can wrap the dropdown list in a PointerInterceptor from pub.dev: pointer_interceptor


text:
Q: Azure Function disabled setting "user" field to HTTP request object on the 26th of April 2022 (!) Issue cannot be reproduced locally.
Azure Function Version ~4
Node Version 14.18.1
Creating a simple HTTP triggered Azure Function and setting just two simple properties we get the following code:
module.exports = async function (context, req) {

    req.auth = {authField: 'some value'}
    req.user = {userField: 'some value'}
    context.log(`${JSON.stringify(req,null,2)}`);

    context.res = {
        body: 'responseMessage'
    };
}

The logger prints the following object:
{
  "method": "POST",
  "url": "xxx",
  "originalUrl": "xxx",
  "headers": {
    /// ...
  },
  "query": {},
  "params": {},
  "body": { "name": "Azure" },
  "rawBody": "{\"name\":\"Azure\"}",
  "auth": { "authField": "some value" }
}

As you see only auth is set and not user.
The same failing behavior can be seen in version 4.2.0.
When I test with Azure Function ~3 the output looks like this:
{
  "method": "POST",
  "url": "xxx",
  "originalUrl": "xxx",
  "headers": {
    // ...
  },
  "query": {},
  "params": {},
  "body": { "name": "Azure" },
  "rawBody": "{\"name\":\"Azure\"}",
  "auth": { "authField": "some value" },
  "user": { "userField": "some value" }
}

As you see the field is set.
The following custom v4 4.1.0-17156 also sets the user field.
The field user was used by us through the express-jwt (v6.1.0) which is using it when no value is provided for requestProperty.
I could not yet reproduce it but in out transpiled from Typescript project, we get the following runtime error:
FailureException: Cannot set property user of [object Object] which has only a getterStack: TypeError: Cannot set property user of [object Object] which has only a getterat Object.run

The issue started at the beginning of the day of 26th of April 2022.
Questions:

*

*what is the reason?

*is a quick roll back to the functioning Azure Function custom version possible?

A: I found the culprit in this PR, which was added for Azure Function runtime v4.2.0.
The user field was added with only a getter.
We took the code and made the minimal example:
class Request {
    #cachedUser?: string | null;
    constructor() {
    }
    get user(): string | null {
        if (this.#cachedUser === undefined) {
            this.#cachedUser = "some value";
        }
        return this.#cachedUser;
    }
}

and got the following transpilied version:
var __classPrivateFieldGet =
    (this && this.__classPrivateFieldGet) ||
    function (receiver, state, kind, f) {
        if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter')
        if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError('Cannot read private member from an object whose class did not declare it')
        return kind === 'm' ? f : kind === 'a' ? f.call(receiver) : f ? f.value : state.get(receiver)
    }
var __classPrivateFieldSet =
    (this && this.__classPrivateFieldSet) ||
    function (receiver, state, value, kind, f) {
        if (kind === 'm') throw new TypeError('Private method is not writable')
        if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter')
        if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError('Cannot write private member to an object whose class did not declare it')
        return kind === 'a' ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value
    }
var _Request_cachedUser
class Request {
    constructor() {
        _Request_cachedUser.set(this, void 0)
    }
    get user() {
        if (__classPrivateFieldGet(this, _Request_cachedUser, 'f') === undefined) {
            __classPrivateFieldSet(this, _Request_cachedUser, 'some value', 'f')
        }
        return __classPrivateFieldGet(this, _Request_cachedUser, 'f')
    }
}
_Request_cachedUser = new WeakMap()

// this section is added for testing
const request = new Request()
request.user = 'new value'
console.log(JSON.stringify(request.user))

So, it always returns the the initial value, which in our example is "some value" but in the original code is simply undefined and does not allow to set it.


text:
Q: How to have different colors appear on command line when I run windows batch file? I'm running a batch file for building my software application. Basically it gets the latest sources, builds the project files, copies some files here and there, runs some custom tools and finally creates an installer using Installshield. For all the above actions I'm logging into a file as well. However I'm looking for something to add a little bit of customization (i.e. to have some colors for the logging messages that appears on the command prompt)
I tried to learn about adding colors on command line using this script
    @ECHO OFF
    :COLORCHANGER
    cls
    echo                   --------------------------------------------
    echo                   Background            Text
    echo                   --------------------------------------------
    echo                   0=Black               A=Bright Green
    echo                   1=Deep Blue           B=Bright Blue
    echo                   2=Dark Green          C=Light Red
    echo                   3=Blue                D=Light Purple
    echo                   4=Dark Red            E=Light Yellow
    echo                   5=Purple              F=Bright White
    echo                   6=Dark Yellow
    echo                   7=White
    echo                   8=Grey
    echo                   9=Deep Blue
    echo                   --------------------------------------------
    set /p col=Color code:
    Color %col%
    if not ERRORLEVEL 0 goto :showerror
    echo "Hello DOS"

    @ECHO Press any key to revert
    set /p col=Color code:
    Color %col%
    if not ERRORLEVEL 0 goto :showerror
    echo "Hello DOS"
    goto :exit

    :showerror
    @ECHO Cannot set color
    goto :exit

    :exit
    @ECHO Press any key to exit
@PAUSE

But this just changes the entire foreground/background color.
I want something like this. Different colors for different line
How do I achieve such a customization?


text:
Q: ListView with CheckBox Scrolling Issue I have android program but my list view doesn't work correctly.
if list view has more item with scrolling when i am going to click last checkbox with scrolling its check another item. please find my code sample.please help me to resolve this.
This my code for getView for adapter class
    @SuppressLint("InflateParams")
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi = convertView;
        if(convertView==null){
            vi = inflater.inflate(R.layout.unsettled_invoice_layout, null);
            holder = new ViewHolder();
            holder.desc = (TextView) vi.findViewById(R.id.usinvoicedesc);
            holder.chkbox = (CheckBox) vi.findViewById(R.id.selected);
            holder.chkbox.setOnClickListener(new OnItemClickListener(position));
            vi.setTag(holder);
            vi.setTag(R.id.selected, holder.chkbox);
        } else
            holder=(ViewHolder)vi.getTag();
        if(data.size()<=0){
            holder.desc.setText("No Data");
        }else{
            tempValues=null;
            tempValues = (Invoice)data.get(position);
            if(mode == 1){
                 int myColor =  Color.rgb(0, 128, 0);
                 if(tempValues.getStatus() == 2){
                        myColor = Color.rgb(0, 128, 0);     // Green
                        holder.chkbox.setChecked(false);
                 }else if(tempValues.getStatus() == 3){
                         myColor = Color.rgb(128, 0, 0);    // Red
                         holder.chkbox.setChecked(true);
                 }
                 holder.desc.setBackgroundColor(myColor);
            }
             holder.desc.setText(tempValues.toString());
             vi.setOnClickListener(new OnItemClickListener( position));
        }
        return vi;
    }

This is layout.xml which i used for android
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:clickable="false"
    android:descendantFocusability="blocksDescendants"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:paddingTop="0dip"
    android:textColor="#000000" >

    <LinearLayout
        android:id="@+id/usinvoicelayout"
        android:layout_width="fill_parent"
        android:layout_height="95dp"
        android:layout_marginBottom="3dp"
        android:layout_marginTop="2dip"
        android:clickable="false"
        android:descendantFocusability="blocksDescendants"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:orientation="horizontal"
        android:paddingTop="0dip" >

        <TextView
            android:id="@+id/usinvoicedesc"
            android:layout_width="520dp"
            android:layout_height="90dp"
            android:layout_gravity="start"
            android:gravity="center_vertical"
            android:textColor="#FFFF00"
            android:textSize="18sp" />

        <CheckBox
            android:id="@+id/selected"
            android:layout_width="50dp"
            android:layout_height="80dp"
            android:layout_marginStart="15dip"
            android:button="@drawable/checkbox_background"
            android:clickable="false"
            android:focusable="false"
            android:focusableInTouchMode="false" />
    </LinearLayout>

</LinearLayout>

A: For this you need to maintain a hashmap. When you clicked on checkbox put position in hashmap and in getview before set checkbox checked check position in hashmap. if exist then checked checkbox.

A: Please check below link:
It is specific solution for your issue of another item checkbox checked on scroll:
http://lalit3686.blogspot.in/2012/06/today-i-am-going-to-show-how-to-deal.html
In above Link example in your listview Adapter class getView() method add below code:
viewHolder.checkbox.setTag(position); // This line is important.

and for checkbox click add below code:
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
        list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
    }
});


text:
Q: Xamarin Unit Testing from the Command Line I'm coming from a native iOS / Android development background and I'm trying to understand the tooling around Xamarin Unit Testing using the Command Line.
From my point of view there are two types of code that you want to Unit Test:

*

*Plain Old C# Code - with no dependencies to any iOS / Android framework - so it shouldn't need an iOS / Android emulator to run on

*Code that depends on iOS / Android frameworks that needs to run on a device / emulator

The official Xamarin documentation mentions NUnitLite / Touch.Unit but it doesn't mention any support around Command Line. I did found an example though, but it's not clear to me if this is a tool that's officially supported by Xamarin. Also it seems that you can run tests only on the emulator/device using that tool.
Another example I've found around refers to xUnit.net - it seems that you can also run tests without an emulator / device, and that you can also run them on an emulator / device - however in that specific blogpost it's not documented how you do that.
So my question is: How should I approach Xamarin Unit Testing and what tools do you recommend using so I can have Command Line support in my CI.
Thank you

A: The most popular unit testing frameworks used with Xamarin are NUnit and XUnit. They are both similar to JUnit.

*

*Usually a Xamarin cross-platform app uses a Portable Class Library (PCL) project where the platform agnostic (shared) code sits: business logic, model, view models, service etc. This code is unit tested in a seperate pcl or.net45 test project which references the source project and nunit/xunit.

To run the nunit/xunit unit tests you need to run the corresponding test runner and point it tou your test assembly. Both nunit and xundit feature console runners which can be parameterized at will from your command line (see links).
Feel free to chose either nunit or xunit. I like them both.

*You might also have platform specific unit tests (which depend on the android/ios/uwp sdks) and that have to be run on a device. These tests can also be created with nunit or xunit and run with nunit device runner or xunit device runner. Basically what will happen here is you add an android/ios app project for testing which references nunit/junit, contains your device specific tests and links to your shared tests and can run them both on the device.

*There is also the layer of coded UI tests where NUnit, Xamarin UITest and Specflow might be of use. Im guessing this part is beyond the scope of your question.
But then again you are coming form Android and are used with gradle. Well Xamarin and .net does not have gradle but it has Cake. I use it to automate all my project builds/tests/ci/deployments etc.

Cake (C# Make) is a cross platform build automation system with a C# DSL to do things like compiling code, copy files/folders, running unit tests, compress files and build NuGet packages.

Your Cake script can look something like this:
Task("Run-Unit-Tests")
 .IsDependentOn("Build")
 .Does(() =>
 {
     NUnit("./src/**/bin/" + configuration + "/*.Tests.dll");
 });

 Task("Build")
  .Does(() =>
    {
       DotNetBuild("YourAndroid.csproj");
       DotNetBuild("YourCoreTests.csproj");
         ...
    }
  );

Cake comes with a bootstrapper file either (ps1 - powershell for windows or sh for mac) which downloads all the tools you need to run your script (cake itself, nuget, nunit/xunit runner etc).
Your command line/CI can run it like this:
./build.sh -Target Run-Unit-Tests

A: Unit testing in painful on Xamarin.
Don't have huge experience in Unit Testing mobile project, but if you want to test the app I would recommend this integration test approach:
1) For any calculation type functionality (you called it "Plain Old C#") use NUnit (it is supported by mono).
However I cannot come up with an example of such code, as heavy calculations should be done on server side. And there you do separate Unit tests
2) UITests(NUnit again) can be done to prove app is working and UI interaction call needed behavior.
Xamarin also providing TestCloud where app could be tested on many devices, but it is paid for Service. As Alternative you can setup build server like Jenkins to do this job for you.
Anyway - it is my view on how this could be done and hope it answered a bit on your question.


text:
Q: How can I retrieve a pointer to a variable that is in a list data structure? (All of this is done in C++)
I am working with a tree of nodes. The node class is simply some variables and a list of child-nodes. My goal is to retrieve a pointer to a node that is X layers down by matching it on a variable.
I am aiming to create a function that looks something like this.
Node* Node::returnChild(int depth, string match)
{
     ...
}

This should recursively iterate down all of the nodes children and then search for a node with a variable matching the string variable. When finding the matching node it should take the address of the node, save it in a pointer and return it to the functioncall.
I managed to make a working function that iterated down the sub-tree of nodes to the specified depth and found the correct node. It even printed out the string value to make sure that it was the correct node. But when trying to use the node via the pointer (provided by the function) outside of the function I got nothing.
In the function I used for a for-loop looking something like this:
for(auto forNode : this->children)

This worked fine, but it seems that the node "forNode" that is accessed within the scope of the loop is a temporary copy of the real node from the list. This copy does not "exist" outside of its for-loops scope and therefore I will not be able to access the node that was located at the pointers address when it is returned to me outside of the function (since there is no node at the address anymore).
So the real question is: How do I manage to get a pointer to the "real" node provided a list of nodes, the depth and a matching string?

A: you'll have to switch your for loop to something like:
for (auto& forNode : this->children)

this will make sure forNode is not copied by value and then invalidated when you leave the for loop scope.


text:
Q: Data structure which is efficient to add new number and count how many stored numbers smaller than some query number I want to find an efficient data structure that can handle the following use case.
I can add new elements to this data structure, e.g.
I call add() API, add([2,3,4,5,3]), then this data structure stores [2,3,3,4,5]. I can query some target and return how many numbers smaller than this target. e.g. query(4), return 3 (since one 2 and two 3). And the frequencies of calling add and query are in the same order.
Firstly, I think of segment tree, however, the input number can be anyone in int value, space will be O(2^32)
Could you give me some advice about which data structure should I use?

A: You can do this using an order statistic tree, which is a kind of binary search tree where each node also stores the cardinality of its own subtree. Inserting into an order statistic tree still takes O(log n) time, because it's a binary search tree, although the insert operation is a little more complicated because it has to keep the cardinalities of each node up-to-date.
Computing the number of members less than a given target also takes O(log n) time; start at the root node:

*

*If the target is less than or equal to the root node's value, then recurse on the left subtree.

*Otherwise, return the left child's cardinality plus the result of recursing on the right subtree.

The base case is that you always return 0 for an empty subtree.


text: Q: Powershell project in visual studio How do I open a powershell project in visual studio. The project was created in GitLab originally and then put in VSTS, am able to clone it to my local machine but do not see an option to open the project. VS2015 is looking for a soln file or similar files. Am guessing because the project was not initially built in VS2015?


text:
Q: Make htaccess RewriteRule ignore certain folders I want to use a rule like this in my htaccess file so that I can have pretty URLs:
RewriteRule ^(.*)/ category.php?cat=$1 [QSA,L]
It works just fine, but also affects the two real subfolders I have in there images/ and blog/.  it makes it so I can't get any pictures on my site and my blog is broken.  How can I ignore those folders?
At first i figured I would just write this and have less pretty URLs:
RewriteRule ^(.*)_category/ category.php?cat=$1 [QSA,L]
But I know there are RewriteConds that will make the "_category" uneccessary, I just don't seem to be able to write it out right.  I've been reading the apache docs but it's a bit over my head.  How should I go about this?

A: I figured this out.  I just needed to use:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/ category.php?cat=$1&id=$2 [QSA,L]
I'm answering it here in case anyone stumbles across it via google.


text:
Q: labeling a group of members as private/public in c# in a c++ class declaration, you can label a group of members as private or public, e.g.
private:
  int x;
  double y;

seems like there's no way to do this in c#. am I wrong?

A: No, you can't not do this in C#.
At best, you can use the default visibility for members, which is private, and not use private, but for public, you have to indicate it for all members.

A: You're correct. Although, if you leave visibility keyword off altogether, a member defaults to private.

A: No you're not wrong. If you don't write any modifiers it will be assumed as private.


text:
Q: Can I limit polygon line length (like 100m) in Google Maps? My Requirement is to limit the polygon line length based on the given input. I've tried the following code but I am not able to successfully limit the length of the line.

The image above is the type of line segment that I would like to limit the length of.
Var drawingManager;

var Map;
map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {lat: 24.886, lng: -70.268},
    mapTypeId: google.maps.MapTypeId.TERRAIN
});

var polyOptions = {
    draggable: true, // turn off if it gets annoying
    editable: true,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
};

drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    markerOptions: {
        draggable: true
    },
    polylineOptions: {
        editable: false
    },
    rectangleOptions: polyOptions,
    circleOptions: polyOptions,
    polygonOptions: polyOptions,
    map: map
});

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
    alert();
        if (e.type != google.maps.drawing.OverlayType.MARKER) {
        drawingManager.setDrawingMode(null);
        var newShape = e.overlay;
        newShape.type = e.type;
        google.maps.event.addListener(newShape, 'click', function() {

        });
    }
     google.maps.event.addListener(newShape, 'set_at', function() {
        // complete functions
        alert();
      });

      google.maps.event.addListener(newShape, 'insert_at', function() {
        // complete functions
        alert();
      });
});


text:
Q: C# - Windows Mobile - Bluetooth Pairing I've been given the task of building a Windows Mobile app for our company that quickly pairs a device by scanning it's bar code. I can discover the device, and talk to it, but I am stuck as far as pairing.
In C# / Windows Mobile 6, how do I pair a device? I don't really need to talk to the device within the app, I need to pair it so other applications can use it.
Is there an API I need to do this? I've seen things saying I need to register a pass key, etc? I can't seem to find any documentation on the actual pairing process, just connecting to it. (Just connecting to it, doesn't actually pair it.)

A: You can use my library 32feet.NET.  Use method BluetoothSecurity.PairRequest See e.g. Bluetooth Security (That should work regardless of whether the device has Microsoft's own Bluetooth stack installed or the device has Widcomm/Broadcom or SSO Bluetopia).
The process of 'pairing' should also enable the services at the same time.  If not we probably have other APIs for that too.  Which services are used?  SerialPort, others?


text:
Q: How to collect async response using RxJava Here is my goal: collect responses from async tasks that come from a third party library
requirement: use RxJava2 to accomplish in order
I'm stuck at thinking use which operator or operators to do so, ideas are appreciated.
My thought is:
Flowable.fromIterable(list)
    .anOperatorCanOnNextTheResponse()
    .buffer()
    .subscribe(newList)

A: Finally I have accomplish by using PublishProcessor, PublishSubject can also do the trick, but I skip the difference between them.
val mPublishProcessor: FlowableProcessor<String> = PublishProcessor.create<String>().toSerialized()

list.forEach {
    doSomeAsyncTasksWithCallback(string) {
      mPublishProcessor.onNext(string)
    }
}

mPublishProcessor
.buffer(list.size)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
   doSomethingWithTheCollectedStrings()
}


text:
Q: Having better control on captions in two languages under each image I need to insert two captions (in polish and exactly the same translated into english) under each of the figures and above each of the tables in my document.
Once captions were defined I would like to have control whether only one or both captions will be displayed in the whole document through boolean variable.
What is the most elegant / smart way to do that?

EDIT
According to suggestions in comments, I used bicaption to define two captions.
\usepackage{polski}
 \usepackage[english, polish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage[lang=english]{bicaption}

\begin{figure}[H]
    \includegraphics[width=0.5\textwidth]{Einrad}

    \bicaption{Polish caption here with special letters: ĄĆŹŚÓŁ}{English caption just below}

    \label{Fig:FIgBicycle}
\end{figure}

However, I don't like:

*

*that I needed to use babel to have properly labelled captions ("Rysunek" for polish and "Figure" for english), because in my document I'm already using many packages and I wish to avoid potential conflicts,

*the big space between two captions,

*that I can't see an option to control whether only the first, second or both captions were displayed

EDIT 2
Minimal Working Example:
%\documentclass[review,authoryear]{elsarticle}
\documentclass[oneside,12pt]{mwbk}

\usepackage{polski}
 \usepackage[english, polish]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage[lang=english]{bicaption}

\usepackage{graphicx,float,multirow}
\graphicspath{ {figures/} }

\usepackage[caption = false]{subfig}
\usepackage{lineno,hyperref,amsmath}
\usepackage[normalem]{ulem}

\linespread{2}

\begin{document}

\linenumbers

\section{Some text}

\subsection{Some subsection}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vulputate nisi dolor, vitae eleifend sem vehicula a. Nulla libero mi, scelerisque et dapibus at.

\begin{figure}[H]
    \includegraphics[width=0.5\textwidth]{Einrad}

    \bicaption{Polish caption here with special letters: ĄĆŹŚÓŁ}{English caption just below}

    \label{Fig:FIgBicycle}
\end{figure}

\begin{table}[H]
    \centering
    \bicaption{Polish caption here with special letters: ĄĆŹŚÓŁ}{English caption just below}
    \label{my-label}
    \begin{tabular}{|l|l|}
        \hline
        1st col   & 2nd col \\ \hline
        some text & ---     \\ \hline
    \end{tabular}
\end{table}

\end{document}


text:
Q: Python memory leak which is not recognized by profiler The program can work fine for days, but at some random point it starts growing ~60MB/hour.

*

*Profilers like guppy and pympler doesn't show leaked memory. (they show ~30mb used, while ps resident memory use is 1,5GB)

*Gdb-heap C profiler shows a lot of chunks of memory as 'uncategorized'.

*Gc.collect didn't show garbage collection problems.

*We don't use any non-default C libraries, so I don't think it's C level leak.

Is that a dead end? Can something else be done to find the issue?


text:
Q: Map [0,1] to [0,1) in floating point math Suppose I have a function on floats:
f whose range is [0, 1].
I'd like to create a function
g whose range is [0, 1)
such that
f(x) < f(y) -> g(x) < g(y).
With finite precision floating point math, I can't get the range of g to be exactly [0,1), but how close can I get, and how do I do it?


text:
Q: Lookup Database record from array value and insert new key and value into array I have an array, I would like to add another value to it from a database, using the [numo] value to lookup the record, here is the current array:
Array
(
    [0] => Array
        (
            [numo] => 667820161009
        )

    [1] => Array
        (
            [numo] => 667820112001
        )

and here is what I want to achieve:
Array
(
    [0] => Array
        (
            [id] => 33
            [numo] => 667820161009
        )

    [1] => Array
        (
            [id] => 34
            [numo] => 667820112001
        )

I presume that would have to loop through the array, nesting a SELECT query and then insert a new key and value, but I have no idea where to start and have searched and searched.
Many thanks in advance for you help
Stu

A: My guess without knowing anything about your DB (or specifically the table that this data comes from) would be:
SELECT id FROM table WHERE numo = 667820112001

Some PHP to go along with this:
<?php
$array = array(
    array(
        'numo' => 667820161009
    ),
    array(
        'numo' => 667820112001
    )
);

$stmt = $pdo->prepare('SELECT id FROM table WHERE numo = :numo');
$stmt->bindColumn('id', $id);

foreach($array as &$child) {
    $stmt->execute(array(
        ':numo' => $child['numo']
    ));

    $child['id'] = ($stmt->fetch(PDO::FETCH_BOUND)) ? $id : null;

    $stmt->closeCursor();
}
?>

However you can eliminate some queries with:
<?php
$array = array(
    array(
        'numo' => 667820161009
    ),
    array(
        'numo' => 667820112001
    )
);

$numos = array()
foreach($array as $child) {
    $numos[] = $child['numo'];
}

$stmt = $pdo->prepare('SELECT id FROM table WHERE numo IN ('.implode(',', $numos).')');
$array = $pdo->fetchAll();
?>

A: You can use one SQL query to fetch all the ID values if you form an array of numo values.
$array = array( ...);

$numos = array();
foreach( $array as $entry)
{
    $numos[] = $entry['numo'];
}

$sql = 'SELECT id, numo FROM table WHERE numo IN ( ' . implode( ', ', $numos) . ' )';
$result = mysql_query( $sql);

$array = array(); // Reset the array
while( $row = mysql_fetch_array( $result))
{
    $array[] = array(
        'id' => $row['id'],
        'numo' => $row['numo']
    );
}


text:
Q: How do OS's handle /etc/hosts algorithmically? I have a huge /etc/hosts file with 18,000 lines.  I use it to block adservers and such.  My browsing performance seems to be fine, but I wonder if there's some size at which I'll start slowing myself down?  How do OS's store the hosts file during operation?  I can think of lots of ways, from slow to fast, and my a priori assumption is that it is handled efficiently since it is so central to networking.  Here are some ways I can think of from simple to more complex:

*

*Read from file each time it's needed.

*Read once

*

*linear search

*sort, then binary search

*use a trie

*use a hash, but how does it minimize collisions

There's lots of ways that seem reasonable.  What's actually used?
It seems like this question must have been answered somewhere, so pointers to an existing resource are welcome.  I did look, but maybe not in the right place.

A: You should tell what OS you are using but anyway, a usual method to improve name resolution performance with Unix and Unix-like system is to use a daemon (commonly nscd) which caches positive and negative resolutions and quickly answers most requests. When /etc/hosts is modified, at least under Solaris, this cache is invalidated.


text:
Q: Como pegar o valor de um input e atribuir a outro? Galera tenho um form com vários input que seguem uma sequencia de par, ou seja: valor1 para custo1, valor2 para custo2 e etc...
Preciso pegar o valor do input valor1 e atribuir o mesmo valor para o custo1.
Porém tenho vários inputs e pensem em criar um script onde irei fazer a atribuição, e em cada input eu chamo o evento e informo o nome do input, o script vai e atribui o valor no input desejado.
O problema e que não sei com fazer isso, será que alguém pode me ajudar?

<input type='text' id='valor1' name='valor1'>
<input type='text' id='custo1' name='custo1'>

<input type='text' id='valor2' name='valor2'>
<input type='text' id='custo2' name='custo2'>

A: Você pode atualizar o custo referente enquanto digita, por exemplo:
HTML (criar uma classe "valor" e um atributo "custo" para tornar um pouco mais dinâmico):
JAVASCRIPT:

    $(document).ready(function(){
        $(".valor").on("input", function(){
            var textoDigitado = $(this).val();
            var inputCusto = $(this).attr("custo");
            $("#"+ inputCusto).val(textoDigitado);
        });
    });

<input type='text' id='valor1' class='valor' name='valor1' custo='custo1'>
<input type='text' id='custo1' name='custo1' >

<input type='text' id='valor2' class='valor' name='valor2' custo='custo2'>

<input type='text' id='custo2' name='custo2' >

A: Basta definir a propriedade value do elemento:

var a = document.getElementById('a');
var b = document.getElementById('b');

b.value = a.value;
<input id='a' type='text' value='StackOverflow'/>
<input id='b' type='text'/>


text:
Q: Why did ActiveRecord::Relation remove array_delegable? in Rails 5? In Rails 4, ActiveRecord::Relation automatically delegated array methods like slice, so you could say, for example SomeModel.where(prop: 'value').slice(0, 10)
That has been removed in Rails 5.  Why?
Here is the relevant code in ActiveRecord::Relation in rails 4:
def array_delegable?(method)
  Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
end

def method_missing(method, *args, &block)
  if @klass.respond_to?(method)
    scoping { @klass.public_send(method, *args, &block) }
  elsif array_delegable?(method)
    to_a.public_send(method, *args, &block)
  elsif arel.respond_to?(method)
    arel.public_send(method, *args, &block)
  else
    super
  end
end

And here it is in Rails 5:
def method_missing(method, *args, &block)
  if @klass.respond_to?(method)
    scoping { @klass.public_send(method, *args, &block) }
  elsif arel.respond_to?(method)
    arel.public_send(method, *args, &block)
  else
    super
  end
end

(Note: I tried to post this question in the Rails forum, but apparently registration is broken there and there is no way to ask for help)

A: Here are a couple commits with brief explanations:
https://github.com/rails/rails/commit/95c24e9f9aed36b2ee650dbf779cf56dcdbbede3
https://github.com/rails/rails/commit/9d79334a1dee67e31222c790e231772deafcaeb8
Seems like there should be an addition to the Changelog though.  I didn't see this mentioned in there.


text:
Q: PHP form validation from jQuery ajax post I have a form (firstname, lastname etc) which is validated client side using http://bassistance.de/jquery-plugins/jquery-plugin-validation/ validator. I am then posting the form fields to the server using ajax serialize() however I was wondering if someone could share a class (or link to class) for the server side validation.
I have tried using http://www.html-form-guide.com/php-form/php-form-validation.html but this looks like this class is expecting the name of the form field to apply validation.
Thanks

A: That library does not require the name of the form. If you look at the example that they have given you, they only use the names of the input fields.
<?PHP
require_once "formvalidator.php";
$show_form=true;
if(isset($_POST['Submit']))
{
    $validator = new FormValidator();
    $validator->addValidation("Name","req","Please fill in Name");
    $validator->addValidation("Email","email",
"The input for Email should be a valid email value");
    $validator->addValidation("Email","req","Please fill in Email");
    if($validator->ValidateForm())
    {
        echo "
Validation Success!
";
        $show_form=false;
    }
    else
    {
        echo "Validation Errors:";

        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
          echo "
$inpname : $inp_err
\n";
        }
    }
}

if(true == $show_form)
{
?>
<form name='test' method='POST' action='' accept-charset='UTF-8'>
Name: <input type='text' name='Name' size='20'>
Email: <input type='text' name='Email' size='20'>
<input type='submit' name='Submit' value='Submit'>
</form>
<?PHP
}//true == $show_form
?>

The name of the form is "test". It is not being checked. Please post your source code so that someone can help you find what the issue is.
You can also checkout the following post for more libraries - Easiest Form validation library for PHP?

A: ...ok, if you are looking for sanitizing the passed value to make sure no bad things get through than you can look here:
http://php.net/manual/en/filter.filters.sanitize.php
if you are looking for 'validation' based on some pre-set rules, please specify.
You can also partially sterilize the passed values like this if you do need only basic char. set:
function sterilize($input) {

$input = htmlentities($input);

$input = strip_tags($input);

    return $input;

}

FYI as you mentioned below, for the email address you could youse something like this:
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL): '';


text:
Q: Heroku - Transfer domain name befor deployment I have reserved a domain name with another hosting provider that I would like to transfer to Heroku before deploying my application. Indeed, the domain name transfer takes up to 2 weeks and I would like it to be transferred as soon as possible so that I can deploy my application on this domain name.
So, can I import my domain name without deploying my application?
Thanks.
Paul-Emile


text:
Q: Windows 10 "unable to connect to this network" I read that a lot of people have this problem, but I am not sure if they have it with all networks like I do.
It started happening about 2 days after I installed Windows 10. There are several solutions I have tried, but they only seem to work for a day. Then, on it's own, while my laptop is in use, internet dies on me and I am unable to connect. Restarting my laptop, turning air plane mode on and off and forgetting the network don't work. Note that I have this with all networks in the list. I really can't connect unless I disable my wifi adapter, or reset the settings, or reinstall it.
I have a Qualcomm Atheros AR9485 Wireless Network Adapter, I run windows 10 Home, version 20H2 (not sure if you need that info for anything)
I have tried several things from this list, but like I said, they only work for a day, or maximum 2:
https://windowsreport.com/windows-10-cant-connect-this-network/
I tried flushing dns, uninstalling the wireless network adapter driver, checking if IPV4 and IPV6 are enabled (which they are), turned IPV6 off, check if the adapter is set to turn off when laptop is not in use (the only thing I was able to do with that is at 5.1 in the article, the rest seemed fine), I checked if I have the latest drivers (which I obviously would have, since I had to uninstall them so often to get my internet to work at all), downloaded and installed them seperately from the Qualcom Atheros site, checked other power options related to the adapter (which would be weird, since it happens when my laptop is in use), ran troubleshoot (which only resets the adapter when connected, and won't work if I can't connect.)
What to do? I never had problems with windows 8.1, but I chose to go to windows 10 for several reasons, and I really don't wanna give that up.

A: It looks like a lot of people are having this problem. Looks like some have solved it by getting an updated driver. Here was on link: http://cdgenp01.csd.toshiba.com/content/support/downloads/TCK0001000D.exe
I'll see if Atheos has one.....


text:
Q: JetBrains PhpStorm / DataGrip introspecting Oracle database error On PhpStorm version 2017.1.3 but I think that this error is present on any JetBrains IDE with database support.
When I choose to synchronize an Oracle schema, some objects like triggers are not shown on database and I found an error on the log.

I could not find any reason and it was working on older PhpStorm / DataGrip version (before 2016.1)
In the options tab I've added an object filter. Without it there are 5000+ tables. Even removing the regular expression on the object filter I still have the same error.
Capture of Options and Advance Options. The oracle client used is Thin.

A: On your connection properties check if you are using Thin Driver and change it to change to OCI.


text:
Q: Trying to profile CodeIgniter Application but can't get report I have tried to include $this->output->enable_profiler(true); in my controller as per the official documentation. I've added the line of code under parent::__construct(); in my constructor, but the webpage doesn't load.
UPDATED
This is withing my constructor:
parent::__construct();
        $this->output->enable_profiler(true);
        $sections = array(
            'config' => FALSE,
            'queries' => TRUE,
            'post' => FALSE,
            'memory_usage' => TRUE,
            'get' => FALSE,
            'benchmarks' => TRUE,
            'controller_info' => FALSE,
            'url_string' => FALSE,
        );
        $this->output->set_profiler_sections($sections);

A: It might just be a copy/paste error but you have
$this-output-set_profiler_sections($sections);

When you should have:
$this->output->set_profiler_sections($sections);


text:
Q: Screen fails to draw the second time it is initiated after exit in android (libgdx) This is the menuscreen class which when called will draw the menuscreen using the spritebatch passed as a parameter. the problem is that the draw command fails to execute the second time around (i.e after we restart the application) while all other features work perfectly (you can still use the buttons we placed on the screen if we click on the position we placed it in )
public class MenuScreen extends Screen
{
    Texture Background,Playgame,Credits;
    Vector2 PlaygamePos,CreditsPos;
    Rectangle PlaygameRect,CreditsRect,touchRect;

public MenuScreen()
{
    Background = GameEngine.LoadTexture("Menu/bg.png");
    GameEngine.BackgroundTexture = Background;

    Playgame = GameEngine.LoadTexture("Menu/newgame.png");
    Credits = GameEngine.LoadTexture("Menu/credits.png");

    PlaygamePos = new Vector2(500,300);
    CreditsPos = new Vector2(500,200);

    PlaygameRect = new Rectangle(PlaygamePos.x,PlaygamePos.y,Playgame.getWidth(),Playgame.getHeight());
    CreditsRect = new Rectangle(CreditsPos.x,CreditsPos.y,Credits.getWidth(),Credits.getHeight());
}

@Override
public void Update(OrthographicCamera camera)
{
    if(GameEngine.isBackButton == true)
    {
        GameEngine.isBackButton = false;
        Gdx.app.exit();
    }

    if(GameEngine.isTouched() == true)
    {
        Vector3 touchPos = new Vector3();
        touchPos = GameEngine.TouchPos(camera);

        touchRect = new Rectangle(touchPos.x,touchPos.y,10,10);

        if(touchRect.overlaps(PlaygameRect))
        {
             SelectScreen = ScreenSelect.GamePlay;
        }
        else if(touchRect.overlaps(CreditsRect))
        {

        }
    }
}

@Override
public void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.draw(Credits,CreditsPos.x,CreditsPos.y);
    spriteBatch.draw(Playgame,PlaygamePos.x,PlaygamePos.y);
}

@Override
public void Resume() {
    // TODO Auto-generated method stub

}

@Override
public void Pause() {
    // TODO Auto-generated method stub

}

@Override
public void Dispose()
{

}

}
Even we tried Disposing textures and SpriteBatches none worked!

A: Most likely you are running into a mismatch between the lifetime of Java objects (tied to the life of the application process) and the lifetime of texture objects (tied to the life of the OpenGL context which is tied to the visibility of the Activity).  On app "restart", I suspect you're actually just exiting the Activity, and Android is caching the process and starting a new Activity in the same process when you "re-start" the you app.  In this case you'll have a valid Java Texture object, but the underlying bytes it "points to" in the OpenGL context are gone (since the OpenGL context is invalidated when the Activity is no longer visible).
The fix is to re-load textures on activity creation.  You can either just make sure all your objects that contain textures (and objects that contain objects that contain textures, etc) are tied to the Activity lifecycle.


text:
Q: java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.NullPointerException Hi I am trying to build our app for its release variant but it triggers the following error when running the app for the first time.
Steps to replicate:

*

*Build a signed apk

*Install the apk on the emulator

*App Crash

FATAL EXCEPTION: main
Process: silicon.android.app.alpha, PID: 7837
java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
         at android.app.ActivityThread.installProvider(ActivityThread.java:7493)
         at android.app.ActivityThread.installContentProviders(ActivityThread.java:6999)
         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6770)
         at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2134)
         at android.os.Handler.dispatchMessage(Handler.java:106)
         at android.os.Looper.loopOnce(Looper.java:201)
         at android.os.Looper.loop(Looper.java:288)
         at android.app.ActivityThread.main(ActivityThread.java:7898)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
         at com.google.firebase.components.AbstractComponentContainer.setOf(Unknown Source:220)
         at com.google.firebase.components.ComponentRuntime.setOf(ComponentRuntime.java:46)
         at com.google.firebase.components.RestrictedComponentContainer.setOf(RestrictedComponentContainer.java:150)
         at com.google.firebase.heartbeatinfo.DefaultHeartBeatController.lambda$component$4(DefaultHeartBeatController.java:157)
         at com.google.firebase.heartbeatinfo.DefaultHeartBeatController$$ExternalSyntheticLambda3.create(Unknown Source:0)
         at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
         at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
         at com.google.firebase.components.Lazy.get(Lazy.java:53)
         at com.google.firebase.FirebaseApp.initializeAllApis(FirebaseApp.java:606)
         at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:307)
         at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:271)
         at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:256)
         at com.google.firebase.provider.FirebaseInitProvider.onCreate(FirebaseInitProvider.java:51)
         at android.content.ContentProvider.attachInfo(ContentProvider.java:2451)
         at android.content.ContentProvider.attachInfo(ContentProvider.java:2421)
         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(FirebaseInitProvider.java:45)
         at android.app.ActivityThread.installProvider(ActivityThread.java:7488)
         at android.app.ActivityThread.installContentProviders(ActivityThread.java:6999)
         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6770)
         at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2134)
         at android.os.Handler.dispatchMessage(Handler.java:106)
         at android.os.Looper.loopOnce(Looper.java:201)
         at android.os.Looper.loop(Looper.java:288)
         at android.app.ActivityThread.main(ActivityThread.java:7898)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

Coincidentally, this only runs on release, but on debug it works fine. I have added -dontshrink, -dontoptimize, -dontobfuscate to my proguard rules which is why I could generate the stack trace.
Build Gradle Values
android {
    compileSdkVersion 33
    buildToolsVersion "33.0.0"
    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 33
        versionCode 1
        versionName '0.1.0'
        consumerProguardFiles "consumer-rules.pro"
}

minifyEnabled, textCoverageEnabled, shrinkResources all turned to false
Firebase Libraries
"analytics"  : "com.google.firebase:firebase-analytics-ktx",
"crashlytics": "com.google.firebase:firebase-crashlytics-ktx",
"config"     : "com.google.firebase:firebase-config-ktx",

A: To everyone who may have encountered this issue, it's because Dexguard obfuscation conflicts with some libraries I am using. In this case, the firebase libraries, crashlytics, and the desugaring SDK are notable.
Bringing down firebase and the desugaring SDK to older versions solved my issue.
If you encounter this next time, double-check your commits and look for SDK dependency updates. Start from there because the logs will not be helpful in any way.
GOODLUCK!


text:
Q: How to change output file directory in latex? I'm using MikTeX 2.9 (pdflatex) and WinEdt 8.2. I know that all output files such as .tex, .pdf, .dvi, .log are important and I cannot simply delete them so I would like to ask how to get files (.pdf and .tex) in one directory and other files in another directory.
I have already found very similar questions here with answers, but I was not still able to sort it out. I have found out that I should use --output-directory=dir and --aux-directory=dir but I don't exactly know how to work with it. Could anyone help me with this problem?

A: Click on the Options menu and select Execution modes…. In the popup window, click on the TeX Options tab. There you'll can choose your TeX aux directory, like in this window:

With such a setting, the aux directory will be a TeXAux subdirectory of your input file (or of your master file if you have one).  If you deselect the Use %P … option underneath, the TeXAux directory will be automatically created if it doesn't exist yet.
I suggest, if not yet done, to create a localtexmf directory: this is where personal file styles, or packages that you install yourself (not through MiKTeX Package Manager)  should be stored. You'll create one with MiKTeX Options, root tab:

and then let WinEdt know about it through the Execution Modes interface.


text:
Q: Using iOS CoreText APIs that don't use a CGContextRef in a non-main Thread The iOS APIs don't mention threading restrictions on CoreText APIs.  To what extent are they safe to use on non-main threads when calling functions that don't use a CGContextRef?
Specifically, I'm trying to create a bunch of NSAttributedStrings using a custom truncation algorithm, and I'd like to be able to background the work.  I'm only using:
CTLineCreateWithAttributedString
CTLineGetTypographicBounds
CTLineGetStringIndexForPosition

A: I should have checked <CoreText/CoreText.h>.
/*!
    @header

    Thread Safety Information

    All functions in this header are thread safe unless otherwise specified.
*/

A: "Multicore Considerations: All individual functions in Core Text are thread safe. Font objects (CTFont, CTFontDescriptor, and associated objects) can be used simultaneously by multiple operations, work queues, or threads. However, the layout objects (CTTypesetter, CTFramesetter, CTRun, CTLine, CTFrame, and associated objects) should be used in a single operation, work queue, or thread."
from https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_Framework_Ref/_index.html


text:
Q: Can it be necessary to require a module (child_process in this case) more than once? In a code I picked up, the app.js contains, in the same scope:
var childProcess1 = require("child_process");
childProcess1.fork(...)
...
var childProcess2 = require("child_process");
childProcess2.fork(...)

Can there be any reason to require twice?
PS: more details on request :)

A: It could be necessary, if requires are in different functions. Like this:
function foo() {
  var childProcess1 = require("child_process");
  childProcess1.fork(...)
}

function bar() {
  // here you can't use childProcess1, so
  var childProcess2 = require("child_process");
  childProcess2.fork(...)
}

But it's better to change the code to something like this:
var childProcess = require("child_process");

function foo() {
  childProcess.fork(...)
}

function bar() {
  childProcess.fork(...)
}

There could be reason not to have global variable like this (but not with built-in child_process module I guess)

A: Typically you just require() a module once, since future require()s for the same module will return the exact same value. Because of this trait, re-using the result of the first require() avoids the additional, minimal overhead of a call to require().

A: No, it will virtually never be necessary. In fact, the values returned by require are cached, so the first call to require("foo") actually runs the module, while additional calls simply access the original return value stored in require.cache (in particular, require.cache[require.resolve("foo")]).
The only case multiple calls would be necessary (or have any effect whatsoever) is if your code tampers with require.cache, which it probably shouldn't do.


text:
Q: Finding the (x,y) value of a figure How do I find the point where the graph cuts x axis (function is zero). I am not familiar with Mathematica plotting. In Matlab, I can use the "data cursor" and move it along the curve to find the point that gives the y value when x is 0. Can a similar thing be done in Mathematica?

A: You can MeshFunctions and Mesh to show the points on the x-axis
plt = Plot[ Sin[x] + x Cos[x], {x, -3 Pi, 3 Pi},
  MeshFunctions -> {#2 &}, Mesh -> {{0}},
  MeshStyle -> Directive[Red, PointSize[.03]]]

and post-process the Plot output to add Tooltips to Points:
Normal[plt] /. Point[x_] :> Tooltip[Point[x], x[[1]]]

A: According to my understanding you want to find coordinates by using mouse cursor, for this i have attached code for simple graph of sin(x). you can add your graph in graphics option and can get your desired coordinates by using code
   {Graphics[Plot[Sin[x], {x, 0, 2 Pi}]], Dynamic[MousePosition["Graphics"]]}
hope you get what you want


text:
Q: SQL Query to comparing the minutes in SQL 2008 R2 server What am trying to do is, I have table with Date field. Date field has entry in datetime format. Using that i have to display todays records after 5PM. Can anyone help me on this to get this query.
Thanks

A: Try this.
Select *
FROM tablename
WHERE datefield < '1/1/2014 17:00:00.000'

A: select * from table1
where
CONVERT(date,Datefield) = CONVERT(date,GETDATE()) and
CONVERT(time,Datefield) > convert(time,'17:00')

A: After 5 Pm ?
Try this:
select *From Table where DATEPART(hh,yourdatefield)>=17 and and convert(date,yourdatefield,103)='2014-04-03'

this will the the records after 5pm .


text:
Q: Sinon Spy / Stub for Function inside Function (Private Function) I'm new Sinon. i'm unable to spy the private ajax function
Actual code in library.js
function ajax () {
    console.log("I'm a");
}

function getJSON() {
    ajax();
    console.log("I'm b");
}

exports.getJSON = getJSON;

Actual Test Code
var sinon = require('sinon');
var lib = require('./library');

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        var ajax = sinon.spy(lib, 'ajax');
        lib.getJSON();

        ajax.restore();
        sinon.assert.calledOnce(ajax);
        done();
    });
});

Note: I already tried with below object example. it works like charm.

Working Code in library.js
var jquery = {
    ajax: function () {
        console.log("I'm a");
    },

    getJSON: function () {
        this.ajax();
        console.log("I'm b");
    }
};

exports.jquery = jquery;

Working Test Cases.
var sinon = require('sinon');
var $ = require('./library').jquery;

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        var ajax = sinon.spy($, 'ajax');
        $.getJSON();

        ajax.restore();
        sinon.assert.calledOnce(ajax);
        done();
    });
});

I'm getting error like below during mocha test
1) Tutor Test getJSON Calling ajax:
     TypeError: Attempted to wrap undefined property ajax as function
      at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:113:29)
      at Object.spy (node_modules/sinon/lib/sinon/spy.js:41:26)
      at Context.<anonymous> (test.js:41:26)

A: As far as i know, Spying private Variables / Function is not possible in Sinon. So avoid using Sinon for those use cases.

Note: Your (ajax) function does not have param and return value and not bind to the exported object is real challenge for sinon

In such case, If you wanted to make sure whether ajax function is triggered or not. You can use rewire.
Below is the working code.
var rewire = require('rewire');
var lib = rewire('./library');
const assert = require('assert');

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        lib.__set__('isAjaxCalled', false);
        lib.__set__('ajax', function () {
            lib.__set__('isAjaxCalled', true);
        });

        lib.getJSON();
        assert.equal(lib.__get__('isAjaxCalled'), true);
        done();
    });
});

No Change your Actual code, library.js

A: Call your method from the exported public API.
var jquery = {
    ajax: function () {
        console.log("I'm a");
    },

    getJSON: function () {
        //this.ajax();
        jquery.ajax(); // <---
        console.log("I'm b");
    }
};

Another approach is to call console.log with a hint, and then spy on the log.
ajax: function () {
  console.log("I'm a");
},

var ajax = sinon.spy(console, 'log');
$.getJSON();
sinon.assert.calledOnceWithExactly("I'm a")


text:
Q: How to print to log in Flutter? I wanted to print a log statement onto any LogCat console (Verbose, Debug, etc) but I can't seem to find a way to do it.
The print() or debugPrint()  doesn't seem to work, or better yet should I say I don't know where they are printing.
Also, for some reason, the LogCat console is saying "No connected devices" and "No debuggable process" even though I have the emulator running in background and the files are executing on the emulator perfectly.

A: Based on Flutter Doc, the logging view displays events from the Dart runtime, application frameworks (like Flutter), and application-level logging events.By default, the logging view shows:

*

*Garbage collection events from the Dart runtime

*Flutter framework events, like frame creation events

*stdout and stderr from applications

*Custom logging events from applications

Refer the Debugging Flutter Applications Programmatically Doc.
You can use:
stderr.writeln('print me');

Or
import 'dart:developer' as developer;

void main() {
  developer.log('log me', name: 'my.app.category');

  developer.log('log me 1', name: 'my.other.category');
  developer.log('log me 2', name: 'my.other.category');
}

Or
import 'dart:convert';
import 'dart:developer' as developer;

void main() {
  var myCustomObject = ...;

  developer.log(
    'log me',
    name: 'my.app.category',
    error: jsonEncode(myCustomObject),
  );
}

to log from your app.


text:
Q: Date Comparison in Select Query Returns False Results I am using following query to display the records.
$query = mysqli_query($con, "SELECT * FROM episode where episodeDate < '$loaddate'
and dramaID != (select dramaID from drama where popularity = '5')
and dramaID != (select dramaID from drama where popularity = '6')
order by episodeDate desc");
  //number of rows
 echo $rowCount = mysqli_num_rows($query);

Where loaddate is a DATE VARIABLE in mysql database. So is episodeDate. Now, the problem is that the $rowCount returns '0' wherease the database has more than 15 records with episodeDate less than the variable loaddate.
What could be the problem? The connection is ok and the query is not returning any error either.

A: Those 2 sub queries are easily replaced with a join, and they only work where the subquery returns one row: the query will still run in instances were both return one.
Ensure that your date is of format "YYYY-MM-DD HH:MM:SS":
$query = mysqli_query($con, "
SELECT *
FROM episode
INNER JOIN drama
ON episode.dramaID = drama.dramaID
AND drama.popularity NOT IN ('5','6')
WHERE episode.episodeDate < '$loaddate'
ORDER BY episode.episodeDate DESC");
//number of rows
echo $rowCount = mysqli_num_rows($query);

A: I don't think that the date comparition has to do something with "no results". It would be interesting to find out how many records select the other two subqueries select dramaID from drama where popularity = '5' and select dramaID from drama where popularity = '6'.
If they bring one record each then try
"SELECT * FROM episode where episodeDate < '$loaddate' order by episodeDate desc"

If not you probably need to change the query to
"SELECT * FROM episode where episodeDate < '$loaddate'
and dramaID not in (select dramaID from drama where popularity = '5')
and dramaID not in (select dramaID from drama where popularity = '6')
order by episodeDate desc"


text:
Q: Plot becomes distorted when uploading to latex using epslatex in gnuplot I wrote the code for a plot in gnuplot and set the output using epslatex terminal as follows:
set term epslatex color
set output "test.tex"

set multiplot layout 2,3 columnsfirst margins 0.1,0.9,0.1,0.9 spacing 0.07,0.0

unset key

set format x " "
#set xtic 400
#set ytic 100
#unset xlabel

set yrange [0:150]

set title "D1"

plot [0:10] x**2 lc -1 lw 2 with lines , [0:5] x**3 lc rgb "#FF4433" pt 5 ps 0.7

#unset key
unset format x

unset title

plot [0:10] x**2 lc -1 lw 2 with lines , [0:5] x**3 lc rgb "#FF4433" pt 5 ps 0.7

set format x " "

set title "D2"

plot [0:10] x**2 lc -1 lw 2 with lines , [0:5] x**3 lc rgb "#FF4433" pt 5 ps 0.7

unset format x

unset title

plot [0:10] x**2 lc -1 lw 2 with lines , [0:5] x**3 lc rgb "#FF4433" pt 5 ps 0.7

set format x " "

set title "D3"

plot [0:10] x**2 lc -1 lw 2 with lines , [0:5] x**3 lc rgb "#FF4433" pt 5 ps 0.7

unset format x
unset title

set label 1 "$x $"  at screen 0.47,0.04
set label 2 "$f(x)$"  at screen 0.05,0.43 rotate by 90
set label 3 "$ (a)\\; NK $" at -25.2696,239.562
set label 4 "$ (b) \\; NKH \\Delta $" at -25.4174,102,370

set key at -22.5856,276.937 box

plot [0:10] x**2 title "$ x^2 $" lc -1 lw 2 with lines , [0:5] x**3 title "$ x^3 $" lc rgb "#FF4433" pt 5 ps 0.7

unset label 1
unset label 2
unset label 3
unset label 4

unset multiplot

set output

When setting output using set terminal jpeg size 1800,900 , I am getting the following:

But after setting the output using epslatex , I am getting a distorted image as follows:

How do I reconcile the outputs and make the later look like the former?
The resulting ".tex" file from the gnuplot code is as follows:
% GNUPLOT: LaTeX picture with Postscript
\begingroup
  \makeatletter
  \providecommand\color[2][]{%
    \GenericError{(gnuplot) \space\space\space\@spaces}{%
      Package color not loaded in conjunction with
      terminal option `colourtext'%
    }{See the gnuplot documentation for explanation.%
    }{Either use 'blacktext' in gnuplot or load the package
      color.sty in LaTeX.}%
    \renewcommand\color[2][]{}%
  }%
  \providecommand\includegraphics[2][]{%
    \GenericError{(gnuplot) \space\space\space\@spaces}{%
      Package graphicx or graphics not loaded%
    }{See the gnuplot documentation for explanation.%
    }{The gnuplot epslatex terminal needs graphicx.sty or graphics.sty.}%
    \renewcommand\includegraphics[2][]{}%
  }%
  \providecommand\rotatebox[2]{#2}%
  \@ifundefined{ifGPcolor}{%
    \newif\ifGPcolor
    \GPcolorfalse
  }{}%
  \@ifundefined{ifGPblacktext}{%
    \newif\ifGPblacktext
    \GPblacktexttrue
  }{}%
  % define a \g@addto@macro without @ in the name:
  \let\gplgaddtomacro\g@addto@macro
  % define empty templates for all commands taking text:
  \gdef\gplbacktext{}%
  \gdef\gplfronttext{}%
  \makeatother
  \ifGPblacktext
    % no textcolor at all
    \def\colorrgb#1{}%
    \def\colorgray#1{}%
  \else
    % gray or color?
    \ifGPcolor
      \def\colorrgb#1{\color[rgb]{#1}}%
      \def\colorgray#1{\color[gray]{#1}}%
      \expandafter\def\csname LTw\endcsname{\color{white}}%
      \expandafter\def\csname LTb\endcsname{\color{black}}%
      \expandafter\def\csname LTa\endcsname{\color{black}}%
      \expandafter\def\csname LT0\endcsname{\color[rgb]{1,0,0}}%
      \expandafter\def\csname LT1\endcsname{\color[rgb]{0,1,0}}%
      \expandafter\def\csname LT2\endcsname{\color[rgb]{0,0,1}}%
      \expandafter\def\csname LT3\endcsname{\color[rgb]{1,0,1}}%
      \expandafter\def\csname LT4\endcsname{\color[rgb]{0,1,1}}%
      \expandafter\def\csname LT5\endcsname{\color[rgb]{1,1,0}}%
      \expandafter\def\csname LT6\endcsname{\color[rgb]{0,0,0}}%
      \expandafter\def\csname LT7\endcsname{\color[rgb]{1,0.3,0}}%
      \expandafter\def\csname LT8\endcsname{\color[rgb]{0.5,0.5,0.5}}%
    \else
      % gray
      \def\colorrgb#1{\color{black}}%
      \def\colorgray#1{\color[gray]{#1}}%
      \expandafter\def\csname LTw\endcsname{\color{white}}%
      \expandafter\def\csname LTb\endcsname{\color{black}}%
      \expandafter\def\csname LTa\endcsname{\color{black}}%
      \expandafter\def\csname LT0\endcsname{\color{black}}%
      \expandafter\def\csname LT1\endcsname{\color{black}}%
      \expandafter\def\csname LT2\endcsname{\color{black}}%
      \expandafter\def\csname LT3\endcsname{\color{black}}%
      \expandafter\def\csname LT4\endcsname{\color{black}}%
      \expandafter\def\csname LT5\endcsname{\color{black}}%
      \expandafter\def\csname LT6\endcsname{\color{black}}%
      \expandafter\def\csname LT7\endcsname{\color{black}}%
      \expandafter\def\csname LT8\endcsname{\color{black}}%
    \fi
  \fi
    \setlength{\unitlength}{0.0500bp}%
    \ifx\gptboxheight\undefined%
      \newlength{\gptboxheight}%
      \newlength{\gptboxwidth}%
      \newsavebox{\gptboxtext}%
    \fi%
    \setlength{\fboxrule}{0.5pt}%
    \setlength{\fboxsep}{1pt}%
\begin{picture}(7200.00,5040.00)%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(588,2520){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(588,3863){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(720,2300){\makebox(0,0){\strut{} }}%
    }%
    \gplgaddtomacro\gplfronttext{%
      \csname LTb\endcsname%%
      \put(1511,4865){\makebox(0,0){\strut{}D1}}%
    }%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(588,504){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(588,1847){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(720,284){\makebox(0,0){\strut{}$0$}}%
    }%
    \gplgaddtomacro\gplfronttext{%
    }%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(2676,2520){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(2676,3863){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(2808,2300){\makebox(0,0){\strut{} }}%
    }%
    \gplgaddtomacro\gplfronttext{%
      \csname LTb\endcsname%%
      \put(3599,4865){\makebox(0,0){\strut{}D2}}%
    }%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(2676,504){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(2676,1847){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(2808,284){\makebox(0,0){\strut{}$0$}}%
    }%
    \gplgaddtomacro\gplfronttext{%
    }%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(4764,2520){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(4764,3863){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(4896,2300){\makebox(0,0){\strut{} }}%
    }%
    \gplgaddtomacro\gplfronttext{%
      \csname LTb\endcsname%%
      \put(5687,4865){\makebox(0,0){\strut{}D3}}%
    }%
    \gplgaddtomacro\gplbacktext{%
      \csname LTb\endcsname%%
      \put(4764,504){\makebox(0,0)[r]{\strut{}$0$}}%
      \put(4764,1847){\makebox(0,0)[r]{\strut{}$100$}}%
      \put(4896,284){\makebox(0,0){\strut{}$0$}}%
      \put(3384,202){\makebox(0,0)[l]{\strut{}$x $}}%
      \put(360,2167){\rotatebox{90}{\makebox(0,0)[l]{\strut{}$f(x)$}}}%
      \put(896,3722){\makebox(0,0)[l]{\strut{}$ (a)\; NK $}}%
      \put(872,1874){\makebox(0,0)[l]{\strut{}$ (b) \; NKH \Delta $}}%
    }%
    \gplgaddtomacro\gplfronttext{%
      \csname LTb\endcsname%%
      \put(466,4114){\makebox(0,0)[r]{\strut{}$ x^2 $}}%
      \csname LTb\endcsname%%
      \put(466,3894){\makebox(0,0)[r]{\strut{}$ x^3 $}}%
    }%
    \gplbacktext
    \put(0,0){\includegraphics{test}}%
    \gplfronttext
  \end{picture}%
\endgroup

And the latex code used to plot it is:
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{graphicx}

\title{plot}
\author{anon }
\date{February 2022}

\begin{document}

\maketitle

\section{Introduction}

\begin{figure}[h]
    \centering
    \input{test.tex}
    \caption{Caption}
    \label{fig:my_label}
\end{figure}

\end{document}

The ".eps" file is available here :
test.eps

A: [original was answer based on a guess shown to be incorrect by the uploaded sample code]
To get a more complete answer I think you need to show the LaTeX code at the site of inclusion.
Amended answer
As theozh points out, you need to use a consistent aspect ratio. If I modify your original script to use
set term epslatex color size 6in, 3in

and modify the top of your .tex script to say
\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\pagestyle{empty}
\usepackage{xcolor}

leaving all else the same as you show, I get the figure below. You have used a mixture of screen coordinates and plot coordinates to position the text labels.  I'm not sure which of those is better, but mixing them may not be a good idea.


text:
Q: Rename/revalue values within a variable I have data that looks like this and want to create the "Funding" Variable
ID   FundingSource    Funding
1     asdf              Yes
2      NA               No
3     ljsdf             Yes
4      NA               No

I want to recode it such that all NA values are automatically coded as No and everything else (with some non-NA value) is coded as Yes since there are so many different Funding Source names. Here's some code I have so far that doesn't work:
 df %>%
  if (FundingSource == "NA") {print(Funding == "No")}
else if (FundingSource =/= "NA") {print(Funding =="Yes")}

if("NA" %in% df$FundingSource) {print("No")} else if {print("Yes")}

A: There are a few options here.
One nice trick of a tibble is you can calculate new columns on the fly as you build it.
Alternatively you could use dplyr::mutate() and either use base::ifelse() or dplyr::if_else() or dplyr::case_when() which is overkill here but useful if you have more than 2 conditions.
library(tidyverse)

# calculate directly as you build tibble
tibble(ID = 1:4,
       FundingSource = c("asdf", NA, "ljsdf", NA),
       Funding = ifelse(!is.na(FundingSource), "Yes", "No"))
#> # A tibble: 4 × 3
#>      ID FundingSource Funding
#>   <int> <chr>         <chr>
#> 1     1 asdf          Yes
#> 2     2 <NA>          No
#> 3     3 ljsdf         Yes
#> 4     4 <NA>          No

# perform mutate based on column with ifelse
# using base::ifelse, but dplyr::if_else works fine here too
tibble(ID = 1:4,
       FundingSource = c("asdf", NA, "ljsdf", NA)) %>%
  mutate(Funding = ifelse(!is.na(FundingSource), "Yes", "No"))
#> # A tibble: 4 × 3
#>      ID FundingSource Funding
#>   <int> <chr>         <chr>
#> 1     1 asdf          Yes
#> 2     2 <NA>          No
#> 3     3 ljsdf         Yes
#> 4     4 <NA>          No

# perform mutate based on column with dplyr::case_when
# useful if more than 2 conditions
tibble(ID = 1:4,
       FundingSource = c("asdf", NA, "ljsdf", NA)) %>%
  mutate(Funding = case_when(
    !is.na(FundingSource) ~ "Yes",
    TRUE ~ "No"
  ))
#> # A tibble: 4 × 3
#>      ID FundingSource Funding
#>   <int> <chr>         <chr>
#> 1     1 asdf          Yes
#> 2     2 <NA>          No
#> 3     3 ljsdf         Yes
#> 4     4 <NA>          No

Created on 2022-08-18 by the reprex package (v2.0.1)


text:
Q: How to Save Data From Firebase to SQLite Android I am fetching some data from Firebase and Trying to Save the data to SQLite Database in the same onDataChange method Below is the code I have tried so far. I am saving fetched data in String variable.when I try with Toast it shows fetched value and also when i use hard coded value for the variable like String drivername="some value" it is saving data to sqlite but when I am trying to save the fetched value it is returning null value hence not saving.What's wrong I am doing
    String mobile_no=localSharedPreferences.getSharedPreferences(Constants.PhoneNumber);

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Driver");

    reference.orderByKey().equalTo(mobile_no).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String drivermobile=localSharedPreferences.getSharedPreferences(Constants.PhoneNumber);

            for(DataSnapshot datas: dataSnapshot.getChildren()){

                    String drivername = datas.child("d_nme").getValue(String.class);
                    String avatorurl = datas.child("d_avtr").getValue(String.class);
                    String vehicleno = datas.child("v_No").getValue(String.class);
                    String vehiclename = datas.child("v_nme").getValue(String.class);

                   //Toast is showing fetched drivername correctly
                   Toast.makeText(SigninActivity.this, drivername, Toast.LENGTH_SHORT).show();

                //Trying to save into SQLITE

                ContactsDB db = new ContactsDB(getApplicationContext());
                db.open();
                db.createEntry(drivermobile, drivername, vehiclename, avatorurl, vehicleno);
                db.close();

                Toast.makeText(SigninActivity.this, localSharedPreferences.getSharedPreferences(Constants.dDrivername), Toast.LENGTH_SHORT).show();
            }

And this is my  ContactsDB Class
public class ContactsDB {

public static final String KEY_ROWID="_id";
public static final String DRIVER_MOBILE="driver_mobile";
public static final String DRIVER_NAME="driver_firstname";
public static final String VEHICLE_NAME="vehicle_name";
public static final String AVATOR_URL="driver_avator";
public static final String VEHICLE_NO="vehicle_no";

private final String DATABASE_NAME="ContactsDB";
private final String DATABASE_TABLE="ContactsTable";
private final int DATABASE_VERSION=1;

private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabse;

public  ContactsDB(Context context)
{
    ourContext=context;
}

private class DBHelper extends SQLiteOpenHelper
{
    public DBHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(sqLiteDatabase);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        /**
         * THIS Only runs if database not exists with specified version
         */

        String sqlcode="CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                DRIVER_MOBILE + " INTEGER NOT NULL, " +
                DRIVER_NAME + " TEXT NOT NULL, " +
                VEHICLE_NAME + " TEXT NOT NULL, " +
                AVATOR_URL + " TEXT NOT NULL, " +
                VEHICLE_NO + " DECIMAL NOT NULL);";

        sqLiteDatabase.execSQL(sqlcode);

    }
}

public ContactsDB open() throws SQLException
{
    ourHelper=new DBHelper(ourContext);
    ourDatabse=ourHelper.getWritableDatabase();
    return this;
}

public void close()
{
    ourHelper.close();
}

public long createEntry(String drivermobile, String drivername, String vehiclename, String avatorurl, String vehicleno) {

    ContentValues cv = new ContentValues();
    cv.put(DRIVER_MOBILE, drivermobile);
    cv.put(DRIVER_NAME,drivername);
    cv.put(VEHICLE_NAME,vehiclename);
    cv.put(AVATOR_URL,avatorurl);
    cv.put(VEHICLE_NO,vehicleno);
    return ourDatabse.insert(DATABASE_TABLE, null, cv);

}

public  String getData()
{
    /*Here you can Specify which column value you want to retrieve*/

    String [] columns=new String[] {KEY_ROWID,DRIVER_MOBILE,DRIVER_NAME,VEHICLE_NAME,AVATOR_URL,VEHICLE_NO};
    Cursor c=ourDatabse.query(DATABASE_TABLE, columns, null,null,null,null,null);

    String result="";

    int iKeyID=c.getColumnIndex(KEY_ROWID);
    int iRowID=c.getColumnIndex(DRIVER_MOBILE);
    int iFirstName=c.getColumnIndex(DRIVER_NAME);
    int iSecondName=c.getColumnIndex(VEHICLE_NAME);
    int iAvatorUrl=c.getColumnIndex(AVATOR_URL);
    int iRatings=c.getColumnIndex(VEHICLE_NO);

    for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
    {

        result=result + c.getString(iKeyID) + ": " + c.getString(iRowID) + ": " + c.getString(iFirstName) + ": " +
                c.getString(iSecondName) + ": " + c.getString(iAvatorUrl) + "+ " +
                c.getString(iRatings) + "\n"; // n is for newline
    }
    c.close();
    return result;

}

public  long deleteEntry(String rowId)
{
    return ourDatabse.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[]{rowId});
}

public  long updateEntry(String rowId, String drivermobile, String drivername, String vehiclename, String avatorurl, String vehicleno)
{
   ContentValues cv=new ContentValues();

   /*if you update one column then put only one column or put as many as many you want to update*/
   cv.put(DRIVER_MOBILE, drivermobile);
   cv.put(DRIVER_NAME,drivername);
   cv.put(VEHICLE_NAME,vehiclename);
   cv.put(AVATOR_URL,avatorurl);
   cv.put(VEHICLE_NO,vehicleno);
   return ourDatabse.update(DATABASE_TABLE, cv, KEY_ROWID + "=?", new String[]{rowId});
}

A: I would suggest that you try the following :-
1.
Add the following getter method to ContactsDB.java :-
public SQLiteDatabase getOurDatabse() {
    return ourDatabse;
}

2
Move the open and close to before and after the loop respectively and also include a beginTransaction before the loop and after the loop a setTransactionSuccessful and an endTransaction.
As such the disk will be written to just the once rather than for each insert.
e.g. :-
public void onDataChange(DataSnapshot dataSnapshot) {

    ContactsDB db = new ContactsDB(getApplicationContext());
    db.open();
    db.getOurDatabse().beginTransaction();

    String drivermobile = localSharedPreferences.getSharedPreferences(Constants.PhoneNumber);

    for (DataSnapshot datas : dataSnapshot.getChildren()) {

        String drivername = datas.child("d_nme").getValue(String.class);
        String avatorurl = datas.child("d_avtr").getValue(String.class);
        String vehicleno = datas.child("v_No").getValue(String.class);
        String vehiclename = datas.child("v_nme").getValue(String.class);

        //Toast is showing fetched drivername correctly
        Toast.makeText(SigninActivity.this, drivername, Toast.LENGTH_SHORT).show();

        //Trying to save into SQLITE

        if (drivermobile != null && drivername != null && vehiclename != null && avatorurl != null && vehicleno != null) {
            if (db.createEntry(drivermobile, drivername, vehiclename, avatorurl, vehicleno) > 0) {
                Toast.makeText(SigninActivity.this, localSharedPreferences.getSharedPreferences(Constants.dDrivername), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(SigninActivity.this, "?????? Not ADDED", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(SigninActivity.this, "?????? Unable to ADD due to NULL value(s)", Toast.LENGTH_SHORT).show();
        }

    }
    db.getOurDatabse().setTransactionSuccessful();
    db.getOurDatabse().endTransaction();
    db.close();

*

*This additionally does some checking so that null values will not result in an attempt to insert but will toast that it is unable to add the row.

*It also checks the return from each insert to see if the row was inserted and Toast's accordingly.

*

*However, I would suggest that writing the messages to the Log rather than (or as well ass) Toast would aid debugging.


text:
Q: Add results to a row regarding the last 12 months rows- SQL Server At my last meeting someone asked me if it was possible to hide people who where ill since a year from a dashboard. So I'm searching for the best way to actually KNOW who has been ill for 12 months.
I am working with a table with the number of days you've been absent for every kind of absence you could have, the number of days you should have been working that month, with a row per person, department and profession each month.
So it looks something like this :

PersonID
YEAR
MONTH
DEPARTMENT
PROFESSION
Absence1
Absence2
Absence3
WORKING DAYS OF THE MONTH...

11111
2021
07
HR
ASSISTANT
0
2
0
22

11111
2021
08
HR
ASSISTANT
0
0
0
22

==> So if I'm on a row of July 2021 I need to check the lines from June 2020 to June 2021.
My guess is that I need to add a column to this table who will say (with some kind of loop maybe) "if for the last 12 months (rows) the total number of days of absence equal the number of working days of the last 12 months then "ILL FOR A YEAR OR MORE" for each person (knowing that a person can work in more than one department or more than one profession so she'll have more than one row per month).
But I really have no idea how to actually write it in a script as I usually do very basic things. I'm using SQL SERVER and have 429 207 rows in the table. I'm thinking about doing it in the whole table and not only treating this month's rows because in the dashboard we show an historic.

A: Your table is heavily denormalized. If you want to represent all this information in the database, I would have expected the following tables, instead of just one:

*

*Person

*Department

*Illness (list of illnesses)

*IllnessAbsence (join table between Person and Illness)

Either way, you can get the information you need with something like this:

*

*I've assumed you want the whole table, so you need a window function

*We need to flip the logic on its head: exclude all rows which have no non-absence in the last 12 months

SELECT
    PersonID,
    YEAR,
    MONTH,
    DEPARTMENT,
    PROFESSION,
    ILLNESS1,
    ILLNESS2,
    ILLNESS3,
    [WORKING DAYS OF THE MONTH]
FROM (
    SELECT *,
      NotIllLast12Months = COUNT(CASE WHEN DATEFROMPARTS(YEAR + 1, MONTH, 1) >= GETDATE()
                  AND ILLNESS1 + ILLNESS2 + ILLNESS3 = 0 THEN 1 END)
        OVER (PARTITION BY ID)
    FROM HETP_ABS
) abs
WHERE NotIllLast12Months > 0;