text:
Q: global variables not working in symfony2 The simple question is how do namespaces affect global variables?read the rest for more info
I have a working website in php.All the link addresses are made using get queries.(e.g:example.com/?page=contact instead of example.com/contact.php).i have overriden the super global variables in my symfony controller and configured the route.so that works.
my problem is with the global variables.there is a main index.php file which i have included in my controller (indexController) and that has all the code for the website.but the global variables don't work anymore(they've disappeared).i figured that was because of controller namespace but in the php documents it states that namespaces don't affect variables.so what could the problem be?the index.php would generate the expected results if run seperately but here i get undeclared variables)
 this would be my code:index.php creates $html with HTML data
namespace example\exampleBundle\Controller

class indexController{
    function indexAction(Request $request){
        $request->overrideGlobals();
        include "/external/index.php";

        $response = new Response();
        $response->setContent($html);
        $response->setStatusCode(Response::HTTP_OK);
        $response->headers->set('Content-Type','text/html');
        return $response;
    }
}

------------------------
symfonytest:
     path: /
     defaults: {_controller: exampleexampleBundle:index:index}

A: I have found out the reason.since the library is included inside a function(indexaction) it is not declared in the global scope.I must use the global modifier inside the included index.php. I will report the results of that.


text:
Q: Cordova/Phonegap: Untrusted certificate crashes on navigator.app.exitApp() I've submitted a patch to hypery2k's untrusted certificate plugin that allows it to run in the latest version of Cordova, but I've run into another one that I can't seem to figure out. For reference, the issue is being tracked here: https://github.com/hypery2k/cordova-certificate-plugin/issues/3
Symptoms:
This works, and after about 10 seconds the app exits cleanly (this is just for demonstration):
onDeviceReady: function() {
    init();
    setTimeout(function() { navigator.app.exitApp(); }, 10000);
},

However, this crashes and pops up the "quit unexpectedly" message in Android:
onDeviceReady: function() {
    init();
    cordova.plugins.certificates.trustUnsecureCerts(true);
    setTimeout(function() { navigator.app.exitApp(); }, 10000);
},

With this in the logcat:
D/CordovaActivity( 2561): onMessage(exit,null)
D/CordovaActivity( 2561): Paused the application!
W/PluginManager( 2561): THREAD WARNING: exec() call to App.exitApp blocked the main thread for 90ms. Plugin should use CordovaInterface.getThreadPool().
D/CordovaActivity( 2561): CordovaActivity.onDestroy()
D/CordovaWebView( 2561): >>> loadUrlNow()
D/CordovaWebViewClient( 2561): onPageFinished(about:blank)
D/AndroidRuntime( 2561): Shutting down VM
W/dalvikvm( 2561): threadid=1: thread exiting with uncaught exception (group=0xb0d58b20)
E/AndroidRuntime( 2561): FATAL EXCEPTION: main
E/AndroidRuntime( 2561): Process: com.mycomp.myapp, PID: 2561
E/AndroidRuntime( 2561): java.lang.NullPointerException
E/AndroidRuntime( 2561):        at org.apache.cordova.CordovaWebViewClient.onPageFinished(CordovaWebViewClient.java:215)
E/AndroidRuntime( 2561):        at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:449)
E/AndroidRuntime( 2561):        at com.android.org.chromium.android_webview.AwContentsClient$AwWebContentsObserver$1.run(AwContentsClient.java:73)
E/AndroidRuntime( 2561):        at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime( 2561):        at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime( 2561):        at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime( 2561):        at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime( 2561):        at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 2561):        at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime( 2561):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime( 2561):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime( 2561):        at dalvik.system.NativeStart.main(Native Method)
I/Process ( 2561): Sending signal. PID: 2561 SIG: 9
I/ActivityManager( 1276): Process com.mycomp.myapp (pid 2561) has died.

Everything else works fine, it just crashes when you try to implement code to exit the application, such as on back button press.
This is the main block of code that runs from the plugin when the above trustUnsecureCerts function is called:
@Override
public boolean execute(String action, JSONArray args,
        CallbackContext callbackContext) throws JSONException {

    if (action.equals("setUntrusted")) {
            allowUntrusted = args.getBoolean(0);
            Log.d(LOG_TAG, "Setting allowUntrusted to " + allowUntrusted);
            cordova.getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                            CertificatesCordovaWebViewClient cWebClient = new CertificatesCordovaWebViewClient(cordova);
                            cWebClient.setAllowUntrusted(allowUntrusted);
                            webView.setWebViewClient(cWebClient);
                            CordovaActivity ca = (CordovaActivity) cordova.getActivity();
                            ca.clearCache();
                    }
            });
            callbackContext.success();
            return true;
    }
    callbackContext.error("Invalid Command");
    return false;
}

And if it helps to see the entire class definition, the two full source files can be found here: https://github.com/hypery2k/cordova-certificate-plugin/tree/master/src/android/de/martinreinhardt/cordova/plugins
Any ideas? Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Create an Array within an Object Constructor in Javascript I am trying to be able to make a list of all instances of a Constructor, so I can check if all of these fit criteria in an IF statement
For Example:

function People() {
  People.allInstances = [];
  People.allInstances.push(this);
}

var Carry = new People();
var Gary = new People();
var Parry = new People();
console.log(People.allInstances);

However, I seem to lose all data except for the last instance I created. How can I make that list/array, and then use that array to test if any of them has a certain property?

A: The constructor runs every time an instance is constructed with it, but you only want to create an empty array once:
function People() {
    People.allInstances.push(this);
}

People.allInstances = [];


text:
Q: Divide irregular polygon into hexagons I'm working on an engineering project, i was asked to divide an irregular polygon into (n) hexagonals like in this image:

would like to know if there is an algorithm for distribution ?


text:
Q: Least residue power modulo May someone confirm that the least residue of $44^8$ modulo $7$ is $4$ please?
And that $2^2 \equiv  4\, (\!\!\!\mod 7)$?
Thanks in advance.

A: It is correct: $44\equiv 2\mod 7$, so  $44^8\equiv 2^8\mod 7$. Now $2^3\equiv 1\mod 7$, so $2^8\equiv 2^{8\bmod 3}=2^2\mod 7=4$, since $0\le 4<7$.

A: Lemma needed : For $a,b,n,r \in \mathbb{Z^+},$
$$a \equiv b \pmod{n} \implies a^r \equiv b^r \pmod{n}.$$
Proof:
$\displaystyle a\equiv b \pmod{n} \implies n | (a - b) \implies$
$\displaystyle \exists ~k \in \mathbb{Z} ~\text{such that}~ a = (b + nk) \implies$
$\displaystyle (a^r - b^r) = (b + nk)^r - b^r$
[Using binomial expansion]
$\displaystyle =~ \sum_{i=0}^r \left[(b)^i (nk)^{r - i}\right]
~-~ b^r$
$\displaystyle =~ \sum_{i=0}^{(r-1)} \left[(b)^i (nk)^{r - i}\right].$
Since the above summation stops at $(r-1)$,
$n$ divides each term in the summation.
Therefore
$n | (a^r - b^r) \implies a^r \equiv b^r \pmod{n}.$


text:
Q: v-model with same selected object I have a array with objects:
array = [{id: 1, value: 0},{id: 2, value: 0},{id: 3, value: 0},{id: 4, value: 0}]

after a quick selection with my UI I have a selected object array
selectedArray = [{id: 1, value: 0},{id: 2, value: 0},{id: 1, value: 0}]

You can not I push 2 time the id:1, it's necessary for my timeline.
so now I make a v-for on it

<input type="number" v-model="item.value">

But If I change the value of the first item , the third change too.
How can I fix this

A: You can add key attribute to each item.

<input type="number" v-model="item.value">


text:
Q: CakePHP bake stacked by database Config: It's the first time I made a bake through the CakePHP console.
I run the cmd as admin and there is a strange thing that after setting
the database config: (default/test) it is stucked there and I don't know
why.
The environment path is setting up correctly.


text:
Q: Вывод любого файла в текстовом виде (выбор файла из файлового менеджера) Kotlin Всем добрый день,
Есть кнопка для открытия системного файлового менеджера, где пользователь выбирает 1 файла(txt,pdf,jpeg). После выбора файла ты должен его открыть и прочитать в текстовое поле (т.е. Прочитать все содержимое файла в виде строки)
Проблема заключается в том, что у меня не получается выбрать любой файл из файлового менеджера и прочитать его в текстовом виде(у меня открывается по кнопке файловый менеджер, но не дает выбрать ни один файл)Как это исправить?
Ниже представлен код моего приложения
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- A TextView to show the data from the text file-->

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="156dp"
        android:layout_marginBottom="68dp"
        android:text="PICK FILE" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="308dp"
        android:layout_height="146dp"
        android:layout_centerInParent="true"
        android:gravity="center" />

</RelativeLayout>

package com.example.writeandread
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.io.*
import java.nio.charset.Charset

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Declaring and initializing the TextView from the layout
        val myTextView = findViewById<TextView>(R.id.textView)
        val myInputStream: InputStream
        val button1 = findViewById<Button>(R.id.button1)

        button1.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "application/pdf"
            intent.type = "application/txt"
            intent.type = "application/jpeg"
            fun getFileContent(FileName: String): String {
                val f = File(FileName)
                return f.readText(Charset.forName("UTF-8"))
            }
            startActivityForResult(intent, PICK_FILE)
        }

    }
    companion object {
        const val PICK_FILE = 99
    }
}

A: Это не добавляет типы, а перезаписывает:
intent.type = "application/pdf"
intent.type = "application/txt"
intent.type = "application/jpeg"

Так все работает:
class MainActivity : AppCompatActivity() {

    companion object {
        const val PICK_FILE = 99
        const val TEXT = "text/*"
        const val IMAGE = "image/*"
        const val PDF = "application/pdf"
    }

    var myTextView: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Declaring and initializing the TextView from the layout
        myTextView = findViewById(R.id.content)
        val button1 = findViewById<Button>(R.id.button)
        button1.setOnClickListener {
            onButtonClick(TEXT, IMAGE, PDF)
        }
    }

    private fun onButtonClick(vararg types: String) {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        intent.putExtra(Intent.EXTRA_MIME_TYPES, types)
        startActivityForResult(intent, PICK_FILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_FILE && resultCode == RESULT_OK) {
            data?.data?.let { uri ->
                val sb = StringBuilder()
                contentResolver
                    .openInputStream(uri)
                    ?.bufferedReader(Charset.forName("UTF-8"))
                    ?.forEachLine {
                        sb.append(it)
                    }
                val content = sb.toString()
                myTextView?.text = content
            }
        }
    }
}

Надо только не забыть в манифест добавить
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

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

    <application
    ...>
      ...
    </application>
</manifest>


text:
Q: what is meaning of "Raise" and "any hour more" in this context?
Ram: Did you ask Mr. Davidson for a raise ?
  Sri: Yes, I asked for 80 cents any hour more.

In first sentence I understand like, Ram asking Davidson for funds. But I didn't get why he used article before "raise".
In second sentence I am not understand why Sri used "any hour more" in that sentence. Please explain what Ram asked and what Sri replied.

A: In your sentence

Did you ask for a raise?

Raise is a noun meaning an increase in income, you might be thinking of the verb

Did you ask to raise your hourly wage?

The reply is

Yes, I asked for 80 cents an hour more (not any )

meaning an 80 cent increase per hour

A:
Ram: Did you ask Mr. Davidson for a raise ?

The indefinite article is used because raise as used is not specific as to the amount. However, if you were already told how much it would be, you could say:

Did you get the raise yet?

In the reply, this seems to be a typographical error between any and an. Using any does not make sense.

Sri: Yes, I asked for 80 cents an hour more.

The indefinite article is used because it will apply to every hour.


text:
Q: Syntax of a string function definition Can someone explain to me what I'm doing wrong with the syntax below? My textbook doesn't have any examples of user-defined string functions and I can't figure out what I should be doing. Thanks in advance!
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>

string dayOfWeek(int day);

using namespace std;

int main()
{
    cout << "Please enter a day of week (0 for Sunday, 1 for Monday, etc): ";
    cin >> day;
    cout << "The name of the day of the week is: " dayOfWeek(day) << endl;
}

string dayOfWeek(int day)
{
    if (day == 0)
        return "SUNDAY";
    else if (day == 1)
        return "MONDAY";
    else if (day == 2)
        return "TUESDAY";
    else if (day == 3)
        return "WEDNESDAY";
    else if (day == 4)
        return "THURSDAY";
    else if (day == 5)
        return "FRIDAY";
    else if (day == 6)
        return "SATURDAY";
}

A: #include <string>
#include <iostream>

std::string dayOfWeek(int day)
{
    if (day == 0)
        return "SUNDAY";
    else if (day == 1)
        return "MONDAY";
    else if (day == 2)
        return "TUESDAY";
    else if (day == 3)
        return "WEDNESDAY";
    else if (day == 4)
        return "THURSDAY";
    else if (day == 5)
        return "FRIDAY";
    else if (day == 6)
        return "SATURDAY";

    return "Invalid input!"; // May be you should guarantee a return value.
 }

int main() {
    std::cout << dayOfWeek(5) << std::endl;
}

should work as expected.

A: The crux of the problem is here:
string dayOfWeek(int day);

using namespace std;

The using is after code that depends on it, so the compiler goes looking for string and can't find it. It doesn't go looking for std::string because it hasn't been told to yet.
You could move using up a few lines, but for the many reasons covered in  the answers to Why is "using namespace std" considered bad practice? and a few not covered, you're probably better off not putting
using namespace std;

in your code at all. Prefix the std:: explicitly and you can avoid a litany of nasty surprises.
I also recommend following @πάνταῥεῖ example with where the function was placed. Forward declaring and then declaring gives you two places to have to change code and one more place to have a bug. Declaring the function ahead where it will be used mean you only ever have to change one declaration.
Putting it all together with a few other small tweaks:
#include <string>
#include <iostream>

std::string dayOfWeek(int day)
{
    switch (day) // for stuff like this, I like a switch. I find it looks nicer.
    {
        case 0:
            return "SUNDAY";
        case 1:
            return "MONDAY";
        case 2:
            return "TUESDAY";
        case 3:
            return "WEDNESDAY";
        case 4:
            return "THURSDAY";
        case 5:
            return "FRIDAY";
        case 6:
            return "SATURDAY";
        default:
            return "No such day"; // functions must always return something.
                                  // in this case what will cout print if you
                                  // don't return a string? Don't know?
                                  // Don't feel bad. Neither do I.
                                  // Welcome to Undefined Behaviour

    }
 }

int main()
{
    int day; //this was missing
    std::cout << "Please enter a day of week (0 for Sunday, 1 for Monday, etc): ";
    std::cin >> day;
    std::cout << "The name of the day of the week is: " << dayOfWeek(day) << std::endl;
}

There's one other trick you can use to get rid of the if or switch entirely
#include <string>
#include <iostream>

// define an array of days of the week to print. const means dayOfWeek cannot be changed
const std::string dayOfWeek[] =
{
    "SUNDAY",
    "MONDAY",
    "TUESDAY",
    "WEDNESDAY",
    "THURSDAY",
    "FRIDAY",
    "SATURDAY"
 };

int main()
{
    unsigned int day;
    //Note unsigned int. Negative numbers are now disallowed

    std::cout << "Please enter a day of week (0 for Sunday, 1 for Monday, etc): ";

    // keep looping until user provides a good number
    while (!(std::cin >> day) // user MUST input a number
           || day > 6) // number is a usable number
    {
        std::cin.clear(); // clean up bad input
        std::cout << "Please enter a day of week (0 for Sunday, 1 for Monday, etc): ";
    }
    // since we know day is a usable (0..6) number we can read the day out of the array
    std::cout << "The name of the day of the week is: " << dayOfWeek[day] << std::endl;
}


text:
Q: How do i print the dictionary using default keys if list=[1,2,3] and list1=['a','b','c','d','e'], how would you print a dictionary containing values from list as keys
and values from list1 as value.
If there are no keys for a value in list1,
it would assign a default key for the same dictionary.

A: You mean something like this:
keys=[1,2,3]
list1=['a','b','c','d','e']

dct = dict(zip(keys, list1[:len(keys)]))

if len(list1) > len(keys):
    dct['default'] = list1[len(keys):]
print(dct)

Out:
{1: 'a', 2: 'b', 3: 'c', 'default': ['d', 'e']}


text:
Q: What's the difference of ANSI Smalltalk and Smalltalk-80? I discovered there is no mentioning about thisContext in ANSI Smalltalk specification (draft).
I assumed ANSI Smalltalk as standardized Smalltalk-80, so I can't understand why it's not there. What's the difference of them?

A: Smalltalk-80 refers to a very specific thing: the version of Smalltalk that was in use at Xerox Parc back in 1980.  While there are many Smalltalks that are based, either in a direct sense (Squeak and Pharo) or an ideological sense (Ambrai Smalltalk and GNU Smalltalk), on that environment, there are no Smalltalks around today that actually fully adhere to the language and virtual machine described in that book.  Even Squeak, which is probably the closest ideologically, has some major deviations: Squeak has closures, Smalltalk-80 does not; Squeak has Unicode, Smalltalk-80 does not; Squeak's VM supports and uses named primitives, Smalltalk-80 does not; Squeak support some bytecodes that Smalltalk-80 does not; and so on.
ANSI Smalltalk, like ANSI Common Lisp, attempted to define a standard that incorporate a common subset of Smalltalk functionality across the major Smalltalk implementations.  Since the ANSI standard was written in 1998, it had to take into account far more than just the original implementation.  In particular, some at-the-time major Smalltalks, such as Smalltalk MT and VisualAge Smalltalk, lacked continuations entirely (and a thisContext variable as a result).  That feature is therefore absent from the ANSI standard.
In practice, these differences are somewhat academic.  You're worried about thisContext, but GNU Smalltalk has a radically different syntax, VisualWorks has namespaces, Squeak has Traits, Pharo lacks MVC...there are simply more pressing differences.  Smalltalk-80 and the ANSI Smalltalk draft are both more guidelines than anything else at this point in Smalltalk's life.


text:
Q: Remove items from Flatlist doesn't work using Redux I'm learning React Redux at the moment and I'm working on a food list in which the user can add and remove items from a Flatlist, up until now I worked on adding the items, which works perfectly, now I'm using the same approach to remove the item from the global state foodList, I use onLongPress to start the function createTwoButtonAlert and from there launch removeFromFoodList in the Diet screen. When I run the code and I proceed to remove the items nothing happens, not even in the Terminal, previously I was using a method which also didn't work because instead of  deleting the selected item it deleted all items in the Flatlist. Thank you for your help.
Diet
class Diet extends Component {

createTwoButtonAlert = (item) =>
Alert.alert(
  "Delete Food",
  "Are you sure to delete this food?",
  [
    {
      text: "Cancel",
      style: "cancel"
    },
    { text: "Delete",
      onPress: () => this.props.removeFromFoodList(item)
    }
  ]
);

 render() {

       return (

                     <FlatList
                      data={this.props.foodList}
                      renderItem={({item}) => (
                        <View>
                          <TouchableOpacity
                            onLongPress={() => this.createTwoButtonAlert(item)}
                          >
                            <Text>{item.foodName}</Text>
                              <Text>
                                {item.calories}
                              </Text>
                              <MaterialIcons name="arrow-forward-ios" />
                          </TouchableOpacity>
                          </View>
                      )}
                      keyExtractor={item => item.foodId}
                    />

}
}

function mapStateToProps(store){
  return{
      foodList: store.userState.foodList
  };
}

const mapDispatchToProps = { removeFromFoodList };

export default connect(mapStateToProps, mapDispatchToProps)(Diet);

INDEX
import {  ADD_FOOD, REMOVE_FOOD } from "../constants/index";

export const updateFoodList = (foodList) => {
  return { type: ADD_FOOD, payload: foodList}
}

export const removeFromFoodList = (item) => {
  return { type: REMOVE_FOOD, payload: item.foodId}
}

REDUCERS
import { ADD_FOOD, REMOVE_FOOD } from "../constants";

const initialState = {
  foodList: [],
};

export const user = (state = initialState, action) => {
  switch (action.type){
      case ADD_FOOD:
      return{
        ...state,
        foodList: [...action.payload],
      }
      case REMOVE_FOOD:
      return{
        ...state,
        foodList: [...state.foodList.filter((item) => item.foodId != action.foodId)],
      }
      default:
        return state
  }

};

ARRAY EXAMPLE
Array [
  Object {
    "calories": "120",
    "foodId": 0.8845240802796346,
    "foodName": "Rice",
  },
]

A: You should be using
foodList: [...state.foodList.filter((item) => item.foodId != action.payload)]


text:
Q: NLP: how do you determine the polarity of a certain word? Sorry for the vague nature of this question, but I don't even know the proper NLP terminology to search constructively.
Basically what I'm attempting to do is to determine whether a word (usually an adjective or a noun) is "confirmed" by its context, or "negated." (Apologies for potential misuse of terminology)
The application is one step of a larger process that parses through a large body of user reviews, and uses keyword frequency to determine certain aspects of a product. However, certain keywords may either apply or not apply depending on the context.
As an example, when looking for a keyword "flimsy", two possible contexts are:
A) "The product felt flimsy in my hands and fell apart within days" --> keyword confirmed
B) "The build quality was very solid and not at all flimsy like its competitors" --> keyword negated
Note that this is different from the sentiment analysis of the phrase; the purpose is not to determine whether or not the opinion is positive or negative, but rather if a word is applicable in context or not.
Is there any standard methodology or technique to achieve this?


text:
Q: Error in Arraylist in c# 2008 I have a array list
private ArrayList rps = new ArrayList();

now below code is working fine in 2005 but not in visual studio 2008
int min = Convert.ToInt32(rps.Item(0));
int max = Convert.ToInt32(rps.Item(rps.Count - 1));

Error: System.Collections.ArrayList does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Collections.ArrayList' could be found (are you missing a using directive or an assembly reference?`

A: Use an indexer.
int min = Convert.ToInt32(rps[0]);

Also consider using List<T> instead of ArrayList.

A: That code wouldn't work in VS 2005 either. Something similar might work in VB, but not in C#. The C# code would be:
int min = Convert.ToInt32(rps[0]);
int max = Convert.ToInt32(rps.Item[rps.Count - 1]);

However, I'd advise you to start using generic collections such as List<T> instead.

A: You have a syntax error:
rps.Item(0)

Should be:
rps[0]

Note - you really shouldn't be using ArrayList - it predates generics which is what you should be using instead.


text:
Q: Problem related to real monic quadratic polynomial
Let $f(x)$ be a real monic quadratic polynomial. If ${x_1},{x_2},{x_3},{x_4},{x_5}$  be the $5$ points where
$g(x) = |f(|x|)|$ is non-differentiable and $\sum_{i = 1}^5 {\left| {{x_i}} \right| = 8} $ then   find the value of $\frac{1}{5}\mathop {\lim }\limits_{x \to \infty } \frac{{{x^2} - f\left( x \right)}}{x}$.

My approach is as follow, real monic quadratic means that leading coefficient viz. the value of $a$ in $ax^2+bx+c=0$ is $1$. That is the equation is of the form $x^2+bx+c$, for real case $b^2-4c\ge0$. But not able to approach.

A: $g$ is non-differentiable at zeroes of $f$ and their reflections across $0$ and at $0$.
So if $x_1=m>0$ and $x_2=n>0$ then $x_3=-m$, $x_4=-n$ and $x_5=0$. Thus $$2n+2m =8 \implies b= -(m+n)=-4$$
So $$f(x) = x^2-4x+c \implies \lim_{x\to \infty}{4x-c\over x} = 4$$
So the result is $4/5$.

A: Hint: $$g(x)=|ax^2+b|x|+c|$$ is non-differentiable at five points if $b^2 > 4ac, b<0, c>0$.


text:
Q: How to split dataframe on based on columns row I have one excel file , dataframe have 20 rows . after few rows there is again column names row, i want to divide dataframe based on column names row.
here is example:
x
0
1
2
3
4
x
23
34
5
6

expected output is:
df1
x
0
1
2
3
4
df2
x
23
34
5
6

A: Considering your column name is col , you can first group the dataframe taking a cumsum on the col where the value equals x by df['col'].eq('x').cumsum() , then for each group create a dataframe by taking the values from the 2nd row of that group and the columns as the first value of that group using df.iloc[] and save them in a dictionary:
d={f'df{i}':pd.DataFrame(g.iloc[1:].values,columns=g.iloc[0].values)
                   for i,g in df.groupby(df['col'].eq('x').cumsum())}

print(d['df1'])
 x
0  0
1  1
2  2
3  3
4  4

print(d['df2'])
    x
0  23
1  34
2   5
3   6

A: Use df.index[df['x'] == 'x'] to look for the row index of where the column name appears again.
Then, split the dataframe into 2 based on the index found
df = pd.DataFrame(columns=['x'], data=[[0], [1], [2], [3], [4], ['x'], [23], [34], [5], [6]])

df1 = df.iloc[:df.index[df['x'] == 'x'].tolist()[0]]
df2 = df.iloc[df.index[df['x'] == 'x'].tolist()[0]+1:]

A: You did't mention this is sample of your dataset.Then you can try this
import pandas as pd

df1 = []
df2 = []

df1 = pd.DataFrame({'df1': ['x', 0, 1, 2, 3, 4]})

df2 = pd.DataFrame({'df2': ['x', 23, 34, 5, 6]})

display(df1, df2)


text:
Q: Itinerant doctor foils a would-be emperor's plans to commandeer old space technology to weaponize space I most likely read this sometime between the late 1990s and 2010.  I have no idea where I would have read it.  It might be closer to novella length than a short story.  It'd be neat to have it identified so I can find out if the author has written any other stories in this world.
The milieu is a post-disaster world (possibly a limited nuclear war) that is recovering and becoming increasingly populated, centralized and technologically advanced.  I believe it was set in a mostly-Mexican-influenced culture on the Pacific coast, extending at least as far north as southern California.  The culture the story takes place in is almost neo-feudalistic, patterned somewhat on pre-independence Spanish culture in Mexico.  Some early 20th century level technologies exist, but I don't know if they are reconstituted or technological remnants.
The protagonist is a travelling doctor.  He is considered a neutral figure in whatever struggles/conflicts are going on, because he has more advanced medicines than anyone else, and because he vaccinates everyone as he makes his rounds.  (It's possible that the back story included some military use of germ warfare, since characters in the story seem to know what that is, and it would provide some justification for why a doctor who provides vaccines would be held in high regard.)
He arrives in a town which is under threat from a neighbouring warlord who dreams of setting himself up as emperor.  In town he meets with a young woman, almost of marriageable age, who he has apparently be keeping an eye on as she grew up; she is smart, curious, scientific and seems to have a much more modern attitude than her contemporaries.
The warlord is trying to discover, excavate and utilize an underground base where a space-capable human-rated launch system was stored to be kept safe in the event of a disaster.  I think there may be an orbital base of some sort still in high orbit, and he plans to use it to threaten possible enemies.  When his forces reach the launch vehicle, the doctor releases a bio-war plague that kills the generalissimo's soldiers (and possibly the generalissimo too), which causes the base to be quarantined.
The young woman realizes that no bio-war agent would have lasted so long (100 years?) underground, and guesses that the doctor spread it, and that her "vaccination" was actually to protect against the germ warfare virus.  The doctor reveals that he is actually part of a secret society dedicated to trying to guide the recovery of humanity, and promises that he will have her sent to a school that will lead to her joining the society.

A: Man of the Renaissance by Michael McCollum. It is a novella not a short story. The story was written in 1988 and I read it in McCollum's 1998 anthology Gridlock and Other Stories.
The travelling Doctor is Darol Beckwith and as you say he is apolitical:

"Beckwith's the name. Darol Beckwith. I am the circuit doctor for these parts. Most recently out of California Free Republic, bound for the village of Nuevo Tubac on my yearly rounds ... and damned if I expected to see Sonorans this far north."
...
Beckwith let his smile degenerate into a sheepish grin. "Now, Captain, you know that my service doesn't take sides in local politics. It would be a violation of my oath to answer such a question."

The general is:

"I am General Miguel Stefan Trujillo of the Militar de Mexico," he said, finally, leaning forward to rest his elbows on the polished surface of the desk. "You are the traveling doctor for this village?"

And the girl is Esperanza Galway:

Espe blushed as Beckwith nodded approvingly. Gone was the gangly little girl whose arm he had set five years ago. In her place was a blossoming young woman of nearly fifteen summers. Espe was one of those lucky people who seemed to have extracted just the right characteristics from her mixed bag of ancestors. She was fast becoming a beautiful young woman.

Beckwith kills General Trujillo by spitting on him. Beckwith has a false tooth filled with live Pasteurella pestis. Espe finds the broken tooth in Beckwith's mouth when she's looking after him after he's been beaten up.
At the end of the novella Beckwith reveals:

"Helping humanity survive the coming crisis is the true goal of the Public Health Service. We advance that goal any way we can. In this particular case, we advanced it by safeguarding High Citadel. In another place and time, we may choose to make certain that a king never produces a legitimate heir. In another, we may give an aged philosopher a new heart in order that he can live a few more years to complete his work. By so doing, we perform more good for humanity than with all the potions and nostrums ever peddled. That is the organization that I am giving you a chance to join, Espe. I await your decision."


text:
Q: Preloading web assets: load less then the full size of the file You (me, we, everyone etc) no doubt aware of methods to load and preload assets on a site. But I was wondering if it's at all possible, either server or client side, to partially load an assets.
Let's say I have 10 images on my site, all 500kb.
But these images are not immediately viewable until a user triggered event.
Is it at all possible, to load say, 200kb of each image on load, and then load the remaining 300kb when needed?
I don't need info on preloading, as it been well documented in many places, just if partial loadin of assets is something anyone has tried and achieved
Thank for any ideas
Andrew

A: You can certainly perform a partial load where you only load X out of your 500 images.  However, it seems highly unlikely that loading only 200K of a 500K file would be useful on the web -- particularly with images.

A: Not exactly what you're looking for, but there are lazy-loading plugins out there that will delay loading of images until the user scrolls them into view.
Most of the frameworks out there currently have a plugin for them (jQuery's Lazy Loading plugin by Mike Tuupola used to not work correctly, but it seems he's done some work on it).  I've also found examples for MooTools, Prototype and YUI


text:
Q: How to get and parse JSON using objective C? Is it possible to get and parse JSON using objective C, then manipulate it within the cocoa framework for the iphone/pad? I'm specifically looking to do this for a couple of public APIs out there.

A: See here: how to do json parsing in iphone
Basically, you should look into the TouchJSON library (with CJSONDeserializer and CJSONSerializer).

A: Used Json-framework on some previous projects, worked really well.
EDIT: I read your post a bit too fast. I've used it on a Mac app before but not targeting the iphone/ipad. I think it should work but have no background to it. Maybe someone else can confirm?

A: It's not only possible, it's dirt simple if you use one of the many existing open source projects dedicated to this task. I recommend trying yajl-objc, which offers a streaming parser, but json-framework is a good one too. They're very similar.

A: I'd stay away from TouchJSON, since it gave me trouble a while back with special characters (line breaks) in strings.
However, I'll join the choir recommending json-framework. Since I switched to that from TouchJSON everything's been running smoothly.
Regarding how to integrate the API in your project, they're equally simple to include and use.
As a side note, I'm just now testing out JSONKit, since it's supposed to be much faster than both TouchJSON and json-framework. However, I can't vouch for its stability yet. The reviews of it are good, though.

A: If you're developing an application that is only iOS 5.0 or later, you can use NSJSONSerialization.


text:
Q: Как создать резиновый баннер в Magento? Почитал литературу и уроки по созданию статических блоков в Magento, не могу найти подходящего решения для установки баннера в правую колонку. При этом изображение должно быть резиновым, как на большом мониторе сохранять пропорции, так и на планшете. Пробовал через создание статического блока и виджета. Возможно можно как-то напрямую создать блок в hml или phtml файле? Подскажите, пожалуйста! Если вопрос звучит неконкретно, то в диалоге постараюсь объяснить чётче. Ещё нюанс, баннер должен выводится первым в колонке.

A: То, какие блоки выводятся, определяется шаблоном и макетом (layout).
На примере magento 1.9 и шаблона RWD, если для раздела каталога используется шаблон frontend/rwd/default/template/page/3columns.phtml, то в нём можно найти такую строчку:

<?php echo $this->getChildHtml('right') ?>

Т.е. он пытается получить блоки 'right'.
Далее смотрим в app/design/frontend/rwd/default/layout/catalog.xml и находим в нём:
<default>
    <reference name="right">
        <block type="catalog/product_compare_sidebar" before="cart_sidebar" name="catalog.compare.sidebar" template="catalog/product/compare/sidebar.phtml"/>
    </reference>
</default>

Т.е. по умолчанию в правой колонке выводится блок для сравнения товаров.

Блоки "Community poll" и "PayPal" добавляются файлами paypal.xml и poll.xml (вариантов добавления блоков несколько). Проще всего добавить блок в уже существующий xml файл, для каталога это будет catalog.xml.
Добавим нужный блок следующим образом:
<default>
    <reference name="right">
        <block type="page/html" name="page.right.banner" output="toHtml" template="page/custom/banner.phtml" />
        <block type="catalog/product_compare_sidebar" before="cart_sidebar" name="catalog.compare.sidebar" template="catalog/product/compare/sidebar.phtml"/>
    </reference>
</default>

И создадим файл app/design/frontend/rwd/default/template/page/custom/banner.phtml со своим содержимым:
<?php
    $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
?>
<img src="<?php echo $url . 'frontend/rwd/default/images/banners/cat.jpg'; ?>" style="width: 100%">

Чистим кеш и получаем:

Сортировка блоков определяется параметрами before="child.block.name" и after="child.block.name". У блока сравнения есть before="cart_sidebar", поэтому сейчас он выводится выше нашего блока. Можем добавить нашему блоку before="catalog.compare.sidebar" и наш блок станет выше.
<block type="page/html" name="page.right.banner" output="toHtml" before="catalog.compare.sidebar" template="page/custom/banner.phtml" />

Ну, а чтобы баннер был респонсив (тянулся под любое разрешение), это уже задача css. Вариантов решения тоже масса, всё зависит от конкретной верстки. Как самый простой вариант, можно для изображения задать width: 100%


text:
Q: Generating an image representing inland surface water using QGis and OSM data I'm trying to generate a raster image representing surface water for a given bounding box. I'm using OpenStreetMaps data as my input for water bodies, and I'm using QGis on Ubuntu to process this data. Eventually I would like to be able to take any bounding box as an input, and generate a raster image (2048px by 2048px) that has blue pixels where there is surface water, and black pixels where there is land (or sea; I'm not concerned with ocean water - these can be blue or black). Given that most maps/visualisation tools that use OSM data (such as openstreetmaps.org, Overpass, GeoJSON.io, etc) display inland water as solid blue polygons, I'm sure this can't be too hard to achieve!
At the moment I am trying to do this manually. Ideally this would all be accomplished with free and open source data and software. I intend to create a tool to do this automatically if and when I figure this out. Here is what I have tried:
First I grabbed some OSM data representing inland water using the Overpass API at http://overpass-turbo.eu/ I used the following query:
(
    way["natural"="water"]({bbox});
    rel["natural"="water"]({bbox});
    way["water"="lake"]({bbox});
    rel["water"="lake"]({bbox});
    way["waterway"]({bbox});
    rel["waterway"]({bbox});
);
(._;>;);
out;

I then exported this data in GPX format and imported it as a vector layer into QGis. The lakes are all presented as outlines and the rivers as one-pixel-wide lines. I also imported a simple GeoJSON polygon that represented my bounding box, set it to have a black style, and clipped the other layer to it. I would now like to export the two layers as a 2048x2048 bitmap/png (or similar). I tried to use Raster Menu > Conversion > Rasterize on just the water layer, but this produced a blank raster. I then tried to use the Print Composer as suggested in an answer to this question but this proved to be a lot of work to get it to stretch correctly, and my polygons were not solid but just outlines so I had to fill them in manually.
I must be missing a relatively simple solution here. How can I generate a simple, 2 colour raster image representing surface water for a given bounding box?

A: I couldn't get your overpass query to work so I tried building it using the wizard. I confess I tend to use the QuickOSM plugin as I find the overpass query language a bit tricky :)
This is the query I went with:-
/*
This has been generated by the overpass-turbo wizard.
The original search was:
"natural=water or water=lake or waterway=*"
*/
[out:json][timeout:25];
// gather results
(
  // query part for: "natural=water"
  node["natural"="water"]({{bbox}});
  way["natural"="water"]({{bbox}});
  relation["natural"="water"]({{bbox}});
  // query part for: "water=lake"
  node["water"="lake"]({{bbox}});
  way["water"="lake"]({{bbox}});
  relation["water"="lake"]({{bbox}});
  // query part for: "waterway=*"
  node["waterway"]({{bbox}});
  way["waterway"]({{bbox}});
  relation["waterway"]({{bbox}});
);
// print results
out body;
>;
out skel qt;

Brought the GPX into QGIS.
However, attempting to rasterize gives the error message "not a known GDAL format". So I downloaded a GeoJSON instead - same problem. So I saved the GeoJSON to a shapefile instead, and used that.
However, I had to manually edit the GDAL command line (using the pencil icon next to the command) and include a "burn" value (here, I chose 10)
gdal_rasterize -burn 10 -ts 3000 3000 /path/to/my.shp /path/to/generated.tif

This should create a raster with 0 for the background, and 10 where there is water.
I got the same result; a black raster. The reason for this is that the default is to not stretch the histogram to the full range of values; instead it clips the bottom and top 2% of values. If fewer than 2% of pixel values are 10, it'll assume the range is 0..0, hence the black image.
If you go into Layer Properties > Rendering > Band Rendering, choose SingleBand Grey, Min/Max, Full Extent, Actual Accuracy and click Load it should show the full range of values (0 to 10).

Apply that, and you should now see your waterways.

In this case I just did one layer, the lines. You might want to use Merge Shapefiles to combine your various layers, and rasterize the combined shapefile.
If that doesn't work (e.g. mixing lines/polygons) you can either

*

*use Raster Calculator to mix your resulting rasters together

*use Buffer on your lines to make them polygons, then merge / rasterize

It looks a bit "gritty", with gaps. These will vanish if you zoom in. (I might have turned off anti-aliasing)
EDIT
To clarify how to fill in the lakes...
Import the GeoJSON file you exported from Overpass, and bring in the Polygon layer:-

If neccessary, save to shapefile. Rasterise this, and your lakes should be filled...

A: Have you tried using gdal_rasterize (http://www.gdal.org/gdal_rasterize.html) ?


text:
Q: Is it possible to know the type of a html input with php? I need to check the type of the different inputs I have in a form.
I need to know if the field xxx is a checkbox, radio, select, etc.
Is it possible?
Thanks!

*

*César -

A: Assuming you mean after submitting the form, then no, only the parameter name and value are sent to the server.  You could be a little clever with your naming to identify them server-side.  At the server, you can then iterate over the request variables and parse chk from the name.  For example:
HTML
<input type="checkbox" name="chkMyCheck" value="1" />

PHP
foreach ($_GET as $key => $value) {
    if (substr($key, 0, 3) == "chk")
        echo 'Checkbox '.$key.' submitted with value '.$value;
}

It makes it harder to get the variables at the server, though, if you don't know the type beforehand.

A: Yes, you can use an HTML parser and fetch the input element's type attribute.
$html = <<< HTML
<form>
    <input type="submit" value="Submit"/>
    <input type="hidden" value="1234"/>
    <input type="text" value="some text" id="xxx"/>
</form>
HTML;

// fetch with
$dom = new DOMDocument;
$dom->loadHTML($html); // use loadHTMLFile to load from file or URL
echo $dom->getElementById('xxx')->getAttribute('type');

will output "text".
There is plenty of examples on SO that cover fetching different parts. Just give it a search.

A: The only data types that reach PHP are strings and arrays, so it's not possible to do that directly.
The way I see it you only have two options:

*

*Use Hungarian-like notation, or

*Parse the form DOM with SimpleXML or similar


text:
Q: I don't understand how works injection dependency. Is there somebody which can explain me clearly I try to realize a little NestJS application in which I want to integrate a task scheduler. One of the first tasks of this scheduler will be to update data in database. This task service will user a UserService like below :
import {
  Injectable,
  Inject,
  UnprocessableEntityException,
  HttpStatus,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { User, UserStatus } from './user.entity';
import { LoggerService } from '../../../logger/logger.service';
import { HammerErrors } from 'src/error/hammer.errors';
import * as Config from '../../../config/global.env';

@Injectable()
export class UserService {
  private readonly _logger = new LoggerService(UserService.name);

  constructor(
    @Inject('USER_REPOSITORY')
    private _userRepository: Repository<User>,
  ) {}
  ....
  async reactiveBlockedUsers() {
    this._logger.setMethod(this.reactiveBlockedUsers.name);
    this._logger.log(`Update blocked users`);
    await this._userRepository
      .createQueryBuilder('hm_users')
      .update(User)
      .set({
        nextValidDate: null,
      })
      .where(
        `hm_users.nextValidDate IS NOT NULL hm_users.nextValidDate < utc_timestamp()`,
      )
      .execute();
    return null;
  }

}
My task service is as follows:
import { LoggerService } from '../../../logger/logger.service';
import { UserService } from '../../providers/user/user.service';
import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';

@Injectable()
export class TasksService {
  private _logger = new LoggerService(TasksService.name);

  constructor(private _userService: UserService) {}

  @Cron(CronExpression.EVERY_MINUTE)
  async reactiveUsers() {
    this._logger.setMethod(this.reactiveUsers.name);
    this._logger.log(`Reactive blocked users`);
    try {
      await this._userService.reactiveBlockedUsers();
    } catch (error) {
      this._logger.log(error);
    }
  }

  @Cron(CronExpression.EVERY_MINUTE)
  startBatchJobs() {
    this._logger.setMethod(this.startBatchJobs.name);
    this._logger.log(`Start batch job service`);
  }

  triggerNotifications() {}
}

The task module is the following :
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { UserService } from 'src/shared/providers/user/user.service';
import { Repository } from 'typeorm';

@Module({
  providers: [
    TasksService,
    UserService,
    {
      provide: 'USER_REPOSITORY',
      useClass: Repository,
    },
  ],
})
export class TasksModule {}

When I the process works, I have the following trap :
[INFO] 06/05/2020 19:57:00.024 [TasksService.reactiveUsers] TypeError: Cannot read property 'createQueryBuilder' of undefined
Or :
(node:13668) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'createQueryBuilder' of undefined
    at Repository.createQueryBuilder (D:\dev\hammer\hammer-server\node_modules\typeorm\repository\Repository.js:17:29)
    at UserService.reactiveBlockedUsers (D:\dev\hammer\hammer-server\dist\src\shared\providers\user\user.service.js:183:14)
    at TasksService.reactiveUsers (D:\dev\hammer\hammer-server\dist\src\shared\services\tasks\tasks.service.js:25:33)
    at CronJob.fireOnTick (D:\dev\hammer\hammer-server\node_modules\cron\lib\cron.js:562:23)
    at Timeout.callbackWrapper [as _onTimeout] (D:\dev\hammer\hammer-server\node_modules\cron\lib\cron.js:629:10)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)
(node:13668) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:13668) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
when I suppress the try catch.
For me it is a problem  of providing Repositiry module which is injected in UserService but I don't understand how that works and how to solve this problem.
If somebody has an idea, I will be interested.
Thanks for your help.

A: Repository is an abstract class in TypeORM and cannot be instantiated directly. Nest does what it can around this, but ultimately it will provide an undefined and thus, calling createQueryBuilder will give you a problem. As you are using TypeORM, is there a reason you aren't using the @nestjs/typeorm package? It manages creating the repository classes for you and makes things much easier. You are are gungho about not using the package, you can always create your own Repository class UserRepository extends Repository decorated with the proper metadata and all, and then use that class instead of Repository

A: Thank you for information I did not know about this existing package. I will try to implement your proposal. I am a novice in these technology and I discover day by day something new. From beginning of March I have learned HTML, CSS, Javascript, Typescript NestJs and Angular and now I try to implement a little project with all these technologies. I think that I have many hole in my knowledge and I apreciate your answer to give me those informations.


text:
Q: Tuning Garbage Collection parameters in Java I have a server java component which has a huge memory demand at startup which mellows down gradually. So as an example at startup the memory requirement might shoot unto 4g; which after the initial surge is over will go down to 2g. I have configured the component to start with memory of 5g and the component starts well; the used memory surges upto 4g and then comes down close to 2g. The memory consumed by the heap at this point still hovers around 4g and I want to bring this down (essentially keep the free memory down to few hundred mb's rather than 2g. I tried using the MinFreeHeapRatio and MaxFreeHeapRatio by lowering them down from the default values but this resulted in garbage collection not being triggered after the initial run during the initial spike and the used memory stayed at a higher than usual level. Any pointers would greatly help.

A: First, I ask why you are worried about freeing up 2 GB of ram on a server?  2GB of ram is about $100 or less. If this is on a desktop I guess I can understand the worry.
If you really do have a good reason to think about it, this may be tied to the garbage collection algorithm you are using. Some algorithms will release unused memory back to the OS, some will not. There are some graphs and such related to this at http://www.stefankrause.net/wp/?p=14   .  You might want to try the G1 collector, as it seems to release memory back to the OS easily.
Edit from comments
What if they all choose to max their load at once?  Are you ok with some of them paging memory to disk and slowing the server to a crawl? I would run them on a server with enough memory to run ALL applications at max heap, + another 4-6GB for the OS / caching. Servers with 32 or 64 GB are pretty common, and you can get more.

A: You have to remember that the JVM reserves virtual memory on startup and never gives it back to the OS (until the program exits)  The most you can hope for is that unused memory is swapped out (this is not a good plan)  If you don't want the application to use more than certain amount of memory, you have to restrict it to that amount.
If you have a number of components which use a spike of memory, you should consider re-writing them to use less memory on startup or use multiple components in the same JVM so the extra memory is less significant.


text:
Q: Solo se guarda la primera palabra, en las demás se cierra el BufferedWriter Estoy haciendo un programa que me cree una ventana gráfica con tres componentes: dos JButton y un JTextField, asignando un evento a cada botón:

*

*El primer botón me abre un JFileChooser para abrir un bloc de notas.

*El segundo botón me deja guardar el texto en el bloc de notas que previamente he abierto en el botón 1.

El problema está en que solo me guarda la primera palabra, en las demás me cierra el BufferedWriter y no entiendo el porqué. Os comparto el código para ver en que estoy fallando y por qué.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class VentanaFrame implements ActionListener, WindowListener {

    private JButton boton1;
    private JButton boton2;
    private JTextField texto;
    private File archivo;
    private BufferedWriter bw;

    public VentanaFrame() {

        boton1 = new JButton("Abrir Archivo");
        boton2 = new JButton("Guardar texto");
        texto = new JTextField();

    }

    public void Ejecuta() {

        //creo la ventana grafica
        JFrame ventana = new JFrame("Ventana");
        ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ventana.setSize(400, 350);
        ventana.setLocation(450, 400);
        ventana.setLayout(new BoxLayout(ventana.getContentPane(), BoxLayout.Y_AXIS));

        //creo el Panel
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBackground(Color.CYAN);

        //creo el tamaño de los botones

        boton1.setSize(50,50);
        boton2.setSize(50,50);

        //indico el tamaño del texto

        texto.setColumns(20);

        //añado los componentes al panel

        panel.add(boton1);
        panel.add(boton2);
        panel.add(texto);

        //añado los eventos a los componentes

        boton1.addActionListener(this);
        boton2.addActionListener(this);
        texto.addActionListener(this);

        //añado el panel a la ventana
        ventana.add(panel);

        //hago visible la ventana
        ventana.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {

        if(event.getSource() == boton1) {

            JFileChooser elegirArchivo = new JFileChooser();
            elegirArchivo.setFileSelectionMode(JFileChooser.FILES_ONLY);
            elegirArchivo.setDialogTitle("Selecciona el fichero");

            int returnVal = elegirArchivo.showDialog(elegirArchivo,"Cargar");

            if(returnVal == JFileChooser.APPROVE_OPTION) {

                archivo = elegirArchivo.getSelectedFile();
                try {

                    this.bw = new BufferedWriter(new FileWriter(archivo));

                } catch (IOException e1) {
                    JOptionPane.showMessageDialog(null, "Error al abrir el archivo");

                }
            }

            else if(returnVal == JFileChooser.CANCEL_OPTION) {
                JOptionPane.showMessageDialog(null, "Has cancelado la operacion.");
            }

        }

        else if(event.getSource() == boton2 || event.getSource() == texto) {

            try {
                bw.write(texto.getText() + "\n");
            } catch (IOException e) {

                JOptionPane.showMessageDialog(null, "Error en la escritura del archivo");
            }

            if(null != bw) {

                try {
                    bw.close();
                } catch (IOException e) {

                    JOptionPane.showMessageDialog(null, "Error al cerrar el Buffer");
                }
            }

        }

    }

    public void windowClosing(WindowEvent event) {

        if(null != bw){

            try {
                bw.close();
            } catch (IOException e) {

                JOptionPane.showMessageDialog(null, "Error al cerrar el buffer");
            }

        }
    }

    @Override
    public void windowActivated(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowClosed(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeactivated(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeiconified(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowIconified(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowOpened(WindowEvent arg0) {
        // TODO Auto-generated method stub

    }
}

A:
El problema está en que solo me guarda la primera palabra, en las
demás me cierra el bufferedWriter y no entiendo el porqué.

Ten en cuenta que:

*

*Si solo se esta guardando la ultima linea que se introduce es porque FileWriter no esta haciendo el append sobre el archivo, lo esta sobre-escribiendo (es el comportamiendo default), se soluciona usando su constructor FileWriter(File file,boolean append);

*Despues de cerrar el stream del BufferedWriter no hay vuelta atras para que se pueda volver a escribir en el archivo, lo mas adecuado es volver a crear una instancia BufferedWriter cada que se vaya a efectuar una escritura sobre el archivo en cuestion.

Quedando algo parecido a lo siguiente en el bloque que escribe los datos:
//...
try {
  bw=new BufferedWriter(new FileWriter(archivo,true));
  bw.write(texto.getText() + "\n");
} catch (IOException e) {
  JOptionPane.showMessageDialog(null,"Error en la escritura del archivo\n"
                                    +e.getMessage());
}
//...


text:
Q: Terminal in Gnome for Arch Linux Not Working I've just installed Arch Linux and installed the gnome package (Note: Not gnome-extra)
I open Gnome using the xinit gnome-session command, as I have already installed X Window.
When I run that command, Gnome opens up and I'm presented with a white terminal titled "login". However, nothing I do in this terminal actually does anything. No commands work, nothing.
Could someone help me figure out what I'm doing wrong? There have been a few questions around similar to this, however none that have been properly answered.
Thank you!

A: After installing gnome session you need to append
exec gnome-sssion

at the end of your .xinitrc file located at your home.
when you get the login: prompt enter your username and then your password.
Once you're logged in type startx to start gnome session

A: Solved! I hadn't set Gnome to startup automatically, so when you login to Arch Linux using your standard root login. Check that gnome is installed and works (Use: xinit gnome-session).
Create an account by going to Settings, Users, Create the account as Administrator. Logout of Gnome Log back in as root to your Arch Linux CLI Use the command: systemctl enable gdm The next time you reboot, you should be presented with the Gnome Login screen.


text:
Q: How to Uploading Base64 / byte[] Image to Azure Blob with ASP.NET Core 6 MVC using C#? Here is my code IFormFile.
public static async Task<string> UploadFileToBlobStorage(IFormFile file)
        {
            string container = "abccontainer";
            string storageAccount_connectionString = "DefaultEndpointsProtocol=https;AccountName=abc/aXQUORlrTMNkxaUFPDDlLEW/mwe5Fihy+zl4p+ysF6Y+9JiMud8khH+AStEDb6DA==;EndpointSuffix=core.windows.net";
            BlobContainerClient blobContainerClient = new(storageAccount_connectionString, container);

            BlobClient blob = blobContainerClient.GetBlobClient(Path.GetFileName(file.FileName));

            var mimeTypes = GetFileContentType(Path.GetFileName(file.FileName));
            var header = new BlobHttpHeaders
            {
                ContentType = mimeTypes
            };

            await blob.UploadAsync(file.OpenReadStream(), header);

            return blob.Uri.AbsoluteUri;
        }

But, I want to upload bytes[]  to blob storage.  Foe that, I will pass only byte[] array, and it should upload.
How can I do ?
public static async Task<string> UploadFileToBlobStorage(byte[] array)
        {
            return blob.Uri.AbsoluteUri;
        }

A: UploadAsync has an overload that takes a BinaryData object.
You should be able to rewrite your code like this:
BlobClient blob = blobContainerClient.GetBlobClient("somename.txt"); // update as necessary

var header = new BlobHttpHeaders
{
    ContentType = "text/plain" // update as necessary
};

byte[] sourceData = getSourceData();
BinaryData uploadData = new BinaryData(sourceData);
await blob.UploadAsync(uploadData, new BlobUploadOptions { HttpHeaders = header });


text:
Q: iptable rule in custom chain is not effective I'm no iptables expert and have 2 strange behaviors that needs fixing !
Problem 1 : Why am I not banned ?
I have a custom chain f2b-nginx-naxsi which has the following iptable rules:
$ sudo iptables -S f2b-nginx-naxsi
-N f2b-nginx-naxsi
-A f2b-nginx-naxsi -s 81.250.100.81/32 -j REJECT --reject-with icmp-port-unreachable #<== Here
-A f2b-nginx-naxsi -j RETURN

81.250.100.81 is my public IP so I should be banned.
Its not working. The rule is innefective !
The chain is loaded from the INPUT chain as follow:
sudo iptables -S INPUT
-P INPUT ACCEPT
-A INPUT -p tcp -m multiport --dports 80,443 -j f2b-nginx-naxsi    #<== Here
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j INPUT_direct
-A INPUT -j INPUT_ZONES_SOURCE
-A INPUT -j INPUT_ZONES
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -j REJECT --reject-with icmp-host-prohibited

Problem 2 : Why am I banned from SSH and not :80 ?
In order to fix problem 1 I took the previous rule and set it inside the INPUTchain:
-I INPUT -s 81.250.100.81/32 -j REJECT --reject-with icmp-port-unreachable
After pressing enter I got disconnected from the machine, lol.
But for some reasons I still can ping our nginx from the browser...
Why did it kill SSH (22) but not standard http connections (80)
Thx in advance,
;-)

A: Troubleshooting steps:

*

*Check that the multiport iptables module is loaded:
 lsmod | grep multiport
 # Should see something like xt_multiport or ipt_multiport in the output

*Verify that your nginx server is actually listening on port 80 and or 443. You could be configured behind a proxy.
 sudo ss -tlnp | grep nginx
 # Should see nginx listed listening on one of those two ports

(edited)
2b. Check which port(s) on your docker host are mapped to the nginx container.
    docker port <container_name>

This command should show which port(s) you need to use in your custom IPtables chain running on the container host.

A: I finaly got to the bottom of the mystery !
The problem comes from docker which is overiding my iptable rule...
In order to drop incoming connection to a docker container you must place your rule inside a chain nammed DOCKER-USER.
This chain is created by Docker itself and those rules will take precedence over the ones from docker engine.
For instance, to ban a specific IP (from fail2ban for example) on port 443 :
sudo iptables -I DOCKER-USER -i eth0 -s <SPECIFIC_IP> -p tcp --dport 443 -j DROP
(Change eth0 to whatever is your external interface)

*

*Don't forget to set a port or the rule might apply on your SSH port (22) and you will ban yourself...

*Adding a rule to the INPUT chain won't work if you are trying to block the access to a docker container.

*The chain called DOCKER is for docker stuff only. Don't put anything in there.


text:
Q: AWS EC2 Server - source ~/.bashrc I am new to AWS and springboot. Here i am trying to deploy my spring application first time in AWS using UBUNTU but getting command not found message as in below screen shot. Some one please guide me
Screenshot:


text:
Q: JSON response appended with extra properties using jQuery File-Upload plugin in Struts 2 I'm using jQuery File-Upload plugin with Struts 2.
In my action I am populating the JSON object "results" and that's all I want my action to return.
But it is also including the plugin's file object as well which is an incomplete JSON and causing everything to break on my callbacks.
(Please note that if I don't populate my result object then it will return a valid JSON "file" object.
Is there any way I could avoid returning the "file" JSON response? I just want my action to return only "results"
{
    "results": [
        {
            "ExcelPath": "/usr/test/test.xlsx",
            "ExcelName": "test.xlsx",
            "TestExcelStatus": "success"
        }
    ]
}
{
    "file": {
        "absolute": true,
        "absoluteFile": null,
        "absolutePath": "\/usr\/local\/apache-tomcat-7.0.39\/temp"
    },
    "path": "\/usr\/local\/apache-tomcat-7.0.39\/temp\/up

My Action is as below:
org.json.JSONObject resp = new JSONObject();
JSONArray resultsArray = new JSONArray();
resp.put("results",resultsArray);
JSONObject result = new JSONObject();
result.put("TestExcelStatus", "success");
result.put("ExcelName", this.fileFileName);
result.put("ExcelPath", fileToCreate.getPath());
resultsArray.put(result);

servletResponse.reset();
servletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
servletResponse.setHeader("CacheControl","no-cache");
servletResponse.setHeader("Pragma","no-cache");
servletResponse.setHeader("Expires","-1");
//resp.writeJSONString(out);
resp.write(servletResponse.getWriter());

I am expecting the below line to clear the existing JSON and only return my "results" JSON. But it is still returning every thing.
servletResponse.reset();

And the desired JSON response must be as below without a "file".
{
    "results": [
        {
            "ExcelPath": "/usr/test/test.xlsx",
            "ExcelName": "test.xlsx",
            "TestExcelStatus": "success"
        }
    ]
}

A: The Struts action is always returning a result code that is used by the action invocation to execute a result configured to this action. I suspect that result is of type json.
If the action returning json result then by default the root property is initialized to the action instance or a model if you are using model-driven action.
It means that all public properties of the root object will be serialized to JSON. You can control this process with annotations placed on the properties, or configure the result with parameters to include/exclude some properties from the result.
Actually you only need to configure the root parameter of the result to return an object that you serialize to JSON. But because you are writing to response directly you can change the result code returned by the action to NONE. This is used by the actions that don't return any result.


text:
Q: Scala 2.11 (/java8) matcher not allowing named capturing groups? Here is some scala matcher code using named groups:
  val regex=".*Completed (?<tstamp>[\d]{4}-[\d]{6})/(?<tname>[\w]+) (?<loops>[\d]+)Loops (?<cores>[\d]+)cores (?<mem>[\d]+)mb (?<inrecs>[\d]+)recs (?<nparts>[\d]+)parts (?<xform>[\w]+) (?<action>[\w]+) - duration=(?<duration>[\d]+\.[\d]+) seconds count=(?<outrecs>[\d]+).*"
  val rmatch = meta.regex.findFirstMatchIn(line)

The input is:
<03:54:26> Completed 0917-035231/CpuMem 100000000Loops 16cores 128mb 5000000recs 20parts GroupByKey Count - duration=41.408 seconds count=5000000

We can see in the screenshot of the Watch screen for the pattern (third entry) that the first capturing group is named tstamp. It is properly captured and viewable as
 m[atch].group(1)

However it is not accessible within the named group
m[atch].group("tstamp")

There is another SOF question touching on this topic but that is five years old (before Java7 came out with support for named groups):  Scala regex Named Capturing Groups
But that one does not address this scenario of scala 2.11 / java8

A: Scala 2.12 requires Java 8 and could progress the API.
Meanwhile, a sample extension:
https://github.com/som-snytt/regextractor/blob/master/core/src/test/scala/regex/GrTest.scala#L85
In another vein, https://github.com/travisbrown/expressier

A: This is more of an extended commentary on the accepted answer from som-snytt.  The extensions that he mentions may be included as dependencies  directly in sbt . Maven requires a bit more work: by including the following the jitpack git-to-maven tool:
Try jitpack, you just need to add the dependency, jitpack will build others for you.

From Can I use a GitHub project directly in Maven?
From home page:

jitpack
Easy to use package repository for Gradle and Maven projects
JitPack builds GitHub projects on demand and provides ready-to-use packages
HOW

Add repository first
<repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
</repository>
Add dependency
<dependency>
    <groupId>com.github.User</groupId>
    <artifactId>Repo name</artifactId>
    <version>Release tag</version>
</dependency>


text:
Q: PHP Xdebug, VSCode, Docker & MacOS - debugger not disconnecting I've encountered a weird problem that seems to have either started appearing when the Xdebug extension was updated or Visual Studio Code received an update.
When the debugger is active in VSCode the website works fine, when stopping the debugger, the Xdebug extension within the docker container seems to be unable to disconnect. And the website is stuck in a loading state.
I receive the following message in the xdebug.log when trying to access the site when the debugger is stopped in VSCode.
[318] Log opened at 2022-04-08 12:19:15.819009
[318] [Step Debug] INFO: Connecting to configured address/port: host.docker.internal:9001.
[318] [Step Debug] INFO: Connected to debugging client: host.docker.internal:9001 (through xdebug.client_host/xdebug.client_port). :-)
[318] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/html/index.php" language="PHP" xdebug:language_version="7.4.0" protocol_version="1.0" appid="318" idekey="VSCODE"><engine version="3.1.4"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2022 by Derick Rethans]]></copyright></init>

This seems like the Xdebug extension still tries to connect (successfully) to the listening port at 9001.
But the port is not listening on the host, when checking with lsof -i :9001.
PHP Xdebug settings:
zend_extension=xdebug.so
xdebug.mode=debug
xdebug.remote_handler=dbgp
xdebug.idekey=VSCODE
xdebug.start_with_request=yes
xdebug.log=/tmp/xdebug.log
xdebug.client_host=host.docker.internal
xdebug.client_port=9001
xdebug.discover_client_host=0

launch.json settings:
{
    "version": "0.2.0",
    "configurations": [{
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": false,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}",
            },
            "ignore": [
                "shared/vendor/*"
            ]
        },
    ]
}

I've also tried with a different client_host setting.
Added an alias to the en0 interface, to reach the host IP from Xdebug.
sudo ifconfig en0 alias 10.128.128.128 255.255.255.0

No variation of settings seems to eliminate this problem, anyone has any ideas?

A: The 4.8.0 build solves this issue.
The Docker for mac ticket: https://github.com/docker/for-mac/issues/6235
The builds that resolves the issue:
Intel: https://desktop-stage.docker.com/mac/main/amd64/78146/Docker.dmg
Apple silicon: https://desktop-stage.docker.com/mac/main/arm64/78146/Docker.dmg


text:
Q: Is there a good way to achieve dependency injection in ASP.NET MVC application without any DI Container? So I have created the simplest of the applications using ASP.NET MVC (in .NET Framework) and I want to demo dependency injection to a junior using this. it is very simple code, even a newbie can understand it.
public interface IMovieRepository
{
    MyViewModel GetDetails(string movie);
}

public class MoviesController : Controller
{
    [HttpPost]
    public async Task<ActionResult> Search(string movie)
    {
        // Confusion here! Is the below line a good place to inject dependency
        IMovieRepository repository = new DBMovieRepository(); // <-- it can be DBMovieRepository or WebServiceMovieRepository or MockMovieRepository
        MovieFinder finder = new MovieFinder(repository);
        MyViewModel model = await finder.Find(movie);
        return View(model);
    }
}

public class MovieFinder
{
    private IMovieRepository _repository;

    public MovieFinder(IMovieRepository repository)
    {
        _repository = repository;
    }

    public async Task<MyViewModel> Find(string movie)
    {
        // Connect to database and return a detailed object
        var myViewModelObj = _repository.GetDetails(movie);
        return myViewModelObj;
    }
}

public class DBMovieRepository : IMovieRepository
{
    public MyViewModel GetDetails()
    {
        // Code for fetching data from a database
    }
}

public class WebServiceMovieRepository : IMovieRepository
{
    public MyViewModel GetDetails()
    {
        // Code for fetching data from a IMDB webservice
    }
}

public class MockMovieRepository : IMovieRepository
{
    public MyViewModel GetDetails()
    {
        // Code for returning a mock object here
    }
}

There is an inline comment in the code where I asked that my confusion is here. Is that a good place to inject dependencies or do I have to inject it in the MoviesController constructor. If yes, then how will I pass it to the constructor? This is a .NET Framework 4.5 application and I don't want to complicate the lesson by introducing a DI Container and just want to use Pure DI to clarify the concept to my junior.

A:
This is a .NET Framework 4.5 application and I don't want to complicate the lesson by introducing a DI Container and just want to use Pure DI to clarify the concept to my junior.

That literally doesn't make sense.

Pure DI

Or Dependency Injection simply means using IOC to provide an Instance of a Dependency to the object (via Constructor or Property).
Inversion of Control simply means that instead of the dependent object creating the Dependency, you invert control to something else to provide the instance.
You can Architect your Controller to use IOC. You can't DI without something providing the instance.  The most lightweight/semi-hacky way to write your DI with minimum effort using your stack is to write your own Controller Factory to inspect your constructor for its dependencies and inject whatever those dependencies are (or just assume what it needs, pass it... yikes).
Relevant SO Question of Mine: My MVC Custom ControllerFactory works but could it be better?


text:
Q: Approval comment mandatory not working I just refered this blog
http://christopheralunlewis.blogspot.com/2012/10/making-all-approval-comments-mandatory.html to make both approval/reject mandatory.
And when I tested,on rejection without comment, it will throw error, it is working properly.
But on approval it is not working, no error is thrown if there is no comment.
kindly help me on this.
TriggerCode
 if(Trigger.isBefore && Trigger.isUpdate){
            System.debug('entry1111');
            // Create a map that stores all the objects that require editing
            Map<Id, Case> approvalStatements =
                new Map<Id, Case>{};
                    for(Case inv: trigger.new)
                {
                     System.debug('entry22222');

                    if (inv.Approval_Comment_Check__c == 'Requested')
                    {
                        System.debug('entry');
                        approvalStatements.put(inv.Id, inv);
                        inv.Approval_Comment_Check__c = null;
                    }
                }

            if (!approvalStatements.isEmpty())
            {

                List<Id> processInstanceIds = new List<Id>{};

                    for (Case invs : [SELECT (SELECT ID FROM ProcessInstances
                                              ORDER BY CreatedDate DESC
                                              LIMIT 1)
                                      FROM Case
                                      WHERE ID IN :approvalStatements.keySet()])
                {
                    processInstanceIds.add(invs.ProcessInstances[0].Id);
                }

                for (ProcessInstance pi : [SELECT TargetObjectId,
                                           (SELECT Id, StepStatus, Comments
                                            FROM Steps
                                            ORDER BY CreatedDate DESC
                                            LIMIT 1 )
                                           FROM ProcessInstance
                                           WHERE Id IN :processInstanceIds
                                           ORDER BY CreatedDate DESC])
                {
                    sYSTEM.DEBUG('FFFF ' +pi.Steps[0].Comments );
                    // If no comment exists, then prevent the object from saving.
                    if ((pi.Steps[0].Comments == null ||
                         pi.Steps[0].Comments.trim().length() == 0))
                    {

                         System.debug('entryEE');
                        approvalStatements.get(pi.TargetObjectId).addError(
                            'Operation Cancelled: Please provide a reason ' +
                            'for your approval / rejection!');
                    }
                }
            }

        }

Workflowrule

Field updates

Approval process


text:
Q: Adding a library to Java CLASSPATH I am not sure if my question is more related about Ubuntu or Java, so pardon me!
I am trying to compile a java program but I get the following error:
package javax.comm does not exist

I have downloaded the required package comm.jar but I do not know how/where should I install/copy this file.
I read somewhere that this should be in CLASSPATH  folder but I dont have this folder.
This is what I get for java -version I guess this means I have already installed Java in my system:
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.4) (6b24-1.11.4-1ubuntu0.12.04.1)
OpenJDK Server VM (build 20.0-b12, mixed mode)

I also have these folders in /usr/lib/jvm/ :
default-java             java-1.7.0-openjdk-i386  java-6-openjdk-i386
java-1.6.0-openjdk       java-6-openjdk           java-7-openjdk-common
java-1.6.0-openjdk-i386  java-6-openjdk-common    java-7-openjdk-i386

A: you need java API for communication see this


text:
Q: How to query history of the balances For various use cases it's valuable to display historical data of the balance on some account.
What is the best way to query this data from NEAR protocol?

A: You'll get the account transaction history from this url:
https://helper.mainnet.near.org/account/<ACCOUNT_NAME>/activity?offset=<TIME_STAMP_NANOS>&limit=<NUMBER_OF_TRANSACTIONS>
Use the block timestamp of the latest transaction in the result to ask for the previous chunk of transactions (given you set the limit to a number that doesn't include all the trasaction). when you've found the initial transaction. Accumulate deposit (look at the signer_id to determine direction) and gas amounts to get the balance after each transaction.


text:
Q: Derivative of $(x+|x|)\sqrt{|x|}$ Calculating the derivative is easy, but online math engines state that
$$f(x) = (x+|x|)\sqrt{|x|}$$
is differentiable at $x_0=0$ as well. The derivative is
$$f'(x) = \frac{3x^2+3x\left|x\right|}{2\left|x\right|\sqrt{\left|x\right|}}$$
Do I need to use the limit definition manually to prove for differentiability at $x_0 = 0$? Note that $f: \mathbb{R} \to \mathbb{R}$.

A: Yes, you have to use the limit definition manually, and check the right and left derivatives separately. So with $x>0$, you have $f(x)=2x^{3/2}$, so that the right-hand-side derivative at zero is zero, and with $x<0$, you have $f(x)=0$ so the left-hand-side derivative at zero is also zero. Therefore, $f(x)$ is differentiable at zero and the derivative there is equal to zero.

*

*My initial answer was wrong, as I mistakenly thought that the function was $(x+|x|)/\sqrt{|x|}$.

A: This function is $2x^{3/2}$ for $x\ge0$ and $0$ for $x<0$, so its derivative is $3x^{1/2}$ for $x>0$ and $0$ for $x<0$. Let's be careful with the derivative at $0$. The left-hand limit is $0$; the right-hand limit is $\lim_{x\to0^+}2x^{1/2}=0$.

A: For $x<0$, we have that $f(x)=0$. For $x>0$, we have that $f(x)=2x\sqrt{x}$, and $f(0)=0$. The derivative from left is trivially $0$, and from right it's
$\lim_{x \to 0^+}\frac{2x\sqrt{x}}{x}=0$.
So it's differentiable at 0.


text:
Q: Finding flux using polar coordinates. I solved exercise using polar coordinates. I thought that $x=rcos(\alpha)$ and $y=rsin(\alpha)$. In my exercise given. Given vector field and I solved it using divergence theorem. Result is: $\iiint$3dxdydz$(x+2)^2$+$y^2$$\le$4;$0$$\le$3y$\le$$\sqrt3$$(x+2)$;
$4(x+4)\le z \le 5(x+4)$
Here I took $(x+2)=rcos(\alpha)$ Is it true? or I should take only $x=rcos(\alpha)$
If I take $(x+2)=rcos(\alpha)$ answer is $2\pi+4$ but if I take $x=rcos(\alpha)$ I can't solve it. Please help me.


text:
Q: Support Library 27.1.0 onLoaderFinished returns a closed cursor when starting a Fragment After updating to Support Library 27.1.0, my application crashes and it appears to be caused by a CursorLoader returning a closed cursor in onLoaderFinished().
I'm using the Loader inside a Fragment and I'm not manually closing the cursor. If I rollback to Support Library 27.0.2, everything works. Here is the stack trace:
03-27 16:27:58.653 18706 18706 E AndroidRuntime: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: ...
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:58)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:151)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.sqlite.SQLiteCursor.onMove(SQLiteCursor.java:123)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:237)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:259)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.database.CursorWrapper.moveToFirst(CursorWrapper.java:71)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at com.example.test.onLoadFinished(LeaderBoardFragment.java:104)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at com.example.test.onLoadFinished(LeaderBoardFragment.java:41)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.LoaderManagerImpl$LoaderObserver.onChanged(LoaderManagerImpl.java:221)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LiveData.considerNotify(LiveData.java:109)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LiveData.dispatchingValue(LiveData.java:121)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LiveData.access$400(LiveData.java:59)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:416)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:368)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:292)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:332)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:137)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.arch.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:123)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.Fragment.performStart(Fragment.java:2377)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
03-27 16:27:58.653 18706 18706 E AndroidRuntime:    at android.os.Handler.handleCallback(Handler.java:790)

My code in onLoaderFinished() is the following:
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    super.onLoadFinished(loader, cursor);
    int score;
    if (loader.getId() == MY_LOADER_ID && cursor != null
            && getAbstractAdapter() != null) {
        getAbstractAdapter().swapCursor(cursor);

        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            score = cursor.getInt(cursor
                    .getColumnIndex(0));
        }
    }
}

It crashes when calling cursor.moveToFirst()
Code from onLoaderReset()
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
    mAdapter.swapCursor(null);
}

A: I had similar problem in support library 28.0.  Although I closed cursor in fragments onStop() on next appearance of fragment I got closed cursor - this helped me
override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor?) {
        if (loader.id == LOADER_ID ) {
            if (cursor?.isClosed == true)
                loaderManager.restartLoader(LOADER_ID, null, this)
            else
                adapter.swapCursor(cursor)
        }
    }

although it looks like workaround - I thought that loader is somehow responsible for managing lifetime of cursor and assure new one when old id closed.


text:
Q: Binding two Perl hashes (not two anonymous hashes) In order to reuse some already written code libraries, I need to "masquerade" a hash (%bar) into another hash (%foo) so that each changes made in %bar can be seen with %foo after their binding.
With an anonymous hash construct, it's easy: just copy the ref of bar into the ref of foo  ( $foo = $bar; ).
How about "not using" an anonymous hash (because the code I have to reuse is built not using anonymous hash constructs) ?  Is this only possible ?
Thanks.
use strict;
use Data::Dumper;

my  %foo = ();
my  %bar = ();

%foo = %bar;    # This won't work as it copies %bar into %foo as at the current time.

$bar{A}->{st} = 'a';
$bar{A}->{qt} = 'a';
$bar{B}->{st} = 'b';
$bar{B}->{qt} = 'b';

# $foo{A}->{st}  doesn't exist

Of course, an anonymous hash construct would have been a blessing.
use strict;
use Data::Dumper;

my  $foo = {};
my  $bar = {};

$foo = $bar;   # This works fine.

$bar->{A}->{st} = 'a';
$bar->{A}->{qt} = 'a';
$bar->{B}->{st} = 'b';
$bar->{B}->{qt} = 'b';

print STDOUT "foo\n---\n";
print Dumper($foo) . "\n\n";

print STDOUT "bar\n---\n";
print Dumper($bar) . "\n\n";

Yields the expected result:
foo
---
$VAR1 = {
          'B' => {
                   'st' => 'b',
                   'qt' => 'b'
                 },
          'A' => {
                   'qt' => 'a',
                   'st' => 'a'
                 }
        };

bar
---
$VAR1 = {
          'B' => {
                   'st' => 'b',
                   'qt' => 'b'
                 },
          'A' => {
                   'qt' => 'a',
                   'st' => 'a'
                 }
        };

A: For your example, you can use Data::Alias to alias %bar to %foo. That allows you to make changes in %bar and later see those in %foo.
use strict;
use warnings;
use Data::Printer;
use Data::Alias;

my  %foo = ();
my  %bar = ();

alias %foo = %bar;

$bar{A}->{st} = 'a';
$bar{A}->{qt} = 'a';
$bar{B}->{st} = 'b';
$bar{B}->{qt} = 'b';

p %foo;
p %bar;

Output:
{
    A   {
        qt   "a",
        st   "a"
    },
    B   {
        qt   "b",
        st   "b"
    }
}
{
    A   {
        qt   "a",
        st   "a"
    },
    B   {
        qt   "b",
        st   "b"
    }
}


text:
Q: Column-Span: all not supporting in CKEditor In the Firefox, the column-span: all not working inside of the CKEditor. Its working fine in the Chrome browser.
How to get the same output in the Firfox (like chrome result)?
Code:

Header 1

Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample

Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample
Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample
Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample
Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample
Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample

Column 1
                Column 1
                Column 2
                Column 3
                Column 4
                Column 5
                Column 6
                Column 7
                Column 8

Column 1
                Column 1
                Column 2
                Column 3
                Column 4
                Column 5
                Column 6
                Column 7
                Column 8

Column 1
                Column 1
                Column 2
                Column 3
                Column 4
                Column 5
                Column 6
                Column 7
                Column 8

Column 1
                Column 1
                Column 2
                Column 3
                Column 4
                Column 5
                Column 6
                Column 7
                Column 8

Column 1
                Column 1
                Column 2
                Column 3
                Column 4
                Column 5
                Column 6
                Column 7
                Column 8

Header 2

Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample

Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample

Screenshot from Chrome

Screenshot from Firefox

A: It has nothing to do with Ckeditor. Even outside Ckeditor it will give same error. You took wrong values in your first
's column count attribute. It is just 2 there while in your inner
 its all. Replace the column count values of your first div to auto or all and see the magic. I did it for you. Your code should look like

Header 1

just do it and see the difference :)


text:
Q: How to listen session:success event in nexmo client js? I follow tutorial here: https://developer.nexmo.com/client-sdk/tutorials/app-to-phone/client-sdk/app-to-phone/main-screen/javascript
listen session:success event with bellow script not working.
const status = $('.input');

app.on('session:success', () => {
 status.val('Ready to call.');
});

Is there any other event i can listen?

A: It seems i don't need to listen nexmo app event.
Just check it with if condition.
if (app.session.sessionReady) {
 callStatus.val("Ready for call.");
}


text:
Q: Is there any ways we can update talend patch from Talend Studio? I am using Nexus repository for new updates of talend and i have new updates But i dont think that updates are getting reflected in my Talend Studio 7.1
I am facing Certificate expiration issue which is resolved in talend patch and i have that patch too just i cannot reflect that into studio.
I Know the way where we create patches folder in talend directory but it is also not working for some reason but is there any way i can do this manually in studio.


text:
Q: Conditional Rails Form Validation I have a rails model that has two field attributes: :commission_fixed & :commission_percentage. The user should only be able to choose between one of the two options either: :commission_fixed or :commission_percentage not both on form submit. Is this possible using Rails validation? If so what is the best way to achieve this?

A: Your problem is within the way you've structured your column names / model attributes.
Ideally you should change your attribute names on your model to :commission_method and :commission_rate. This allows for greater flexibility. Then in your view you can achieve what you're looking for with a radio button. You can store your :commission_rate as a decimal in the db.
<%= f.radio_button :commission_method, "Fixed" %>
<%= f.radio_button :commission_method, "Percentage" %>
<%= f.number_field :commission_rate %>

In your view files if you need to switch between showing a fixed amount and a percentage you can just do:
<% case @sales_associate.commission_method %>
<% when 'Fixed' %>
  Fixed: <%= number_to_currency(@sales_associate.commission_rate) %>
<% when 'Percentage' %>
  Percentage: <%= "% #{@sales_associate.commission_rate}" %>
<% end %>

However, you "could" write a custom validation method that throws an error if both attributes were assigned.
In whatever model:
class SalesAssociate
   validate :only_one_selected_commission

   def only_one_selected_commission
     errors[:base] << "Please select only one form of commission" if self.commission_fixed.present? && self.commission_percentage.present?
   end
end