text:
Q: Finding Nothing with Range.Find I have read the documentation and have been using the method with mixed success but I keep running into situations where the object I'm looking for is obviously right there but Range.Find returns nothing.
test = Search_Range.Cells(4,4).Value = Search_Text 'returns true
set test2 = Search_Range.Find(What:=Search_Text) 'returns nothing

I'm so frustrated! The target cell is within the Search_Range. The Search_Range is on the correct sheet. The data type of the value is the same as Search_Text. Even if I add things like LookAt:=xlPart or LookAt:=xlWhole, nothing changes. Same with LookIn:=xlValues.
What other sources could be causing the method to return nothing?
Here is the function causing me to rip my hair out. I made it so the user could quickly identify what the macro failed to find.
Private Function Look_For(ByVal Search_Text As String, ByRef Search_Range As Range, _
                            Optional LookAt As Long = xlPart, _
                            Optional Error_Message As Boolean = True) As Variant
    On Error Resume Next
    Set Look_For = Search_Range.Find(What:=Search_Text, LookAt:=LookAt, MatchCase:=False)
    On Error GoTo 0

    If Look_For Is Nothing Then
        Look_For = False
        If Error_Message = True Then MsgBox "Could not find """ & Search_Text & _
            """ in the area " & Search_Range.Address & "." & vbNewLine & _
            "Please fix the sheet or this macro and try again.", _
             vbCritical, "Fatal Error!"
    End If

End Function

Edit:
Here is a sub that can recreate the issue.
Sub Test()
    Const Txt As String = "FSQP 4.16-04F Skid Detail Sheet"
    Dim target As Range
    If Not Look_For(Txt, Sheet1.Range("A1:D8")) = False Then
        Set target = Look_For(Txt, Sheet1.Range("A1:D8"))
    End If
    If target Is Nothing Then MsgBox "Minimal Reproducible Example"
End Sub

There is no error message, I am just trying to get a cell object using Range.Find and save it to a variable but I am getting nothing from Range.Find

A: Thanks to advice from John Coleman, BigBen and Tim Williams, I was able to find the answer to this problem.
The problem is that Range.Find was not able to handle a merged cell that was partially outside the defined range. The cell we were looking for in D4 was actually merged D4:F4. To avoid this problem, I edited the function to check and expand the search range prior to doing Range.Find.
Here is the revised function
Private Function Look_For(ByVal Search_Text As String, ByRef Search_Range As Range, _
                            Optional LookAt As Long = xlPart, _
                            Optional Error_Message As Boolean = True) As Variant

    Dim oCell As Range, mCell As Range
    For Each oCell In Search_Range
        If oCell.MergeCells = True Then
            For Each mCell In oCell.MergeArea
                If Intersect(mCell, Search_Range) Is Nothing Then
                    Set Search_Range = Union(Search_Range, oCell.MergeArea)
                End If
            Next mCell
        End If
    Next oCell

    Set Look_For = Search_Range.Find(what:=Search_Text, LookAt:=LookAt, MatchCase:=False)

    If Look_For Is Nothing Then
        Look_For = False
        If Error_Message = True Then MsgBox "Could not find """ & Search_Text & _
            """ in the area " & Search_Range.Address & "." & vbNewLine & _
            "Please fix the sheet or this macro and try again.", _
             vbCritical, "Fatal Error!"
    End If

End Function

With advice from Tim Williams, I removed On Error Resume Next and On Error Goto 0, they were unnecessary.


text:
Q: Incompatible pointer types on array initialization The following array initializer:
const char** AST_NODE_TYPE_NAMES = {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};

Makes gcc raise the following warning:
initialization of 'const char **' from incompatible pointer type 'char *'

Help me figure this out?

A: you want array of pointers
const char *AST_NODE_TYPE_NAMES[] = {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};

and this array can eventually decal to the pointer you want:
const char **foo1 = AST_NODE_TYPE_NAMES;
const char **foo = &AST_NODE_TYPE_NAMES[0];

you can also use the compound literal (which actually is the array of pointers in this case) to initialize this pointer
const char** AST_NODE_TYPE_NAMES =(const char *[]) {
    "AST_NODE_CONSTANT",
    "AST_NODE_BINARY",
    "AST_NODE_UNARY",
    "AST_NODE_VARIABLE",
    "AST_NODE_ASSIGNMENT",
    "AST_NODE_STATEMENTS",
};

A: A pointer is not an aggregate but a scalar, and it expects one value to initialize it. In C it is also permissible to wrap the scalar initializer in { }!
Thus:
const char** AST_NODE_TYPE_NAMES = {
     "AST_NODE_CONSTANT",
     "AST_NODE_BINARY",
     "AST_NODE_UNARY",
     "AST_NODE_VARIABLE",
     "AST_NODE_ASSIGNMENT",
     "AST_NODE_STATEMENTS",
};

tries to initialize one pointer to pointer to const char with the address of the first character of string literal "AST_NODE_CONSTANT", but that does not have type const char ** but just char *. In addition to that, there are 5 excess initializers, namely the following strings.

What you of course want to do is to initialize an array, as P__J__ already showed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Дубли в валютах (angular) Подскажите как избавиться от дублей?

public uniqueCurrencyList(listIntRate: any[]) {
        let listCurrencyObj: any[] = [];
        listCurrencyObj = listIntRate.map(item => item.Currency.LetterCode);
        let listUniqueCurrency: any[] = [];
        for (let str of listCurrencyObj) {
            var item = listUniqueCurrency.find(x => x == str);
            if (item === null || item === undefined) {
                let newObj = this.listItemsCurrencies.find(x => x.LetterCode == str);
                listUniqueCurrency.push(newObj);
            }
        }

        this.listItemsCurrencies = listUniqueCurrency;
    }

public uniqueCurrencyList(listIntRate: any[]) {
        let listCurrencyObj: any[] = listIntRate.map(item => item.Currency.LetterCode);
        let listUniqueCurrency: any[] = Array.from(new Set(listCurrencyObj));
        let result: CurrencyModel[] = [];
        this.listItemsCurrencies.find(x => x.LetterCode == listUniqueCurrency[0]);
        let listCurrency = this.listItemsCurrencies.map(x => x.LetterCode);
        for (let item of listCurrency) {
            if ((listUniqueCurrency.indexOf(item) !== -1)) {
                let curUnique: CurrencyModel = this.listItemsCurrencies.filter(x => x.LetterCode === item)[0];
                result.push(curUnique);
            }
        }
        this.listItemsCurrencies = result;
    }

начал вот так делать, но при след проходу он смотрит уже на фильтрованный массив - как его привести к начальному при инициализации?

A: Самый простой и быстрый способ получить список уникальных элементов - это Set().
const currencies = ['BTC', 'EUR', 'EUR'];
const uniqueCurrencies = Array.from(new Set(currencies)); // ['BTC', 'EUR'];


text:
Q: Errors when creating new columns in pandas Trying to count occurrences of user ids (id) in a dataframe, by creating a new column called n_occurrences. It always results in a KeyError and I'm unsure why. In the same method, I create a new column for elapsed time (elapsed_time) which works without errors.
code sample:
import pandas as pd

class Clean_Data:
    def __init__(self, data): #data is path to csv
        self.make_df(data)
        self.df

    def make_df(self,data):
        data_raw = pd.read_csv(data,header=0,nrows=100)
        #do stuff that returns valid dataframe, cleans up unwanted data
        self.df = data_raw
        return self.df #df with shape 100 rows, 27 cols

    def analyze_the_data(self):
        self.df['n_occurrences'] = self.df.groupby(['id','time']).transform('count')
        # ^ fails as well if I try with or without the line 'self.df['n_Occurrences']'
        # has error ValueError: Wrong number of items passed 25, placement implies 1

        self.df['time_elapsed'] = (self.df['time']-self.df['time'].shift()) # works--creates time_elapsed col
        print(self.df.shape) #shows dataframe shape of 100 rows, 28 cols

if __name__ == '__main__':
    c = Clean_Data(r'/path/to.csv')
    c.analyze_the_data()

Dataframe (should) change to 63 rows, 28 cols after the groupby line. There are upwards of 50,000 lines so I'm just using 100 to save on time until everything is working.
output of error line:
ValueError: Wrong number of items passed 25, placement implies 1

why does it fail when I create the n_occurrences col but not when i do the time_elapsed col?


text:
Q: How check if a script is running? I am using a custom script (stream.sh) which starts on boot. However, I want to check after every 5 minutes if the script is running. If it is not running, I want to run it again. How can I configure it in crontab or else?
I am using Ubuntu 18.04.

A: You may then, if your need is to have it running perpetually, to avoid running it from crontab, run it from inittab with respawn option.

A: Schedule below mentioned script in crontab
*/5 *  *  *  * /path_of_script
code
#!/bin/bash
process=`ps -eaf | grep -i scriptname | grep -iv 'grep' | wc -l`
if [[ $process > 0 ]]
then
echo "script is running"
else
echo "script is not running"
echo "Need to start the script"
sh scriptname
fi


text:
Q: On-demand reminders Scenario: I come across a question that is poorly written, but is very new (like a few minutes old). If the question were older (as in an hour or so), I would submit a close-vote. However, since the question is very new, I like to give the OP a chance to improve the question, so I don't close-vote immediately. Instead, I comment on the question. In my comment I try to point out the issues with the question (e.g. "What do you mean by... ?"). Then, I keep the question open in a background tab and return to it later (like in 5 minutes or so).
However, sometimes I just don't feel like investing in a question like that, so I just abandon it. Which is why I had this idea. Imagine if you could set a reminder for a particular question. You would set the time (e.g. 30 minutes), and an optional message (e.g. "close-vote if question hasn't been improved").
Of course, if OP responds to my comment, I don't need the reminder. But from my experience, new users tend to ignore constructive comments, and just focus on getting a solution without having to invest any more time in explaining the issue.
So, with this feature, I could:

*

*comment on the question (pointing out how the question should be improved),

*set a reminder (30 minutes),

*if the OP responds to my comment, I get the notification; otherwise I get the reminder after the specified time.

Btw, this feature is trivial to implement in JavaScript using localStorage.
So, what do you think?

A: I initially liked the idea, but on further thinking, it suffers from the same problem as did my similar suggestion to introduce timed downvotes: it would add a huge amount of complexity for relatively little gain.
I, too, want to be gentle to newbies, and I'm still hesitant to welcome them with negative voting. However, these days, I closevote straight away anyway, and sometimes even downvote.
This is for three reasons:

*

*There's simply too many bad questions.

*Most OP's simply aren't worth delaying or second-guessing your negative vote, because they aren't going to fix their question anyway because they don't care or don't know what's expected of them.

*For those OP's who are actively interested in improving their question,  there is usually enough time for them to do so before the required five close votes trickle in that seal the question's fate. The five vote threshold is most often already enough of a delay.
I guess I largely buy into Jeff Atwood's  philosophy now: that a question should be evaluated as it is in the moment you look at it, and not based on some theoretical improvement in the future. (I can't find where he said this right now.)
If anything, I'd favour an approach that puts the onus of acting completely on the asker: if my question gets closed or downvoted, give me one shot - just one - to ping @downvoters and @closevoters when I've edited it, and appeal to them to reconsider their vote. This requires the OP's active interest in getting their question revived.
But then, there is a  solution already that doesn't require a feature at all. When closevoting, we could leave comments to the effect of:

I voted to close because I think the following is wrong with this question: ....... ping me when you fix this problem so I can vote to reopen.

this would have almost the same effect, but not require a new feature at all.


text:
Q: Query Optimization i'm having problem with a query generated by mondrian OLAP Server . it's taking too long. the query look like as follows.
select "TABLE1"."column0" as "c0" from "FACT_TABLE" as "FACT_TABLE",
"TABLE7" as "TABLE7",
"TABLE6" as "TABLE6",
"TABLE5" as "TABLE5",
"TABLE4" as "TABLE4",
"TABLE4" as "TABLE3",
"TABLE2" as "TABLE2",
"TABLE1" as "TABLE2"
 where "FACT_TABLE"."column1" = 'VALUE' and
 "FACT_TABLE"."column2" =0 and
 "FACT_TABLE"."column3" = 0 and
 "TABLE2"."table1Fk" = "TABLE1"."table1Id" and
 "TABLE3"."table2Fk" = "TABLE2"."table2Id" and
 "TABLE4"."table3Fk" = "TABLE3"."table3Id" and
 "TABLE5"."table4Fk" = "TABLE4"."table4Id" and
 "TABLE6"."table5Fk" = "TABLE5"."table5Id" and
 "TABLE7"."table6Fk" = "TABLE6"."table6Id" and
 "FACT_TABLE"."table7Fk" = "TABLE7"."table7Id"
  group by "TABLE1"."column0"
  order by "TABLE1"."column0" ASC

FACT_TABLE has 1.346.000 rows aprox.
TABLE7 has 895 rows aprox.
TABLE6 has 445 rows.
TABLE5 has 183 rows.
TABLE4 has 258 rows.
TABLE3 = TABLE4.
TABLE2 has 126 rows.
TABLE1 has 29 rows.
The query is taking 2.00 seg aprox over the production enviroment, and i really dont know what to do to improved query performace.
im over a 8GB RAM.
intel xeon L5420 at 2.50GHZ.
MSSQL 2005.
i'll apreciated any help that you can give me

A: Have a look at the execution plan. It will notify you if it notices any tables that could use a non-clustered index to improve query time.
Link
That link helps a lot with optimizing queries (and learning a ton of other things.)

A: I would suspect that you don't have indexes on your foreign key fields.
This is not causing your problem but I personally wouldn't want to use a tool that creates implicit instead of explicit joins. How can you trust something that is using a syntax that was replaced 18 years ago with something better?
Oh something else I just noticed, I don't see any aggregates, so why are you grouping by?


text:
Q: ALM Excel macro for test-lab extractor folder wise I am looking to develop a excel macro which will be able to fetch data from ALM test-lab folder wise. I need the data in the following format  :

*

*Test Set Folder Name,

*Test Set Name,

*Test Case Name,

*Test Case Status,

*Tester Name,

*Test Step Execution Date

I am new to SQL so any help to build the SQL will be very much helpful.
Also want the folder path for data extraction to be specified by the user and to use the path in the SQL query.

A: I used the following format but the report generated is in a different format:
SELECT CF_ITEM_NAME as 'Test Set Folder Name',CY_CYCLE as 'Test Set Name',TS_NAME as 'Test Case Name',RN_STATUS as 'Test Case Status',ST_STEP_NAME as 'Test Step Name',ST_STATUS as 'Test Step Status',ST_DESCRIPTION as 'Test Step Description',ST_EXPECTED as 'Test Step Expected Result',ST_ACTUAL as 'Test Step Actual Result',RN_HOST as 'Test Host Name',RN_TESTER_NAME as 'Tester Name',ST_EXECUTION_DATE as 'Test Step Execution Date',ST_EXECUTION_TIME as 'Test Step Execution Time' FROM STEP a, TEST b, CYCLE c,RUN d,CYCL_FOLD e where a.ST_TEST_ID=b.TS_TEST_ID and c.CY_CYCLE_ID=d.RN_CYCLE_ID and d.RN_TEST_ID=b.TS_TEST_ID and e.CF_ITEM_ID=c.CY_FOLDER_ID and RN_HOST IS NOT NULL and RN_TESTER_NAME IS NOT NULL and CF_ITEM_PATH like 'AAAAAAAAD%' ORDER BY TS_NAME,RN_RUN_ID,ST_RUN_ID,ST_EXECUTION_DATE,ST_EXECUTION_TIME ASC


text:
Q: How can I upload a file using Ajax to asp.net? How can I asynchronously Upload file to asp.net Website (Webforms) without any post backs?

A: Its simple to use jQuery Forms plugin for this purpose. We can use it in asp webforms like shown below.
HTML / ASPX Page
    <form id="myForm" action="fileupload.ashx" method="post">
        Name: <input type="text" name="name" />
        File: <input type="file" name="filetoupload" />
        <input type="submit" value="Submit Comment" />
    </form>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
        <script src="http://malsup.github.com/jquery.form.js"></script>
     <script>
         $(document).ready(function () {
        // attach handler to form's submit event
        $('#myForm').submit(function () {
            // submit the form
            $(this).ajaxSubmit();
            // return false to prevent normal browser submit and page navigation
            return false;
        });
    });
</script>

Pure HTML used in this example. If aspx webforms then, there will be only one form tag in a page.
Add a WebHandler (.ashx extension) to Website.
using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    HttpPostedFile MyFile=context.Request.Files["filetoupload"];
    if (MyFile.ContentLength > 0 && MyFile != null)
    {
        MyFile.SaveAs(context.Server.MapPath("Path/On/Server"));
    }
    context.Response.Write("Saved Successfully");
}

public bool IsReusable {
    get {
        return false;
    }
}


text:
Q: How to Pass a List of Objects from activity A to activity B in Kotlin? I have 2 Activities, I want to pass an arraylist of an Object and show it on a ListView

Activity A:

     btnGuardar.setOnClickListener{

                if(edtNombre.text.toString().equals("") ||
                     edtApellido.text.toString().equals("") ||
                     edtFecha.text.toString().equals("")){

                    Toast.makeText(this@Main2Activity, "Debes llenar todos los campos!", Toast.LENGTH_SHORT).show()
                }else{
                    var estadoSel : String
                    estadoSel = estado.onItemSelectedListener.toString()
                   var per = Persona(edtNombre.text.toString(),edtApellido.text.toString(),estadoSel,edtFecha.text.toString())
                    personas.add(per)
                    val intent = Intent(this@Main2Activity,Main3Activity::class.java)
                    //intent.putExtra("Personas",  personas as Serializable)
                    intent.putParcelableArrayListExtra("Personas", ArrayList(personas))
                    edtFecha.text = null
                    edtApellido.text = null
                    edtNombre.text = null
                    estado.setSelection(0)
                    Toast.makeText(this@Main2Activity, "Registro Guardado", Toast.LENGTH_SHORT).show()
                }
            }

Activity B:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main3)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        //val intent = Intent()
        val bundle = getIntent().extras
        var arr  = bundle?.getParcelableArrayList<Persona>("Personas")!!
        //var arr : ArrayList<Persona> = (ArrayList<Persona>())intent.getSerializableExtra("Personas")
        //intent.getSerializableExtra("Personas")
        //arr = intent.extras!!.get("Personas")
        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arr)
        listaPersonas.adapter = adapter
    }

But I'm getting a Null Pointer Exception

A: In your app's build.gradle under android scope add this and sync gradle -
androidExtensions {
        experimental = true
    }

Then make your object class parceble as follows -
@Parcelize
data class Persona() : Parcelable {

}

Now you can send and receive Parcelable list by intent.
Update : @Parcelize is no more experimental now, follow this answer for updated implementation https://stackoverflow.com/a/64925204/9854554

A: In your activity B to get your list try like the following
var arr = this.getIntent().getParcelableArrayListExtra<Parcelable>("Personas")

and make sure your Persona is extend Parcelable like below.
class Persona() : Parcelable {
   // ....
   @Override
   public void writeToParcel(Parcel dest, int flags) {
       //....
   }

   private void readFromParcel(Parcel in) {
      //....
   }
   override fun describeContents(): Int {
      return 0
   }

   companion object CREATOR : Creator<Persona> {
    override fun createFromParcel(parcel: Parcel): Persona{
      return Persona(parcel)
    }

    override fun newArray(size: Int): Array<Persona?> {
      return arrayOfNulls(size)
    }
  }

}

A: In your, Activity A send array list with
intent.putParcelableArrayListExtra("Personas", personas)

In your, Activity B get array list with
intent.getParcelableArrayListExtra("Personas")

In your app's build.gradle inside android tag add this and sync with gradle -
androidExtensions {
        experimental = true
    }

Data Class
@Parcelize data class Persona(
    val name: String,
    ) : Parcelable

A: To pass List of Data via intent implement Parcelable interface on Model class.
Person Model Class:
import android.os.Parcel
import android.os.Parcelable

data class Person(val name: String?, val age: Int) : Parcelable {
    constructor(source: Parcel) : this(
        source.readString(),
        source.readInt()
    )

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeString(name)
        writeInt(age)
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<Person> = object : Parcelable.Creator<Person> {
            override fun createFromParcel(source: Parcel): Person = Person(source)
            override fun newArray(size: Int): Array<Person?> = arrayOfNulls(size)
        }
    }
}

MainActivity:
class MainActivity : AppCompatActivity() {

    var personList = arrayListOf<Person>()

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

        personList.add(Person("Person1", 31))
        personList.add(Person("Person2", 32))
        personList.add(Person("Person3", 33))

        var intent = Intent(this, BActivity::class.java)
        intent.putParcelableArrayListExtra("personList", personList)
        Handler().postDelayed( {startActivity(intent)}, 2000)
    }
}

BActivity:
class BActivity : AppCompatActivity() {

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

        val extras = intent.extras
        val personList = extras?.getParcelableArrayList<Person>("personList")

        if (personList != null) {

            personList.forEach { Log.i("BActivity", "Name: ${it.name} Age: ${it.age}" ) }

        }else{
            Log.i("BActivity", "PersonList in null");
        }
    }
}

A: Step 1. add this in your app build.gradle inside android scope.
 androidExtensions {
        experimental = true
    }

Step 2: Make object class implement Parcelable
@Parcelize
 class Persona():Parcelable {
}

Step 3. In activity A send data via intent:
  val intent = Intent(this, B::class.java)
            intent.putParcelableArrayListExtra("list", personaArrayList)
            startActivity(intent)

Step 4: In activity B for recieving data:
 val list = intent.getParcelableArrayListExtra<Persona>("list")


text:
Q: Visual studio C++ relative path In Visual studio C++/Cli, relative pathes are relative to what? Which directory is equivalent to "." ? For example, if the solution file is at "C:\dir1\project.sln" the where is "."?

A: At runtime, relative paths are relative to the working directory that the application was started with.

*

*When you run from Visual Studio, the working directory is where the project file is located.

*When you double-click an exe in Windows Explorer, the working directory is generally the same as where the exe is located.

*From the command line, you can have the working directory be anything: navigate to the directory you want to use as the working directory, and run your exe by typing the full path.


text:
Q: JavaFX ScrollPane on Android - Too Slow I have just coded a simple example of using a scrolling pane in JavaFX. Just one ScrollPane placed in the Scene, and the ScrollPane holds a Label component with a large text. Using gradle I have uploaded the app on a Nexus 4 android device. As you can see from the video I have uploaded, the scrolling is way too slow. I am sure others have experienced this. Any suggestion of how this can be changed to the native speed scroll is really much appreciated.
Source code of the app can be downloaded from here.
AndroidFX.java
public class AndroidFX extends Application{

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent mySearchListFXML = getFXMLPane("/fxml/ScrollPaneWithLabel.fxml");
        primaryStage.setScene(new Scene(mySearchListFXML));
        primaryStage.setWidth(Screen.getPrimary().getVisualBounds().getWidth()); primaryStage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
        primaryStage.show();
    }

    public static Parent getFXMLPane(String url) throws IOException {
        URL location = AndroidFX.class.getResource(url);
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(location);
        Parent pane = fxmlLoader.load();
        return pane;
    }
}

ScrollPaneWithLabel.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<ScrollPane fx:id="scrollPane" fitToWidth="true" hbarPolicy="NEVER" pannable="true" style="-fx-background: white;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <content>
      <Label text="<VERY LARGE TEXT HERE>" wrapText="true" />
   </content>
</ScrollPane>

A: Faced similar issues. The problem is worse on hidpi devices, disabling the hipdpi setting in the properties file helps but you will have to do any scaling your self for hidpi screens.
Another thing that might help is caching the fonts. I believe the end result of a javafx ported application is more like a big image with hot spots. Scrolling I think is just telling the application to redraw the whole image every time. Just a theory really. Caching does help but can make your text look kinda fuzzy. Although I had some success in scaling the font large, setting the cache to true and then scale down, normally x2 and .5 gives pretty good results. Using em for the fonts helps the fuzzy text too.
If you need to show a huge amount of text and it must be scrolled, you will probably get much better results displaying it through a webview. I haven't ever really used it to be honest, but I would imagine that it is replaced when ported with the native browser window so performance should be pretty good I think. I guess it is possible they wrote a html renderer in javafx and then you would run into the same pitfalls.
http://www.gluonhq.com is offering something called the charm, down, and connect package that is supposed to mimic native apps. It sounds promising and I am currently trying to get more info to see if they have solutions to these types of issues. I will add to the post if I receive any more info about charm.


text:
Q: Who is behind LXLE? I understand Canonical is funding Ubuntu, and that LUbuntu at least has Canonical's endorsement.  Who funds and who manages LXLE?  (I could not find information on the LXLE web site.)
For those who aren't aware, LXLE is a "respin" of LUbuntu, and stands for "Lubuntu Extra Life Extension"-- hence the reason the question is asked here.

A: According to LXLE website, LXLE Linux is a self funded community Linux distribution.
User contributions through donations and store purchases help cover the administrative and hosting cost of the distribution.


text:
Q: How do the current Illuminati, Age of Ultron, and Avengers story lines connect? I can never keep up with the different story lines. Its all a doozy.

*
*So the Illuminati with their gems are fighting some kind of alternate reality earth.
*Age of Ultron has the world in ruins and most supers dead, and Nick Fury and friends are traveling time to try and fix it
* Avengers is fighting Ex Nihilo on Mars
*Fantastic Four apparently left Earth and present time to find a cure for Reed, yet they are in all story lines?

All of these stores are published in different titles which are published at the same time. So it seems to me that Iron Man is fighting alternate Earth, Ultron, and Ex Nihilo all at the same time at different places. Are they happening in different points of time? Or are they happening on different parallel Earths?
So confused. Please help set this straight. Thank you

A: As I'm currently reading through the Avengers books from this time frame:

*

*Reed's participation with the Illuminati in NEW AVENGERS was due to his having a back-door to contact Earth that he didn't tell the rest of the FF about. He was, indeed, on that search for a cure to his condition; however, the impending destruction of the universe was worth a few minor interruptions.

*In AGE OF ULTRON, the FF returned to Earth after Ultron had taken over, and only Sue survived. Once the timeline was reset, of course, none of that needed to happen, so it didn't.

*One of the reasons Tony pushed for the expansion of the Avengers' roster seen in AVENGERS at that time was to help free him up to spend more time dealing with the incursions. In fact, he was one of the few Avengers who did not go into space to fight the Builders in the "Infinity" storyline, precisely so he could stay on Earth to deal with incursions.

*I've gotten the impression that, possibly, the multiple time travel trips seen in AGE OF ULTRON are connected to the collapse of the Marvel multiverse. While it's not the only possible cause (the events happening out in the universe during "War of Kings" and "Realm of Kings" definitely ripped a hole in the universe), the strong warnings and concern about using time travel to fix the problem, followed by the fact that there were multiple trips by the same people to the same time, seems like a strong candidate for causing major problems. This is certainly not explicitly stated anywhere; I simply feel like it was being hinted at.
Looking at your specific question, it looks like you're asking about the first storylines in Jonathan Hickman's runs on AVENGERS and NEW AVENGERS, and AGE OF ULTRON. If I had to try to place those on a timeline, I'd tend to put NEW AVENGERS 1-6 first, then AVENGERS 1-6, then AVENGERS: AGE OF ULTRON.
Why?

*

*As I noted, one of the reasons Tony promoted the expansion of the team was the threat of the incursions.

*AVENGERS requires that the selection and organization of the new team have all happened. Logical, all this would have been going on while the Illuminati (inclkuding Steve Rogers at that point) were figuring things out from their end. Hence, the first storyline in AVENGERS following the first storyline in NEW AVENGERS.

*AGE OF ULTRON didn't start until we were already well into the other two storylines. Therefore, place it after they conclude, as that's the simplest solution. Since Ultron's attack, in the final version of the timeline, wasn't really that much of a threat overall (no worse by comparison that some of his other attacks, certainly), there wasn't much discussion of it in the other books outside of the .AU issues.


text:
Q: Display one div if nothing is selected I use this javascript to display different div classes upon selection. I need to display one div class if nothing is selected, for example when page is loaded, and that replace it with one of the divs according to the selection...

css:

HTML:
<form id="FormName" action="blah.php" method="get" name="FormName">
        <select name="selectName" size="1" onChange="showDiv(this.value);">
            <option value="">Choose One...</option>
            <option value="one">first</option>
            <option value="two">second</option>
            <option value="three">third</option>
        </select>
    </form>

This is paragraph 1.

This is paragraph 2.

This is paragraph 3.

Can anyone please help?

A: <select onChange="showDiv(this.value);">

The <select> element doesn't have a value attribute. The value is sitting in its <option> children. To get the value of the currently selected option of a <select> element you need the following:
var selected = dropdown.options[dropdown.selectedIndex].value;

So your onchange call needs to be altered as follows:
<select onchange="showDiv(this.options[this.selectedIndex].value);">

That said, the onchange attribute should be spelt all lowercase and a paragraph is not a div.

A: Assign id to select list
<select name="selectName" id="selectName" size="1" onChange="showDiv(this.value);">

call window.onload function
window.onload =function (){
        showDiv(document.getElementById("selectName").value);
}


text:
Q: Ios - filter the asset group I would like to get some photos from the Asset Library using the url of the asset as filter parameter:
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
    usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (nil != group) {
            // be sure to filter the group so you only get photos
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            [group enumerateAssetsUsingBlock:
            ^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if (nil != result) {
                    ALAssetRepresentation *repr = [result defaultRepresentation];
                    BOOL exists = [...[repr.url absoluteString]];
....

The problem is that the enumerateAssetsUsingBlock block get all the photos one by one and that process is too slow. Is there any other way to filter the asset group?
Thanks


text:
Q: Need assistance with specific CSS div layout I've been fiddling with this for a while and can't get what I want. Can someone give me some guidance to achieve the layout in the attached drawing?

A: I started this off for you. It uses flexbox which is a suggestion by @Keith M (and a good one, I would also recommend flexbox).
Hope it gets you on your way!

.body {
  display:flex;
  flex-direction:column;
  width:100vw;
  height:100vh;
}

.body > .topNav {
  flex:0 0 50px;
  background: blue;
}

.body > .page {
  display:flex;
  flex-direction:row;
  flex: 1 1 auto;
}
.body > .page > .leftNav{
  flex: 0 0 300px;
  background: red;
}
.body > .page > .content{
  flex: 1 1 auto;
}


text:
Q: How does heating in the atmosphere look above 100 km I have tried without luck to find a graph of temperature change through the atmosphere that goes further up than about 100 km. On this graph:

(Source: http://www.windows2universe.org/kids_space/temp_profile.html)
as on many others the temperature rises and rises and continues like that out of the scale. How will the temperature curve look further up when the exosphere gets closer (at about 700 km or so, according to Wikipedia)? What is the max temperature the thermosphere will reach?

A: A team at the University of Western Ontario used a lidar to measure "temperature" by inferring it from the blackbody spectrum of atmospheric gases at various heights. They arrived at this:

However, as noted in the comments to the OP, the atmosphere at very high altitudes isn't really in thermal equilibrium and doesn't have a well-defined concept of temperature.


text:
Q: Why the category of core-compact spaces with continuous maps is not cartesian closed ? According to ESCARDÓ-LAWSON-SIMPSON paper 'Comparing cartesian closed categories of (core) compactly generated spaces' The following four propositions are true:

*

*A topological space $X$ is exponentiable iff $X$ is core-compact.

*The category of core-compact topological spaces is not cartesian closed, because even though when $X$ and $Y$ are core-compact, we can build the exponential object $Y^X$, but $Y^X$ will not necessarily be itself core-compact.

*The category of Core-compactly generated spaces is cartesian closed.

*The category of Core-compactly generated spaces contains the category of core-compact spaces.
It seems that there is a contradiction if the four propositions are all true. A sub-category of the category of topological spaces cannot be cartesian closed if it is not strictly included in the sub-category of core-compact spaces. What Am i getting wrong here ?

A: Andrej and Qiaochu are right. Let me elaborate. If X and Y are core-compactly generated (ccg for short), then the exponential in the category of topological spaces need not exist (it exists iff X is core compact). But the exponential always exists in the category CCG. You have to take into account the facts that (1) the finite products change when you pass to a subcategory (there are fewer spaces to test the universal property), (2) consequently the exponentials change too. Thus CCG is cartesian closed without contradicting the fact that the exponential of two ccg spaces in CCG is not an exponential in the whole category of topological spaces.


text:
Q: How is it called when a police officer puts handcuffs on a criminal? In Spanish, when a police officer traps a criminal it's called "reduce", i.e. "El policía redució al criminal". The literal translation of "reduce" to English is also reduce, but I believe this is one of the meaning the English word doesn't have (correct me if I'm wrong). Therefore, how should I call the act of a criminal being handcuffed or trapped by the police?

A: Arrest.

The criminal was arrested by the police.

Arrest does have a legal sense, when the police take somebody's freedom. They would normally handcuff someone when they are arrested.
Alternative possibilities
"Subdue" means "bring under control". Police officers learn to subdue a knife-wielding criminal without lethal force.
"overcome" It took three officers to overcome the violent criminal.
"restrain". The criminal was restrained by one officer while a second called for backup.
The only example I could find online of the use of "reduce" was "la policía redució al atacante a tiros." which seems to indicate that "Police shot the attacker".

A: The question was about putting handcuffs on a person. For that the word must surely be "restrain".
Arrest has a technical meaning in English law, and although @James K is right in saying that the police might well handcuff a person who has been arrested, that is incidental to the legal effect of arrest. It is certain that an arrest can occur without handcuffs being involved in any way. For example a prisoner already in jail for one crime might be arrested for another alleged offence.

A: The word is detained. You can be cuffed while being detained for questioning and to ensure safety while figuring out a situation.
You can be detained and handcuffed without being legally arrested.
The officer has to tell the suspect that they haven't yet been arrested or charged with a crime, that the officer is handcuffing to ensure safety, and that they may be released after the questioning.


text:
Q: Highlight New Posts for Returning Visitors in Wordpress I am working on highlighting new content in wordpress multisite so that I attract visitor's attention to the latest content. To achieve this. In your functions.php you need to add:
function wpb_lastvisit_the_title ( $title, $id ) {

if ( !in_the_loop() || is_singular() || get_post_type( $id ) == 'page' ) return $title;

// if no cookie then just return the title

if ( !isset($_COOKIE['lastvisit']) ||  $_COOKIE['lastvisit'] == '' ) return $title;
$lastvisit = $_COOKIE['lastvisit'];
$publish_date = get_post_time( 'U', true, $id );
if ($publish_date > $lastvisit) $title .= 'New';
return $title;

}

add_filter( 'the_title', 'wpb_lastvisit_the_title', 10, 2);

// Set the lastvisit cookie

function wpb_lastvisit_set_cookie() {

if ( is_admin() ) return;
$current = current_time( 'timestamp', 1);
setcookie( 'lastvisit', $current, time()+60+60*24*7, COOKIEPATH, COOKIE_DOMAIN );
}

add_action( 'init', 'wpb_lastvisit_set_cookie' );

In your CSS, you need to add:
.new-article {
background: #feffdd;
padding: 3px;
border: 1px solid #eeefd2;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
margin-left:5px;
font-size: small;
font-weight: bold;
}

This only works on wordpress single site install, it does not work on wordpress multisite. Do I have anything missing? I need this work on wordpress multisite.
Thanks


text:
Q: Purpose of no-codegen option on crystal build? What is purpose of no-codegen option when building crystal project ?
I have quite large codebase and when building without this option, it can take up to 20 seconds to build. When I use no-codegen option, it reduces build time to 6 seconds. But I don't understand can executable be debugged when that option is included (currently I debug using LLDB when building with --debug flag)?

A: In short, it allows to check things are alright, but without generating a binary.
In long, there are four main phases within the Crystal compiler:

*

*Typechecking and macro expansion

*Code generation to LLVM

*Optimization (by LLVM)

*Binary generation (by LLVM)

Each process takes some time. In the first phase, the compiler just checks all the types and expand the macros in your program. In the second phase, the dead code is thrown away, some other language-specific optimizations take place, and the program is generated as LLVM. In the fourth phase (only with --release), Crystal calls LLVM to peform many optimization of the generated code. In the last phase LLVM creates the platform-specific binary.
In your case, it's taking 6s to do typechecking, and ~14s to do all the other phases (but 3).

A: --no-codegen means no code is generated. It does not produce any binary.
The purpose of this flag is to check the validity of a program, without actually building it. This is useful when you can't execute the result anyway, then the binary generation can be skipped. For example, this is used for the code examples in the Crystal repo: They are built in CI with --no-codegen just to check that the code is valid, but verifying their execution is out of scope for automated tests.


text:
Q: HTTP connection gets prematurely terminated in nodejs app hosted on Amazon EC2 I have a REST api hosted on Amazon EC2, which is written with Nodejs (Express).
In a particular REST call, a reply of about 5MB is sent to the client. Before the client completely receives the reply, client prints following error message.
Premature end of Content-Length delimited message body

I added a connection listener in nodejs server like below to check what is going on the server.
var app = express();

var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
server.on('connection', function (socket) {
    log.debug('SOCKET OPENED' + JSON.stringify(socket.address()));
    socket.setTimeout(300000);   //5 minute timeout
    socket.on('end', function () {
        log.debug('SOCKET END: other end of the socket sends a FIN packet');
    });

    socket.on('timeout', function () {
        log.warn('SOCKET TIMEOUT');
    });

    socket.on('error', function (error) {
        log.warn('SOCKET ERROR: ' + JSON.stringify(error));
    });

    socket.on('close', function (had_error) {
        log.debug('SOCKET CLOSED. IT WAS ERROR: ' + had_error);
    });
});

I observed that SOCKET TIMEOUT gets logged in backend. In above code, I have increased the socket timeout to 5 minutes, but it doesn't seem to have any effect.
Earlier I had the REST API hosted in Google compute engine, and I didn't have this problem back then.
What could be the problem here?
Edit: Here is the code of REST API call.
I have following code in my app.js
require('./routes/index')(app);

Following is the index.js of routes directory.
var changeCase = require('change-case');
var express = require('express');
var routes = require('require-dir')();

module.exports = function (app) {
    Object.keys(routes).forEach(function (routeName) {
        var router = express.Router();
        require('./' + routeName)(router);
        app.use('/api/' + changeCase.paramCase(routeName), router);
    });
};

As it can be seen, it loops through all the js files in the routes directory and registers the file name as the URL path in app.
Here is the code of this particular route for which I face this problem.
   module.exports = function (router) {
       router.get("/fetch", function (req, res, next) {
            itemModel.fetch(req.user.clientId, function (error, items) {
                if (error) {
                    res.status(500).json({error: error});
                } else {
                    res.json(items);    //items is a JSON array
                }
            });
        });
    }

A: Setting timeout for the HTTP server resolved the issue.
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
server.setTimeout(300000, function (socket) {
});


text:
Q: Devise and Ruby on Rails: On Sign Up All Validations fail with "Can't be Blank" I am trying to sign up an Affiliate using Devise.
/affiliates/registrations_controller.rb
class Affiliates::RegistrationsController <
    Devise::RegistrationsController
    include StatesHelper, ApplicationHelper

    before_action :configure_sign_up_params, only: [:create]
    before_action :configure_account_update_params, only: [:update]

    # GET /resource/sign_up
    def new
        @plan = AffiliatePlan.find_by(nickname: params.permit(:plan)[:plan].downcase)
        super
    end

    # GET /resource/edit
    def edit
        @states = us_states
        super
    end

    # PUT /resource
    def update
        @states = us_states
        super
        if resource.address_coordinates.length > 1
            resource.services.each{ |s| s.update_attributes( {lonlat: "POINT(#{resource.address_coordinates.join(' ')})"})}
        end
    end

    def update_resource(resource, params)
        resource.update_without_password(params)
    end

    protected

    # If you have extra params to permit, append them to the sanitizer.
    def configure_sign_up_params
        devise_parameter_sanitizer.permit(:sign_up, keys: [:business_name, :website, :phone, :affiliate_plan_id, contact_name: [:first_name, :last_name], address: [:street_address, :address_line2, :city, :state, :zip_code]])
    end

    # If you have extra params to permit, append them to the sanitizer.
    def configure_account_update_params
        devise_parameter_sanitizer.permit(:account_update, keys: [:business_name, :website, :phone, :affiliate_plan_id, contact_name: [:first_name, :last_name], address: [:street_address, :address_line2, :city, :state, :zip_code]])
    end

    # The path used after sign up.
    def after_sign_up_path_for(resource)
        affiliate_signups_path
    end
end

/affiliates/registrations/new.html.erb
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

    <%= devise_error_messages! %>

    <% if @plan %>
        <%= f.hidden_field :affiliate_plan_id, value: @plan.id %>
    <% else %>
        <%= f.hidden_field :affiliate_plan_id, value: resource.affiliate_plan_id %>
    <% end %>

    <%= f.fields_for :contact_name do |n| %>

        <%= n.text_field :first_name, autofocus: true, placeholder: "First Name*", class: "form-control", required: true %>

        <%= n.text_field :last_name, placeholder: "Last Name*", class: "form-control", required: true  %>
     <% end %>

    <%= f.text_field :business_name, placeholder: "Company Name", class: "form-control" %>

    <%= f.email_field :email, autocomplete: "email", placeholder: "Email Address*", class: "form-control", required: true %>

    <%= f.password_field :password, autocomplete: "new-password", placeholder: "Create a Password", class: "form-control", required: true %>

    <%= f.password_field :password_confirmation, autocomplete: "new-password", placeholder: "Confirm Password", class: "form-control", required: true %>

    <%= f.submit "Next", class: "btn btn-primary btn-sm" %>
<% end %>

routes.rb
devise_for :affiliates, path: "partners", controllers: {
  sessions: 'affiliates/sessions',
  registrations: 'affiliates/registrations'
}

When submitting the form I always get validation errors:
7 errors must be fixed
   - Email can't be blank
   - Password can't be blank
   - Password is too short (minimum is 9 characters)
   - Password must contain at least one digit
   - Password must contain at least one punctuation mark or symbol
   - Password must contain at least one upper-case letter
   - Affiliate plan must exist

The log shows an immediate rollback, but no other information:
Started POST "/partners" for 127.0.0.1 at 2020-05-25 14:09:59 -0400
Processing by Affiliates::RegistrationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SowYVWzTqVYdwZWjYjNc3hlGC5UITqt+bKjQuSATOpLcdVGb52x7gEi8p15MmhlZrLNLpD07fCxp5Gya8/cQMg==", "affiliate"=>{"affiliate_plan_id"=>"2", "contact_name"=>{"first_name"=>"Stephen", "last_name"=>"Tilly"}, "business_name"=>"1995", "email"=>"sarwerera@email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Next"}
(0.2ms)  BEGIN
  ↳ app/controllers/affiliates/registrations_controller.rb:18
   (0.2ms)  ROLLBACK
  ↳ app/controllers/affiliates/registrations_controller.rb:18
  Rendering affiliates/registrations/new.html.erb within layouts/application
  Rendered affiliates/registrations/new.html.erb within layouts/application (2.6ms)

I'm not quite sure where to go from there, any ideas?

A: I'll assume you have another Devise resource setup which is why you've created this setup. I'll assume it's User. In that case one of the main reasons could be that Devise is expecting that model as the resource which is why it's throwing erros about missing validations. Since Devise::RegistrationsController is expecting a params[:user] containing the e-mail and password.
Suggestion: If that's the case I would consider associating the Affiliate profile to the existing resource and go on from there. I.e. Affiliate -> belongs:to -> User. It would make your life easier.

A: I think this may work.
We assume that an Affiliate does not have a plan, because he has not yet registered. The Plan must exist!
In the file new.html.erb it is not recommended to use logic, if you want, you can do it in the controller. Sample: before_action :set_plan, only: [:new]
class Affiliates::RegistrationsController < Devise::RegistrationsController
  include StateHelper, ApplicationHelper

  before_action :set_plan, only: [:new]
  before_action :configure_permitted_parameters, only: [:create]

  protected
    def set_plan
      @plan = AffiliatePlan.find_by(nickname: params[:plan])
    end

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) do |user_params|
      user_params.permit([
        :email, :password, :password_confirmation,
        :business_name, :website, :phone, :affiliate_plan_id,
        contact_name: [:first_name, :last_name],
        address: [:street_address, :address_line2, :city, :state, :zip_code]
      ])
    end
  end
end

On the other hand, it would be great if you separated the extra information of the Affiliate from the information of the Affiliate as a user.
Example:
For the User:

Affiliate data is: email, password, password_confirmation, username, etc

For the extra info of Affiliate:

Affiliate Info data is: :business_name, :website, :phone, etc


text:
Q: Are android, ios pip mode is only for the video playback? I am a 5+ years web developer and I am trying to develop an app which supports pip mode using react-native.
Since I have only a minimum understanding of app development, I've read through the android documentation but still I want to ask 2 things.
According to the android pip documentation (https://developer.android.com/develop/ui/views/picture-in-picture),

PiP is a special type of multi-window mode mostly used for video playback

1. Is pip mode only for the video playback?
What I want to do is just to show a certain UI (character) in the right bottom corner of the screen. It definitely is not a video, so I am curious if it is okay to proceed with this approach (pip mode)
2. If pip mode is not only for the video playback, is pip mode switches app into the background mode?
While showing a certain UI in pip mode, still I want to do some calculation in my app.
But as I know, if an app goes into the background mode, there comes a limit calling an external APIs. so if it is in background mode, I will just do the client-side calculation.
I am sorry for asking this question for the native app developers if it is too basic.
Anyway, appreciate in advance for your help.
P.S)
I found this question, Is it possible to use PIP mode which is not for videos?
but I think this is only for the web.
if it is for the video also in the app, is it possible to execute some calculations while playing videos?

A: On Android
1)No.  PIP allows one app to display on top of another in a little window.  So it doesn't need to be video.  However you wouldn't use PIP within your app-  you'd use it to display your app on top of other apps.  If you want to display a character in the bottom right of the screen when your app is on, you'd just add a view there to your layout.
2)No, a PIP app is in the foreground.


text:
Q: Antd Popover freezes the application as I hover Description
My app and Popover were running just fine but when I updated react app to version "^18.0.0-rc.3" from that day on, this problem started to occur.

The code I have written
import React, { useState, useEffect } from 'react'
import { Popover } from 'antd';
const content = (

Generating timestamp on the backend using socket.io

);
const title = (

Socket IO

);
function TimeStamp({ socket }) {
    const [response, setResponse] = useState("");
    useEffect(() => {
        socket.on("getCurrentTime", data => {
            setResponse(data);
        });
    }, [socket]);

    return (

            <Popover content={content} title={title} placement="topLeft">

                            {response ? new Date(response).toLocaleTimeString() : "Loading..."}

            </Popover>

    )
}

export default TimeStamp

The Ui

Github Repo


text:
Q: Does SMS Forward to Mac work if iPhone is turned off? I have a MacBook and an iPhone. The iPhone is setup to forward SMS to my MacBook. If the iPhone is turned off can I still send/receive SMS in Messages on my MacBook?

A: No, iPhone has to be turned on in order for SMS messages to be received by it and then forwarded to your computer, or for you to send messages, which are sent back to the phone and then out to your carrier from there.


text:
Q: Is it possible to rob Marcus a second time? After completing a main story quest, you're teleported back to Sanctuary into a room that is full of chests and other lootable boxes. The obvious thing to do is to take it all. Apparently, this room is Marcus's weapons warehouse and a door leads out into his shop. The door locks behind you and you're not able to get back into it from that side. Is it possible to enter this room again and rob Marcus of more delicious loot?

A: A character can actually be there twice, but sadly only by getting there in the normal playthrough and the "True Vault Hunter" mode playthrough.
Apart from that there is nothing in my personal experience and on the internet suggesting an alternate entrance. The door is locked and there is no quick travel point. Close examination of Marcus entire store yields no success.
It would be amazing considering the amount of gun boxes in there.
So sorry to disappoint, but should anyone discover anything post it immediately!^^

A: Possible solution to this is while playing multiplayer mode, one player must be on that current mission that leads you to Marcus' storage room.
Once in the storage room , loot all you can and trade to the player(s) who isn't hosting that mission. The player(s) with the loot walks out the door while the host stays in the room. That player can then save the loot in their backpack/storage whatever and save/quit. The host player quits without saving thus not finishing that mission. Rinse/Repeat.
Note * Probably best for Host to save and quit before you get to ANGEL core. You will have to repeat the mission's boss fight.


text:
Q: How to count multiple numerical variables in a column in R without installing a package? I'd like to count the number of recurring numerical variables in a given column.
My data set is: mydata
And I have a dataframe that looks like this:
mydata <- structure(list(VARIABLE = c(1, 1, 2, 3, 3, 3, 4, 4)),
  .Names = "VARIABLE",   row.names = c(NA, -8L), class = "data.frame")

mydata
##     VARIABLE
## 1        1
## 2        1
## 3        2
## 4        3
## 5        3
## 6        3
## 7        4
## 8        4

I'd like to calculate the number of 1s,2s,3s,4s in column VARIABLE (Two 1, One 2, Three 3, Two 4). Is there anyway I can do this without installing an additional package?

A: Yes, use table as follows, it comes from the base package:
mydata <- data.frame(VARIABLE = c(1, 1, 2, 3, 3, 3, 4, 4))
table(mydata$VARIABLE)

# 1 2 3 4
# 2 1 3 2

As suggested by Maiasaura, you can turn the output into a nice data.frame:
data.frame(table(mydata$VARIABLE))
#   Var1 Freq
# 1    1    2
# 2    2    1
# 3    3    3
# 4    4    2

A: As an alternative to ?table you could also use ?rle in the instance of wanting to detect "runs" of particular repeating values in a variable/vector. In this instance, you will get the same results as using the table function, though this is not always the case.
mydata <- data.frame(VARIABLE = c(1, 1, 2, 3, 3, 3, 4, 4))
rle(mydata$VARIABLE)

Result:
Run Length Encoding
  lengths: int [1:4] 2 1 3 2
  values : num [1:4] 1 2 3 4

You can subset the results of the rle function as well, like so:
rle(mydata$VARIABLE)$values
[1] 1 2 3 4

rle(mydata$VARIABLE)$lengths
[1] 2 1 3 2


text:
Q: Odd behavior of button in linear layout that has one line of text instead of two I have a linear layout wrapped in a HorizontalScrollView. Everything seems to be working fine except that one of the buttons in the layout is higher then the rest.
The reason this button seems to be higher then the rest of the buttons is because it only has one line of text instead of two.
Here is a screenshot of the problem:

While the layout is being used for a keyboard service, I do not think that is the problem because in the design tab of the XML layout file this problem still occurs.
Here is the layout code for the entire service:
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="50dp">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:id="@+id/tablayout">

    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="What did you say?!"
        android:id="@+id/T_YouSay"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="I identify as a..."
        android:id="@+id/T_Identify"
        android:textSize="12sp"
        android:textAllCaps="false"/>

//This button is the one that is higher then the rest. Notice how
//it is only one line of text instead of two.
    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="That's some..."
        android:id="@+id/Thats_some"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="Here's the thing..."
        android:id="@+id/theThing"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="Other copypastas"
        android:id="@+id/tab_Misc"
        android:textSize="12sp"
        android:textAllCaps="false"/>

</LinearLayout>

</HorizontalScrollView>

So, why is a button with only one line of text higher then the others in this Linear Layout wrapped in a HorizontalScrollView and what can I do to fix it?

A: Add
android:baselineAligned="false"

to your LinearLayout containing the buttons (id == tabLayout).

A: The easy and simple solution is to just add gravity attribute to the LinearLayout of @id/tablayout.
android:gravity="center_vertical"

A: You can use weights to assign equal space to your button. Hard codeding widths might not be a good idea as you your buttons will not be taking advantage of big screens and landscape mode . here is enhanced version of your layout.

<LinearLayout
    android:weightSum="5"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/tablayout">

    <Button
         android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="What did you say?!"
        android:id="@+id/T_YouSay"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
         android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="I identify as a..."
        android:id="@+id/T_Identify"
        android:textSize="12sp"
        android:textAllCaps="false"/>

//This button is the one that is higher then the rest. Notice how
//it is only one line of text instead of two.
    <Button
         android:layout_weight="1"
         android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="That's some..."
        android:id="@+id/Thats_some"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
         android:layout_width="0dp"
         android:layout_weight="1"
        android:layout_height="50dp"
        android:text="Here's the thing..."
        android:id="@+id/theThing"
        android:textSize="12sp"
        android:textAllCaps="false"/>

    <Button
         android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:text="Other copypastas"
        android:id="@+id/tab_Misc"
        android:textSize="12sp"
        android:textAllCaps="false"/>

</LinearLayout>

</LinearLayout>

Result


text:
Q: How to install web browser and browsing website in linx vps/dedicated server I have a centos vps server. I want to install web browser on my server and browsing website from installed web browser. Is it possible. If possible please, help me sharing your idea. Thanks

A: There are several possibilities for doing this:

*

*Install a full graphical environment and then
a. Use X-Forwarding and run a browser on the remote server.
b. Use remote desktop/VNC to connect remotely to the server.

*Install a proxy server and proxy your web browsing through it.

*Install a VPN server and connect your computer to the VPN.

In the last two options, you would be running your browser on your local computer, but your network traffic will go out through the server, so you will appear to be coming from the server's IP address.


text:
Q: Multiple filters not working elasticsearch rails In my Invoice Model i have 3 term filters defined in 3 separate methods. The query works fine but at a time only filter is applied on the query.
If i change the order of the filters then only the top filter is applied remaining two filters are ignored.
Following is the code of model:
Invoice.search(self.search_options(options, qry))

def self.search_options(options, qry)
  [query(qry),
   status_filter(options[:status]),
   state_filter(options[:invoice_state]),
   office_filter(options[:current_office_id]),
   aggregates
  ].compact.reduce(:merge)
end

def self.status_filter(status)
  {filter: {term: {invoice_status: status}}}
end

def self.state_filter(state)
  {filter: {term: {state: state}}}
end

def self.office_filter(current_office_id)
  {filter: {term: {office_id: current_office_id}}}
end

How can i apply all the 3 filters at a time ?


text:
Q: How to bring view in front of everything? I have activity and a lot of widgets on it, some of them have animations and because of the animations some of the widgets are moving (translating) one over another. For example the text view is moving over some buttons . . .
Now the thing is I want the buttons to be always on the front. And when the textview is moving I want to move behind the buttons.
I can not achieve this I tried everything I know, and "bringToFront()" definitelly doesn't work.
note I do not want to control  the z-order by the order of placing element to layout cause I simply can't :), the layout is complex and I can not place all the buttons at the begging of the layout

A: With this code in xml
 android:translationZ="90dp"

A: i have faced the same problem.
the following solution have worked for me.
 FrameLayout glFrame=(FrameLayout) findViewById(R.id.animatedView);
        glFrame.addView(yourView);
        glFrame.bringToFront();
        glFrame.invalidate();

2nd solution is by using xml adding this attribute to the view xml
android:translationZ=""

A: I've been looking through stack overflow to find a good answer and when i couldn't find one i went looking through the docs.
no one seems to have stumbled on this simple answer yet:
ViewCompat.setTranslationZ(view, translationZ);

default translation z is 0.0

A: You can try to use the bringChildToFront, you can check if this documentation is helpful in the Android Developers page.

A: An even simpler solution is to edit the XML of the activity. Use
android:translationZ=""

A: There can be another way which saves the day. Just init a new Dialog with desired layout and just show it. I need it for showing a loadingView over a DialogFragment and this was the only way I succeed.
Dialog topDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
topDialog.setContentView(R.layout.dialog_top);
topDialog.show();

bringToFront() might not work in some cases like mine. But content of dialog_top layout must override anything on the ui layer. But anyway, this is an ugly workaround.

A: You can use BindingAdapter like this:
@BindingAdapter("bringToFront")
public static void bringToFront(View view, Boolean flag) {
    if (flag) {
        view.bringToFront();
    }
}

  <ImageView
        ...
        app:bringToFront="@{true}"/>

A: bringToFront() is the right way, but, NOTE that you must call bringToFront() and invalidate() method on highest-level view (under your root view), for e.g.:
Your view's hierarchy is:
-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6

So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView. To bring it over (above) the ImageView you must call bringToFront() and invalidate() method on your LinearLayouts. Then it will work :)
**NOTE: Remember to set android:clipChildren="false" for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:
.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hw="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_theme_color"
    android:orientation="vertical" >

    <com.binh.helloworld.customviews.HWActionBar
        android:id="@+id/action_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_actionbar_height"
        android:layout_alignParentTop="true"
        hw:titleText="@string/app_name" >
    </com.binh.helloworld.customviews.HWActionBar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/action_bar"
        android:clipChildren="false" >

        <LinearLayout
            android:id="@+id/layout_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>

        <ImageView
            android:id="@+id/imgv_main"
            android:layout_width="@dimen/common_imgv_height"
            android:layout_height="@dimen/common_imgv_height"
            android:layout_centerInParent="true"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:id="@+id/layout_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

Some code in .java
private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example)
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);

GLuck!

A: The order of the overlapping views really depends of 4 things:

*

*The attribute android:elevation which is measured in dp/sp

*The attribute android:translationZ which is also measured in dp/sp.

*In Constraint Layout, the order in which you put the views in your Component Tree is also the order to be shown.

*The programmatically order that you set through methods like view.bringToFront() in your kotlin/java code.

The numerals 1 and 2 compite with each other and take preference over the points 3 and  4: if you set elevation="4dp" for View 1 and translationZ="2dp" for View 2, View 1 will always be on top regardless of the numerals 3 and 4.

A: Try FrameLayout, it gives you the possibility to put views one above another. You can create two LinearLayouts: one with the background views, and one with foreground views, and combine them using the FrameLayout. Hope this helps.

A: If you are using ConstraintLayout, just put the element after the other elements to make it on front than the others

A: You can call bringToFront() on the view you want to get in the front
This is an example:
    yourView.bringToFront();

A: Thanks to Stack user over this explanation, I've got this working even on Android 4.1.1
((View)myView.getParent()).requestLayout();
myView.bringToFront();

On my dynamic use, for example, I did
public void onMyClick(View v)
     {
     ((View)v.getParent()).requestLayout();
     v.bringToFront();
     }

And Bamm !

A: You can use elevation attribute if your minimum api level is 21. And you can reorder view to the bottom of other views to bring it to front. But if elevation of other views is higher, they will be on top of your view.

A: If you are using a LinearLayout you should call myView.bringToFront() and after you should call parentView.requestLayout() and parentView.invalidate() to force the parent to redraw with the new child order.

A: Arrange them in the order you wants to show. Suppose, you wanna show view 1 on top of view 2. Then write view 2 code then write view 1 code. If you cant does this ordering, then call bringToFront() to the root view of the layout you wants to bring in front.

A: Try to use app:srcCompat instead of android:src

A: You can set visibility to false of other views.
view1.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
...

or
view1.setVisibility(View.INVISIBLE);
view2.setVisibility(View.INVISIBLE);
...

and set
viewN.setVisibility(View.VISIBLE);

A: You need to use framelayout. And the better way to do this is to make the view invisible when thay are not require. Also you need to set the position for each and every view,So that they will move according to there corresponding position


text:
Q: mvvmcross navigation issue, getting exception: Could not find view for [ViewModelName] I seem to be confused at how to make MvvmCross detect my ViewModels that are associated with views in Mono for Android. I tried to follow TwitterSearch in implementing the navigation but it just won't work.
RequestNavigate<LoginViewModel>();

here's my view:
[Activity(Label = "Login")]
public class LoginActivity : MvxBindingActivityView<LoginViewModel>
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        App.InitializeRestConnection(this);
    }

    protected override void OnViewModelSet()
    {
        SetContentView(Resource.Layout.LoginBindable);
    }

}

here's the exception:
I/ActivityManager(  307): Displayed com.desco.pendulum/pendulum.androidapp.SplashScreenActivity: +1s373ms (total +4s420ms)
I/Navigation( 8643):   0.50 Navigate to LoginViewModel with args
I/mono-stdout( 8643): Navigation:Diagnostic:  0.50 Navigate to LoginViewModel with args
I/MonoDroid( 8643): UNHANDLED EXCEPTION: System.Collections.Generic.KeyNotFoundException: Could not find view for dESCO.Mobile.ViewModels.LoginViewModel
I/MonoDroid( 8643): at Cirrious.MvvmCross.Views.MvxViewsContainer.GetViewType (System.Type) <0x001a4>
I/MonoDroid( 8643): at Cirrious.MvvmCross.Droid.Views.MvxAndroidViewsContainer.GetIntentFor (Cirrious.MvvmCross.Views.MvxShowViewModelRequest) <0x00023>
I/MonoDroid( 8643): at Cirrious.MvvmCross.Droid.Views.MvxAndroidViewPresenter.Show (Cirrious.MvvmCross.Views.MvxShowViewModelRequest) <0x00037>
I/MonoDroid( 8643): at Cirrious.MvvmCross.Droid.Views.MvxAndroidViewDispatcher/<>c__DisplayClass1.<RequestNavigate>b__0 () <0x0002f>
I/MonoDroid( 8643): at Java.Lang.Thread/RunnableImplementor.Run () <0x0003f>
I/MonoDroid( 8643): at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) <0x00037>
I/MonoDroid( 8643): at (wrapper dynamic-method) object.7060b187-418d-4bca-ad4f-8b9cae936501 (intptr,intptr) <0x0003b>

any suggestions?

A: I can't see anything obviously wrong with your setup.
The default Droid framework setup looks for classes which implement IMvxAndroidView in the ExecutingAssembly using the logic in: https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross/Platform/MvxBaseSetup.cs#L200
So I can't see any obvious reason why your LoginActivity View isn't being picked up.
One quick thing you could do is to add some debug code to your Setup.cs to see what views are being detected:
  protected override IDictionary<Type, Type> GetViewModelViewLookup()
  {
      var toReturn = base.GetViewModelViewLookup();
      MvxTrace.Trace("Tracing viewModels and views");
      foreach (var kvp in toReturn)
      {
          MvxTrace.Trace("Seen pair {0} : {1}", kvp.Key.Name, kvp.Value.Name);
      }
      return toReturn;
  }

If that shows the list is empty or missing your activity, then I'm afraid we'd need to step through the reflection logic to find out why it's not picking up your Activity.

In real desperation, you could also fake the results:
  protected override IDictionary<Type, Type> GetViewModelViewLookup()
  {
      return new Dictionary<Type,Type>() { { typeof(LoginViewModel), typeof(LoginActivity) } };
  }

But this probably isn't the right long-term solution for you

If this is caused by some kind of 'solution setup' difference - e.g. if you have somehow put your Setup.cs in a different project to your views - then it may be that somehow overriding the default convention will help you.
To achieve this, in you Setup.cs, override the code:
    public virtual Assembly ExecutableAssembly
    {
        get { return GetType().Assembly; }
    }

    protected override IDictionary<System.Type, System.Type> GetViewModelViewLookup()
    {
        return GetViewModelViewLookup(ExecutableAssembly, typeof (IMvxAndroidView));
    }

in the base setup class - https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Droid/Platform/MvxBaseAndroidSetup.cs
This can be done either by overriding the ExecutingAssembly property (although this seems a bit wrong given it's name) or by overriding the GetViewModelViewLookup method. For example, if you wanted to look in several separate assemblies you could use:
    public List<Assembly> MyViewAssemblies { get; set; }

    protected override IDictionary<System.Type, System.Type> GetViewModelViewLookup()
    {
        var toReturn = new Dictionary<Type, Type>();

        foreach (var assembly in MyViewAssemblies)
        {
            var contributions = base.GetViewModelViewLookup(assembly, typeof (IMvxAndroidView));
            foreach (var kvp in contributions)
            {
                toReturn[kvp.Key] = kvp.Value;
            }
        }

        return toReturn;
    }


text:
Q: About double points of an immersion If we have an immersion $f:M^n\to\mathbb{R}^{2n}$, where $M^n$ denotes a smooth $n$-manifold, then the double points of $f$ (that is, points $a\in\mathbb{R}^{2n}$ such that there exists $x\neq y$ in $M^n$ with $f(x)=f(y)=a$) form a discrete set or only of zero measure?

A: I think the topologists sin curve lends itself to make an example where the set of double points is not discrete.
Let $f\colon (0,\infty)\to \mathbb R^2$ be defined by
$$
f(t) = \left\{\begin{array}{cc} (t,sin(1/t)) & t\in (0,1] \\
g(t) & t \in (1,2)\\
(t-2,0) & t\geqslant 2.
\end{array}\right.
$$
Here $g(t)$ is any curve such that $f$ becomes smooth, and such that $(0,0)$ becomes a double point. Then $(0,0)$ is not discrete among the double points.
This wouldn't work if we asked $f$ to be proper.
Edit:
I have given this some more thought and would like to address the concerns of Ted Shifrin in the comments. There is a way to get a more concrete $g$, as well as a fix to make the example work for $f$ proper.
We start out by proving a lemma:

Let $f\colon \mathbb R\to \mathbb R^2$ be a continuous map which is
smooth on $\mathbb R\backslash \sqcup_{j=1}^k[a_j,b_j]$. Then for any $\epsilon,\
\epsilon'>0$ we can find a smooth map $f_\epsilon\colon \mathbb R\to \mathbb R^2$ such that for $x\in\mathbb R\backslash \sqcup_{j=1}^k[a_j-\epsilon',b_j+\epsilon']$, $f(x)=g(x)$, and for any $x\in\mathbb R$
we have $|f(x)-g(x)|\leqslant \epsilon$.

Proof: We will just prove this for $k=1$; clearly applying the same technique $k$ times will then prove the result for any $k$. We use the technique of the proof of [1, Theorem 2.2. p.44]. Since $f$ is continuous, there is for each $t\in \mathbb R$ an open neighborhood $U_t$ of $t$ such that for each $t'\in U_t$ we have $|f(t)-f(t')|\leqslant \epsilon$. On $U_t$ we consider the constant function $c_t(x)=f(t)$. Let $\mathscr U = \{U_i\}_{i\in I}$ be a finite subset of $\{U_t\}_{t\in \mathbb R}$ such that $\bigcup_{i\in I}U_i\supset [a,b]$. Shrinking the open sets containg $a$ and $b$ if necessary, we can assume
$$
[a,b]\subset\bigcup_i U_i\subset (a-\epsilon',b+\epsilon').
$$
Let $\{\lambda_i\}$ be a smooth partition of unity on $[a,b]$ subordinate to $\mathscr U$. By this we mean that $\mathrm{supp}\lambda_i\subset U_i$, that $0\leqslant \lambda_i(t)\leqslant 1$, and that $\sum_i\lambda_i(t)=1$ for $t\in [a,b]$. Consider the map $f_\epsilon:\mathbb R\to\mathbb R^2$ defined by
$$
f_\epsilon(t) = (1-\sum_i \lambda_i(t))\cdot f(t)+ \sum_i\lambda_i(t)\cdot c_i(t).
$$
Then $f_\epsilon$ is smooth, equal to $f$ outside of $\bigcup_i U_i$, and satisfies for all $t\in\mathbb R$:
\begin{align*}
|f(t)-f_\epsilon(t)| &= |f(t)-(1-\sum_i\lambda_i(t))\cdot f(t)+\sum_i\lambda_ic_i(t)|\\
&= |f(t)-f(t)-\sum_i\lambda_i(t)(f(t)-c_i(t))| \\
&< \sum_i \lambda_i\cdot \epsilon\leqslant \epsilon
\end{align*}
This proves the lemma.
Using this, we can redefine $f(t)$ as follows. First we just draw the straight line from $(1,sin(1))$ through the origin, down to $(-1,-sin(1)$. Then we go up to the $x$-axis. Then for $t\geqslant 2$ we use $t\mapsto (t-3,0)$. We then smooth out the three non-smooth points of $f$ using the above lemma.
We can also get a proper $f$. I tried to use $\left(t,\exp\left(-\frac{1}{t^2}\right)\cdot \sin(1/t)\right)$ instead of $sin(1/t)$, but then the selfintersection at the origin is not transverse.
[1] Hirsch, Morris W., Differential topology, Graduate Texts in Mathematics. 33. New York - Heidelberg - Berlin: Springer-Verlag. (1976). ZBL0356.57001.


text:
Q: how can i get user's favorite video of youtube using JSONHTTPClient? I am working on the youtube app. i want to get users favourite video using JSON.
I am using following code
  NSString *strURL=[NSString stringWithFormat:@"http://gdata.youtube.com/feeds/api/users/%@/favorites",auth.userEmail];
     [JSONHTTPClient getJSONFromURLWithString: strURl
                                      completion:^(NSDictionary *json, JSONModelError *err) {

                                      if (err) {
                                          HideProgress();

                                          [[[UIAlertView alloc] initWithTitle:@"Error"
                                                                      message:@"Please try different keywords or try again later"
                                                                     delegate:nil
                                                            cancelButtonTitle:@"Ok"
                                                            otherButtonTitles: nil] show];
                                          return;
                                      }

                                      //initialize the models
                                      videos = [VideoModel arrayOfModelsFromDictionaries:
                                                json[@"feed"][@"entry"]
                                                ];
                                      if (videos) {
                                          //show the videos
                                          [self showVideos];
                                      } else {
                                          HideProgress();

                                          [[[UIAlertView alloc] initWithTitle:@"Error"
                                                                      message:@"Please try different keywords or try again later"
                                                                     delegate:nil
                                                            cancelButtonTitle:@"Ok"
                                                            otherButtonTitles: nil] show];
                                      }
                                  }];

}

But I am getting error that says:Error Domain=JSONModelErrorDomain Code=1 "Bad network response." UserInfo=0x923d8a0 {NSLocalizedDescription=Bad network response.}


text:
Q: What happens to the Correlation coefficient for a multilevel random intercept regression? Suppose we have a two level random intercept regression model:
that is, for i = 1,...n, $$X_{i} \sim N(\mu_{xi}, \sigma_{xi}) $$ and $$Y_{i} \sim N(\mu_{yi}, \sigma_{yi})  $$ where $$\mu_{yi} = a_{i} + \mu_{xi} * b$$ and $$a_{i} \sim N(\alpha, \psi)$$.
How would we compute the correlation coefficient in this case? is there something similar to the relationship for simple linear regression $$b = \rho\frac{\sigma_{y}}{\sigma_{x}}$$


text:
Q: How to update xml value with latest? I have input.xml file like following.
<Root>

        Success
        <Maintain>Install period</Maintain>

        failure
        <Maintain>uninstall period</Maintain>

        failure
        <Maintain>discard period</Maintain>

        Done
        <Maintain>Got Output</Maintain>

    </Root>

I used this input.xml and write it on output.xml by using following code.
XmlDocument xml = new XmlDocument();
xml.Load(@"C:\input.xml");
XmlNodeList MainNameList = xml.SelectNodes("/Root/Main");
XmlNodeList MainDetailsList = xml.SelectNodes("/Root/Main/Details");
XmlNodeList MainMaintainList = xml.SelectNodes("/Root/Main/Maintain");
for (int count = 0; count < MainNameList.Count; count++)
{
    string mainName = MainNameList[count].Attributes[0].Value;
    string mainDetails = MainDetailsList[count].InnerText;
    string mainMaintain = MainMaintainList[count].InnerText;
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml("<Root></Root>");
    XmlNode MainNode = xmldoc.SelectSingleNode("Root").AppendChild(xmldoc.CreateElement("Main"));
    MainNode.Attributes.Append(xmldoc.CreateAttribute("Name")).Value = mainName;
    MainNode.AppendChild(xmldoc.CreateElement("Details")).InnerText = mainDetails;
    MainNode.AppendChild(xmldoc.CreateElement("Maintain")).InnerText = mainMaintain;
}
xmldoc.Save(@"C:\output.xml");

But I need output xml like following:
<Root>

   failure
    <Maintain>uninstall period</Maintain>

    failure
    <Maintain>discard period</Maintain>

    Done
    <Maintain>Got Output</Maintain>

</Root>

i.e. I need Main element's latest entry only. Like the same for all element, latest element's details only should enter in output.xml file. help me for this. thanks in advance.

A: I personally find XDocument from  System.Xml.Linq namespace easier to manipulate than XmlDocument. The code below does what you want (I think it's pretty self-explanatory):
        XDocument xDoc1 = XDocument.Load(inputFileName);

        var elems = xDoc1.Element("Root").Elements("Main");

        XElement xInstall = elems.LastOrDefault(a => a.Attribute("Name").Value == "Install");
        XElement xUninstall = elems.LastOrDefault(a => a.Attribute("Name").Value == "Uninstall");
        XElement xDiscard = elems.LastOrDefault(a => a.Attribute("Name").Value == "Discard");

        XDocument xdoc2 = new XDocument();

        xdoc2.Add(
            new XElement("Root", new XElement[]
            {
                xInstall,
                xDiscard,
                xUninstall
            })
        );

        xdoc2.Save(ouputFileName);

A: If i understand correctly, and you want every last main element with distinct name attribute, then this should work for you. You just need to change the path to input and ouput elements
try
{
       const string uninstallName = "Uninstall";
       const string installName = "Install";
       const string discardName = "Discard";
       const string nameAttribute = "Name";
       const string mainElement = "Main";
       const string rootElement = "Root";

       XDocument xdoc = XDocument.Load("../../input.xml");
       XElement root = xdoc.Root;
       if (root == null)
           throw  new Exception("No root element found");
       var mains = root.Elements(mainElement);
       if (!mains.Any())
           throw new Exception(String.Format("No element named {0} was found", mainElement));
       var lastInstall = mains.LastOrDefault(m => m.Attribute(nameAttribute).Value == installName);
       var lastDiscard = mains.LastOrDefault(m => m.Attribute(nameAttribute).Value == discardName);
       var lastUninstall = mains.LastOrDefault(m => m.Attribute(nameAttribute).Value == uninstallName);

       XDocument output = new XDocument();
       output.Add(new XElement(rootElement));
       if (lastUninstall != null)
           output.Root.Add(lastUninstall);
       if (lastDiscard != null)
           output.Root.Add(lastDiscard);
       if (lastInstall != null)
           output.Root.Add(lastInstall);
       output.Save("output.xml");

}
catch (Exception ex)
{
     // log, write to output or anything
}


text:
Q: R cumulative sum with condition (For those of you that are familiar with MCMC I am trying to write (a step of) the Metropolis-Hastings algorithm).
I am trying to do a cumulative sum of a vector of small random values with a starting value of 0.5. However, if the cumulative sum at any point gets under 0 or over 1 I need to copy the previous value and continue on the cumulative sum, without summing the values, which would break this condition.
Note: I need a vectorized solution (no loops or indices) for optimization purposes or something fast. Bonus points for using only base R functions.
Example:
set.seed(1)
temp=c(0.5,runif(20,-0.3,0.3))
cumsum(temp)

 [1] 0.5000000 0.3593052 0.2825795 0.3262916 0.5712162 0.3922254 0.6312592
 [8] 0.8980644 0.9945430 1.0720115 0.8090832 0.6326680 0.4386020 0.5508157
[15] 0.4812780 0.6431828 0.6418024 0.7723735 1.0675171 0.9955382 1.1620054

But what I need is
 [1] 0.5000000 0.3593052 0.2825795 0.3262916 0.5712162 0.3922254 0.6312592
 [8] 0.8980644 0.9945430 0.9945430 0.7316148 0.5551995 0.3611336 0.4733473
[15] 0.4038095 0.5657144 0.5643339 0.6949050 0.9900487 0.9180698 0.9180698

Using a for loop we could do this with
for (i in 2:21) {
    temp[i]=temp[i-1]+temp[i]
    if(temp[i]<0 | temp[i]>1) {
        temp[i]=temp[i-1]
    }
}

A: A faster C++ version:
library(Rcpp)
Cpp_boundedCumsum <- cppFunction('NumericVector boundedCumsum(NumericVector x){
  int n = x.size();
  NumericVector out(n);
  double tmp;
  out[0] = x[0];
  for(int i = 1; i < n; ++i){
     tmp = out[i-1] + x[i];
     if(tmp < 0.0 || tmp > 1.0)
        out[i] = out[i-1];
     else
        out[i] = tmp;
  }
  return out;
}')

Comparison with R version:
R_boundedCumsum <- function(x){
    for (i in 2:length(x)){
        x[i] <- x[i-1]+x[i]
        if(x[i]<0 || x[i]>1)
            x[i] <- x[i-1]
    }
    x
}

x <- runif(1000)
all.equal(R_boundedCumsum(x), Cpp_boundedCumsum(x))
[1] TRUE

library(microbenchmark)
microbenchmark(R_boundedCumsum(x), Cpp_boundedCumsum(x))
Unit: microseconds
                 expr      min        lq       mean   median       uq      max neval
   R_boundedCumsum(x) 2062.629 2262.2225 2460.65661 2319.358 2562.256 4112.540   100
 Cpp_boundedCumsum(x)    3.636    4.3475    7.06454    5.792    9.127   25.703   100


text:
Q: Replace list name with variable I have several dictionaries for each day of the week, Sunday ["a", "b", "c"], Monday ["d", "f", "g"], and so on, they are located in another script (xscript.py), and I would want to print them out depending on the day of the week I'm currently on, something like this:
import datetime
import xscript

def print_daily_list():
    day_of_week = datetime.datetime.today().weekday()
    print(xscript.day_of_week)

I wouldn't want to create a bunch of if statements to replace day_of_week with "Sunday" or "Monday" depending on the day.

A: I believe you can make a dictionary in xscript.py
dic = { 'Monday': ['a', 'b'], 'Sunday': ['e', 'f']}  # and all the weeks

and to access that I recommend creating a function in xscript, say
def get_dict(key):
    return dic.get(key, "Default List")

And now in your main file, you can call it like:
print(xscript.get_dict(day_of_week)

A: Store them in a dictionary
days = {
    'Sunday': ['a', 'b', 'c'],
    'Monday': [1, 2, 3],
    'Tuesday': ['a', 'b', 'c'],
    'Wednesday': [1, 2, 3],
    'Thursday': ['a', 'b', 'c'],
    'Friday': [1, 2, 3],
    'Saturday': [1, 2, 3],
}

Then pass the day of the week to your script, and call the dictonary with the day.
days[day]

A: This solution uses getattr to get the attribute of an object in this instance the module xscript. If the script module has a variable named Thursday and today is Thursday this script will get and print that variable.
day_of_week = datetime.datetime.today().strftime('%A')
print(getattr(xscript, day_of_week))


text:
Q: Splitting output power of a PFC stage to three flyback converters I want to design three flyback converters whose input is taken from a single power factor correction circuit based on boost converter topology. The PFC stage delivers 200 W (400 V, 0.5 A), and I want three flyback converters one with an output of 150 W (200 V, 0.75 A), another of 25 W (25 V, 1 A) and another of 5 W (12 V, 0.6 A). How can I achieve this, with stable outputs from all converters?

A:
The PFC stage delivers 200W(400V,0.5A), and I want three flyback
converters one with an output of 150W(200V,0.75A), another of
25W(25V,1A) and another of 5W(12V,0.6A). How can I achieve this, with
stable outputs from all converters.

That's an input power of 200 watts and an output power of 180 watts. That's an anticipated power efficiency of 90%.
It will be tricky to achieve this because flyback converter power efficiency is more likely to be a shade under 90%. So, maybe you could just about have all three flyback converters feeding a net load power of about 175 watts. I think a total load power of 180 watts might be difficult unless you are going to compromise and make one flyback converter with multiple outputs.
The power saving for one converter (using only one controller chip) might just get you where you need to be but, there will be load regulation compromises you need to take into account.


text:
Q: How to pass delegates and "normal type" arguments in a function I will explain my problem directly with code. Initially, I had the code below:
class Program
{
   private static Obj A = new Obj(...);

   private static void Function(Func<object[]> m)
   {
      object[] result = m();
      ...
   }

   static void main()
   {
      double a,b,c = 0;
      string d = " ";
      Function(() => A.MethodX(a,b,c));
      Function(() => A.MethodY(d,a,b));
      ...
   }
}

This allows me to use a same function in which I can use any methods of my object. Now, what I'm asking for is: is it possible to have another argument in this function so it will be like:
class Program
{
   private static Obj A = new Obj(...);

   private static void Function(List<string> b, Func<object[]> m)
   {
      object[] result = m();
      ...uses my other argument
   }

   static void main()
   {
      List<string> x = new List<string>();
      double a,b,c = 0;
      string d = " ";
      //Function(() => A.MethodX(a,b,c)); -> How to give my List named "x" to the Function ?
      ...
   }
}

And if yes, how can I implement it ?
Thanks !

A: Simple; pass x as the first argument:
static void main()
{
    List<string> x = new List<string>();
    double a,b,c = 0;
    string d = " ";
    Function(x, () => A.MethodX(a,b,c));
}


text:
Q: In R, test whether coefficients in lm are different each to a given value (other than zero) In R, is there a way to use the lm function to test for the hypothesis that the coefficients are different from a value other than zero? For instance, if the model is:
Y = a + b1x1 + b2x2 + b3x3 + e

It is easy to test whether a single b is different from an arbitrary number. If you wanna test for b1 = 10, then you can estimate:
h0 <- lm(Y ~ offset(10*x1) + x2 + x3)
h1 <- lm(Y ~ x1 + x2 + x3)
anova(h0,h1)

However, what if you want to test at the same time that a=3, b1=10, b2=9 and b3=4 but get the p-values for each? Then an anova would only test whether those restrictions are all true at the same time or not. Is there a way to test such restrictions at once but get the p-values of each coefficient?

A: It's not clear what your confusion is... but the model
$$Y = X \beta + Z \gamma + \varepsilon$$
Can be equivalently expressed as
$$\left( Y - X\beta^0 \right) = X \left( \beta - \beta^0 \right) + Z\gamma + \varepsilon$$
If we're trying to directly test that $\beta = \beta^0$.

A: Rather than using anova() to carry out the F test, you can also use summary() to get the marginal Wald tests for each coefficient. So it is easy to simply include the entire offset of all terms and then use summary(). Here, I use some artificial data with coefficients as suggested in your post:
set.seed(1)
d <- data.frame(
  x1 = runif(100, -1, 1),
  x2 = runif(100, -1, 1),
  x3 = runif(100, -1, 1)
)
d$y <- 3 + 10 * d$x1 + 9 * d$x2 + 4 * d$x3 + rnorm(100)
m <- lm(y ~ x1 + x2 + x3, data = d,
  offset = 3 + 10 * x1 + 9 * x2 + 4 * x3)
summary(m)
## Call:
## lm(formula = y ~ x1 + x2 + x3, data = d, offset = 3 + 10 * x1 +
##     9 * x2 + 4 * x3)
##
## Residuals:
##      Min       1Q   Median       3Q      Max
## -3.00507 -0.67884 -0.08825  0.68643  2.55013
##
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)  0.03520    0.10947   0.322    0.748
## x1          -0.09123    0.20091  -0.454    0.651
## x2          -0.19222    0.19572  -0.982    0.329
## x3           0.01885    0.19285   0.098    0.922
##
## Residual standard error: 1.058 on 96 degrees of freedom
## Multiple R-squared:  0.9824, Adjusted R-squared:  0.9818
## F-statistic:  1784 on 3 and 96 DF,  p-value: < 2.2e-16

Another convenient option to conduct these tests of linear hypotheses is the linearHypothesis() function from the car package. This can replicate both the marginal Wald tests:
library("car")
m2 <- lm(y ~ x1 + x2 + x3, data = d)
linearHypothesis(m2, "(Intercept) = 3")
## Linear hypothesis test
##
## Hypothesis:
## (Intercept) = 3
##
## Model 1: restricted model
## Model 2: y ~ x1 + x2 + x3
##
##   Res.Df    RSS Df Sum of Sq      F Pr(>F)
## 1     97 107.67
## 2     96 107.55  1   0.11586 0.1034 0.7485

...
linearHypothesis(m2, "x3 = 4")
## Linear hypothesis test
##
## Hypothesis:
## x3 = 4
##
## Model 1: restricted model
## Model 2: y ~ x1 + x2 + x3
##
##   Res.Df    RSS Df Sum of Sq      F Pr(>F)
## 1     97 107.56
## 2     96 107.55  1    0.0107 0.0096 0.9224

And it can also conduct the F test of all coefficients:
linearHypothesis(m2,
  c("(Intercept) = 3", "x1 = 10", "x2 = 9", "x3 = 4"))
## Linear hypothesis test
##
## Hypothesis:
## (Intercept) = 3
## x1 = 10
## x2 = 9
## x3 = 4
##
## Model 1: restricted model
## Model 2: y ~ x1 + x2 + x3
##
##   Res.Df    RSS Df Sum of Sq     F Pr(>F)
## 1    100 108.93
## 2     96 107.55  4    1.3802 0.308  0.872