text:
Q: How to use Query Builder to make a relation in an array? Laravel I would like to make a relation with query builder... I have three tables, and I would like to join the tables for work with the function.. I'm working in a model.. not in a controller
This is my function
public function map($contactabilidad): array
{
    $relation = DB::table('tbl_lista_contactabilidad')
        ->join('tbl_equipo_postventaatcs', 'tbl_equipo_postventaatcs.id', '=', 'tbl_lista_contactabilidad.postventaatc_id')
        ->join('users', 'users.id', '=', 'tbl_equipo_postventaatcs.asesor_id')
        ->get();

    return [
        $contactabilidad->$relation->name,
        $contactabilidad->postventaatc_id,
        $contactabilidad->rif,
        $contactabilidad->razon_social,
        $contactabilidad->fecha_contacto,
        $contactabilidad->persona_contacto,
        $contactabilidad->correo_contacto,
        $contactabilidad->numero_contacto,
        $contactabilidad->celular_contacto,
        $contactabilidad->comentarios,
        $contactabilidad->contactado,
        $contactabilidad->respuesta->respuesta
    ];
}

A: Query\Builder is best thought of as the primary tool used by Eloquent, but is, nontheless, a completely different package. Query\Builder's purpose is to decouple SQL syntax from the logic that feeds into it, whereas Eloquent's purpose is to decouple that logic from table structures and relationships. So only Eloquent supports Model and Relation classes, Query\Builder does not. And what you're asking for has to do with Relations, so in short, you're kind of barking up the wrong tree.
By the way, I'm differentiating 'Query\Builder' here because Eloquent also has its own wrapper for that class called Eloquent\Builder that shares most of the same syntax. For better or for worse, Eloquent attempts to allow the developer to interact with it in a way that's familiar; not having to track a new set of method names even if you've been seamlessly dropped out of Eloquent and into a Query\Builder object via a magic __call method. It also does something similar regarding Eloquent\Collections vs. Support\Collections. But that can make things very confusing at first, because you have to just kind of know what package you're talking to.
So, to answer your question...

*

*Build a Model class for each of your three tables

*Apply relationship methods to each one to pre-configure the model with an awareness of your foreign keys

*Call on them using lazy or eager-loading
Something else to note is that with() does not ask Eloquent to perform a JOIN. All it does is run the parent query, extract the key values from the result, run the child query using them in an IN() statement, and marrying the results together afterwards. That's what results in nested results. Speaking from experience, it's kind of a mess generating true JOIN statements off Model Relations and keeping the table aliases unique, so it makes sense this package just skips trying to do that (except with pivot tables on many-to-many relations). This also has the added benefit though, that your related tables don't need to live in the same database. A Query\Builder join() on the other hand, as you have there, would present all fields for all tables at the top-level.


text:
Q: Get type parameters from generic type argument and use in recursive function call This code is supposed to deserialize a JSON array or JSON object into its respective scala class. The problem I am having is with this line
case x if x <:< typeOf[Array[_]] => deserialize[TypeTag[_]](s.getJSONArray(i))'

I want the function to detect if the X type argument is an Array of something, and pass that something as the type argument to the recursive function call.
So if I call deserialize[Array[Int]](JSONArray), it should return an Array[Array[Int]]. I need to somehow extract Int from Array[Int] and pass that to deserialize[???](JSONArray).
def deserialize[X: TypeTag](s: JSONObject): X = {
    val m = ru.runtimeMirror(getClass.getClassLoader)
    val classType = ru.typeOf[X].typeSymbol.asClass
    val cm = m.reflectClass(classType)
    val constructor = typeTag.tpe.decl(ru.termNames.CONSTRUCTOR).asMethod
    val constructorMethod = cm.reflectConstructor(constructor)

    val params = constructor.asMethod.paramLists.head
    val args = new Array[Any](params.length)

    for(i <- params.indices) {
        val name = params(i).name.decodedName.toString
        println(params(i).typeSignature.toString)
        args(i) = params(i).typeSignature match {
            case t if t =:= typeOf[String] => s.getString(name)
            case t if t =:= typeOf[Int] => s.getInt(name)
            case t if t =:= typeOf[Double] => s.getDouble(name)
            case t if t =:= typeOf[Boolean] => s.getBoolean(name)
            case t if t =:= typeOf[Long] => s.getLong(name)
            case t if t =:= typeOf[Array[_]] => deserialize[WeakTypeTag[_]](s.getJSONArray(name))
            case t => deserialize[t.type](s.getJSONObject(name))
        }
    }

    constructorMethod(args:_*).asInstanceOf[X]
}

def deserialize[X: ClassTag: TypeTag](s: JSONArray): Array[X] = {
    val arr = new Array[X](s.length())
    for(i <- 0 until s.length) {
        arr(i) = (typeOf[X] match {
            case x if x =:= typeOf[String] => s.getString(i)
            case x if x =:= typeOf[Int] => s.getInt(i)
            case x if x =:= typeOf[Double] => s.getInt(i)
            case x if x =:= typeOf[Boolean] => s.getInt(i)
            case x if x =:= typeOf[Long] => s.getInt(i)
            case x if x <:< typeOf[Array[_]] => deserialize[TypeTag[_]](s.getJSONArray(i))
            case x => deserialize[X](s.getJSONObject(i))
        }).asInstanceOf[X]
    }
    arr
}

A: So while I dont quite understand why it works, I was able to hack a working solution together based on a bunch of other stackoverflow questions.
def deserialize[X](s: JSONObject)(implicit tTag: TypeTag[X]): X = {
    val m = ru.runtimeMirror(getClass.getClassLoader)
    val classType = ru.typeOf[X].typeSymbol.asClass
    val cm = m.reflectClass(classType)
    val constructor = typeTag.tpe.decl(ru.termNames.CONSTRUCTOR).asMethod
    val constructorMethod = cm.reflectConstructor(constructor)

    val params = constructor.asMethod.paramLists.head
    val args = new Array[Any](params.length)

    for(i <- params.indices) {
        val name = params(i).name.decodedName.toString
        args(i) = params(i).typeSignature match {
            case t if t =:= typeOf[String] => s.getString(name)
            case t if t =:= typeOf[Int] => s.getInt(name)
            case t if t =:= typeOf[Double] => s.getDouble(name)
            case t if t =:= typeOf[Boolean] => s.getBoolean(name)
            case t if t =:= typeOf[Long] => s.getLong(name)
            case t if t <:< typeOf[Array[_]] => {
                deserialize(s.getJSONArray(name))(getSubInfo(0)(typeToTypeTag(t, m)))
            }
            case t => deserialize(s.getJSONObject(name))(typeToTypeTag(t, m))
        }
    }

    constructorMethod(args:_*).asInstanceOf[X]
}

def deserialize[X](s: JSONArray)(implicit tTag: TypeTag[X]): Array[X] = {
    val mirror = runtimeMirror(getClass.getClassLoader)
    implicit val xClassTag = ClassTag[X](mirror.runtimeClass(tTag.tpe))

    val arr = new Array[X](s.length())

    for(i <- 0 until s.length) {
        arr(i) = (typeOf[X] match {
            case x if x =:= typeOf[String] => s.getString(i)
            case x if x =:= typeOf[Int] => s.getInt(i)
            case x if x =:= typeOf[Double] => s.getInt(i)
            case x if x =:= typeOf[Boolean] => s.getInt(i)
            case x if x =:= typeOf[Long] => s.getInt(i)
            case x if x <:< typeOf[Array[_]] => {
                deserialize(s.getJSONArray(i))(getSubInfo[X](0))
            }
            case x => {
                deserialize[X](s.getJSONObject(i))
            }
        }).asInstanceOf[X]
    }
    arr
}

def typeToTypeTag[T](tpe: Type, mirror: reflect.api.Mirror[reflect.runtime.universe.type]): TypeTag[T] = {
    TypeTag(mirror, new reflect.api.TypeCreator {
        def apply[U <: reflect.api.Universe with Singleton](m: reflect.api.Mirror[U]) = {
            assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
            tpe.asInstanceOf[U#Type]
        }
    })
}

def getSubInfo[X](i: Int)(implicit tTag: TypeTag[X]): TypeTag[_] = {
    typeToTypeTag(tTag.tpe.asInstanceOf[TypeRefApi].args(i), tTag.mirror)
}

The essence of the solution are the last to functions. getSubInfo[X](i: Int) will return a TypeTag for the type parameter at i. So calling getSubInfoArray[Int] will return a TypeTag for Int. typeToTypeTag takes a reflection#type as a parameter and uses black magic to create a typetag.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect when a NativeModule is running in React-native So I'm using a few different NativeModules in an App (both Android and iOS specific) for playinmg Videos and such. This means that the screen is taken over by Native code eg. Java or Swift and their respective ViewControllers control the views instead of React-Native.
This is all good and works as should, but I do need to detect whether the NativeModule is running or not, eg. it's views or RN's views are showing.
If i use { useIsFocused } from '@react-navigation' it cannot detect when a NativeModule is taking over the views, it always says the view from where I activated the NativeModule is inFocus.
Same with { AppState } from 'react-native' it always shows as active even though the Native views are overlayed.
Anyone found a solution to this problem?

A: *

*make sure you handle the app state in the right way.

*you can use  RCTEventEmitter to send events and manage them manually

*use the callback or promise and change the state in your app

A: If you are working with your own custom component as a NativeModule, then you can

*

*Declare a boolean property isVisible in your code and set it to true or false when your component is initialized or destroyed respectively. For UIViewController in iOS you can use viewWillAppear and viewWillDisappear for this purpose.

*Create a getter for isVisible property and export it to Javascript.
You can take help from this link:
https://reactnative.dev/docs/native-modules-ios#export-a-native-method-to-javascript

*Call the getter from inside your react native code to check if NativeModule is visible on the screen.


text:
Q: withoutOverlapping() is not working in Laravel Schedule $schedule->call(function ()
        {
            error_log("Line Schedule 1:Start");
            //Send Email
            error_log("Line Schedule 1:End");

        })->everyFiveMinutes()->name('event_name:1')->withoutOverlapping();

        $schedule->call(function ()
        {
          error_log("Line Schedule 2:Start");
           //Send Email
          error_log("Line Schedule 2:End");
        })->everyFiveMinutes()->name('event_name:2')->withoutOverlapping();
        $schedule->call(function ()
        {
          error_log("Line Schedule 3:Start");
              //Send Email
          error_log("Line Schedule 3:End");
        })->everyFiveMinutes()->name('event_name:3')->withoutOverlapping();

i run these schulders using command php artisan schedule:run and i am running many instances in parallel. and my logs file says that schulder 2 is starting second time even its previous instance has not completed it yet .
[01-Jan-2016 11:30:08 UTC] Line Schedule 1:Start
[01-Jan-2016 11:30:11 UTC] Line Schedule 2:Start
[01-Jan-2016 11:30:13 UTC] Line Schedule 3:Start
[01-Jan-2016 11:30:15 UTC] Line Schedule 1:End
[01-Jan-2016 11:30:15 UTC] Line Schedule 2:Start
[01-Jan-2016 11:30:17 UTC] Line Schedule 2:End
[01-Jan-2016 11:30:17 UTC] Line Schedule 3:Start
[01-Jan-2016 11:30:19 UTC] Line Schedule 3:End
[01-Jan-2016 11:30:21 UTC] Line Schedule 2:End
[01-Jan-2016 11:30:21 UTC] Line Schedule 3:Start
[01-Jan-2016 11:30:22 UTC] Line Schedule 3:End
[01-Jan-2016 11:30:25 UTC] Line Schedule 3:End

A: because these are different tasks, withoutOverlapping works when there is a task scheduled everyFiveMinutes for example, and takes more than 5 minutes to finish so it will not start another instance of the same task until the old one is finished,

A: Just name your task with a call to name() and chain the methods that define when your task should be run.
$schedule->call(function () {
  //Some Code
})->everyFiveMinutes()
->name('some_name')
->withoutOverlapping();

For anonymous functions the name is required to prevent overlapping.


text:
Q: AppEngine Flex custom readiness & liveness endpoints not firing I have configured custom readiness & liveness probe endpoints as described on this page for my AppEngine Flex app:
https://cloud.google.com/appengine/docs/flexible/python/reference/app-yaml
However, looking at the logs, it is clear that it is ignoring my settings which look like the following:
liveness_check:
  path: "/liveness_check_custom"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 4
  success_threshold: 2

readiness_check:
  path: "/readiness_check_custom"
  check_interval_sec: 5
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2
  app_start_timeout_sec: 300

I have a custom log message behind these endpoints which aren't appearing in the logs, and also looking at the nginx.health_check logs I see that it's still hitting the "liveness_check" and "readiness_check" endpoints and not my custom endpoints.
If I hit my endpoints directly myself I see my log messages. Is this Google documentation incorrect or am I missing something? Is there a setting I'm missing?

A: This is an expected behavior. Nginx rewrites the the liveness_check and readiness_check to the customized path provided in the app.yaml file when logging the health checks and that's why in the logs you will see the default '/readiness_check' and '/liveness_check' in the nginx logs.
App Engine creates redundant copies of each health checker, and in case a health checker fails, the redundant copy take over with no delay.
Tthe nginx.health_check logs for your application are showing logs for the redundant health checkers. They are created automatically by App Engine and they cannot be configured.
The custom health checks logs can be found under health_logs in Logging for Google App Engine Application.
There was already a Public Issue Tracker created for this issue where it explains the previous information about the health checks in App Engine.

A: the liveness_check and readiness_check sections defined in app.yaml is the new method for health checks in app engine flex. liveness_check signals that VM and the Docker container are running, and readiness_check signals that an instance can accept incoming requests.
you can customize a specific path to reach your application. However, nginx rewrites the paths '/readiness_check' and '/liveness_check' to custom-specified paths when sending requests to the application within the VM. You will therefore see '/readiness_check' and '/liveness_check' in the nginx logs.
That's aside, if you want to apply warming up on your App Engine, you have to use initial_delay_sec setting in your liveness_check section. The default is 300 but you can change that to what you believe is enough for your app to accept request (you can put it between 0-3600 seconds)


text:
Q: Use OpenOffice from command line to convert HTML to RTF I'm trying to build a bash script in Cygwin that will convert HTML files to RTF. In OS X this is trivial with textutils, but that doesn't exist for regular Linux or Cygwin. Instead I'm trying to use OpenOffice from the command line.
I've read elsewhere that OpenOffice can run headlessly with a program normally installed as /usr/bin/ooffice, but in Cygwin under Windows this obviously doesn't work—the OpenOffice installer doesn't built native Cygwin symlinks and might not even install the Windows equivalent of ooffice.
How can I use OpenOffice from the command line in Cygwin to convert HTML files to RTF files?

A: I would suggest the JODConverter.  It is a java wrapper around the OpenDoc Api for conversion.  Allows you to convert files like this:
java -jar jodconverter-cli-2.2.0.jar foo.html foo.rtf

It's also available in python.
instead of using the openoffice SDK DocumentSaver class like this:
java -classpath .;./bin;\
                $OO/program/classes/jurt.jar;\
                $OO/program/classes/ridl.jar;\
                $OO/program/classes/sandbox.jar;\
                $OO/program/classes/unoil.jar;\
                $OO/program/classes/juh.jar  \
    DocumentSaver uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager  file:///C:/test/foo.html file:///C:/test/foo.rtf

A: There is a really handy shell script called unoconv that handles conversion of any files from and to any file format that OpenOffice/LibreOffice supports. You can read up about it on its site and be sure to check out the man page. Many distros have packages for it that you can install easily, including, I believe, cygwin.
Once you have it installed, usage in your case would mean specifying an input html file and an output rtf file like this:
unoconv file.html file.rtf

All done :)
Of course this could be scripted to handle multiple file situations as well. If you are using zsh, you could run something like this to convert a whole folder of html files:
for file in *html; do
    unoconv "$file" "${file/html/rtf}"
done

A: I can help with the first part of your question. Here's an example of running OpenOffice from the Cygwin command line:
/cygdrive/c/Program\ Files/OpenOffice.org\ 3/program/soffice.exe -help

That will give you a list of command line arguments. I didn't see any that would convert file types or even "Save As", but I didn't research the API. Perhaps you can fill in that part. I have OpenOffice.org 3.2 320m12(Build:9483).


text:
Q: Hartshorne-Eisenbud cross reference? Is there a page online that lists where exactly all the algebraic theorems in Hartshorne appear in Eisenbud?  I know that Eisenbud uses the term "codimension" instead of "height", but just Flipping through the chapters on dimension theory, I'm not finding it very easy to locate the particular theorems referenced by Hartshorne.
I'm trying to find the proofs for the dimension theory in the first section, specifically:

*

*Theorem 1.8A (M, Ch. $5$, $\S14$)

*Theorem 1.11A (A-M, p. $122$)

*Theorem 1.12A (M, p. $141$)

Here "M" refers to Matsumura's Commutative Algebra and "A-M" to Atiyah and MacDonald's Introduction To Commutative Algebra, which are the references given in Hartshorne.

A:
Theorem 1.8A

Part (a) is Theorem A, $\S13.1$, p. $286$ in Eisenbud:
Theorem A. If $R$ is an affine domain over a field $k$, then
$$
\dim(R) = \operatorname{tr. deg.}_k(R),
$$
and this number is the length of every maximal chain of primes in $R$.
The proof is given on p. 289.
Part (b) is Corollary 13.4, p. 286:
Corollary 13.4. If $R$ is an affine domain, and $I \subseteq R$ is an ideal, then
$$
\dim(I) + \DeclareMathOperator{\codim}{codim} \codim(R) = \dim(R) \, .
$$

Theorem 1.11A (Krull's Hauptidealsatz)

Chapter 10, p. 232 of Eisenbud. Here $R$ is a (commutative) noetherian ring.
Theorem 10.1 (First version of the Principal Ideal Theorem). If $x \in R$, and $P$ is minimal among primes of $R$ containing $x$, then $\codim(P) \leq 1$.

Theorem 1.12A

Chapter 10, p. 234 of Eisenbud. $R$ is assumed noetherian.
Corollary 10.6. A domain $R$ is factorial if every codimension $1$ prime of $R$ is principal.


text:
Q: LoadMoreItemsAsync is not called I am trying to implement lazy loading of items inside a ListView.
but LoadMoreItemsAsync is never called.
xaml:
<Grid>
    <ListView Grid.Row="1" x:Name="MasterListView" ItemsSource="{x:Bind ViewModel.News}">
        <!--
            <ListView.ItemTemplate>
        -->
    </ListView>
</Grid>

ViewModel:
public class HomeViewModel
{
    public HomeViewModel()
    {
        News = new PaginateCollection<NormalNews>(LoadNews);
    }

    public PaginateCollection<NormalNews> News { get; set; }

    public async Task<IEnumerable<NormalNews>> LoadNews(uint size)
    {
        // ...
    }
}

PaginateCollection:
public class PaginateCollection<T> : ObservableCollection<T>, ISupportIncrementalLoading
{
    Func<uint, Task<IEnumerable<T>>> load;
    public PaginateCollection(Func<uint, Task<IEnumerable<T>>> load)
    {
        this.load = load;
    }

    public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        return AsyncInfo.Run(async c =>
        {
            var data = await load(count);
            foreach (var item in data)
            {
                Add(item);
            }
            return new LoadMoreItemsResult
            {
                Count = (uint)data.Count()
            };
        });
    }

    public bool HasMoreItems { get; set; }
}

A: In the constructor of the PaginateCollection set the HasMoreItems property to true.This will insure the first load trigger. So the Method LoadNews() will be called and your logic will run.
public PaginateCollection(Func<uint, Task<IEnumerable<T>>> load)
{
    this.load = load;
    HasMoreItems = true;
}


text:
Q: Searching two columns and returning value from third VBA A colleague of mine has an excel spreadsheet made up of 3 columns and would like to make searching them easier.
What he has is two cells off to one side that he enters a value from column one into and a value from column two into. What he would like to do is search the spreadsheet for instances where value one and two exist in the same row within column one and two respectively and then return the value from column three that resides in the same row.
For example I have a table like the one shown below, so if he enters B and 2 into the cells BP is then returned to a third cell.
A 1 AP
B 2 BP
C 3 CP
Thanks

A: Let's create the following function in a new Excel module:
Function FindValue(rng1 As Range, rng2 As Range) As Variant
Dim varVal1 As Variant
Dim varVal2 As Variant
Dim rngTargetA As Range
Dim rngTargetB As Range
Dim lngRowCounter As Long
Dim ws As Worksheet

varVal1 = rng1.Value
varVal2 = rng2.Value

Set ws = ActiveSheet
lngRowCounter = 2
Set rngTargetA = ws.Range("A" & lngRowCounter)
Set rngTargetB = ws.Range("B" & lngRowCounter)
Do While Not IsEmpty(rngTargetA.Value)
    If rngTargetA.Value = varVal1 And rngTargetB.Value = varVal2 Then
        FindValue = ws.Range("C" & lngRowCounter).Value
        Exit Function
    End If

    lngRowCounter = lngRowCounter + 1
    Set rngTargetA = ws.Range("A" & lngRowCounter)
    Set rngTargetB = ws.Range("B" & lngRowCounter)
Loop

' if we don't find anything, return an empty string '
FindValue = ""

End Function

The above function takes in two range values, so you can use it like you would use any other function in Excel.  Using the example you provided above, copy those cells into cells A2:C5.  Next, in cell A1 put A.  In cell B1 put 1.  In C1, put =FindValue(A1,B1).  This will execute the code above and return a match if it finds it.
Furthermore, if you change the "input values" from cells A1 or B1, your answer will update accordingly.

A: If he can put up with another colum to the left of the ones mentioned above (which you can hide from normal view), you can do it without using any VBA.
Insert a colum to the left of the first one, and set it to =A1&B1, =A2&B2 etc. You can then use VLOOKUP(x,A1:Dn,4) - where x is the string ("A1", "B2", etc.) that he wants to look up, and n is the number of rows in the dataset.
Hope that helps.

A: Another possibility using ADO:
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim r1 As Range
Dim r2 As Range
Dim r3 As Range

strFile = ActiveWorkbook.FullName

''Note HDR=No, so F1,F2 etc is used for column names
''If HDR=Yes, the names in the first row of the range
''can be used.
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
Set r1 = Worksheets("Sheet11").Range("F1")
Set r2 = Worksheets("Sheet11").Range("F2")
Set r3 = Worksheets("Sheet11").Range("F3")

cn.Open strCon

''Case sensitive, one text (f1), one numeric (f2) value
strSQL = "SELECT F3 FROM [Sheet11$A1:C4] WHERE F1='" & r1.Value _
       & "' AND F2=" & r2.Value

rs.Open strSQL, cn, 3, 3

''Copies all matches
r3.CopyFromRecordset rs


text:
Q: How to query for Numbers in SQL when data is VARCHAR? I cloned .csv file into my database table in SQL,
and example data looks like this :
[
    {
        "year": "1955",
        "rank": "1",
        "company": "General Motors",
        "revenue": "9823.5",
        "profit": "806"
    },
    {
        "year": "1955",
        "rank": "2",
        "company": "Exxon Mobil",
        "revenue": "5661.4",
        "profit": "584.8"
    },

Some of the profit columns have "N.A.", and also NEGATIVE integers but these values are all stored as "strings" or VARCHAR in the SQL tables..
so how can I query for data that is a number or not equal to "N.A." (Basically I just want data that includes any integer positive or negative) in sql? I've tried ISNUMERIC() but it says I need to do type cast?

A: You could use a regex like here:
SELECT *
FROM yourTable
WHERE profit ~ '^-?\d+(?:\.\d+)?$';

But the best design approach here would be to just make the profit column numeric.  Then use NULL to represent missing values.


text:
Q: jQuery change event logic on getting previous value? After refer to page as Getting value of select (dropdown) before change, I am trying to implement below logic with jQuery:
Two element relation: indicator toggle yes/no to control reason editable or not
The 1st column is when page load indicator initial value, last column is final choice, column(s) between are redundant option(especially in case user just toggle it but not really want anything on reason), because indicator actually only contain yes/no two values, simplify 4 cases below:
(1) Y - N  (indicator on page load as Y, finally change to N)  --> reason editable
(2) Y - N - Y (indicator on page load as Y, redundant change as N, finally change to Y)  --> reason editable
(3) N - Y (indicator on page load as N, finally change to Y)  --> reason editable
(4) N - Y - N (indicator on page load as N, redundant change as Y, finally change to N)  --> reason NOT editable
The problem now is as code below, it never hit case (4), I observe indicator previous value retrieved, but it seems NOT keep as initial value when page load, e.g when page load, indicator is 'N', user first change it to 'Y', then change back to 'N', but the pre data value will be 'Y', not what I expect as original page load initial value 'N', I use a pop up dialog to observe this issue.
Could someone help me to figure out how to change this code to implement the logic above which including case (4) ?
(I guess it relate to last statement in script section as jqThis.data("prev", after_change); which update the previous data) ? But how to add logic before that to keep a real initial previous value (on page load value) for use in if-else logic ?

$(window).load(function() {
  var indicator = $(document.getElementById("indicator"));

  // set the pre data, usually needed after you initialize the select element
  indicator.data("prev", indicator.val());

  // Handle initial status of indicator, when page load, if it is 'N' disable
  // reason field, if it is 'Y' open reason field
  if (indicator.data("prev") == 'N') {
    $(document.getElementById("reason")).attr('disabled', 'disabled');
  } else {
    $(document.getElementById("reason")).removeAttr('disabled');
  }

  // Handle change status of indicator,
  indicator.change(function(data) {
    var jqThis = $(this);

    // get changed data
    var after_change = jqThis.val();

    // get the pre data (Question : I expect the pre data should be original page load value, but
    // seems it always the latest one before current value ?)
    // e.g when page load, indicator is 'N', user first change it to 'Y', then change back to 'N', but
    // the pre data value will be 'Y', not what I expect as original page load initial value 'N'
    // I use a pop up dialog to observe this issue.
    var before_change = jqThis.data("prev");

    // Debug
    console.log("before:",before_change);

    // do your work here
    if (before_change == 'N' && after_change == 'Y') {
      // Change indicator from No to Yes, please type in reason
      $(document.getElementById("reason")).attr('disabled', 'disabled');
    } else if (before_change == 'Y' && after_change == 'N') {
      // Change indicator from Yes to No, please type in reason
      $(document.getElementById("reason")).attr('disabled', 'disabled');
    } else if (before_change == 'N' && after_change == 'N') {
      // Keep indicator as its initial status No
      $(document.getElementById("reason")).removeAttr('disabled');
    } else if (before_change == 'Y' && after_change == 'Y') {
      // Keep indicator as its initial status Yes, if necessary you can type in new reason
      $(document.getElementById("reason")).attr('disabled', 'disabled');
    }

    // update the pre data
    jqThis.data("prev", after_change);
  });
});
.htmlClass {
  padding: 8px;
  border: 1px solid blue;
  margin-bottom: 8px;
}

<form name="myform">

    <select id="indicator">
      <option value="Y">Yes</option>
      <option value="N">No</option>
    </select>
    <textarea id="reason">
    </textarea>
</form>

A: Perhaps if you

*

*use prop

*do NOT remove the prop

*simplify your logic

*use a more recent version of jQuery

$(window).load(function() {
  var $indicator = $("#indicator"); // if you have colons, use #mypage\\:indicator
  var $reason = $("#reason");

  // set the pre data, usually needed after you initialize the select element
  $indicator.data("prev", $indicator.val());

  // Handle initial status of indicator, when page load, if it is 'N' disable
  // reason field, if it is 'Y' open reason field
  $reason.prop('disabled', $indicator.data("prev") == 'N');

  // Handle change status of indicator,
  $indicator.on("change", function(data) {
    var jqThis = $(this);

    // get changed data
    var after_change = jqThis.val();

    // get the pre data (Question : I expect the pre data should be original page load value, but
    // seems it always the latest one before current value ?)
    // e.g when page load, indicator is 'N', user first change it to 'Y', then change back to 'N', but
    // the pre data value will be 'Y', not what I expect as original page load initial value 'N'
    // I use a pop up dialog to observe this issue.

    var before_change = jqThis.data("prev");

    // Debug
    console.log("before:", before_change);

    // do your work here
    /* var dis = (before_change == 'N' && after_change == 'Y') ||
              (before_change == 'Y' && after_change == 'N') ||
              (before_change == 'Y' && after_change == 'Y') */
    var dis = !(before_change == 'N' && after_change == 'N');
    $reason.prop('disabled', dis);

    // update the pre data
    jqThis.data("prev", after_change);
  });
});
.htmlClass {
  padding: 8px;
  border: 1px solid blue;
  margin-bottom: 8px;
}

<form name="myform">

    <select id="indicator">
      <option value="Y">Yes</option>
      <option value="N">No</option>
    </select>
    <textarea id="reason">
    </textarea>
</form>

A: First thanks to mplungjan's work, as I am trying to edit on his version but refused by peer reviewer and suggest with post a new one, I will post one based on his answer which declare and resolve the issue.

$(window).load(function() {
  var $indicator = $("#indicator"); // if you have colons, use #mypage\\:indicator
  var $reason = $("#reason");

  // set the pre data, usually needed after you initialize the select element
  $indicator.data("prev", $indicator.val());

  // Handle initial status of indicator, when page load, if it is 'N' disable
  // reason field, if it is 'Y' open reason field
  $reason.prop('disabled', $indicator.data("prev") == 'N');

  // Handle change status of indicator,
  $indicator.on("change", function(data) {
    var jqThis = $(this);

    // get changed data
    var after_change = jqThis.val();

    // get the pre data (Question : I expect the pre data should be original page load value, but
    // seems it always the latest one before current value ?)
    // e.g when page load, indicator is 'N', user first change it to 'Y', then change back to 'N', but
    // the pre data value will be 'Y', not what I expect as original page load initial value 'N'
    // I use a pop up dialog to observe this issue.

    var before_change = jqThis.data("prev");

    // Debug
    console.log("before:", before_change);

    // do your work here
    /* var dis = (before_change == 'N' && after_change == 'Y') ||
              (before_change == 'Y' && after_change == 'N') ||
              (before_change == 'Y' && after_change == 'Y') */
    //var dis = !(before_change == 'N' && after_change == 'N');
    //$reason.prop('disabled', dis);

    // Before concise I just keep original logic in question
    // to show the issue
    if (before_change == 'N' && after_change == 'Y') {
      $reason.prop('disabled', false);
    } else if (before_change == 'Y' && after_change == 'N') {
      $reason.prop('disabled', false);
    } else if (before_change == 'N' && after_change == 'N') {
      $reason.prop('disabled', true);
    } else if (before_change == 'Y' && after_change == 'Y') {
      $reason.prop('disabled', false);
    }

    // update the pre data
    // !! IMPORTANT !! --> This is exactly what cause only
    // get most recent value before current changed value,
    // as continuously update the value in data.
    // As I test, the easiest way is to comment out this
    // line, it will never update the indicator's real
    // initial value when page load, so that's my goal which
    // compare "real initial value" with "current changed value"
    jqThis.data("prev", after_change);
  });
});
.htmlClass {
  padding: 8px;
  border: 1px solid blue;
  margin-bottom: 8px;
}

<form name="myform">

    <select id="indicator">
      <option value="Y">Yes</option>

      <option value="N" selected="selected">No</option>
    </select>
    <textarea id="reason">
    </textarea>
</form>


text:
Q: AWS Lambda - Python - ModuleNotFoundError: No module named 'pandas' I'm running into errors, no matter how many different configurations I try.
Activating Conda env - wfl
Conda env, wfl, activated
Setting up paths
/app/python
/opt/conda/lib/python3.9
/opt/conda/lib/python39.zip
/opt/conda/lib/python3.9/lib-dynload
/opt/conda/lib/python3.9/site-packages
/app/python/domain
/app/python/persistence
/app/python/processors
/app/python/sharedpython
/app/python/tools
/app/python/tests
Traceback (most recent call last):
File "/app/python/lambdas/test.py", line 3, in <module>
import pandas as pd
ModuleNotFoundError: No module named 'pandas'
Activating Conda env - wfl

I've got an AWS Lambda function, python, that points to a docker image in ECR. The app uses conda
which adds a little complexity as well. (the full requirements.txt includes fbprophet which needs conda). To activate the conda env, I need entrypoint to be a wrapper shell script, docker-entrypoint.sh. Below is obviously a dumbed-down version, but should contain enough information to glean insight from. When running this locally or executing the docker container directly, the script runs without issues, it's not until it's executing within the context of an AWS Lambda when it's throwing these errors... Is there something with the path/python path I'm missing? Any help would be greatly appreciated!
Note: I'm a novice with Dockerfile/commands/optimizing layers/images as you might tell... any insight to slim down the image would be helpful as well! (and a little novice to python/conda environments/management.....bleh!)
python/lambdas/test.py
import json
import time
import pandas as pd

def lambda_handler(event, context):
    print("event: " + json.dumps(event, indent=2))
    print("context: " + json.dumps(context, indent=2))
    x = pd.DataFrame()
    print(x)

print('test.py')
x = pd.DataFrame()
print(x)
time.sleep(200)  # used to allow time to search file contents of container

Dockerfile
# Base Image
####
FROM ubuntu:20.04 AS core
# Upgrade installed packages
RUN apt update -y  &&  apt upgrade -y && \
    apt install -y --no-install-recommends python3.8 unixodbc gnupg2 curl ca-certificates python3-distutils unixodbc-dev && \
    update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1

# Add SQL ODBC Driver 17 for Ubuntu 20.04 -- https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#ubuntu17
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \
    curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list && \
    apt update && \
    ACCEPT_EULA=Y apt install -y --no-install-recommends --allow-unauthenticated msodbcsql17 && \
    ACCEPT_EULA=Y apt install -y --no-install-recommends --allow-unauthenticated mssql-tools && \
    echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile && \
    echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc

RUN apt clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
    apt remove -y --purge curl gnupg2

# Set entrypoint
ENTRYPOINT [ "/bin/bash" ]

####
# Developer / Compiler Image
####
FROM core AS dev
# Upgrade installed packages
RUN apt update -y  &&  apt upgrade -y && \
    apt install -y --no-install-recommends curl python3.8-dev git python3-pip unixodbc-dev build-essential

# Install miniconda
RUN apt install wget
ENV CONDA_DIR /opt/conda
RUN wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \
    /bin/bash ~/miniconda.sh -b -p /opt/conda
# Put conda in path so we can use conda activate
ENV PATH=$CONDA_DIR/bin:$PATH

RUN conda init bash && \
    conda create --name wfl && \
    activate wfl

# Install Python dependencies
COPY requirements.txt .

# Install pip and dependencies
RUN python3 -m pip install -U pip setuptools wheel && \
    python3 -m pip install --user -r requirements.txt && \
    rm -f requirements.txt

RUN apt clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
    apt remove -y --purge git curl python3.8-dev python3-pip unixodbc-dev build-essential

# Set entrypoint
ENTRYPOINT [ "/bin/bash" ]

####
# Runtime Image
####

# This is the third and final image; it copies the compiled
# binary over but starts from the core ubuntu:20.04 image.
FROM core AS runtime

COPY --from=dev /root/.local /root/.local
# Make sure scripts in .local are usable:
ENV PATH=/root/.local/bin:$PATH
ENV CONDA_DIR /opt/conda
ENV PYTHON_APP_DIR /app/python
# copy conda to be available for env activation
COPY --from=dev $CONDA_DIR $CONDA_DIR
ENV PATH=$CONDA_DIR"/bin:$PATH"
RUN pip install pandas

# cleanup any non application files
RUN rm -rf ./python/tests
# Load application files
COPY ./python $PYTHON_APP_DIR
COPY ./docker-entrypoint.sh $PYTHON_APP_DIR

# Set work directory
WORKDIR $PYTHON_APP_DIR
ENV PYTHONPATH $PYTHON_APP_DIR

# Set entrypoint
ENTRYPOINT ["/app/python/docker-entrypoint.sh"]
CMD ["lambdas/test.py"]

setup_paths.py
import os
import sys

PROJECTS_ROOT = os.path.dirname(os.path.abspath(__file__))

def add_package_to_sys_path(base, package_relative_path):
    package_path = os.path.join(base, package_relative_path)
    if package_path not in sys.path:
        sys.path.append(package_path)

add_package_to_sys_path(PROJECTS_ROOT, 'lambdas')
add_package_to_sys_path(PROJECTS_ROOT, 'domain')
add_package_to_sys_path(PROJECTS_ROOT, 'persistence')
add_package_to_sys_path(PROJECTS_ROOT, 'processors')
add_package_to_sys_path(PROJECTS_ROOT, 'sharedpython')
add_package_to_sys_path(PROJECTS_ROOT, 'tools')
add_package_to_sys_path(PROJECTS_ROOT, 'tests')

for p in sys.path: print(p)

docker-entrypoint.sh
#!/bin/bash
set -e

echo 'Activating Conda env - wfl'
activate wfl
echo 'Conda env, wfl, activated'

python setup_paths.py
python "$@"

requirements.txt
pandas==1.2.4

Project structure

A: There are 2 possibilities
A. You might not activate your virtual environment so please make sure
B. You have not installed pandas so write pip install pandas


text:
Q: 20.04 autoinstall ejecting iso after first reboot I am working on upgrading an offline/disconnected installation of Ubuntu that used to be 18.04 with D-I to 20.04 with autoinstall/cloud-init.
I have most everything working out so far, but one of the changes I cannot find documentation for is hurting my unattended install.  Basically when cloud-init is finished with the first cloud-config stage before it reboots into the installed 20.04 system, it ejects the media (in my case ejecting the virtual drive in a VM).
Debian-Installer had a catch for this with d-i cdrom-detect/eject boolean false but I cannot find a similar setting for my cloud-config file.
Hoping this exists, or if not is there a workaround?  Thanks!

A: If you want to stop the physical ejection, then I think you'd have to patch the /sbin/casper-stop script in the installation environmment.  If you simply want to avoid the prompt to "Please remove the installation medium, then press ENTER" then you can create the file /run/casper-no-prompt.  Either of these options could be done in early-commands of your autoinstall config.
autoinstall config like the following might work
early-commands:
    - sed -ie 's/eject -p/#eject -p/' /sbin/casper-stop
    - touch /run/casper-no-prompt

When the installer, subiquity, finishes and reboots, it simply runs /sbin/reboot.  This can be seen in the subiquity source code.
The installer environment will run /sbin/casper-stop during shutdown because of the systemd service defined in /lib/systemd/system/casper.service.  This script will display the prompt and eject the media.  The source code of the script shows that the prompt is configurable, but the eject command is called as long as the cdrom is mounted, and advertised as removable.
See also

*

*https://unix.stackexchange.com/questions/528577/how-to-skip-please-remove-the-installation-medium-then-press-enter


text:
Q: How to make nginx support mysql I have install php5-mysql in my server.
But when I use function mysql_connect ,it's no working .
and I wrote these code to Test.It's said unavailable
<?php
if ( function_exists("mysql_connect")){
  echo "support";
}else{

 echo "unavailable";
}
?>

How can I configuration my ubuntu server to support php connect mysql??


text:
Q: gnu makefile linux set environment variable in calling shell, is it possible? So, I have a makefile that works great. In it I set a variable LD_LIBRARY_PATH_VAL to contain all the paths to all the libraries that the executable needs.
Now, for convenience I want a rule that sets the LD_LIBRARY_PATH environment variable by doing: make set_ld_lib_path, such that I get the following output:
> echo $LD_LIBRARY_PATH
>       (empty)
> make set_ld_lib_path
> echo $LD_LIBRARY_PATH
> path/to/lib1:path/to/lib2

Here is my rule as it is at the moment:
# Set the LD_LIBRARY_PATH needed to find all dependant libs - for convinience
LD_LIBRARY_PATH_VAL := test123
.PHONY: set_ld_lib_path
set_ld_lib_path: export LD_LIBRARY_PATH := $(LD_LIBRARY_PATH_VAL)
set_ld_lib_path:
    @$(ECHO) "$(COLOUR_ACT)LD_LIBRARY_PATH:$(COLOUR_RST) $$LD_LIBRARY_PATH"

Note: I put the line LD_LIBRARY_PATH_VAL := test123 just to make this a complete example - so I would want to get the output for LD_LIBRARY_PATH to be test123, but in my real makefile this would print a long list of lib paths.
So I have read lots of ways to set / export variables, but I have not found a way to do what I want here. I think it may not be possible because I can't update the variable of the calling shell... but in case it is possible I am asking the question :)
Info update
I have gnu make version:

GNU Make 4.1 Built for x86_64-pc-linux-gnu Copyright (C) 1988-2014
  Free Software Foundation, Inc. Licence GPLv3+: GNU GPL version 3 or
  later http://gnu.org/licenses/gpl.html This is free software: you
  are free to change and redistribute it. There is NO WARRANTY, to the
  extent permitted by law.

A: Yeah, you cannot do that.  It's a fundamental aspect of all Unix systems for 50 years that a child process cannot modify the environment of its parent.  Make can do many things, but it cannot subvert that basic restriction.


text:
Q: MVC View loaded without calling the controller I have a view to set the authentication status of a user loaded from the submission of a form that is not executing the controller. When the Home-Page is loaded, everything is working without any problem (I get true for the SuccessfullyLogged) , but when I submit the form, the View is loaded but only the View and the controller is not executed and I get SuccessfullyLogged = false:
EDIT:
The structure of the page is:
<Layout>
   <Login Header Partial View>
        @{ Html.RenderAction(MVC.Account.LoginHeader()); }
   </Login Header Partial View>

        @RenderBody() <-- GetAllByCategory.cshtml rendered inside of it

</Layout>

Logic of the flow:
CategoryGetAllBySearch.cshtml --> Controller GetAllByIds -> View GetAllByCategory inside of the Layout

EDIT:
Layout context of the Login Header:

    @{ Html.RenderAction(MVC.Account.LoginHeader()); }

Login Header View:
@model Heelp.ViewModels.LoginViewModel

<input type="hidden" id="IsUserAuthenticated" value="@Model.SuccessfullyLogged.ToString()" />

Login Header Controller:
[AllowAnonymous]
public virtual PartialViewResult LoginHeader()
{
    var model = new LoginViewModel();

    if (WebSecurity.IsAuthenticated)
    {
        model.SuccessfullyLogged = true;
    }
    else
        model.SuccessfullyLogged = false;

    return PartialView(model);
}

View CategoryGetAllBySearch.cshtml with the form submitted:
@model Heelp.ViewModels.CategoryGetAllBySearchListViewModel

@if (@Model.TotalSearchCount == 0)
{

lamentamos mas não foram encontrados resultados para a sua pesquisa

        sugestões:

          » veja a lista de carros, motos ou comerciais a partir do menu

          » tente utilizar outras ou menos palavras

}
else
{

encontrámos @Model.TotalSearchCount resultado(s) na(s) categoria(s):

    foreach (var item in Model.CategoryGetAllBySearch)
    {
    @using (Html.BeginForm("GetAllByIds", "Ads", FormMethod.Post, new { id = "homeCategoryForm_" + item.Id }))
    {
        @Html.AntiForgeryToken()

        @Html.Hidden("ids", string.Join("-", item.Ids))
        @Html.Hidden("categoryId", item.Id)
        @Html.Hidden("search", (string)ViewBag.search)
        @Html.Hidden("location", (string)ViewBag.location)
    }

@Html.DisplayFor(modelItem => item.SearchCount) @Html.DisplayFor(modelItem => item.Name)ver

    }
}

The controller GetAllByIds of this form:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult GetAllByIds(string ids, int categoryId, string search, string location)
{
    AdGetAllByCategoryListViewModel model = new AdGetAllByCategoryListViewModel();

    model.Ads = Mapper.Map<IList<AdGetAllByCategoryDto>, IList<AdGetAllByCategoryViewModel>>(_adService.GetAllByIds(ids));

    model.Category = Mapper.Map<CategoryDto, CategoryViewModel>(_categoryService.GetById(categoryId));

    return View(MVC.Ad.Views.GetAllByCategory, model);
}

So why is the form submit not calling the controller/View and only the view?
Thanks

A: After making somes test with the help of @Racil Hilan, I was able to find the issue here.
The problem was that I had two Actions called LoginHeader, one with the [HttpPost] attribute, and another without it.
[AllowAnonymous]
public virtual PartialViewResult LoginHeader()
{
    var model = new LoginViewModel();

    if (WebSecurity.IsAuthenticated)
    {
        model.SuccessfullyLogged = true;

        MemberDto memberDto = _memberService.GetMemberById(WebSecurity.CurrentUserId);
        model.MemberType_Id = memberDto.MemberType_Id;
    }
    else
        model.SuccessfullyLogged = false;

    return PartialView(model);
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual PartialViewResult LoginHeader(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
    {
        // The user is valid so it will be redirected based on the returnUrl. If null it will return to the Home-Page
        model.SuccessfullyLogged = true;
        model.Result = @HeelpResources.AccountLoginViewAutenticationValidMsg;
    }
    else
    {
        // Invalid credentials, so the user will have to try again
        model.SuccessfullyLogged = false;
        model.Result = @HeelpResources.AccountLoginViewAutenticationInvalidMsg;
    }

    return PartialView(model);
}

In this situation, when the form was submited by Post, the system was going into the one marked with the [HttpPost], and was not doing the correct validation.
So the advice is, be very careful when you use two Actions with the same name, because the system may call the one you don't expect.


text:
Q: How to remove RVM (Ruby Version Manager) from my system How can I remove RVM (Ruby Version Manager) from my system?

A: A lot of people do a common mistake of thinking that 'rvm implode' does it . You need to delete all traces of any .rm files . Also , it will take some manual deletions from root . Make sure , it gets deleted and also all the ruby versions u installed using it .

A: If the other answers don't remove RVM throughly enough for you, RVM's Troubleshooting page contains this section:

How do I completely clean out all traces of RVM from my system, including for system wide installs?
Here is a custom script which we name as cleanout-rvm. While you can definitely use rvm implode as a regular user or rvmsudo rvm implode for a system wide install, this script is useful as it steps completely outside of RVM and cleans out RVM without using RVM itself, leaving no traces.
#!/bin/bash
/usr/bin/sudo rm -rf $HOME/.rvm $HOME/.rvmrc /etc/rvmrc /etc/profile.d/rvm.sh /usr/local/rvm /usr/local/bin/rvm
/usr/bin/sudo /usr/sbin/groupdel rvm
/bin/echo "RVM is removed. Please check all .bashrc|.bash_profile|.profile|.zshrc for RVM source lines and delete
or comment out if this was a Per-User installation."

A: Remove the RVM load script from /.bash_rc or /.zsh_rc, then use:
rm -rf /.rvm

Or:
rvm implode

A: When using implode and you see:
Psychologist intervened, cancelling implosion, crisis avoided :)

Then you may want to use --force
rvm implode --force

Then remove RVM from the following locations:
rm -rf /usr/local/rvm
sudo rm /etc/profile.d/rvm.sh
sudo rm /etc/rvmrc
sudo rm ~/.rvmrc

Check the following files and remove or comment out references to RVM:
~/.bashrc
~/.bash_profile
~/.profile
~/.zshrc
~/.zlogin

Comment-out/remove the following lines from /etc/profile:
 source /etc/profile.d/sm.sh
 source /etc/profile.d/rvm.sh

/etc/profile is a read-only file so use:
sudo vim /etc/profile

And after making the change write using a bang!
:w!

Finally re-login/restart your terminal.

A: Run:
rvm implode

Now you need to uninstall the RVM gem using:
gem uninstall rvm

Check if there are any remaining RVM files in your home directory, if yes remove them.
Go to the home directory and list all hidden files:
ls -a

rm  .rvm
rm  .rvmrc

A: Note that if you installed RVM via apt-get, you have to run some further steps than rvm implode or apt-get remove ruby-rvm to get it to really uninstall.
See "Installing RVM on Ubuntu".

A: For other shell newbies trying to fix the PATH variable
After following instructions in accepted answer, check and modify your PATH variable if necessary :
env | grep PATH

if you see "rvm" anywhere, you need to figure out where you are setting PATH and modify.  I was setting it in 3 files - so check all the following files:
vim .bashrc

Delete the lines in the file referencing rvm using the dd command.  :wq to save and exit.
source .bashrc to "reload"
Repeat this process (starting with the vim command) for .profile and .bash_profile

A: If you're still getting a env: ruby_executable_hooks: No such file or directory when calling some Ruby package, that means RVM left a little gift for you in your $PATH.
Run the following to find the offending scripts:
grep '#!/usr/bin/env ruby_executable_hooks' /usr/local/bin/*

Then rm all the matches. You'll have to reinstall all of those libraries with an RVM-free gem, of course.

A: In addition to @tadman's answer I removed the wrappers in /usr/local/bin as well as the file /etc/profile.d/rvm.
The wrappers include:
erb
gem
irb
rake
rdoc
ri
ruby
testrb

A: There's a simple command built-in that will pull it:
rvm implode

This will remove the rvm/ directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too, if you installed that:
gem uninstall rvm

There may be elements left over from a Homebrew, Apt or DNF install of it that require removal as well. This depends on how you installed it in the first place. That clean-up step is optional, as RVM will no longer be involved in Ruby, but can help keep things organized.
If you've made modifications to your PATH you might want to pull those, too. Check your .bashrc, .profile and .bash_profile files, among other things.
You may also have an /etc/rvmrc file, or one in your home directory ~/.rvmrc that may need to be removed as well.

A: I am running Ubuntu 19.04 and followed all the instructions above and then some. Finally, what worked for me was to run
sudo apt autoremove rvm

and now when I try and reinstall RVM it's actually gone. RVM is invasive, to say the least.

A: Per RVM's troubleshooting documentation "How do I completely clean out all traces of RVM from my system, including for system wide installs?":

Here is a custom script which we name as 'cleanout-rvm'. While you can definitely use rvm implode as a regular user or rvmsudo rvm implode for a system wide install, this script is useful as it steps completely outside of RVM and cleans out RVM without using RVM itself, leaving no traces.
#!/bin/bash
/usr/bin/sudo rm -rf $HOME/.rvm $HOME/.rvmrc /etc/rvmrc /etc/profile.d/rvm.sh /usr/local/rvm /usr/local/bin/rvm
/usr/bin/sudo /usr/sbin/groupdel rvm
/bin/echo "RVM is removed. Please check all .bashrc|.bash_profile|.profile|.zshrc for RVM source lines and delete or comment out if this was a Per-User installation."

A: Complementing  @Kingsley Ijomah answer...
It may be necessary to fix the PATH so that the rvm command also disappears from the terminal.
To check your PATH:
env | grep PATH

To fix your PATH removing RVM directories:
dir_to_remove=/home/user/.rvm/bin
PATH=:$PATH:
PATH=${PATH//:$dir_to_remove:/:}
PATH=${PATH#:}; PATH=${PATH%:}

In this case, if you have more than one directory, change dir_to_remove one at a time.
I needed to remove some rvm and rbenv directories as I am now using asdf.
Be careful.


text:
Q: Show tick labels when sharing an axis in matplotlib I'm running the following function:
def plot_variance_analysis(indices, stat_frames, legend_labels, shape):
    x = np.linspace(1, 5, 500)
    fig, axes = plt.subplots(shape[0], shape[1], sharex=True sharey=True)
    questions_and_axes = zip(indices, axes.ravel())
    frames_and_labels = zip(stat_frames, legend_labels)
    for qa in questions_and_axes:
        q = qa[0]
        ax = qa[1]
        for fl in frames_and_labels:
            frame = fl[0]
            label = fl[1]
            ax.plot(x, stats.norm.pdf(x, frame['mean'][q], frame['std'][q]), label=label)
            ax.set_xlabel(q)
            ax.legend(loc='best')
    plt.xticks([1,2,3,4,5])
    return fig, axes

Here's what I get with some of my own sample data:

I'm trying to maintain the shared state between axes, but at the same time display the tick labels for the x axis on all subplots (including the top two). I can't find any means to turn this off in the documentation. Any suggestions? Or should I just set the x tick labels axis by axis?
I'm running matplotlib 1.4.0, if that's important.

A: In Matplotlib 2.2 and above the tick labels can be turned back on using:
ax.xaxis.set_tick_params(labelbottom=True)

A: You can find extra information about labels of matplotlib here:
https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html
In my case, I need to turn on all the x and y labels and this solution works:
for ax in axes.flatten():
    ax.xaxis.set_tick_params(labelbottom=True)
    ax.yaxis.set_tick_params(labelleft=True)

A: The ticks that are missing have had their visible property set to False. This is pointed out in the documentation for plt.subplot. The simplest way to fix this is probably to do:
for ax in axes.flatten():
    for tk in ax.get_yticklabels():
        tk.set_visible(True)
    for tk in ax.get_xticklabels():
        tk.set_visible(True)

Here I've looped over all axes, which you don't necessarily need to do, but the code is simpler this way.  You could also do this with list comprehensions in an ugly one liner if you like:
[([tk.set_visible(True) for tk in ax.get_yticklabels()], [tk.set_visible(True) for tk in ax.get_yticklabels()]) for ax in axes.flatten()]


text:
Q: How to display clear background image on Android Wear notification? As far as I can work out, there are two ways to set the background image for a notification in Android Wear. For the record, both start with:
   Bitmap bitmap;
   Notification.Builder bob = new Notification.Builder(this)
            .setContentTitle(title)

...and so on to set up the notification. Also assume that bitmap has been initialized to an appropriately-sized image (though that's another issue).
Method 1:
   bob.setLargeIcon(bitmap);

This works, but AFAICT bitmap is always blurred-out in the background of the notification, regardless of its size.
Method 2:
   bob.setStyle(new Notification.BigPictureStyle().bigPicture(bitmap));

This clears up the bitmap, but has the unfortunate side effect of inserting an extra "page" on the wearable, a page that is blank except for the bitmap. I suppose the thinking here is that you're trying to show the image to the user - but I'm not, I just want a non-blurry background.
Is there a way to accomplish this?

A: Please use setBackground(Bitmap) method from WearableExtender instead of setLargeIcon(Bitmap). It will set the background bitmap that won't be blurred.
Notification.Builder wearableBuilder = new Notification.Builder(context)
    ...
    .extend(new WearableExtender().setBackground(bitmap));


text:
Q: Installing Kubuntu 15.10 x64: An error occurred while restoring previously-installed applications I try to install Kubuntu 15.10 x64 from a DVD. At the last step of the installation, I get the error message:

An error occurred while restoring previously-installed applications. The
  installation will continue, but you may have to manually reinstall some applications after the computer reboots."

What could cause this issue?

A: It looks like the issue stemmed from the fact that when choosing the partition on which to install Kubuntu, I was deleting then creating a new one. I instead selected the partition, clicked on "changed", marked as to be formatted and to be mounted as \: this time, it worked.

A: Yep. This question is the top Google hit for "An error occurred while restoring previously-installed applications", so I'll confirm your finding that the error is invoked by installing to a partition that you'd formatted prior to the installation rather than during the installation. It's still happening with (K)ubuntu 19.04. I've raised a new bug report against the installer (Ubiquity), because although bug reports on this date back to 2012, the previous reports didn't explicitly state the cause:
https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1825355


text:
Q: How to get the list varible which is generated from the tkinter widget command function I have python GUI code which creates list of indices. There is two buttons "Add" and "Remove", by clicking "Add" it adds the value from the entry widget and append into the index_list list, similarly with the "Remove" widget. I want to use this generated list in other code. see the code...
from tkinter import *
master = Tk()
Label(master, text='Add_index').grid(row=0,column=0)
var = IntVar()
INDEX = Entry(master, width=10, textvariable=var) #Entry widget with int variable
                                                  # widget is not packed yet

Functions
index_list = []
def add_input():
    global INDEX
    INDEX.grid(row=1,column=0, sticky=E,padx=40,pady=3)
    index_list.append(int(INDEX.get()))
    Label(master, text=f"Index {INDEX.get()} added, full list {index_list}").grid(row=1,column=0)
    #here it displays the list correctly directly into the GUI window

def remove_input():
    global INDEX
    #global index_list
    INDEX.grid(row=1,column=0, sticky=E,padx=40,pady=3)
    index_list.remove(int(INDEX.get()))
    Label(master, text=f"Index {INDEX.get()} removed, full list {index_list}").grid(row=1,column=1)

Adding button to the Functions
b1 = Button(master,text='Add', command=add_input)
b1.grid(row=2,column=0, sticky=W,padx=25,pady=3)

b2 = Button(master,text='Remove', command=remove_input)
b2.grid(row=2,column=1, sticky=W,padx=25,pady=3)

master.mainloop()

I want the generated list variable (index_list) out of the function, I used return value by using all the code in one function, I also tried using class, also declared it global, but nothing works. I still have not used listbox widget because I thought it doesn't necessary. Any help...


text:
Q: How to define a function that returns half of input, in two different ways? I am reading a Gentle Introduction to Symbolic Computation and it asks this question. Basically, the previous content deals with making up bigger functions with small ones. (Like 2- will be made of two 1- (decrement operators for lisp))
So one of the questions is what are the two different ways to define a function HALF which returns one half of its input. I have been able to come up with the obvious one (dividing number by 2) but then get stuck. I was thinking of subtracting HALF of the number from itself to get half but then the first half also has to be calculated...(I don't think the author intended to introduce recursion so soon in the book, so I am most probably wrong).
So my question is what is the other way? And are there only two ways?
EDIT : Example HALF(5) gives 2.5
P.S - the book deals with teaching LISP of which I know nothing about but apparently has a specific bent towards using smaller blocks to build bigger ones, so please try to answer using that approach.
P.P.S - I found this so far, but it is on a completely different topic - How to define that float is half of the number?
Pdf of book available here - http://www.cs.cmu.edu/~dst/LispBook/book.pdf (ctrl+f "two different ways")

A: It's seems to be you are describing peano arithmetic. In practice it works the same way as doing computation with fluids using cups and buckets.
You add by taking cups from the source(s) to a target bucket until the source(s) is empty. Multiplication and division is just advanced adding and substraction. To halve you take from source to two buckets in alterations until the source is empty. Of course this will either do ceil or floor depending on what bucket you choose to use as answer.
(defun halve (x)
  ;; make an auxillary procedure to do the job
  (labels ((loop (x even acc)
             (if (zerop x)
                 (if even (+ acc 0.5) acc)
                 (loop (- x 1) (not even) (if even (+ acc 1) acc)))))
    ;; use the auxillary procedure
    (loop x nil 0)))

Originally i provided a Scheme version (since you just tagged lisp)
(define (halve x)
  (let loop ((x x) (even #f) (acc 0))
    (if (zero? x)
        (if even (+ acc 0.5) acc)
        (loop (- x 1) (not even) (if even (+ acc 1) acc)))))

A: Edit: Okay, lets see if I can describe this step by step. I'll break the function into multiple lines also.
(defun half (n)
;Takes integer n, returns half of n
    (+
         (ash n -1) ;Line A
         (if (= (mod n 2) 1) .5 0))) ;Line B

So this whole function is an addition problem. It is simply adding two numbers, but to calculate the values of those two numbers requires additional function calls within the "+" function.
Line A: This performs a bit-shift on n. The -1 tells the function to shift n to the right one bit. To explain this we'll have to look at bit strings.
Suppose we have the number 8, represented in binary. Then we shift it one to the right.
 1000| --> 100|0
The vertical bar is the end of the number. When we shift one to the right, the rightmost bit pops off and is not part of the number, leaving us with 100. This is the binary for 4.
We get the same value, however if we perform the shift on nine:
1001| --> 100|1
Once, again we get the value 4. We can see from this example that bit-shifting truncates the value and we need some way to account for the lost .5 on odd numbers, which is where Line B comes in.
Line B: First this line tests to see if n is even or odd. It does this by using the modulus operation, which returns the remainder of a division problem. In our case, the function call is (mod n 2), which returns the remainder of n divided by 2. If n is even, this will return 0, if it is odd, it will return 1.
Something that might be tripping you up is the lisp "=" function. It takes a conditional as its first parameter. The next parameter is the value the "=" function returns if the conditional is true, and the final parameter is what to return if the conditional is false.
So, in this case, we test to see if (mod n 2) is equal to one, which means we are testing to see if n is odd. If it is odd, we add .5 to our value from Line A, if it is not odd, we add nothing (0) to our value from Line A.


text:
Q: let app.use() wait untill connection to redis instance is made I'm writing an express middleware function that depends on a redis store, to enable rate limiting. It works, but the problem is that I store my redis credentials in google cloud's secret manager. I need to do an asynchronous request to secret-manager, so there is a small delay on the state of the redis connection.
My function to connect with the redis instance returns a promise. When the promise is fullfilled, the redis connection is established.
'use strict'
// global variables for use in other functions as well
let globals = {}

// redis component where the connection with the redis instance is established
const Redis = require('./components/redis')

// connect is a promise
Redis.connect.then(conn => {
    // connection established
    globals.redis = conn
    // globals.redis contains now the connection with the redis instance
    // for use in other functions, this works
}).catch(err => console.log('could not connect with the redis instance')

// rate limiter function which depends on a redis instance
const RateLimiter = require('./components/rate-limiter')
const rateLimiter = RateLimiter({
    store: globals.redis,
    windowMs: 60 * 60 * 1000,
    max: 5
})

app.use(rateLimiter)

This code will not work because app.use(ratelimiter) is executed before the redis connection has established. Moving the RateLimiter code inside the then()-function of the redis promises does not cause an error, but the app.use()-function does not work then.
My ideal solution would be:
// connect is a promise
Redis.connect.then(conn => {
    // connection established
    globals.redis = conn
    // globals.redis contains now the connection with the redis instance
    // for use in other functions, this works

    // <-- MOVING THE RATE LIMITER CODE INSIDE THE THEN()-FUNCTION
    // DOES NOT WORK / THE MIDDLEWARE IS NOT USED -->

    // rate limiter function which depends on a redis instance
    const RateLimiter = require('./components/rate-limiter')
    const rateLimiter = RateLimiter({
        store: globals.redis,
        windowMs: 60 * 60 * 1000,
        max: 5
    })

    app.use(rateLimiter)
}).catch(err => console.log('could not connect with the redis instance')

How can I let app.use() 'wait' untill there is a redis connection?

A: You could setup redis in an async function and use async/await like this:
'use strict'
// global variables for use in other functions as well
let globals = {}

// redis component where the connection with the redis instance is established
const Redis = require('./components/redis')

async function setupRedis()
try {
    // connect is a promise
    const conn = await Redis.connect;
    // connection established
    globals.redis = conn
    // globals.redis contains now the connection with the redis instance
    // for use in other functions, this works

    // rate limiter function which depends on a redis instance
    const RateLimiter = require('./components/rate-limiter')
    const rateLimiter = RateLimiter({
        store: globals.redis,
        windowMs: 60 * 60 * 1000,
        max: 5
    })

    app.use(rateLimiter)
} catch (error) {

    console.error("could not connect with the redis instance");
    // rethrow error or whatever, just exit this function
}

setupRedis();


text:
Q: If $A\cup B=B$, does it follows that $A \subseteq B$? We know that $A \subseteq B \Rightarrow A \cup B = B$. Is the theorem valid in the other direction $\Leftarrow$?
I thought of it to be intuitive that the $\Leftarrow$ direction should be valid too. Is it?

A: Suppose $A\cup B=B$ and let $a\in A$. Then clearly $a\in A\cup B$ and thus $a\in B$. This shows that $A\subseteq B$.

A: This is obvious since $A\subseteq A\cup B = B$.

A:
Given : $A\cup B = B$
Since $A\cup B$ contains all elements of $A$, $B$ should also contain all elements of $A$. Hence $A\subseteq B$


text:
Q: How can i use ng-repeat inside ng-repeat but inner ng-repeat should print one value of an array at a time In the code below, mydt data is coming from a json and chkdur data is coming from a different array. I want to print the mydt and chkdur values simultaneously...
My Code

    {{sdetail.pmsg}}
    {{sdetail.displaytime}}
    {{st}}

A: You should use $index to print respective json data from second array

                    {{sdetail.pmsg}}
                    {{sdetail.displaytime}}
                    {{chkdur[$index]}}

A: Try This

    {{sdetail.pmsg}}
    {{sdetail.displaytime}}
    {{chkdur[pIndex]}}


text:
Q: urlopen() and read() [urllib2] I am testing for some exception handling and would want to know, which network related errors could occur in the following code:
candidate =  urllib2.urlopen() #1
candidate.read() #2

I know that #1 causes URLError. Are there any other errors that could be raised? In particular does #2 require network connection?

A: Reading requires that the socket is still open; although some response data will be buffered generally you pull data down by reading. The candidate.read() call will block until the whole response has been read.
As such socket.error (a subclass of IOError) can be raised even during the candidate.read() call.
Apart from the urllib2.URLError exception (plus subclass), urllib2.urlopen() can also raise httplib.HTTPException with various subclasses, socket.error, or when fed invalid data (illegal URL string, etc.), ValueError. Once you have a response object, response.read() can also raise socket.error and httplib.HTTPException.
httplib.HTTPException is a straight Exception subclass. socket.error and urllib2.URLError are IOError subclasses.


text:
Q: Structured Streaming mapGroupWithState not working for custom sink Spark structured streaming, trying mapgroupwithstate. Did anyone face the situation where .format("console") works perfectly and prints incremental state changes perfectly but whenever I try to change the .format("anyStreamingSinkClass") the dataframe received at the sink class only has the current batch but no memory of the state or incremental effect.
case class WordCount(word:String,count:Int)
case class WordInfo(totalSum:Int)
case class WordUpdate(word:String,count:Int,expired:Boolean)

val ds = df.as[String].map{ x=>
  val arr = x.split(",",-1)
  WordCount( arr(0), arr(1).toInt )
}.groupByKey(_.word)
  .mapGroupsWithState[WordInfo,WordUpdate](GroupStateTimeout.NoTimeout()) {
  case( word:String, allWords:Iterator[WordCount], state:GroupState[WordInfo]) =>
    val events = allWords.toSeq
    val updatedSession = if (state.exists) {
      val existingState = state.get
      val updatedEvents = WordInfo(existingState.totalSum + events.map(event ⇒ event.count).sum)
      updatedEvents
    }
    else {
      WordInfo(events.map(event => event.count).sum)
    }
    state.update(updatedSession)

    WordUpdate(word,updatedSession.totalSum,false)

}

val query = ds
  .writeStream
    //.format("console")
  .format("com.subhankar.streamDB.ConsoleSinkProvider")
  .outputMode(OutputMode.Update())
  .trigger(Trigger.ProcessingTime(3.seconds))
  //.option("truncate",false)
 .option("checkpointLocation","out.b")
  .queryName("q2090" )
  .start()

query.awaitTermination()

for sink format I get
Batch 21's distinct count is 1
x,1
Batch 22's distinct count is 1
x,2
Batch 23's distinct count is 1
x,3
For console format I get
-------------------------------------------
Batch: 1
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
|   x|    1|  false|
+----+-----+-------+

-------------------------------------------
Batch: 2
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
|   x|    3|  false|
+----+-----+-------+

-------------------------------------------
Batch: 3
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
|   x|    6|  false|
+----+-----+-------+

the sink does a simple print...
override def addBatch(batchId: Long, data: DataFrame) = {

  val batchDistinctCount = data.rdd.distinct.count()
  if(data.count()>0) {
    println(s"Batch ${batchId}'s distinct count is ${batchDistinctCount}")
    println(data.map(x=> x.getString(0) + "," + x.getInt(1)).collect().mkString(","))
  }
}

A: I had the same problem as yours.
When I tested it on Spark 2.2.0, the state got reset and lost between every mini-batches.
Then I tested it on Spark 2.3.0, the result became a thrown exception:
Queries with streaming sources must be executed with writeStream.start()

Through this exception I figured out that my customer Sink had unsupported operations.
In your case, your unsupported operations are multiple aggregations.
You have data.rdd.distinct.count() and data.count() and data.map in one mini-batch, which is so-called multiple aggregations, and considered unsupported.
Although on Spark < 2.3 your code can run with wrong results, on Spark >= 2.3 it simply gets the exception.
To fix it, the following modification which avoid multiple aggregations can get correct results.
override def addBatch(batchId: Long, dataframe: DataFrame) = {
  val data = dataframe.collect()  // now do everything in this Array (care for OUT OF MEMORY)
  val batchDistinctCount = Set(data).size()
  if(data.length > 0) {
    println(s"Batch ${batchId}'s distinct count is ${batchDistinctCount}")
    println(data.map(x=> x.getString(0) + "," + x.getInt(1)).mkString(","))
  }
}


text:
Q: I have a large number of row data coming in from server. How do I display this data on a new page(i.e Redirected Page)? On Page 1, I have a large number of row data(JSON) coming in from server in an array.
I want to display this data on Page 2 which is the page to be redirected to on clicking a Page 1.
I am using Javascript/Jquery and PHP code on server.
I read elsewhere that this can be done using forms, but how do I assign values to to the fields?
Can someone show how exactly this is done?

A: As I mentioned in the comments, there are multiple ways of achieving what you want, deciding on one or another will highly depend on how or what you want to do:

*

*Is it a large amount of data?

*Do you want it to be done in client or server side?

*Do you have any security concerns?

*Are there any bandwidth limitations?

*etc.

You need to consider the answer to those questions before deciding from one method or another. Here are some options:

Forms
You could put the data in a form on page 1 (either formatted or just as one big chunk that will be reprocessed on page 2), and submit the data from one to the other.
<form method="POST" action="page2.php">
    <textarea name="data">YOUR DATA HERE</textarea>
</form>

If you already have a form to send data from page 1 to page 2, then consider adding it as a hidden input that you can read on page 2.
Pros:

*

*Easy to implement.

*Various possibilities (GET or POST, all in one field or each element in a field)

*More flexible if you allow user to make changes to the data.

Cons:

*

*Heavy traffic load. The same data would travel multiple times: server > client (when loading page 1), client > server (submitting form), server > client (loading page 2).

*Limited size if you use the GET method: you'd be restricted in size limit by server and client (browser).

For your particular case: I probably wouldn't go for this method as you would be sending (a large amount of) data back and forth, and that is not good for performance, specially in mobile connections.

Cookies
You could store the data in a cookie on page 1, then read that cookie on page 2. And you could implement it in JavaScript (client side) or PHP (server side) and the result would be equivalent.
<?php
    $cookie_name = "data";
    $cookie_value = "YOUR DATA HERE";
    setcookie($cookie_name, $cookie_value, time() + (3600 * 24), "/");
?>

Pros:

*

*Easy to implement.

*PHP or JavaScript, the result will be similar (unless you use some HTTPOnly cookies)

Cons:

*

*Limited size. Again it will depend on the browser that the client is using (You can see some data on this web site).

*Not as secure as other methods (you cannot really trust what you are reading).

*User may have disabled/rejected cookies (you don't know if the cookie will be there).

For your particular case: I wouldn't go for this method either. It is less safe and cookies are sent to the server with each page load anyway.

Server Database / Files
Store the data in a database before sending it to page 1 (if you already have it on a database and don't want to rerun the query because it takes a long time, you could create a cached version of the result), then read that record on page 2.
Alternatively, you could follow a similar approach but instead of storing the data on a table, save the results on a file. Then page 2 would read that file and get the data.
Pros:

*

*You always have control over the data.

*No need to worry if user has JavaScript/cookies activated.

Cons:

*

*Complex implementation (requires permissions / redesign of solution).

*Data will still travel twice (server > page1, and server > page2).

For your particular case: This is probably what you are doing right now, and you want to change it :)

IndexedDB
Another HTML5 feature that will allow you to create a local object-oriented database, where you can store and retrieve objects using a key index.
Pros:

*

*Good performance.

*Good for large amounts of data.

*Data is stored locally, it does not travel to the server.

Cons:

*

*Not fully supported (see this page).

*Complex implementation.

For your particular case: I wouldn't go with this method because it is complex and not fully supported.

LocalStorage / SessionStorage
HTML5 introduced the Web Storage API with two methods to store data locally within the user's browser: localStorage and sessionStorage. The difference between the two is that with one the data will persist even when the browser is closed (localStorage), while with the other the data will only live while the page session is active (sessionStorage)
<script type="text/javascript">
    localStorage.setItem("data", "YOUR DATA HERE");
</script>

Pros:

*

*Easy to implement.

*It allows larger amounts of data than cookies (at least 5MB).

*Data is stored locally, it does not travel to the server.

Cons:

*

*Disabling cookies will disable LocalStorage too.

*LocalStorge values on secure pages are isolated (which can lead to interesting errors if your page changes between http and https).

For your particular case: This is the method I would go with, as long as the size of your data fits within the limits.

A: you are getting data in an array on page 1.
you will have to pass this data on page 2 to display results there.
For passing the data to page 2, following steps should be performed.
1. get json array and serialize it.
   {best alternative is get the parameters you are using to get json data. pass those parameters to page 2 and use them to get json data. so instead of passing array of json data pass parameters by which you can generate json data again from page 2.}
2. To pass the parameters/json data serialized one whichever you prefer,
    hide the data in dom.
the hidden data will be inside form.
<form action='.page2' method='POST' id='redirect_form'>
  <hidden data in dom >
 <button type='submit' which on click redirects to page 2>
</form>

3. on page 2, make use of the data you have posted to show array.


text:
Q: Powershell - Replace first occurrences of String I've searched for a fair amount for the answer but all I get is how I do it with multiple Strings. I'm pretty new to PowerShell but want to know how I can manage to do it.
I simply want to remplace the first occurence of "1" with "2" ... I only can close to it but no more. The code I found was:
Get-ChildItem "C:\TEST\1.etxt" | foreach {
$Content = Get-Content $_.fullname
$Content = foreach { $Conten -replace "1","2" }
Set-Content $_.fullname $Content -Force
}

The content of the txt is just random: 1 1 1 3 3 1 3 1 3 ... for keeping it simple.
Could someone please explain how I do it with the first occurence and if it is possible and not to time consuming how I can replace for example the 3rd occurrence?

A: Same answer as Martin but a bit more simplified so you might better understand it:
$R=[Regex]'1'
#R=[Regex]'What to replace'

$R.Replace('1 1 1 3 3 1 3 1 3','2',1)
#R.Replace('Oringinal string', 'Char you replace it with', 'How many')

#Result = '2 1 1 3 3 1 3 1 3'

If you want this in a one-liner:
([Regex]'1').Replace('1 1 1 3 3 1 3 1 3','2',1)

Found this information here.

A: You could use a positive lookahead to find the position of the first 1 and capture everything behind. Then you replace the 1 with 2 and the rest of the string using the capture group $1:
"1 1 1 3 3 1 3 1 3" -replace '(?=1)1(.*)', '2$1'

Output:
2  1 1 3 3 1 3 1 3

To caputre the third occurence, you could do something like this:
"1 1 1 3 3 1 3 1 3" -replace '(.*?1.*?1.*?)1(.*)', '${1}2$2'

Output:
1 1 2 3 3 1 3 1 3

A: That was pretty good advice. But now im wondering how it could work when the input file has more then one line.

*

*1

*1

*1

*3

*3

*1
Get-ChildItem "C:\TEST\1.txt" | ForEach-Object {
$Content = Get-Content $_.fullname
$R=[Regex]'1'
$Content = ForEach-Object { $R.Replace($Content, '2', '1') }
Set-Content $_.fullname $Content -Force
}
If I use the code I used in my first post it will just put everything back in one line, I understand why but not how I could put it back in the same place again after the String manipulation. I use PowerGUI atm to get a better grip on it.


text:
Q: Server side APNs push notification behind proxy I need to send push notification using a control panel from server.
The server is a Linux virtual Cloud box which is behind a proxy. The control panel is designed using J2EE with Tomcat
I am using JAVA based https://github.com/notnoop/java-apns/releases API for push
The code
ApnsService service = APNS.newService().withSandboxDestination().withCert("mycert.p12", "mypassword").build();
String messageTobeSent = APNS.newPayload()
    .alertBody("Message with badge 2")
    .badge(2)
    .alertTitle("Message with badge 2")
    .sound("ding.wav")
    .build();
service.push("d81f0080ed7bf05ac96261dc1805fbf00230073f606f1388a644469b1893446f",  messageTobeSent, new Date());

I am getting an error Couldn't connect to APNS server, My Questions are

*

*Is this because of the proxy?

*Does APNs works with proxy?

*Will this library capable or connecting behind proxy?

A: Yes You APNS client is unable to connect to the APNS server form that machine. Please test TCP connectivity to the APNS server from the machine where your application is running.  You can use nc command to test connectivity to APNS server from your linux box. Yes APNS has nothing to do with proxy as APNS conection works over TCP. If you can configure your firewall to connect to APNS then it should work.
nc apns_server_host apns_server_port

A: Answering your 3rd Question which will solve the first two questions regardlessly. NotNoop Java-Apns definitely supports proxy.
Refer the Java Doc provided ApnsServiceBuilder withProxy(java.net.Proxy)
Specify the proxy to be used to establish the connections to Apple Servers
In your code you can put as following
ApnsService service = APNS
.newService()
.withSandboxDestination()
.withProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<your proxy host>", <your proxy port>)))
.build();

Now the library itself will connect via proxy


text:
Q: Cleartool command performance: lshistory or find -exec I am looking for query optimization, but IBM is not very chatty about that in the clearcase documentation.
So in short, we have quite big vob, and we would like to list all the change made between 2 dates, which query do you thing is the fastest, and do you see any improvement to be made ?
Method 1:
cleartool find -avobs -type f -element '(created_since(1-Jun-2016) &&                  !created_since(1-Sep-2016))
 && (Element_Type==""Program"" || Element_Type==""Output"" || Element_Type==""Data"")'
-ver 'created_since(1-Jun-2016) && !created_since(1-Sep-2016)'
-exec 'cleartool describe -fmt ""#Name:%Xn Date:%Nd User:%u Label:%1.400Cl Attributes:%a Version:%Vn Comment:%Nc \n"" $CLEARCASE_XPN'
>| test.txt

Method 2:
cleartool lshistory -avobs -since 1-Jun-2016 -fmt '#Name:%Xn Date:%Nd User:%u Label:%1.400Cl Attributes:%a Version:%Vn Comment:%Nc \n' -nco -pname >| test.txt

Thank you!

A: cleartool lshistory is about event records, the minors ones can be scrubbed. It offer less filtering options, which means you get everything and only then apply a filter yourself (grep)
Generally, a cleartool find can be faster, as you can add criteria to refine the search.
From "Additional examples of the cleartool find command", in order to see all changes (not just creations at the element level, but changes, at the version level), the query is:
cleartool find . -version "{created_since(date1) && !created_since(date2)}"

-print
The fact that you can add:

*

*type f (you want only files, not folders)

*any other criteria (Note: I don't see "Element_Type" in query_language)

Those will help to speed up the query.

The OP M4hd1 adds in the comments:
Based on your comment I changed the query to that:
cleartool find -avobs -type f -element '(attr_sub(Element_Type,==,"Output"))' -ver 'created_since(1-Jun-2016) && !created_since(1-Sep-2016)' -exec 'cleartool describe -fmt ""#Name:%Xn Date:%Nd User:%u Label:%1.400Cl Attributes:%a Version:%Vn Comment:%Nc \n"" $CLEARCASE_XPN' >| test.txt

In multiple lines:
cleartool find -avobs -type f -element '(attr_sub(Element_Type,==,"Output"))' \
  -ver 'created_since(1-Jun-2016) && !created_since(1-Sep-2016)'  \
  -exec 'cleartool describe -fmt ""#Name:%Xn Date:%Nd User:%u Label:%1.400Cl Attributes:%a Version:%Vn Comment:%Nc \n"" $CLEARCASE_XPN' \
>| test.txt


text:
Q: ADM Hamiltonian formalism and Quantum gravity Is there a Hamiltonian reformulation of gravity ? If so using the usual Quantization scheme we cannot quantize gravity ??
In terms of a Gauge Theory with the potential $A_{\mu}^{i}$ how can we get the Schroedinger equation ?

A: 1. Short Answer. You're interested, probably, in the ADM formalism and its quantization. This "has happened" (in the sense we can write down the equations) but "cannot be solved" (in the sense we don't know how to solve them!).
The fields taken are the ("spatial") metric tensor and its conjugate momentum is, more or less, its time derivative. This might seem strange at first, but what happens in the canonical formalism is we take a foliation of spacetime: i.e., we split spacetime into space+time.
There is an extensive literature dedicated to this subject. There are several different Hamiltonian formulations of classical GR, but usually people use the ADM formalism (named after its founders Arnowitt, Deser, and Misner). There is another approach, Loop Quantum Gravity, which more closely resembles other common quantum field theories.
2. Know Classical GR First! If you don't know classical General Relativity, you need to learn that first. You should study it first classically, then quantum mechanically. It's hard enough at the classical level!
You should be able to read through Misner, Thorne, and Wheeler's Gravitation or Wald's General Relativity. If you haven't started learning relativity, I highly recommend Bernard Schultz's A First Course in General Relativity first, then Poisson's A Toolkit for Relativity (or his lecture notes linked below), and then read through either Misner, Thorne, and Wheeler or Wald (or both!).
3. What Quantization Scheme to Use? Well, in the 80 years people have pursued quantum gravity, they have tried every quantization scheme you could think of!
To get a sense of how complicated quantum gravity is (and an overview of the different approached), I recommend reading Rovelli's "Notes for a brief history of quantum gravity" arXiv:gr-qc/0006061, which is an easy read.
Just a few remarks about quantization schemes: quantization is always problematical on its own, in the sense that presumably nature is already quantum and formulating a procedure to go from classical to quantum is nonsensical. This is discussed in many articles, I'll give a few free good references, e.g., S Twareque Ali and Miroslav Engliš' "Quantization Methods: A Guide for Physicists and Analysts" (arXiv:math-ph/0405065) and MJ Gotay's " Obstructions to Quantization" (arXiv:math-ph/9809011).
4. Reading List on Canonical Quantum Gravity. I'll just give a few references on canonical gravity, both classical and quantum. These I have found useful:

*

*Claus Kiefer's Quantum Gravity. Just published in its third edition, and a great overview of the field.

*Arnowitt, Deser, and Misner's "The Dynamics of General Relativity" arXiv:gr-qc/0405109 first describes the (classical) Hamiltonian formalism.

*Eric Poisson's "Advanced General Relativity" lecture notes (the basis for his book) describes the mathematics and physical intuition underpinning the foliation of spacetime into space + time. Great preparation for more advanced relativity!

*Yvon Choquet-Bruhat's General Relativity and the Einstein Equations (2009) discusses the conformal treatment of canonical GR quite beautifully, which is not discussed in any other textbooks I've found.

*Steve Carlip's Quantum Gravity in 2+1 Dimensions (2003), beautifully discusses many aspects of quantum gravity which are exemplified in 2+1 dimensional models. (Don't dismiss 2+1d gravity because it's "trivial", it actually allows us to gaze at the problems underpinning 3+1d quantum gravity.)

*Martin Bojowald's Canonical Gravity and Applications: Cosmology, Black Holes, and Quantum Gravity (2011). If you get only one book, get this one! It discusses exactly what you are looking for at the advanced undergraduate level.

5. Quantum Field Theory. You also need to know how to quantize fields, specifically constrained systems. This is a tricky subject, and there is no single book I'd recommend because each book discusses one aspect or one approach really well.
The usual text on quantizing constrained systems is Henneaux and Teiteilboim's Quantization of Gauge Systems (1994). It's not a good text, but it's the only text on the subject. (I had to work through the first few chapters by re-writing it in a mathematician's style, in the sense of "Each main idea gets a numbered item on a list, and elaborations on ideas get sub-items. Some items are theorems, others are definitions. A proof is a collection of steps.") I have heard of another book, which might serve well as preparation for Henneaux and Teiteilboim (but not a replacement!): Lev V Prokhorov and Sergei V Shabanov's Hamiltonian Mechanics of Gauge Systems (2011).
If you don't know quantum field theory, I recommend working your way through Brian Hatfield's Quantum Field Theory of Point Particles and Strings (1992) since it's the only textbook which actually discusses the functional Schrodinger equation, gives an "honest enough" account of the path integral, and shows all the calculations/steps in derivations. Caveat: the first edition of Hatfield, though cheaper secondhand, is full of typos...I took this as an exercise to double check every calculation in at least three different ways. The second edition has fixed the typos, or so I hear. (Usually Peskin and Schroeder's Introduction to Quantum Field Theory (1995) is recommended. This is a good text, but I found it slow reading.)
Personally, I preferred reading Ticciati's Quantum Field Theory for Mathematicians (2008) followed up by Edson de Faria and Welington de Melo's Mathematical Aspects of Quantum Field Theory (2010).
(Addendum: you might want to eventually work your way through the first volume of Weinberg's The Quantum Theory of Fields, since it uses the same metric signature as used in the ADM decomposition.)
One last book I'd recommend reading is NMJ Woodhouse's Geometric Quantization (1997), because it discusses an approach to quantization that isn't discussed in other texts.
6. Canonical Quantum Gravity Today? The canonical approach has led to Loop Quantum Gravity, which is actively researched today. There are a number of good books on this subject (Rovelli wrote one, Thiemann wrote another, etc.).


text:
Q: Mysql database - primary key problem I have 2 tables: let say table 1 (userid, username, password) and table 2 (userid, a, b, c).
table 1 has a userid field (primary key), table 2 also has userid (references table 1).
If I do an insert statement, to add a row to table 2, how does table 2 generate the userid field?
Edit:
I want to insert things into table 2 where the userid in table 2 MUST match userid in table 1 - what constraints do I need to set up

A: The database doesn't understand the relationship between table1 and table2 unless you explicitly specify it.  You can use SQL foreign keys if you are using a database engine the supports them (InnoDB).
CREATE TABLE table1 (
    userid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL);
CREATE TABLE table2 (
    rowid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
    userid INTEGER NOT NULL
        REFERENCES table1(userid)
        ON DELETE CASCADE ON UPDATE CASCADE
    -- other columns here
);

The REFERENCES option will tell the database engine that table2.userid requires that a row exist in table1 such that table1.userid = table2.userid.   The ON DELETE and ON UPDATE clauses will cause the deletion of a row in table1 to automatically delete/update rows in table2.
You cannot create a row in table2 until you have created a row for the user in table1.  The row in table1 will auto-generate the userid.  When you insert into table2, you will explicitly include the user id from table1 to establish the linkage between the rows.

A: If the userid field on table2 is not autoincrement then you have to provide the value or the insert will fail.

A: If username and password is not null then don't insert in tabel 1 and give error

A: If you have defined userID in table2 as foriegn key constraint, then you will need to have the corresponding userID in the table1 as reference when inserting rows to table2, else if you have not defined any such constraints, then it will not matter.
Keep in mind, if the constraint is defined, then table2 will not generate ID by itself. It would require the ID to be present in the table1 column which is referenced.


text:
Q: How to specify in a code that it must be a number, because if I enter a word in an integer input the program crashes Tell me the code that would support this, because if I enter a word into an integer input the program crashes. I know this would be a simple one line code, but I just can't get my head around it.
Traceback (most recent call last):
  File "N:/Controlled Assessment/Task Three v1.py", line 9, in <module>
    c1_strength = int(input("What is character 1's strength? (Between 1 and 50, must be number): ")) #asks user for the strength value of character 1
ValueError: invalid literal for int() with base 10: 'fresd'

A: Try this:
while True:
    try:
        a = int(input())
    except ValueError:
        print "Enter an integer"
        continue
    break


text:
Q: How to create Idle time? I am creating a batch file program where if you open a mspaint.exe, if its idle for 10 seconds the program will close automatically. I have created this:
@echo off

:Start
tasklist /FI "IMAGENAME eq mspaint.exe" | findstr "mspaint.exe" >nul
IF "%ERRORLEVEL%" == "0" GOTO Running
IF "%ERRORLEVEL%" == "1" GOTO NotRunning

:Running
***::Check if idle***

GOTO Terminate

:NotRunning
 GOTO EOF

:Terminate
timeout 5
taskkill /im mspaint.exe /f
ECHO Paint has been terminated due to inactivity
PAUSE

:EOF
EXIT

I have trouble finding the idle syntax(seems it doesn't exist), is there another way to make the idle time work? And since this is my first time creating a batch file, I really need a helping hand here.

A: Not the answer you want to hear, but the one that you need. The only way to monitor another process for activity is to install a window hook, but that's going to require a much lower level language (C or C++).
If that doesn't put you off then start with the Microsoft Hooks Overview and post further questions. Good luck (you'll probably need it).

A: Thanks for the help but that seems complicated. I used SCHTASKS instead and it worked :)