Angular App not loading on stock Android browsers

Question: I am working on a project built in Angular (1), and can confirm that it works in both Dev & Production environments across all of my desktop browsers, as well as my mobile ones (Android: Chrome, Firefox, Adblock Browser; iOS: Stock Browser, Firefox, Chrome). Unfortunately we have found that it is not loading in multiple people's stock Android browsers (I've personally tested it in DuOS 5.1.1, and on a couple different devices on Browserstack).
In looking through previous responses here on SO, I have taken some peoples' suggestions and added core-js with require('core-js') to our routes.js file (with  in our index.html); but that did not seem to have any effect.
I am wondering if anyone has any suggestions for additional things I should try. I can post any portions of the code people think would be relevant; but it's a fairly large project (thousands of lines)
Screenshot
On the left, working on my phone. On the right, not working on an emulated device.
Thanks a bunch!!
Answer: Polyfills were not working, so in the end we decided to detect if users were on the Stock Android Browser - and, if they were, bringing them to a page recommending them to use Firefox, Chrome, etc to use the site/app.
Here is the code we used to do so:
    var navU = navigator.userAgent;
    // Android Mobile
    var isAndroidMobile = navU.indexOf('Android') > -1 && navU.indexOf('Mozilla/5.0') > -1 && navU.indexOf('AppleWebKit') > -1;
    // Apple webkit
    var regExAppleWebKit = new RegExp(/AppleWebKit\/([\d.]+)/);
    var resultAppleWebKitRegEx = regExAppleWebKit.exec(navU);
    var appleWebKitVersion = (resultAppleWebKitRegEx === null ? null : parseFloat(regExAppleWebKit.exec(navU)[1]));
    // Chrome
    var regExChrome = new RegExp(/Chrome\/([\d.]+)/);
    var resultChromeRegEx = regExChrome.exec(navU);
    var chromeVersion = (resultChromeRegEx === null ? null : parseFloat(regExChrome.exec(navU)[1]));
    // Native Android Browser
    var isAndroidBrowser = isAndroidMobile && (appleWebKitVersion !== null && appleWebKitVersion <= 537) || (chromeVersion !== null && chromeVersion <= 38);

    //If isAndroidBrowser, redirect
    if(isAndroidBrowser){
        window.location = "/views/compatibility/compatibility.html";
    }


jquery find fails when argument has invalid characters

Question: I am using jquery. If I have a div that looks like this:

and I run:
find('div.container["title=Mark"]');

then it works. Which means, the element is found.
However, if I have another div that looks like this:

then it doesnt work. Which means: the element is not found and jquery give an exception:
Error, Syntax Error: unrecognized expression.

It seems that when "title" is a string with no whitespaces or other characters like slash, then it works. In other case, jquery doesnt understand that tag.
is there a way to avoid changing in my code everywhere (it is a lot of changes) and make find-function to work with this elements?
Comment: Please have a look at the [**documentation**](http://api.jquery.com/attribute-equals-selector/) again. It's right there in the heading: "Attribute Equals Selector `[name="value"]`". [I somehow doubt `div.container["title=Mark"]` works](http://jsfiddle.net/n3hno1an/).
Answer: You've got your " marks in the wrong place. Place them around the value:

var mp = $(document).find('[title="Mark Person"]');

mp.css('font-weight', 'bold');

should be bold

should not be bold


This page was last modified on 1 January 1970

Question: Including the following code:
<?php print 'This page was last modified on ' . date('j F Y', $node->changed);?>

in node.tpl.php displays the correct information on the site. However, I would like to display it in the footer instead at the end of the content so have moved it to page.tpl.php.
The problem with this is that on the homepage the following is being displayed:

This page was last modified on 1 January 1970

Which is clearly incorrect.
In addition, These error messages are displayed on every page:

Notice: Undefined variable: node in include() (line 201 of /home/mysite/public_html/sites/all/themes/mysite/templates/page.tpl.php).
Notice: Trying to get property of non-object in include() (line 201 of /home/mysite/public_html/sites/all/themes/mysite/templates/page.tpl.php).

How do I include the Page last updated text in the footer of every page?
Comment: Just check your server timezone
Answer: You are trying to access the property of a loaded Node's object in the page template. This variable, $node, will only be available to the page template, typically page.tpl.php, only if the current path is loading a node.
In other words, if you are loading a path like node/NODE_ID, then you are guaranteed the variable will be available. Otherwise it won't be.
The error you are seeing is because of this reason. Try to navigate to a valid node URL and the error will be gone, the variable will be defined, and you can access it normally.
Provide a conditional check in your page template to make sure the variable exists before you access it.
Good Luck!
Comment: Thanks for that @9ee1
My front page is not a node, in the site settings the Default front page is set to "blank". What variable should I use on the homepage instead of $node?
My front page is made up of menus and blocks...
Comment: @kine456 Short and sweet answer is nothing out of the box :). Makes sense if you think about it too. Nodes are the building blocks of your content and thus, for all purposes, they are the pages that are being modified. If your front page is made up of only blocks and menus, what would the modification date represent in that context? If you really wanted to, you can probably write up a module that would calculate such a date based on your requirements and make it available to your template. I am not sure if there are any custom modules that you can use.


PHP Instagram friendships/create/ Error

Question: I trying to friendships/create/ function in Instagram but I've got some error.
account/login function is working.
friendships/create Error: "Please update your Instagram app to continue following."
require_once("instagram.php");
$username = '';
$password = '';
$agent = 'Instagram 6.21.2 Android (19/4.4.2; 480dpi; 1152x1920; Meizu; MX4; mx4; mt6595; en_US)';
$guid = GenerateGuid();
$device_id = "android-".$guid;
$data ='{"device_id":"'.$device_id.'","guid":"'.$guid.'","username":"'.$username.'","password":"'.$password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig    =   GenerateSignature($data);
$data   =   'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
$login  =   SendRequest('accounts/login/', true, $data, $agent, false);
print_r($login);

/**********

Login working successfully! No problem...

***********/

/*********
But error area is here.
**********/

$device_id = "android-".$guid;
$data = '{"device_id":"'.$device_id.'","guid":"'.$guid.'","device_timestamp":"'.time().'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig            =   GenerateSignature($data);
$new_data       =   'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
$follow         =   SendRequest('friendships/create/29180689', true, $new_data, $agent, true);

=== instagram.php ===
function SendRequest($url, $post, $post_data, $user_agent, $cookies) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://instagram.com/api/v1/'.$url);
/*
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
*/
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

if($post) {
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}

if($cookies) {
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}

$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($http, $response);
}
function GenerateGuid() {
 return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 65535),
        mt_rand(0, 65535),
        mt_rand(0, 65535),
        mt_rand(16384, 20479),
        mt_rand(32768, 49151),
        mt_rand(0, 65535),
        mt_rand(0, 65535),
        mt_rand(0, 65535));
}
function GenerateSignature($data) {
 return hash_hmac('sha256', $data, '25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5');
}

Comment: Did you find a fix for this?
Answer: Modify this line:
$data = '{"device_id":"'.$device_id.'","guid":"'.$guid.'","device_timestamp":"'.time().'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';

to be
$data = '{"user_id":"'.$user_id.'","device_id":"'.$device_id.'","guid":"'.$guid.'","device_timestamp":"'.time().'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';

You missed the user_id parameter within the request.
Comment: Is the ```$user_id``` the same as ```$username```?
Answer: change this line
$data ='{"device_id":"'.$device_id.'","guid":"'.$guid.'","username":"'.$username.'","password":"'.$password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';

to
$data = '{"user_id":"'.$userId.'","_uuid":"'.$guid.'","_uid":"'.$loggedInUserId.'"}';

and change this line
SendRequest('friendships/create/29180689', true, $new_data, $agent, true);

to
SendRequest('friendships/create/29180689/', true, $new_data, $agent, true);

Answer: You are trying to use private APIs, which is not allowed by Instagram's Terms of Use, so only people who works there knew what's missing here.
There're public APIs that can achieve what you wanted to do here: https://instagram.com/developer/endpoints/relationships/#post_relationship
Comment: My app is new. So i can't add relationships scope. Do you know a solution for new apps ?
Comment: You have to submit the app for review, then you can use relationships scope. There's no other way around afaik.

PHP Instagram friendships/create/ Error


Force DFS-R into a dirty state

Question: We use Windows Server 2012 as our file system running DFS-R between our two sites as part of our business continuity systems. Last week, DFS-R failed at one site requiring the file server to be rebooted. The same thing has just happened at the other site causing several hours of downtime whilst we tried to resolve - although now we know to simply reboot which isn't nice.
The DFS-R service is currently disabled whilst we diagnose the root cause (timeout errors in ESENT) but I'd like to bring it back online overnight.
I'd like to be able to force the same code that runs when a dirty shutdown occurs, i.e. check the database when the service is restarted. I know this takes many hours but I'd prefer that than bringing up a service that might instantly fail again.
Is this possible?
Comment: Simply stopping the service isn't doing that?  Every time I do, I get DFSR whining at me about a dirty shutdown state.
Comment: Not for us - it usually comes back up cleanly unless it was a dirty shutdown; we have had one when the Hyper-V host crashed
Comment: I will be restarting the service this evening and will be watching the event logs *very* carefully
Answer: Well you could delete the database and cause dirty shutdown recovery if you really want to.
But I think what you should really do here is take a backup, gather the debug logs (for analysis) as is and then decide whether you want to start the service or perhaps re-initialize the RF/database.
You need to pick a server to be the starting primary if you are going down this route.
Debug log analysis docs if you want a stab at log analysis are here:
http://blogs.technet.com/b/askds/archive/2009/04/09/dfsr-debug-log-series-wrapup-and-downloadable-copies.aspx
Comment: In the end I restarted it and it came up cleanly. But the same fault that prompted this post occurred again on Wednesday night requiring an all night session to take the down-time opportunity to update the servers. Not nice. DFS-R is a critical part of our business continuity plan (replicate to sister site) and we need it to work reliably. It had worked reliably for six months and then start wobbling at all three sites. Whilst watching updates install through the night, I was reading about the improvements in DFR-2 in R2 with interest...
Comment: You may have an issue that merely needs to be troubleshooted. I suggest raising a case with Microsoft if you need help with log analysis. You do obviously want to find a fix and/or perhaps root cause (assuming you have data to determine this or repro steps) so you can get that reliability back.

Force DFS-R into a dirty state


nginx-rtmp-module HLS with DVR

Question: I've set up nginx-rtmp-module with HLS and I'm wondering if there's a way to set up DVR like Wowza's nDVR feature that lets you rewind a live stream, even to the very beginning of the stream. Right now I only get the most recent 40 seconds or so. Thanks!
(I gather it's possible from the comments here: http://nginx-rtmp.blogspot.ca/2013/02/multiple-locations-for-vod-in-098.html)
Answer: Entirely possible, you just need to increase the HLS playlist length in your app config section. I've been using this myself and it works well!
For example if you'd like a DVR playlist of 30 minutes long, you'd put this inside your app section:
<code>hls_playlist_length 30m;
</code>
See nginx-rtmp-module hls directives for more info.
Note
The HLS player you use needs to support this. For example Flowplayer/JWplayer will however Safari (both Mac/iOS) will just play the live stream.
Comment: Having had experience with Wowza, I can tell you it also stores its DVR chunks on disk. As you can imagine having hundreds of clients access these segments is horrible for performance. Nginx does the same. The solution is to create a RAM Disk and store them in "memory" by changing the HLS segment path.  `mount -t tmpfs -o size=512m tmpfs /mnt/ramdisk` then point your nginx config so it stores HLS at `/mnt/ramdisk`. You'll find that your server will have no trouble serving lots of clients that way (provided you have enough RAM to store the segments!)
Comment: That works! Have you tried setting hls_playlist_length to something very large, say 4h? How does it affect performance? E.g. I think Wowza stores its DVR in memory, so longer streams can cause it to fill up heap space. Does nginx-rtmp-module also store the DVR in memory or is everything self-contained in those .ts chunks and the .m3u8 playlist?
Comment: It also depends on the player. I used to have trouble seeking live video (VOD no problem) with Android version of JW Player(Windows version no problem), but newer version, e.g. jwplayer-8.1.4, has fixed this and seeks well on Android.

nginx-rtmp-module HLS with DVR


How can I allow my function to accepts two different objects in swift?

Question: I have a function which takes one argument. I wanted my function to accept two object types. How can I do it? Here is the example below:
func accept(user: Customer) {
  ...
}

It should accept Customer and Employee object reference.
accept(objRefCustomer)
accept(objRefEmployee)

Please help me in this case.
Comment: why cant you try using func accept(user: NSObject)
Comment: but how can use their properties?
Comment: then you can have to inherit the classes
Answer: Alternative to super-classing: use protocols
You needn't necessarily use a superclass for this case (if Customer and Employee are struct value types; superclass option is not possible), but can rather use the more generic approach of protocols.
Define a protocol Users which blueprints properties and methods for your Customer and Employee instances (if we let Customer and Employee conform to Users, then we promise that instances of these two structures will have accessible the blueprinted properties and methods):
protocol Users {
    var name: String { get }
    func printTypeOfUser()
}

Define the Customer and Employee structures, and their conformance to the protocol Users:
struct Customer : Users {
    let name: String
    init(name: String) { self.name = name }

    func printTypeOfUser() {
        print("Is a Customer!")
    }
}

struct Employee : Users {
    let name: String
    let id: Int
    init(name: String, id: Int) { self.name = name; self.id = id }

    func printTypeOfUser() {
        print("Is an Employee!")
    }
}

Now you can define a generic function where its generic, say T, is type constrained to types conforming to the protocol Users, which in this case is equivalent to the Customer or Employee types
func accept<T: Users>(user: T) {
    print("Name of user: \(user.name) [\(user.dynamicType)]")
    user.printTypeOfUser()

    // do something additional employee-specific if user is an employee?
    if let employee = user as? Employee {
        print("User is an employee with id: \(employee.id)")
    }
}

Example usage of this function for Employee as well as Customer instances:
let employee = Employee(name: "John", id: 1)
let customer = Customer(name: "Sarah")

accept(employee) /* Name of user: John [Employee]
                    Is an Employee!
                    User is an employee with id: 1 */

accept(customer) /* Name of user: Sarah [Customer]
                    Is a Customer!                 */

Comment: @coolly the above is just as valid for classes as for structs (just replace `struct` with `class` in the definitions of `Customer` and `Employee` above). For classes, you do indeed have the alternative of introducing a superclass; if this superclass is never explicitly used as a type itself (i.e., no superclass objects), however, then protocols might be a more Swifty solution.
Comment: Thanks for the input. But I need to stick to class type
Comment: name is not required in both the classes. I tried to make it optional but it throws me an error. I tried var optional name:String in protocol.
Comment: @coolly I think you would benefit greatly by reading the [Swift Language Guide - The Basics](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html), making sure you understand the very important concepts of **optionals** and **protocols** in Swift. After grasping the basics of these subjects, feel free to update this question with more details regarding your specific implementation. I will suspect, however, that you will possibly be able to solve these issues yourself once you've thoroughly covered the fundamental concepts of Swift.
Comment: may be you have understood my above comment in a different way, it was specific to optional of a property but not property optional. Anyhow, I was able to solve the problem :)
Answer: Instead of changing your Class structure and code base, you can use AnyObject. It will also be easier for you if, for example, in future you have to make this function accept parameters of class WaterMelon. Making all these classes inherit from a common parent class would be unnecessary overhead, not to mention hectic.
AnyObject is swift equivalent of objective c id. AnyObject is a protocol that can represent an instance of any class type.
It also has a more general counterpart, Any, which can represent any type at all (including structs and enums).
Following code will accept any class type parameter you pass:
func accept(sender : AnyObject) { //Or AnyObject? if you want to handle nil as well
      ...
    }

To access properties of the classes you pass as AnyObject, you can use type casting.
For example below code will check sender type and typecast it for you:
if let customerRef = sender as? Customer {
    // ...
    // Sender is of customer class type. Use it with customerRef that we created
    let customerName = customerRef.dynamicType.sampleNameProperty //Access a property of class Customer
    customerRef.funcOfCustomerClass() //Call a method of class Customer
}
else{
 //Sender is not of customer class type.
//Then it must be Employee??? Handle cases for employee here.
}

Comment: Note that `accept(...)` as above will allow being called with _any kind of class instance_, not just the intended instances of `Customer`/`Employee` class. Hence, the statement _"then it must be Employee"_ in the `else` clause above is not true, as it might as well be any class instance "wrapped" by the `AnyObject` type. Imho, `AnyObject` has its uses (esp. when working with obj-c/cocoa), but this is not one of them, as `accept(...)` function as above is way more general/generic than it need to be: as more "encapsulating" alternatives exists, I believe the solution as above should be avoided.
Comment: how can i access sender properties?
Comment: you mean like this sender.propertyName as Customer ?
Comment: it throws me compilation error if I am trying to access its property "Value of type has no member" @nsnoob
Comment: but anyhow customer.propertyName is not able to accept during app build.
Comment: @dfri I agree and that's why I made the comment about it being Employee a question with three question marks. I am relying on OP here that he will only send either Customer or Employee as parameters. If he wants to send more types, he will have to handle their cases as well. Here our assumption is that there are going to be either Customers or Employees. Anyways, You might be right as my knowledge of swift is limited as I primarily work in Obj-c
Comment: @coolly that's strange [It should work with instance](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html). Did you try accessing it after removing `dynamicType`?
Comment: It would be helpful to debug this if you added classes customer and employee here.
Comment: yes I tried it in both ways with and without dynamicType. It didn't worked. Ended up going with protocol. But got stuck there like how to declare an optional property, not this '?' by the way. Property itself an optional.
Answer: create a protocol, and use it as argument type. protocol can be also empty, it will work anyway. Works with struct and class as well;
ex:
protocol SomeFakeProtocol {}
class SomeClass: SomeFakeProtocol { //code here }
struct SomeStruct: SomeFakeProtocol { //code here }

func someFunction(arg: SomeFakeProtocol) { //code here }

Benefits - you can allow to use only types you want to. And, sure, you can do things like this:
extension String: SomeFakeProtocol {}

Answer: You can create a super class called People of Cutomer and Employee.
Then set user as type of People:
func accept(user: People) {
  ...
}

Comment: @coolly Just because you want to pass different objects to the same function _does not mean you necessarily need to introduce a super class_, another alternative is [using protocols](http://stackoverflow.com/a/37000368/4573247).
Comment: well, ya that's what first comment on this answer :)
Comment: just because I want to pass different objects for the same function do I need to make a super class?
Comment: Cast them to `Customer` or `Employee`, then you can access them.
Comment: you mean like this sender.propertyName as Customer
Comment: first I have to check whether passed value was customer or employee right?
Comment: Yes, then you just cast this.
Answer: You don't need a super class, you can just pass an object of type AnyObject and in your function check the type of the object passed:
func accept(user: AnyObject) {
    if let usr = user as? Person {
        ...
    }
}

But if you have many types you want to pass you may want to make a protocol or a super class.
Comment: but if I access usr property it throws me an error while building the project
Comment: This is the code I took from the testing playground and it works, no errors: class

Person {
    var name:String = ""
    var time:NSDate?
}

func accept(user: AnyObject) {
    if let usr = user as? Person {
        print(usr.name)
    }
}
Comment: But the best way to achieve what you want is to use protocols, like others mentioned above :-).


Programmatically collapsible/expandable toolbar without CoordinatorLayout?

Question: I want to have a toolbar that can be expanded when the user clicks on a certain item in a layout. However, I don't need to have a toolbar that can collapse when scrolling, so I don't see the use of the CoordinatorLayout. The problem is that calling setExpanded(false) on my AppBarLayout doesn't do anything. Is there a way to just have a toolbar that I can expand or collapse programmatically without nesting it inside a CoordinatorLayout? I don't want to use that layout because there are multiple children in my root layout and I don't need special behavior on scrolling.
Answer: Make a custom view.
ExpandableToolbar.java
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

public class ExpandableToolbar extends Toolbar {

    private Drawable expandedDrawable;
    private boolean isExpanded = false;

    public ExpandableToolbar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initToolbar(attrs);
    }

    private void initToolbar(AttributeSet attrs) {
        TypedArray a = getContext().getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.ExpandableToolbar,
                0, 0);

        try {
            expandedDrawable = a.getDrawable(R.styleable.ExpandableToolbar_expandedDrawable);
        } finally {
            a.recycle();
        }

        if (expandedDrawable == null) {
            expandedDrawable = new ColorDrawable(Color.GRAY);
        }
        expandedDrawable.setAlpha(0);

        Drawable[] drawables = { getBackground(), expandedDrawable };
        LayerDrawable layer = new LayerDrawable(drawables);

        setBackground(layer);
    }

    public void expand() {
        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateAnimation(value);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                isExpanded = true;
            }

            @Override
            public void onAnimationEnd(Animator animation, boolean isReverse) {
                isExpanded = true;
            }
        });
        anim.start();
    }

    public void collapse() {
        ValueAnimator anim = ValueAnimator.ofFloat(1f, 0f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateAnimation(value);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                isExpanded = false;
            }

            @Override
            public void onAnimationEnd(Animator animation, boolean isReverse) {
                isExpanded = false;
            }
        });
        anim.start();
    }

    private void updateAnimation(float value) {
        ViewGroup.LayoutParams params = getLayoutParams();
        float heightProgress = 56f + (value * (112f - 56f));
        params.height = (int) (heightProgress * getResources().getDisplayMetrics().density);
        setLayoutParams(params);

        expandedDrawable.setAlpha((int) (value * 255));
    }

    public boolean isExpanded() {
        return isExpanded;
    }
}

attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpandableToolbar">
        <attr name="expandedDrawable" format="reference|color"/>
    </declare-styleable>
</resources>

Usage:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <marabillas.loremar.expandabletoolbar.ExpandableToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:title="My Toolbar"
        app:titleTextColor="#fff"
        app:menu="@menu/main_menu"
        app:expandedDrawable="@drawable/city_buildings"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="92dp"
        android:layout_height="41dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

</androidx.constraintlayout.widget.ConstraintLayout>

public class MainActivity extends AppCompatActivity {

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

        final ExpandableToolbar toolbar = findViewById(R.id.toolbar);
        final Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (toolbar.isExpanded()) {
                    toolbar.collapse();
                } else {
                    toolbar.expand();
                }
            }
        });

        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

Result:


Initialize Slick Slider when page loads completely

Question: I'm using Slick Slider with content in each slide (text and images):

The problem is when I load page, at the beginning Slick Slider looks like this with one slide above the other until it finishes load page and then it starts working:

I tried to put these lines on CSS but It doesn't work, the slider is completely hidden:
#misresenas{display:none;}
#misresenas .slick-initialized{display:block;}

How can I fix it?
Comment: what about adding css like `.resena {
  display:inline-block;
}` ?.
Answer: Here you go. Replace $(document).ready() with $(window).load() function.

Comment: I used this option but in Chrome it takes a lot of time to load, in another browers like Firefox and Opera it loads faster.
Comment: It may be because other browsers are showing you a cached version of your page. Basically `$(window).on('load', function())` runs when the document is fully loaded. Please don't use `$(window).load` in place use `$(window).on('load')` I have edited my answer please check.
Answer: That's the correct code
#misresenas{display:none;}
#misresenas.slick-initialized{display:block;}


ServiceStack DateTime Local not UTC

Question: I am having a problem with the Servicestack I am getting a datetime from an external system and if I am using the DateTimeOffset I can se that the time is
15:00:00 +0200 I know that this is utc time stamp but Servicestack set is as local time this results in the time moving the wrong way.
I have read that you can tell the servicestack to allways use UTC but I cant find any where how to set it up and I don't know it this will help me.
from
Kenneth Foli Jørgensen
Answer: You can tell ServiceStack.Text's JSON/JSV/CSV text serializers to use UTC with:
<code>JsConfig.AlwaysUseUtc = true;
</code>
Comment: Just refer to it fully qualified: ServiceStack.Text.JsConfig
I set it in my AppHost configure() method
Comment: the problem is how do i use this
JsConfig.AlwaysUseUtc = true;

where am i impleminding JsConfig

ServiceStack DateTime Local not UTC


extrair dados de um json

Question: Tenho o seguinte JSON:
[{
"ItensReceitaModel": [{
    "t0081_id_receita_itens": 1,
    "t0081_lote": "1233"
}, {
    "t0081_id_receita_itens": 2,
    "t0081_lote": "123"
}],
"PacienteModel": {
    "t0031_id_pessoa": 1,
    "t0031_tipo_pessoa": "cliente",
},
"PrescritorModel": {
    "t0031_id_pessoa": 29,
    "t0031_tipo_pessoa": "prescritor",
},
"t0080_id_receita": 1,
"t0080_tipo_receita": "Receita Branca"
}, {
"ItensReceitaModel": [{
    "t0081_id_receita_itens": 3,
    "t0081_lote": "qqq"
}, {
    "t0081_id_receita_itens": 4,
    "t0081_lote": "3123"
}, {
    "t0081_id_receita_itens": 5,
    "t0081_lote": "12321",
    "t0081_qtde": 1
}],
"PacienteModel": {
    "t0031_id_pessoa": 1,
    "t0031_tipo_pessoa": "cliente"
},
"PrescritorModel": {
    "t0031_id_pessoa": 28,
    "t0031_tipo_pessoa": "prescritor"
},
"t0080_id_receita": 2,
"t0080_tipo_receita": "Receita Branca"
}, {
"ItensReceitaModel": [{
    "t0081_id_receita_itens": 6,
    "t0081_lote": "123"
}],
"PacienteModel": {
    "t0031_id_pessoa": 1,
    "t0031_tipo_pessoa": "cliente",
},
"PrescritorModel": {
    "t0031_id_pessoa": 29,
    "t0031_tipo_pessoa": "prescritor"
},
"t0080_id_receita": 3,
"t0080_tipo_receita": "Receita Branca"
}]

e preciso criar um array somente com ItensReceitaModel, como posso fazer isso?
Answer: Fiz um processo de leitura de chaves e se for confirmado que existe é lido para o $scope.ItensReceitaModel = []; criando um array das informações.
Código para criação do novo array:
$scope.ItensReceitaModel = [];
$scope.load = function() {
  for (var i = 0; i < $scope.items.length; i++)
  {
    for (var j = 0; j < $scope.items[i].ItensReceitaModel.length; j++)
    {
       $scope.ItensReceitaModel.push($scope.items[i].ItensReceitaModel[j]);
    }
  }
}
$scope.load();

Código completo:

var app = angular.module('app', []);
app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.items = [{
      "ItensReceitaModel": [{
        "t0081_id_receita_itens": 1,
        "t0081_lote": "1233"
      }, {
        "t0081_id_receita_itens": 2,
        "t0081_lote": "123"
      }],
      "PacienteModel": {
        "t0031_id_pessoa": 1,
        "t0031_tipo_pessoa": "cliente",
      },
      "PrescritorModel": {
        "t0031_id_pessoa": 29,
        "t0031_tipo_pessoa": "prescritor",
      },
      "t0080_id_receita": 1,
      "t0080_tipo_receita": "Receita Branca"
    }, {
      "ItensReceitaModel": [{
        "t0081_id_receita_itens": 3,
        "t0081_lote": "qqq"
      }, {
        "t0081_id_receita_itens": 4,
        "t0081_lote": "3123"
      }, {
        "t0081_id_receita_itens": 5,
        "t0081_lote": "12321",
        "t0081_qtde": 1
      }],
      "PacienteModel": {
        "t0031_id_pessoa": 1,
        "t0031_tipo_pessoa": "cliente"
      },
      "PrescritorModel": {
        "t0031_id_pessoa": 28,
        "t0031_tipo_pessoa": "prescritor"
      },
      "t0080_id_receita": 2,
      "t0080_tipo_receita": "Receita Branca"
    }, {
      "ItensReceitaModel": [{
        "t0081_id_receita_itens": 6,
        "t0081_lote": "123"
      }],
      "PacienteModel": {
        "t0031_id_pessoa": 1,
        "t0031_tipo_pessoa": "cliente",
      },
      "PrescritorModel": {
        "t0031_id_pessoa": 29,
        "t0031_tipo_pessoa": "prescritor"
      },
      "t0080_id_receita": 3,
      "t0080_tipo_receita": "Receita Branca"
    }];

    $scope.ItensReceitaModel = [];

    $scope.load = function() {
      for (var i = 0; i < $scope.items.length; i++)
      {
        for (var j = 0; j < $scope.items[i].ItensReceitaModel.length; j++)
        {
           $scope.ItensReceitaModel.push($scope.items[i].ItensReceitaModel[j]);
        }
      }
    }
    $scope.load();
  }
]);

    {{it.t0081_id_receita_itens}} - {{it.t0081_lote}} - {{it.t0081_qtde || 0}}

Comment: Perfeito Virgilio!!!

extrair dados de um json


Square units of area in a circle

Question: I'm studying for the GRE and came across the practice question quoted below. I'm having a hard time understanding the meaning of the words they're using. Could someone help me parse their language?

"The number of square units in the area of a circle '$X$' is equal to $16$ times the number of units in its circumference. What are the diameters of circles that could fit completely inside circle $X$?"

For reference, the answer is $64$, and the "explanation" is based on $\pi r^2 = 16(2\pi r).$
Thanks!
Answer: Let the diameter be $d$. Then the number of square units in the area of the circle is $(\pi/4)d^2$. This is $16\pi d$. That forces $d=64$.
Remark: Silly problem: it is unreasonable to have a numerical equality between area and circumference. Units don't match, the result has no geometric significance.
"The number of square units in the area of" is a fancy way of saying "the area of."
Comment: Thanks for responding. Is a "square unit" the same as "area of"? Or is it a square circumscribed in a circle? Where are you getting (π/4)d2 ?
Comment: The area of a circle of radius $r$ is, as you mentioned, $\pi r^2$. So the area of a circle of diameter $d$ is $\pi(d/2)^2$, We coudld have instead worked with $r$, and translated to diameter at the end.  Yes, "the number of square units in the area of" is a fancy way of saying "the area of."
Comment: @AndréNicolas: Of course, the phrasing "the number of square units in the area of" (and "the number of [linear] units") isn't just to be fancy; it's *specifically* to address your objection that units of length and area don't match, saying, in effect, "We know *that*. This isn't about units. Just make the *numbers* equal to each other." This is a *perfectly* reasonable algebraic exercise. Apples aren't oranges, either, but we can certainly compare *numbers* of each.
Answer: I'm currently doing this, and how I see the problem is:
$πr^2 = (2πr) * 16 $
If you solve this, r gives $32$, and since diameter $d = 2*r$, $d = 64$.
So, any circle with a lesser diameter fits in this circle $(d<64)$

Square units of area in a circle


Converting a DFA to a regular expression

Question:
I have this state diagram, and I am trying to describe the language of this DFA and finding the regular expression for it.
I tried doing it by listing possible strings and at first I thought it was strings that have odd numbers of 1 or 0 in the end but it is not the case. I've been trying to figure out for the last 30 minutes and need help. How would you describe the language for this state diagram as well as the regular expression for it? Thank you!
Comment: There are several general solutions [here](https://cs.stackexchange.com/questions/2016/how-to-convert-finite-automata-to-regular-expressions). In my opinion it is a very technical question.
Answer: You almost had it. It accepts strings with an odd number of ones AND an odd number of zeroes.


Redshift UDF aggregate or window error

Question: I have written the following function
create function sevRun (text,text,int)
returns int stable as $$
SELECT count(*)
  FROM (SELECT case_id
          FROM dbname.tablename
         WHERE create_date >= TO_DATE('2017-' || $1::text || '-01', 'YYYY-MM-DD')
           AND create_date < TO_DATE('2017-' || $2::text || '-01', 'YYYY-MM-DD')
           AND min_impact <= $3
           AND assigned_to_group IN ('listitem','listitem','....')
       ) inline_view
$$language sql;

when I call the function select sevRun ('01','02',2); I get the following error
Invalid operation: The select expression can not have aggregate or window function.;
I'm trying to create a function that I can call multiple times and change the month to suit
Comment: From the error i would say that the `COUNT` is the Problem, since that is the only Aggregate function in there.
Comment: Your function works for me on PostgreSQL 9.6 if I replace `RETURNS int` with `RETURNS bigint`.
Comment: this is on redshift which is based on postgre
Answer: You can't select from the table inside the SQL UDF in Redshift. The only allowed functions are scalar functions that operate on the input parameters and return the output.
UPD: Redshift now support stored procedures in plpgsql. official docs
Comment: Is there any other way to store and call queries that are used repetitively in Redshift?
Comment: Redshift now supports stored procedures similarly to other databases (see the answer update).
Answer: Why not this query -
SELECT COUNT(*)
FROM dbname.tablename
WHERE create_date >= TO_DATE('2017-' || $1::text || '-01', 'YYYY-MM-DD')
AND create_date < TO_DATE('2017-' || $2::text || '-01', 'YYYY-MM-DD')
AND min_impact <= $3
AND assigned_to_group IN ('listitem','listitem','....')

Redshift UDF aggregate or window error


SelectPDF Erro C#

Question: Estou usando o ou SelectPDF para converter uma string HTML em pdf local funciona perfeitamente, mas emprodução mostra o seguinte erro.

Estou está usando um servidor IIS.
Todos os .ddl's de produção estão no servidore, já tentei alterar o web.config para aumentar o tamanho dos arquivos suportados (esse .pdf tem apenas uma página imagino que não haja problema aí).
Answer: Era a largura da Imagem, não sei pq mas em produção ela nn tava conseguindo converter o html com a imagem com a largura de 1700px de largura ,é isso fé.

SelectPDF Erro C#


How to solve the ordinary differential Equations?

Question: \begin{equation}
\begin{aligned}
\frac{\mathrm{d} x_1}{\mathrm{d} t} & =-x_1+x_2\\
\frac{\mathrm{d} x_2}{\mathrm{d} t} & =x_1\cos t -x_2
\end{aligned}
\label{eq:3.6}
\end{equation}
At the beginning, I prove the zero solution is stable, then I used Maltab ode45 function test more than 10 different initial points, they all convergenced to zero, so I guess the zero solution asymptotically stable, But I can't prove it. So I want to know how to solve the ODEs.
Comment: $x_2=x_1+\frac{dx_1}{dt}$ . Put it into the second equation leading to a linear second order ODE. The solution involves special functions MathieuS and MathieuC.
Answer: This is not a complete answer to the question.
$$(x_1e^t)'=x_2e^t$$
$$(x_2e^t)'=(x_1e^t)\cos t$$
Then substitute $u=x_1e^t$ and $v=x_2e^t$:
$$u'=v$$
$$v'=u\cos t$$
Now we need to solve the differential equation :
$$u''-u\cos t=0$$
This is Mathieu's differential equation and there are no solution with elementary functions.
$$y''(x)+(a-2q \cos (2x))y(x)=0$$
Comment: Thanks !!!!!!!!!
Comment: You're welcome @Nichts__97


What will happen if the wing flap does not close after passing the DRS zone?

Question: In some races in 2022, Max Verstappen had problems with his DRS and was unable to open it. My question is, what would happen to the driver if the wing flap cannot be closed due to mechanical error during the race? Would the driver get a penalty, or are they forced to retired from the race?
Answer: In the case of a mechanical problem, the driver will first be shown a Black and Orange flag like below:

This flag is normally signalled at the Start/Finish line and instructs the driver that they have a problem deemed to be unsafe should they continue, and must pit and the end of this lap, in which engineers are able to try and rectify the problem.
From Appendix H of the International Sporting Code

Black flag with an orange disc 40 cm in
diameter
This flag should be used to inform the driver concerned that his car has mechanical problems likely to endanger himself or others and means that he must stop at his pit on the next lap. When the mechanical problems have been rectified to the satisfaction of the chief scrutineer, the car may rejoin the race.

A failure to come in to the pits following being shown the Black and Orange flag would normally result in a Black flag for the car in question - essentially disqualifying them from the race - plus any other potential reprimand deemed fit by the stewards - eg fines.
A DRS failure in particular is deemed to be especially dangerous to the driver, as reduced downforce, especially in the braking zone, can lead to disastrous consequences - as Marcus Ericsson found out in Monza 2018

This has also happened already in the 2022 season, with Yuki Tsunoda at the Azerbaijan GP, where his DRS flap snapped in half, leaving one side in the "open" DRS state. He was shown the the Black and Orange flag, and pitted the next lap, to which the engineers used trusty duct tape to tape the wing shut (F1 twitter post)


Prove that either both sequences converge to the same limit or both diverge.

Question: The full question wouldn't fit in the title. Here it is:
Let ($a_n$)$_n$$_\in$$_\Bbb{N}$ and ($b_n$)$_n$$_\in$$_\Bbb{N}$ be two sequences and suppose that the set {n$\in$$\Bbb{N}$: $a_n\neq b_n$} is finite ($a_n$ and $b_n$ differ for finitely many values of n). Prove that either both sequences converge to the same limit or both diverge.
Our definition for convergence is: Given a real number $L$, we say that $(X_n)$ converges to L if for every $\epsilon$>0, there exists N∈$\Bbb{N}$ such that for all n∈N satisfying n>N, we have |$X_n-L$|<$\epsilon$. I'm just not sure if I'm supposed to apply that definition to this problem and if so, then how?
Comment: Hint: take $N = 1+\max\{n\in\Bbb{N}: a_n\neq b_n\}$
Comment: There is such an N iff all but finitely many values are within epsilon of L iff all but finitely many values of a sequence that is identical except at finitely many values  is within epsilon of L.
Comment: Their difference converges to 0. This is sufficient.
Answer: If the set $\{n\in \mathbb N: a_n \neq b_n\}$ is finite, there is an $N_0$ such that $a_n=b_n \ \forall n>N_0$. Now, suppose that $\lim_{n} a_n=L$ exists and it's a real number. Then,
$$\forall \varepsilon>0 \quad \exists N\in \mathbb N: n>N \Rightarrow |a_n-L|
<\varepsilon$$
and now we'd like to prove that $\lim_{n} b_n=L$, that is,
$$\forall \varepsilon>0 \quad \exists M\in \mathbb N: n>M \Rightarrow |b_n-L|
<\varepsilon$$
but if we choose $M=\max\{N, N_0\}$, then
$$n>M \Rightarrow |b_n-L|=|a_n-L|<\varepsilon$$
Comment: How are you saying that if the set is finite, then there is an $N_0$ such that $a_n$=$b_n$? Also, what do you mean by 0$\exists$$M$?
Comment: It is a typo. It has to be $a_n \neq b_n$.
Comment: @johnie4usc reasoning by contradiction, if for every $n\in \mathbb N$, there is $k(n)>n$ such that $a_{k(n)}\neq b_{k(n)}$, we have that $k(1), k(2), k(3)...$ are indices for which $a_{k(n)}\neq b_{k(n}$, and there are as many as the natural numbers. That contradicts the finiteness of the set.
Comment: @NiklasHebestreit no, it's not. If $a_n\neq b_n$ for finite terms, that set of indices can't have indices as big as you want.
Comment: @flytothesurface Yeah, it is late ... Sorry for that.
Comment: @NiklasHebestreit no problem at all~
Comment: @flytothesurface okay. You're basically saying that since $\Bbb{N}$ is infinite and the set {n$\in$$\Bbb{N}$ : $a_n$ $\neq$ $b_n$} is finite, that there must exist an $N_0$ such that $a_n$ = $b_n$?
Comment: @flytothesurface I'm also getting confused about your n<$N$. Why would that be true? The definition of convergence is that n>$N$?
Comment: Yes, for all $n>N_0$, $a_n=b_n$. The $nN$. Sorry about that.
Comment: Okay, so are you saying they converge to the same limit?
Comment: Yes, that's it, because the sequences are equal, except for the first $N_0$ terms.
Comment: Okay. Let me write this all out in english and see if I'm understanding. Let $a_n$ and $b_n$ be sequences and suppose that the set {n$\in$$\Bbb{N}$: $a_n$$\neq$$b_n$} is finite. Then, there exists an $N_0$ such that $a_n$=$b_n$. Suppose the limit of $a_n$ = L. Then for each $\epsilon$>0, there exists an N$\in$$\Bbb{N}$ such that if n>N then |$a_n$ - L| < $\epsilon$. To show that the limit of $b_n$ = L, we must show that for all $\epsilon$ > 0, there exists an M$\in$$\Bbb{N}$ such that if n>M then |$b_n$ - L| < $\epsilon$. Let M=max{N, $N_0$}, then n>M and |$b_n$ - L| = |$a_n$ - L| < $\epsilon$
Comment: I'm confused about a couple parts. First, how do you know that for all n, n>$N_0$? And why are you choosing the max{N, $N_0$} for M?
Comment: Could we just get rid of the n>$N_0$ and then when choosing M, we break down into cases such that M=N or M=$N_0$? Either way, the limit is the same.
Answer: There exists an $N$ for $\{a_n\}$ iff there exists an $N$ larger than max$\{n:a_n\neq b_n\}$ for $\{a_n\}$ iff there exists an $N$ for $\{b_n\}.$


Ajuda para sobrepor texto em imagem

Question: boa noite.
Gostaria da ajuda de vocês para colocar um texto de determinada classe do .css em cima de uma imagem.
Vocês poderão entender melhor o que eu preciso acessando o site Agência Stage, logo na primeira página temos o slogan

Comunicação e marketing
certeiros para cada estágio do seu negócio.

Eu quero pegar este texto cujo o código é

/* .....................................

Google Font

..................................... */
@import url('https://fonts.googleapis.com/css?family=Quattrocento');

/* .....................................

Padrões

..................................... */

body{
    font-family: 'Quattrocento', serif !important;
}

:root {
    --cor1: #242526;
    --cor2: #3D3E40;
    --cor3: #F2EFE9;
    --cor4: #A6A29C;
    --cor5: #FFBB00;
}

.logo{
    position: absolute;
    z-index: 2;
    padding: 30px;
}
canvas{
    position: absolute;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 100vh;
    background-image: url(imagens/1920.jpg);
    background-size: cover;
}

.clear50x{ height: 50px; }
.clear100x{ height: 100px; }

/* .....................................

loader

..................................... */

#loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 100;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border: 2px solid var(--cor3);
    border-radius: 50%;
    border-top: 2px solid var(--cor5);
    width: 120px;
    height: 120px;
    -webkit-animation: spin .6s linear infinite;
    animation: spin .6s linear infinite;
}
#loader-bg {
    position: fixed;
    z-index: 100;
    width: 100%;
    height: 100%;
    background-color: var(--cor5);
}

@-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* .....................................

navegação

..................................... */

.toggle{
    width: 100%;
    text-align: right;
    position: fixed;
    z-index: 10;
    padding: 38px;
}
.navigation-mobile{
    width: 100%;
    height: 100vh;
    z-index: 99 !important;
    position: absolute;
    background-color: var(--cor3);
    padding: 35px;
}
.navigation-mobile a{
    font-size: 50px;
    color: var(--cor1);
    transition: color .5s ease-out;
    -moz-transition: color .5s ease-out;
    -webkit-transition: color .5s ease-out;
    -o-transition: color .5s ease-out;
}
.navigation-mobile a:hover{
    color: var(--cor5);
    transition: color .5s ease-out;
    -moz-transition: color .5s ease-out;
    -webkit-transition: color .5s ease-out;
    -o-transition: color .5s ease-out;
}
.back{
    width: 100%;
    z-index: 99 !important;
    position: absolute;
    text-align: right;
    padding: 35px;
}

/* .....................................

home

..................................... */

.slogan{
    position: absolute;
    width: 100%;
    z-index: 3;
    text-align: center;
    top: 40%;
}
.super{
    font-size: 80px;
    color: wheat;
}
.sub-super{
    font-size: 40px;
    color: floralwhite;
    margin-top: -25px;
}
footer{
    text-align: right;
    width: 100%;
    z-index: 2;
    position: absolute;
    bottom: 0;
    padding: 40px;
}
footer ul li{ display: inline; padding: 5px;}
#icons{ width: 4%;}

/* .....................................

fade + tab

..................................... */

#fechar{
    width: 100%;
    text-align: right;
    font-size: 90px;
    padding: 20px;
    margin-top: -50px;
    cursor: pointer;
}
#fade{
    width: 100%;
    height: 100%;
    background-color: black;
    position: absolute;
    z-index: 4;
    opacity: 0;
    display: none;
}

/* .....................................

quem somos

..................................... */

#section1{
    width: 85%;
    height: 100%;
    background-color: var(--cor5);
    position: absolute;
    z-index: 5;
    opacity: 0;
    left: -2000px;
}
#quemsomos{
    margin-top: -60px;
    text-align: justify;
    position: absolute;
    padding-left: 60px;
    padding-right: 140px;
    font-size: 20px;
    color: var(--cor1);
}

/* .....................................

portfolio
..................................... */

.bg-portfolio{
    background-image: url(imagens/bg-portfolio.jpg);
    background-attachment: fixed;
    background-size: cover;
}

.portfolio-menu li{ display: inline; padding: 10px; font-size: 20px; }
.portfolio-menu a{ background-color: black; padding: 10px;}

#socialmedia, #apps{ color: #666; }

.thumb-portfolio{
    text-align: center;
    padding-right: 80px;
    padding-left: 80px;
}
.thumb-portfolio img{
    border-radius: 20px;
}
.thumb-portfolio a{

}

@keyframes goToOpacity {
    from { opacity: 1; }
    to {   opacity: .2; }
}

.thumb-portfolio a:hover{
    animation-name: goToOpacity;
    animation-duration: .2s;
    animation-iteration-count: infinite;
}

.credits{
    padding: 100px;
    width: 100%;
    height: auto;
    background-color: var(--cor1);
}

.credits p{
    color: var(--cor4) !important;
}

@media screen and (orientation: portrait) {
    .credits{
        padding: 10px;
    }
    .thumb-portfolio{
        text-align: center;
        padding-right: 0px;
        padding-left: 0px;
    }
}

/* .....................................

mobile

..................................... */

@media screen and (orientation: portrait) {
    #section1{  width: 100%; height: 100vh; }
    #quemsomos{ padding-left: 0px; padding-right: 0px; padding: 30px; }

    .logo{ width: 70%; }
    .navigation-mobile a{ font-size: 30px; }

    .super{     font-size: 30px; color: wheat; }
    .sub-super{ font-size: 20px; color: floralwhite; margin-top: -10px; }

    #emc2-image{ display: none; }
    .toggle{ display: block; }
    #icons{ width: 20%; }
    footer{ text-align: center; }
}

Comunicação e Marketing

certeiros para cada estágio do seu negócio.

e colocar em cima desta imagem:
Talvez isto os ajude a me ajudar, então estou deixando aqui o meu css completo também

/* .....................................

Google Font

..................................... */
@import url('https://fonts.googleapis.com/css?family=Quattrocento');

/* .....................................

Padrões

..................................... */

body{
    font-family: 'Quattrocento', serif !important;
}

:root {
    --cor1: #242526;
    --cor2: #3D3E40;
    --cor3: #F2EFE9;
    --cor4: #A6A29C;
    --cor5: #FFBB00;
}

.logo{
    position: absolute;
    z-index: 2;
    padding: 30px;
}
canvas{
    position: absolute;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 100vh;
    background-image: url(imagens/1920.jpg);
    background-size: cover;
}

.clear50x{ height: 50px; }
.clear100x{ height: 100px; }

/* .....................................

loader

..................................... */

#loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 100;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border: 2px solid var(--cor3);
    border-radius: 50%;
    border-top: 2px solid var(--cor5);
    width: 120px;
    height: 120px;
    -webkit-animation: spin .6s linear infinite;
    animation: spin .6s linear infinite;
}
#loader-bg {
    position: fixed;
    z-index: 100;
    width: 100%;
    height: 100%;
    background-color: var(--cor5);
}

@-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* .....................................

navegação

..................................... */

.toggle{
    width: 100%;
    text-align: right;
    position: fixed;
    z-index: 10;
    padding: 38px;
}
.navigation-mobile{
    width: 100%;
    height: 100vh;
    z-index: 99 !important;
    position: absolute;
    background-color: var(--cor3);
    padding: 35px;
}
.navigation-mobile a{
    font-size: 50px;
    color: var(--cor1);
    transition: color .5s ease-out;
    -moz-transition: color .5s ease-out;
    -webkit-transition: color .5s ease-out;
    -o-transition: color .5s ease-out;
}
.navigation-mobile a:hover{
    color: var(--cor5);
    transition: color .5s ease-out;
    -moz-transition: color .5s ease-out;
    -webkit-transition: color .5s ease-out;
    -o-transition: color .5s ease-out;
}
.back{
    width: 100%;
    z-index: 99 !important;
    position: absolute;
    text-align: right;
    padding: 35px;
}

/* .....................................

home

..................................... */

.slogan{
    position: absolute;
    width: 100%;
    z-index: 3;
    text-align: center;
    top: 40%;
}
.super{
    font-size: 80px;
    color: wheat;
}
.sub-super{
    font-size: 40px;
    color: floralwhite;
    margin-top: -25px;
}
footer{
    text-align: right;
    width: 100%;
    z-index: 2;
    position: absolute;
    bottom: 0;
    padding: 40px;
}
footer ul li{ display: inline; padding: 5px;}
#icons{ width: 4%;}

/* .....................................

fade + tab

..................................... */

#fechar{
    width: 100%;
    text-align: right;
    font-size: 90px;
    padding: 20px;
    margin-top: -50px;
    cursor: pointer;
}
#fade{
    width: 100%;
    height: 100%;
    background-color: black;
    position: absolute;
    z-index: 4;
    opacity: 0;
    display: none;
}

/* .....................................

quem somos

..................................... */

#section1{
    width: 85%;
    height: 100%;
    background-color: var(--cor5);
    position: absolute;
    z-index: 5;
    opacity: 0;
    left: -2000px;
}
#quemsomos{
    margin-top: -60px;
    text-align: justify;
    position: absolute;
    padding-left: 60px;
    padding-right: 140px;
    font-size: 20px;
    color: var(--cor1);
}

/* .....................................

portfolio
..................................... */

.bg-portfolio{
    background-image: url(imagens/bg-portfolio.jpg);
    background-attachment: fixed;
    background-size: cover;
}

.portfolio-menu li{ display: inline; padding: 10px; font-size: 20px; }
.portfolio-menu a{ background-color: black; padding: 10px;}

#socialmedia, #apps{ color: #666; }

.thumb-portfolio{
    text-align: center;
    padding-right: 80px;
    padding-left: 80px;
}
.thumb-portfolio img{
    border-radius: 20px;
}
.thumb-portfolio a{

}

@keyframes goToOpacity {
    from { opacity: 1; }
    to {   opacity: .2; }
}

.thumb-portfolio a:hover{
    animation-name: goToOpacity;
    animation-duration: .2s;
    animation-iteration-count: infinite;
}

.credits{
    padding: 100px;
    width: 100%;
    height: auto;
    background-color: var(--cor1);
}

.credits p{
    color: var(--cor4) !important;
}

@media screen and (orientation: portrait) {
    .credits{
        padding: 10px;
    }
    .thumb-portfolio{
        text-align: center;
        padding-right: 0px;
        padding-left: 0px;
    }
}

/* .....................................

mobile

..................................... */

@media screen and (orientation: portrait) {
    #section1{  width: 100%; height: 100vh; }
    #quemsomos{ padding-left: 0px; padding-right: 0px; padding: 30px; }

    .logo{ width: 70%; }
    .navigation-mobile a{ font-size: 30px; }

    .super{     font-size: 30px; color: wheat; }
    .sub-super{ font-size: 20px; color: floralwhite; margin-top: -10px; }

    #emc2-image{ display: none; }
    .toggle{ display: block; }
    #icons{ width: 20%; }
    footer{ text-align: center; }
}

OBS: sei que deixei o tópico com bastante redundância de informações, peço desculpas por isso, apenas não consegui encontrar outra maneira de especificar tão bem o que eu necessito.
Comment: Você tentou colocar a imagem como background de uma `div` e inserir o texto nessa `div`?  ***Off-topic*** Seria melhor você postar um printscreen do site. Assim, seria mais rápido para o leitor do post.
Comment: é uma boa ideia, tentarei isto e até amanhã ja posto o resultado, valeu pela dica
Answer: Marcus vc vai precisar mexer pouca coisa no CSS
Na classe do logo coloque dessa forma, isso vai alinhar ela no centro horizontal da página e deixar um espaço de 140px do topo da página, deixei o comentário no código:
.logo {
    position: absolute;
    z-index: 2;
    padding: 30px;
    top: 140px; /* altura do topo da página */
    left: 50%; /* classe para centralizar no meio horizontal */
    transform: translateX(-50%); /* classe para centralizar no meio horizontal */
}

Agora o slogan, basta colocar o top:0, porém vc vai precisar fazer um tratamento responsivo nele usando @media para o seu layout não quebrar em telas pequenas.
.slogan {
    position: absolute;
    width: 100%;
    z-index: 3;
    text-align: center;
    top: 0; /* altura do topo da página */
}

Veja no print como ficou no Chrome Desktop
Comment: Oi Hugo, agradeço sua ajuda. Porém acho que você não entendeu bem o propósito da questão rsrsrsrsrs. Eu gostaria de colocar apenas o elemento preto no centro da pagina e o texto em cima deste. A logo fica onde estava, no canto superior esquerdo
Comment: PS: quando eu digo "colocar em cima" não é em cima de posição, mas sim, sobreposição, usar a imagem como fundo, entende?
Comment: @MarcusVinicius tentei olhar agora e o site da Agencia parece que está offline, ai não da pra eu te ajudar, mas se o silte voltar pro ar eu tento ver o que da pra fazer. Mas se me lembro a logo (texto + simbolo) era um .png só, vc vai ter que separar a logo em duas imagem, uma com o texto e outra com o simbolo e alinha-las. Se é o que eu entendi que vc quer...

Ajuda para sobrepor texto em imagem


How can i display tokens with html tags?

Question: On assigning tokens(both custom and exisiting tokens) with values like
$replacements[$original] = "Hello";

and then using that token either in full html or any other text format(all the text formats) it displays on the screen Hello i.e actual tags are being rendered instead of Hello . Same is happening with other html tags i.e entire

 all the html tags get display.
This although does not happen in Drupal 7.
Is there any configuration i am missing? How to render html values properly using tokens?
Answer: Try this one -
$replacements[$original] = \Drupal\Core\Render\Markup::create("Hello");

Helpful links:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Markup.php/class/Markup/8.2.x
http://www.drupaldump.com/drupal-8-how-have-custom-tokens-html-them-properly-replaced
Answer: If you just need to access the token under the html tag then another way is that, you just create token as
  switch ($name) {
   case 'custom_token':
     $text = 'Hello World!';
     $replacements[$original] = $text;
   break;

After, into the body part you can access this token with html tags.
(i.e) [custom:custom_token]

even i used it as screen shot

Answer: After you replace, you have to use:
'htmlspecialchars_decode' like this:
$body = htmlspecialchars_decode($token->replace($body, $data));

Comment: The problem with this solution is it will decode the entire $body which may be undesirable. Ideally the solution would only affect the tokenized values.


Expectation value and conditional expectation

Question: I was wondering how the ordinary expectation value $E(X)$ is related to $E(X|\mathcal{F})$ where $\mathcal{F} \subset \mathcal{E}$ where the latter is supposed to be the sigma algebra on our probability space.
My first thought was that $E(X|\mathcal{E}) = E(X),$ but this is clearly wrong, as $X$ is $\mathcal{E}$ measurable and thus $E(X|\mathcal{E})= X.$
Then I noticed that by the total law of expectation $E(E(X|\mathcal{F}))=E(X)$ we have something like a tower property for the standard expectation value, but in the sense that $E(.)$ wins over any $E(.|\mathcal{F}).$ Spoken in terms of tower properties, this would mean that if $E(X)$ can be represented as a conditional expectation, it must be a maximally small sigma algebra. So my guess is $E(X|\{\emptyset, \Omega\})=E(X),$ is this true?
At first glance, it seems to fulfill all the properties of the conditional expectation, so my guess is yes, but I would like to have your confirmation.
Answer: Yes, this is true. By the definition of the conditional expectation, $\operatorname E(X\mid\{\emptyset,\Omega\})$ is a random variable $Y$ that is $\{\emptyset,\Omega\}$-measurable and $\operatorname E[XI_A]=\operatorname E[YI_A]$ for every $A\in\{\emptyset,\Omega\}$. If $A=\Omega$, then $I_A=1$ and $\operatorname EX=\operatorname EY$, if $A=\emptyset$, then $I_\emptyset=0$. Hence, $Y$ is a random variable that is equal to $\operatorname EX$ almost surely. We can think about $\{\emptyset,\Omega\}$ as a $\sigma$-algebra that contains no information and the best way in some sense to predict the value of a random variable $X$ is $\operatorname EX$ if we have no additional information (see this answer).
Answer: Yes, you are right. As constants are $\{\emptyset,\Omega\}$-measurable, the constant $E[X]$ is, moreover we have
$$ \int_\Omega E[X]\, dP = \int_\Omega X\, dP $$
and likewise for the empty set, so $E[X]$ is the conditional expectation with respect to the trivial $\sigma$-algebra $\{\emptyset, \Omega\}$


Ler arquivo em pasta anterior python

Question: então estou querendo salvar um arquvio python numa pasta anterior ao que está rodando o script
ex:meu script esta no diretorio /app/controllers/script.py
eu quero colocar o arquivo que eu vou criar na pasta: /app/statics/download/arq.zip
codigo:
import os.path
basedir = os.path.abspath(os.path.dirname(__file__))

localsalvar = basedir + '../statics/downloads/'
with open(localsalvar + id + '.zip', "w") as f:
    f.write(cvcompacto)#criando o arquivo .zip

Ele nao ta conseguindo subir de pasta, ta achando que o '/../' é uma pasta
FileNotFoundError: [Errno 2] No such file or directory: '/root/extrator/app/controllers../statics/downloads/9837509907462335.zip'

Comment: Lucas, já tentou colocar apenas o valor '../static/downloads/' sem concatenar o basedir?
Comment: Sim sim da o mesmo problema
FileNotFoundError: [Errno 2] No such file or directory: '../statics/downloads/'
Answer: No caminho da mensagem de erro
'/root/extrator/app/controllers../statics/downloads/9837509907462335.zip'

está aparentemente faltando um separador de diretórios (barra) entre 'controllers' e '..' - seu sistema está procurando por uma pasta chamada 'controllers..', que provavelmente não existe.
Modifique a linha
localsalvar = basedir + '../statics/downloads/'

para
localsalvar = basedir + '/../statics/downloads/'

ou melhor ainda, utilize os.path.join para que seu código adicione os separadores automaticamente (funcionando tanto para Windows quanto para Mac e Linux):
localsalvar = os.path.join(basedir, '..', 'statics', 'downloads')

Comment: Então ele continua o mesmo erro, ele ta entendendo que o '..' é o nome de uma pasta

```python
FileNotFoundError: [Errno 2] No such file or directory: '/root/extrator/app/controllers/../statics/downloads/9837509907462335.zip'
```
Comment: Por favor confirme que o diretório `'/root/extrator/app/statics/downloads/` existe no seu computador. O caminho parece válido, portanto a única forma de gerar este erro é se o diretório não existir.
Answer: No Python, para mover um arquivo para outro diretório basta usar o módulo shutil:
import shutil
shutil.move("cvcompacto", "/../statics/downloads/")

Ler arquivo em pasta anterior python


Must $Q^\mathsf{T}Q = I$ if $(Qx)^\mathsf{T}(Qx) = x^\mathsf{T}x$

Question: Suppose $Q$ is a matrix (perhaps neither square nor real) that satisfies $(Qx)^\mathsf{T}(Qx) = x^\mathsf{T}x$ for all real column vectors $x$ of the right dimensions.
Must $Q^\mathsf{T}Q = I$? Why?
Answer: Yes if $Q$ is real; if $Q$ isn't real you probably don't want to be taking the transpose.
First note that by polarization this condition is equivalent to the condition that $\langle Qx, Qy \rangle = \langle x, y \rangle$ for all vectors $x, y$, where $\langle x, y \rangle = x^T y$. This is in turn equivalent to the condition that $\langle x, Q^T Q y \rangle = \langle x, y \rangle$ for all $x, y$, or
$$\langle x, (Q^T Q - I) y \rangle = 0$$
for all $x, y$. Taking $x = (Q^T Q - I) y$ gives that $\| (Q^T Q - I) y \| = 0$ for all $y$, hence $(Q^T Q - I) y = 0$ for all $y$, hence $Q^T Q = I$.
Matrices satisfying this condition are sometimes called isometries.
Answer: Note that $(Qx)^T(Qx)=x^Tx$ is equivalent to $x^TQ^TQx=x^Tx$ for all $x$. Thus for all $x,y$,
$$ (x+y)^T(x+y)=(x+y)^TQ^TQ(x+y)^T$$
or
$$ x^Tx+2x^Ty+y^Ty=x^TQ^TQx+2x^TQ^TQy+y^TQ^TQy$$
from which one has
$$ x^Ty=x^TQ^TQy. $$
Take $x=e_i,y=e_j$ and then
$$ (Q^TQ)_{ij}=\delta_{ij}, i,j=1,2,\cdots,n. $$
Thus $$ Q^TQ=I.$$


Bisector of two lines in the euclidean space $\mathbb{E}_3$

Question: Let $$r: \begin{cases} x  +  z = 0 \\ y + z + 1 = 0\end{cases}$$ and $$s: \begin{cases} x  - y - 1  = 0 \\ 2x - z -1 = 0\end{cases}$$
be two lines in the euclidean space $\mathbb{E}_3$. It is easily seen that their intersection is one point.
How do I find the cartesian equation of the bisector of the angle that these lines form?
Answer: The unit direction vectors of the first line and the second line are
$$\overline a=\left(\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},-\frac{1}{\sqrt{3}}\right)$$
and
$$\overline b=\left(\frac{1}{\sqrt{6}},\frac{1}{\sqrt{6}},\frac{2}{\sqrt{6}}\right),$$
respectively. (The scalar product of these two vectors is $0$. That is, our lines are perpendicular.)
(Proof: Take $x=0$ and $x=1$. In the case of the first line we have  $(0,-1,0)$ for $x=0$ and $(1,0,-1)$ for $x=1$. Subtracting the first vector from the second one: a direction vector is $(1,1,-1)$; the length of this vector is $\sqrt{3}$. Then, in the case of the second line if $x=0$ then $(0,-1,-1)$ , if $x=1$ then we have $(1,0,1)$ . Subtracting the first vector from the second one we get $(1,1,2)$, the length is then $\sqrt{6}$.)
Summing $\overline a$ and $\overline b $ we get the following vector
$$\overline c=\left(\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{6}},\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{6}},-\frac{1}{\sqrt{3}}+\frac{2}{\sqrt{6}}\right).$$
I claim that $(\overline c, \overline a, \overline b)$ are coplanar and $\overline c$ is their angle bisector. This follows from the paralelogramma rule but it can be checked by taking the following scalar products $$(\overline a,\overline c)=(\overline b,\overline c)=1.$$ So, these angles equal. (Don't be mistaken, the length of $\overline c$ is not $1$. So, the value $(1)$ of the scalar products does not tell exactly the value of the angle, it tells only that the angles equal. But we know that the angle is $\frac{\pi}{4}.$
The two lines meet at the point
$$\overline m=\left(\frac{1}{3},-\frac{2}{3},-\frac{1}{3}\right).$$
As a result the angle bisector line in parametric form is
$$\overline  l= \overline m+ t\overline c, \ -\infty \le t \le \infty.$$
Or
$$x(t)=\frac{1}{3}+t\left(\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{6}}\right) \tag 1,$$
$$y(t)=-\frac{2}{3}+t\left(\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{6}}\right) \tag 2,$$
$$z(t)=-\frac{1}{3}+t\left(-\frac{1}{\sqrt{3}}+\frac{2}{\sqrt{6}}\right) \tag 3.$$

In order to get the Cartesian equation of the angle bisector line, first, we express $t$ from $(1)$:
$$t=\frac{x-\frac{1}{3}}{\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{6}}} \tag 4$$
Subtracting $(2)$ from $(1)$ we get
$$x-y=1. \tag 5$$
Comparing $(3)$ and $(4)$ gives that
$$z=-\frac{1}{3}+\left(x-\frac{1}{3}\right)\frac{2-\sqrt 2}{1+\sqrt 2}  \tag 6.$$
Finally, $(5)$ and $(6)$ are the Cartesian equations of the angle bisector.
Answer: You said "easy to see" so I am assuming you know how to find it: you find the parametric equation of the lines in the form:
$x=a_1t+k$, $y=b_1t+l$, $z=c_1t+m$
And then your vectors become $(a_1,b_1,c_1)$ and $(a_2,b_2,c_2)$
And then you use the following formula and find $\theta$


Adding a specific property to each json object in an array in powershell

Question: I have an array of JSON objects and I want to add a particular property to each object present.
For example, the array is as follows:
[
    {
        "Average":  1.3085,
        "ExtendedStatistics":  {

                               },
        "Maximum":  0,
        "Minimum":  0,
        "SampleCount":  0,
        "Sum":  0,
        "Timestamp":  "\/Date(1496972280000)\/",
        "Unit":  {
                     "Value":  "Percent"
                 }
    },
    {
        "Average":  1.4324999999999999,
        "ExtendedStatistics":  {

                               },
        "Maximum":  0,
        "Minimum":  0,
        "SampleCount":  0,
        "Sum":  0,
        "Timestamp":  "\/Date(1496944680000)\/",
        "Unit":  {
                     "Value":  "Percent"
                 }
    }
]

I want to add "source": "CPU" to all objects. How do I go about doing that? I am new to PowerShell and haven't been able to get this done.
Answer: You could do the following:
$JSON | ConvertFrom-Json | ForEach-Object {
    $_ | Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru
} | ConvertTo-Json

This assumes your JSON input is in a variable named $JSON, you'll need to replace this with however you access your JSON content (e.g Get-Content yourfile.json).
Once you have the JSON, we use ConvertFrom-JSON to convert it to a PowerShell object.
We then use the pipeline to send this to a ForEach-Object loop which uses the Add-Member cmdlet to add a property to each item in the collection (the current item is represented by $_) named 'Source' with a value of 'CPU'. Per the comments from mklement0, it is necessary to use the -PassThru switch to send the result back to the pipeline.
Then we pipe that output to ConvertTo-JSON to convert it back.
Answer:
Mark Wragg's helpful answer works well, but you may wonder why the Add-Member cmdlet cannot be piped to directly, as opposed to requiring an enclosing ForEach-Object call:
Arguably, the following should work, but in Windows PowerShell doesn't:
# !! Does NOT work as expected in Windows PowerShell.
# OK in PowerShell (Core) 7+
$JSON | ConvertFrom-Json |
  Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru

The idea is that Add-Member uses pipeline input directly, and, after modifying each input object, outputs it, thanks to -PassThru (by default Add-Member produces no output).
The reason that it doesn't work is that when Windows PowerShell's ConvertFrom-Json outputs an array, it outputs it as a single object rather than sending its elements one by one through the pipeline, as one would expect.

In PowerShell [Core] 7.0, the behavior was changed to align with the usual enumeration-of-elements behavior, and a -NoEnumerate switch was added as an opt-in to the old behavior. For the discussion that led to this change, see GitHub issue #3424.

Workarounds:

Use (...), which forces enumeration of the array:

# Enclosing the ConvertFrom-Json command in (...) forces enumeration.
($JSON | ConvertFrom-Json) |
  Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru

Note that, generally, using (...) to force collection of a command's entire output in-memory in an array is convenient, but can be problematic with large output sets. As PetSerAl points out, however, in this case it is fine, because ConvertFrom-Json itself constructs the entire output array in memory up front anyway.

Alternative: A pass-through call to
Write-Output -NoEnumerate (Windows PowerShell) /
just Write-Output (PowerShell Core), whose sole purpose is to force enumeration of the array elements:

# Inserting Write-Output [-NoEnumerate] between ConvertFrom-Json and Add-Member
# forces enumeration of the array elements.

# *Windows PowerShell*, as of v5.1:
$JSON | ConvertFrom-Json | Write-Output -NoEnumerate |
  Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru

# PowerShell *Core*:
$JSON | ConvertFrom-Json | Write-Output |
  Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru

Optional reading: the quirks of Write-Output:
Windows PowerShell as of v5.1:
Due to a bug, Write-Output invariably enumerates single objects that are collections themselves, even when you add -NoEnumerate.
Paradoxically, -NoEnumerate is actually needed in this case - even though we do want to enumerate! - so as to prevent Write-Output from applying enumeration twice: once (invariably) to the input array, and again to the individual array elements (thanks again, PetSerAl); e.g.:
# !! Unexpectedly returns 4(!): enumerates the outer 2-element array
# !! *and* its elements.
# (In PowerShell *Core*, this yields 2, as expected.)
Write-Output -InputObject (1, 2), (3, 4) | Measure-Object

# BETTER: yields 2, because only the outer 2-element array is enumerated
# (In PowerShell *Core*, this yields 1, as expected.)
Write-Output -NoEnumerate -InputObject (1, 2), (3, 4) | Measure-Object

PowerShell (Core) v6.2.3+:
The above problem has been fixed - see GitHub issue #5955 - which means that - sensibly - you mustn't use -NoEnumerate if you do want Write-Output to enumerate pipeline objects that are themselves collections (and enumeration no longer recurses 1 level).


Como obter o id do botão clicado em uma linha de listagem de resultados pelo Angular JS?

Question: Como obter o id do botão clicado em uma linha de listagem de resultados pelo Angular JS?
No página HTML posso usar o list.id, porém no código em AngularJS, os códigos abaixo me retornam undefined:
id;

$scope.id;

$scope.listagensRelatorios.id;

$scope.parametro.id;

$routeParams.id

    app.controller("listagemRelatoriosController", function($scope, $http, $location, $q) {

    $scope.listagensRelatorios = [];
    $scope.listagemRelatorio = {};

    carregarListagemRelatorios = function() {

        $http({
            method : 'GET',
            url : 'http://localhost:8080/listagemRelatorios',

        }).then(function(response) {
            $scope.listagensRelatorios = response.data;

        }, function(response) {
            console.log(response.data);
            console.log(response.status);
        });

    };

    gerarRelatorioSelecionado = function() {

        $http({
            method : 'GET',
            url : 'http://localhost:8080/listagemRelatorios' + $scope.listagensRelatorios.id,

        }).then(function(response) {
            $scope.listagensRelatorios = response.data;

        }, function(response) {
            console.log(response.data);
            console.log(response.status);
        });

    };

    carregarListagemRelatorios();
    gerarRelatorioSelecionado();

});

Answer: Você pode passar o id na chamada da função no html.
HTML:

List item

Função:
 $scope.getId = function(param) {
   console.log(param);
   //insira o código aqui
 }

Espero ter ajudado.


Is there a way to make the icons in Geany IDE brighter?

Question: I'm using the Geany IDE with the GTK3 theme set to Adwaita-Dark. For the most part this works perfectly fine. However, the icons at the top screen are too dark to see clearly:
Is it possible to change these icons to make them more visible against the dark background? Thanks for any help!
Answer: I fixed it. If anyone else is in a similar situation I used the Xfce appearance settings (I'm using Manjaro Linux). In retrospect it was a little illogical to be searching for solutions using the GTK settings when I have an Xfce desktop, but now I know.


iOS: Xcode appears to be inserting an extra space into XIB file name causing "Could not load XIB file" issue

Question: I have a UITableViewController that uses custom table view cells (and I have created an XIB for my custom UITableViewCell subclass)
When my app attempts to load the table view controller it crashes with the following error:
<code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/CoolDocsMan/Library/Application Support/iPhone Simulator/5.1/Applications/Z7BB7085F-37A7-4B92-89A3-37EC34531B08/FunkySpaces.app> (loaded)' with name 'AdminConfirmTableViewCell''
</code>
Following one of the suggestions in the post Could not load NIB in bundle, I checked the app folder in my Libraries by exploring contents of:
<code>/Users/CoolDocsMan/Library/Application Support/iPhone Simulator/5.1/Applications/Z7BB7085F-37A7-4B92-89A3-37EC34531B08/FunkySpaces.app
</code>
I am using the same technique for other similar tableVCs but found that while all other XIB files were properly translated into .nib this specific tableview cell XIB got tranlated with an extra space at its end.
i.e. 'AdminConfirmTableViewCell .nib'  instead of 'AdminConfirmTableViewCell.nib'
I did a global search in XCode to see if I had made a typo and inserted an extra space after AdminConfirmTableViewCell, but found none.
Here is section of code from the ViewDidLoad of the tableVC which contains the AdminConfirmTableViewCell:
<code>//Load the NIB file
UINib *nib = [UINib nibWithNibName:@"AdminConfirmTableViewCell" bundle:nil];

//register this NIB whch containes the cell
[[self tableView] registerNib:nib forCellReuseIdentifier:@"AdminConfirmTableViewCell"];
</code>
Thanks!
Answer: this is my first answer in stack overflow! How about trying this, obviously customising to your needs
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

RootViewController *addController = [[RootViewController alloc]
                                      initWithNibName:@"nibnamehere" bundle:nil];

UINavigationController *navigationController = [[UINavigationController alloc]
                                                initWithRootViewController:addController];
[self presentModalViewController:navigationController animated:NO];

[navigationController release];
[addController release];
</code>
}
Comment: thanks for taking the time to respond and congrats on putting up your first answer. I was looking for something specific to the extra space not a redesign :-)
Answer: I found the problem finally and understand now why it was not showing up when I scanned the code. The issue is actually in the way I specified the Custom Class for my custom UITableView cell (AdminConfirmTableViewCell) under Identity inspector in interface builder.
I had spelled out 'AdminConfirmTableViewCell ' with an extra space at the end in Identity Inspector under Custom Class...therefore the AdminConfirmTableViewCell.xib had this name with the extra space (see screenshot...) and while building, XCode translated this into a NIB file as 'AdminConfirmTableViewCell. nib' with an extra space.
On removing the extra space everything worked out! It appears quite unlike Apple to leave this gap in Interface Builder implementation which allows a developer to potentially make these kind of errors.


Electric Violin care

Question: I'm a beginner violinist. I'm planning to buy a used electric violin, but I don't know  much about them.
Is the maintenance for an electric violin the same as with the acoustic one?
Any tips on how to choose one would be highly appreciated.
Comment: The 'gotcha' I wish I'd considered when buying mine is weight. It is so much heavier than my acoustic which makes it is less fun to play (and to carry through airports!)
Answer: What you should look for is a well built instrument, with good sound and that looks and sounds good for you.
If you are inexperienced can be good to take someone with you that is more advanced in violin playing. Anyway you can think about this:

Some electric violins are very heavy, this will hurt your back. Wood violins weight about 0,5 Kg
Check if the overtones are tuned. If the empty strings are tuned then the overtones should also be, otherwise it might be strange proportions in the instrument which will give you problems with intonation.
Try the sound. You have to like the sound of the instrument. Ask also what kind of pickup it has and check the cable exit is comfortable with your way of holding the violin.
Some instruments have nice electronics, like volume knobs and eq, this can be good but not essential. More features more weight and higher price.
Some E.Violin needs a battery inside. In that case you need to change it as a part of the maintenance, and have a spare battery around. Big advantage to violins with batter is that often you can play them with headphones anywhere without needing more power.

The maintenance is very much the same, more simple actually. Cleaning rosin from your strings is one good habit to have.
Comment: String care is certainly part of the maintenance that doesn't change. However, you may choose different types of strings than you would for an acoustic instrument.  On the bright side :-), typically the bridge on an electric sits on a flat surface so it's much easier to replace should the need arise.

Electric Violin care


O que é Jakarta EE?

Question: Só mudou a nomenclatura do JavaEE ou ocorrerão outras alterações significativas?
Terá compatibilidade com JavaEE 8-?
O JavaEE e o JakartaEE serão mantidos pela mesma comunidade?
Answer: JCP (Java Community Process  - https://www.jcp.org/) - é um grupo de padronização da Oracle composto por mais de 800 empresa que definem a tecnologia.
Lembrando que Java não é apenas uma linguagem, é uma plataforma composta de  especificações(documento que diz como deve ser o java),implementações ( que é o software, linguagem, jvm ...) e testes de compatibilidades( que garante que estes softwares podem ser implementados).
Java EE é uma conjunto grande varias especificações feita pela JCP, por exemplo JSP, JMS, Servlets são algumas das especificações que compõe o Java EE.
Ou seja, as empresas se reúnem para fazer as especificações, e depois cada uma desenvolve suas implementações.
Um outro exemplo é o Hibernate que é utilizado para mapeamento objeto relacional, que não existia especificação no Java EE, e posteriormente foi incluido no Java EE através da especificação JPA.
Ultimamente com o lançamento de novos produtos a Oracle havia deixado meio que de lado os investimento no Java EE, sendo que as especificações Java eram em sua maioria quase sempre iniciadas e lideradas pela Oracle. Ou seja, em determinado momento, a Oracle tinha outra prioridades e tinha decidido não continuar seus investimentos no Java EE, e cedeu todos os direitos das especificações do Java EE para a Eclipse Foundation, o que tornou possível a Eclipse Foundation dar continuidade a evolução do Java EE.
A Oracle cedeu todo o código da especificação Java EE para a Eclipse Foundation, mas o nome Java é uma marca registrada da Oracle, e não poderia ser utilizado pela Eclipse Foundation, por isso eles fizeram um estudo e renomearam para Jakarta EE e criaram uma comunidade/organização chamada EE4J - Eclipse Enterprise for Java (EE4J) https://projects.eclipse.org/projects/ee4j, que a responsável pela especificação Jakarta EE.
Logo nos primeiros passos da especificação do Jakarta EE 8 foi especificado que deveria ser mantida a compatibilidade com o Java 8.
Answer: Jakarta EE é a plataforma de desenvolvimento para Java empresarial. Ela é gerenciada pela Eclipse. Eles mudaram o nome antigo, que era JavaEE, porque havia muito referências à plataforma, que será marca registrada da Oracle. A permissão para usar a marca registada "Jakarta EE" dependerá de um programa de compatibilidade, pelo qual as tecnologias candidatas têm de passar e ainda não foi desenvolvido. Ele será gerido pela EE.next.

O que é Jakarta EE?


What is the HTML code for a double forward slash symbol //?

Question: I'm looking for a symbol that looks like two forward slashes in succession. Of course I can just enter two slashes like this: // but I would prefer a single symbol with these slashes very close together. I tried to google it, to no avail.
Answer: You appear to be looking for COMBINING LONG DOUBLE SOLIDUS OVERLAY which you can just enter directly. If you really want to use an entity then it is ⃫.

 ⃫

⃫

You might find font support for it is weak though, it is an obscure combination of diacritical marks.
Comment: That's great! I would certainly prefer to enter it directly. But how do I do it?
Comment: Go to the link above and check out the links starting with 'Browser Test Page'.


Mutually exclusive types in a function signature

Question: Is this possible to achieve with conditional types in TypeScript?
type Type1 = {
  field: string,
}

type Type2 = {
  field: number,
}

// I would like to make sure that if arg1 is Type1 then arg2 is Type2
// and vice versa
const func = (arg1: Type1 | Type2, arg2: Type1 | Type2) {
  // do something
}

Comment: You can achieve this using function overloading
Answer: Yet another solution but this one does not use overloads or is similar to the conditional types provided by @lawrence-witt.
function func(arg1: A, arg2: Exclude<Type1 | Type2, A>) { ... }

You can retain the type of the first argument using a generic, then for the type of the second one, exclude the first argument's type, giving you the other constituents.
Playground with example calls
Answer: There are a few ways you could approach this, but you'll probably find it's easier to just overload the signature and be done with it.
You could use a union of tuples:
const func = (...args: [arg1: Type1, arg2: Type2] | [arg1: Type2, arg2: Type1]) => {
    const arg1 = args[0]
      // Type1 | Type2
    const arg3 = args[2]
      // Property '2' does not exist on type ...
    return;
}

func({field: 32}, {field: "hi"})
  // ok
func({field: "hi"}, {field: 32})
  // ok
func({field: 32}, {field: 2})
  // Type at position 1 in source is not compatible with type at position 1 in target.

This provides fairly descriptive error messages, but the function signature is not easy to read in my opinion.
You could go the conditional route as suggested in your original question:
type Exclusive =
    A extends T1
        ? B extends T2
            ? A : never
    : A extends T2
        ? B extends T1
            ? A : never
    : never;

type ExclusiveTypes = Exclusive

const func = <T, U>(arg1: ExclusiveTypes<T, U>, arg2: ExclusiveTypes) => {
    return;
}

func({field: 32}, {field: "hi"})
  // ok
func({field: "hi"}, {field: 32})
  // ok
func({field: 32}, {field: 2})
  // Type 'number' is not assignable to type 'never'.

The signature here is even more obscure to me, and the error message is not very useful at all. It's confusing to be told that a parameter is never.
Or you could use overloads:
function func(arg1: Type1, arg2: Type2): void;
function func(arg1: Type2, arg2: Type1): void;
function func(arg1: Type1 | Type2, arg2: Type1 | Type2) {
    return
}

func({field: 32}, {field: "hi"})
  // ok
func({field: "hi"}, {field: 32})
  // ok
func({field: 32}, {field: 2})
  // No overload matches this call.

This is still the idiomatic way to handle polymorphic function signatures in TypeScript.


Converter List para T... dinamicamente na chamada de um metodo

Question: Estou necessitando de algo que parece ser simples, mas já estou a algum tempo pesquisando e tentando e não encontrei nada que me ajuda-se.
Problema
Tenho uma lista do tipo List<T> que recebo como parâmetro de um outro método, e tenho que fazer uma chamada para um método que recebe T... como parâmetro.
Pergunta
Como eu faria para converter dinamicamente um List<T> para T...?
Exemplo
Para exemplificar, vou mostrar o que estou fazendo em minha situação real:
private Object invokeMethodPrivateClassBase(Class<?> clazz,
        String nameMethod, List<Class<?>> paramsTypeClazz, Object... args) {
    try {
        // esse método 'getDeclaredMethod' recebe o primeiro parâmetro String e o segundo Object...,
        // mas eu não posso receber 2 (dois) parametros '?...', pois só o ultimo pode ser desse tipo (por questões obvias).
        Method method = clazz.getDeclaredMethod(nameMethod, paramsTypeClazz);
        method.setAccessible(true);
        return method.invoke(AbsHorizontalListView.this, args);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    return null;
}

Comment: Convertendo para `array` não funciona? Usando o `toArray`?
Comment: @Wakim, sim, tinha acabado de ver isso [aqui](http://www.mkyong.com/java/how-to-use-reflection-to-call-java-method-at-runtime/), e ver que `T...`, nada mais é que `T[]`, então é só eu pegar minha `List list` e dar um `list.toArray()` como você disse, valeu ai. Se você puder/quiser elaborar uma boa resposta para futuras pesquisas, eu analiso depois. (Tem horas que coisa simples parecem complicadas, hehe).
Answer: Preparei um exemplo funcional de como o método com argumentos variados deve ser chamado.
A ideia principal é você deve passar um array de parâmetros para o invoke, só que os argumentos de tamanho variado devem ser um outro array que será o último elemento do array principal.
Considere os comentários no código que explicam passo-a-passo o que ele faz:
class Exemplo {

    private static Object invokeMethodPrivateClassBase(
            Class<?> clazz,
            Object instance,
            String nameMethod,
            List<Class<?>> paramsTypeClazz,
            Object... args) {
        try {

            //localiza o método
            Method method = clazz.getDeclaredMethod(
                nameMethod,
                paramsTypeClazz.toArray(new Class[paramsTypeClazz.size()]));

            //torna-o acessível mesmo sendo private
            method.setAccessible(true);

            //verifica se tem argumentos variados
            if (method.isVarArgs()) {

                //cria um array de parâmetros que deve ter a exata quantidade de parâmetros declarados,
                //isto é, sem considerar os argumentos variantes
                Object[] parameters = new Object[paramsTypeClazz.size()];

                //copia os parâmetros fixos para o novo array, desconsiderando apenas o último que é variante
                System.arraycopy(args, 0, parameters, 0, paramsTypeClazz.size() - 1);

                //calcula quantos argumentos variantes foram passados
                int varArgsSize = args.length - paramsTypeClazz.size() + 1;

                //cria um array com o tipo dos parâmetros variantes
                Object varArgsParameter = Array.newInstance(
                    paramsTypeClazz.get(paramsTypeClazz.size() - 1).getComponentType(),
                    varArgsSize);

                //copia todos os demais argumentos para o array de argumentos variantes
                System.arraycopy(args, paramsTypeClazz.size() - 1, varArgsParameter, 0, varArgsSize);

                //coloca o array de argumentos variantes como último parâmetro para o método a ser chamado
                //isso porque o "..." equivale a um array
                parameters[paramsTypeClazz.size() - 1] = varArgsParameter;

                //chama o método
                return method.invoke(instance, parameters);
            } else {
                return method.invoke(instance, args);
            }
        } catch (Throwable e) {
            //apenas para teste
            System.out.println(e.getMessage());
        }
        return "Y";
    }

    /**
     * Método de exemplo a ser chamado via reflexão
     */
    public String meuMetodo(String label, Integer... valores) {
        Integer soma = 0;
        for (Integer v : valores) soma += v;
        return label + ": " + soma;
    }

    public static void main (String[] args) throws java.lang.Exception {

        //modo normal
        System.out.println(new Exemplo().meuMetodo("S1", 3, 4, 1));

        //prepara lista de tipos dos argumentos
        List<Class<?>> paramsTypeClazz = new ArrayList<Class<?>>();
        paramsTypeClazz.add(String.class);
        paramsTypeClazz.add(Integer[].class);

        //modo reflexivo
        System.out.println(Exemplo.invokeMethodPrivateClassBase(
            Exemplo.class,
            new Exemplo(),
            "meuMetodo",
            paramsTypeClazz,
            "S1", 3, 4, 1));
    }
}

Demo no Ideone
Comment: É até mais do que era esperado para a pergunta, pois nem necessitava chamar um método por _reflection_ que contivesse `varargs` ou "argumentos variados". Ótima explicação e implementação, cobrindo todas os cenários. +1 (Uma boa resposta assim eu esperava [nessa outra pergunta](http://pt.stackoverflow.com/questions/27012/%C3%89-poss%C3%ADvel-chamar-m%C3%A9todo-internalsem-operador-de-visibilidade-de-uma-class-her), hehe)
Comment: @Fernando A resposta do Kyllopardiun é basicamente o que eu recomendaria. Lá, colocar a classe no mesmo pacote não funciona porque o Java implementa restrições de segurança que impede o desenvolvedor de criar classes que executem no mesmo pacote de classes internas dele, evitando que elas acessem atributos e métodos que não deveriam. E a solução por *reflection* não é segredo, basta usar o `setAccessible` mesmo.
Answer: Esse método da classe Class da API do Java recebe uma string e um varargs de Class<?>.
O real problema então é converter seu List<Class<?>> paramsTypeClazz para varargs ou um array.
Neste caso tente o seguinte (não testado):
Class<?>[] arrayDeClass = paramsTypeClass.toArray(new Class<?>[paramsTypeClass.size()]);
Method method = clazz.getDeclaredMethod(nameMethod, arrayDeClass);

Qualquer dúvida é só retornar.
Abraços
Comment: Sim funcionou corretamente, não tinha visto que `varargs` são a mesma coisa de Array ou `T... = T[]`, até que @Wakim citou nos comentários da pergunta. Obrigado pelo esclarecimento. +1