text:
Q: Why does it occur error: type of expression is ambiguous without more context? I am studying the swift programming language.
Now I'm looking at how opaque types works.
Why does it occur error: type of expression is ambiguous without more context? (Swift 5.1)
protocol NumericExpression {
    associatedtype TNumeric: Numeric
    var value: TNumeric { get }
}

struct Expression {

    static func sum<TA: NumericExpression, TB: NumericExpression>(_ a: TA,_ b: TB) -> some NumericExpression
        where TA.TNumeric == TB.TNumeric {

        return NumericExpressionSum(a: a, b: b)
    }

    static func multi<TA: NumericExpression, TB: NumericExpression>(_ a: TA, _ b: TB) -> some NumericExpression
        where TA.TNumeric == TB.TNumeric {

        return NumericExpressionMulti(a: a, b: b)
    }
}

extension Int: NumericExpression {
    var value: Self {
        return self
    }
}

struct NumericExpressionSum<TA: NumericExpression, TB: NumericExpression>: NumericExpression
    where TA.TNumeric == TB.TNumeric {

    let a: TA
    let b: TB
    var value: TA.TNumeric { a.value + b.value }
}

struct NumericExpressionMulti<TA: NumericExpression, TB: NumericExpression>: NumericExpression
    where TA.TNumeric == TB.TNumeric {

    let a: TA
    let b: TB
    var value: TA.TNumeric { a.value * b.value }
}

No compile error.
Sample code with compile error:
var s1 = Expression.sum(1, 2)
var s2 = Expression.sum(2, 3)

var m1 = Expression.multi(s1, s2)
var m2 = Expression.multi(3, 4)

print(m1.value) // 15
print(m2.value) // 12

print(type(of: m1)) // NumericExpressionMulti<NumericExpressionSum<Int, Int>, NumericExpressionSum<Int, Int>>
print(type(of: m2)) // NumericExpressionMulti<Int, Int>

print(type(of: m1).TNumeric) // Int
print(type(of: m2).TNumeric) // Int

let m3 = Expression.multi(m1, m2) //Error: type of expression is ambiguous without more context

Does this work for swift 5.5?
Thanks!


text:
Q: Use Url.Action to generate fully qualified anchor I'm using Url.Action to generate link in e-mails (with the Postal MVC Framework) that was sent by my application, however, the links generates are showing with "localhost" name, and not domain name.
I'm using the following code:
@Url.Action("AlterarSenha", "Account", null, this.Request.Url.Scheme)

The result is the following:
http://localhost/Account/AlterarSenha

After that, I tried the following code:
@Url.Action("AlterarSenha", "Account", null, this.Request.Url.Scheme, Request.ServerVariables["HTTP_HOST"])

And I got the same result.
How can I get the link with my domain like:
http://www.servicili.com/Account/AlterarSenha

A: Assuming that you want to use your domain name in the URL even when the application runs on localhost, you could use this overload of Url.Action:
public virtual string Action(
    string actionName,
    string controllerName,
    RouteValueDictionary routeValues,
    string protocol,
    string hostName
)

And pass your domain name as hostName.
https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action(v=vs.118).aspx

A: if your local server uses port 80 you can use

Url.Action("AlterarSenha", "Account",null, null, "www.servicili.com");

Result is
http://www.servicili.com/Account/AlterarSenha

If your project uses any other port (like 123) the result will be
 http://www.servicili.com:123/Account/AlterarSenha

Also you may set protocol as  https it won't add any port
Url.Action("AlterarSenha", "Account",null, "https", "www.servicili.com");

The result is
https://www.servicili.com/Account/AlterarSenha

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get type of a "singleton type" We can create a literal types via shapeless:
import shapeless.syntax.singleton._
var x = 42.narrow
// x: Int(42) = 42

But how can I operate with Int(42) as a type if it's even impossible to create type alias
type Answ = Int(42) // won't compile
// or
def doSmth(value: Int(42)) = ... // won't compile

A: Int(42) is not a valid Scala syntax for type.
IIRC singleton types were implemented in scalac for a while, but programmers had no syntax of defining such. Shapeless provides that, with macros, as well as some extra machinery.
In particular, shapeless.Witness is an object that contains both type information and associated value, and also can be summoned from either.
import shapeless.Witness
import shapeless.syntax.singleton._
import shapeless.test.illTyped // test string for causing type-errors when compiled

// --- Type aliases ---
val w = 42.witness
type Answ1 = w.T // that is your Int(42) singleton type
type Answ2 = Witness.`42`.T // same, but without extra variable
implicitly[Answ1 =:= Answ2] // compiles, types are the same

// --- Value definitions ---
val a: Answ1 = 42 // compiles, value OK, and no need to `narrow`
illTyped { "val b: Answ1 = 43" } // would not compile
val c: Witness.`43`.T = 43 // that syntax is OK here too

// --- Summoning values ---
val answ = Witness[Answ1].value // will not compile for non-singleton
def genericSingletonMethod[A](implicit W: Witness.Aux[A]) = s"Summoning ${W.value}"
assert { genericSingletonMethod[Answ1] == "Summoning 42" }
assert { genericSingletonMethod[Witness.`"string"`.T] == "Summoning string" }

A: *

*In Typelevel Scala you can write just
val x: 42 = 42

type Answ = 42

def doSmth(value: 42) = ???

*In Dotty Scala you can write the same.

*In Lightbend Scala (i.e. standard Scala) + Shapeless you can write
import shapeless.Witness
import shapeless.syntax.singleton._

val x: Witness.`42`.T = 42.narrow

type Answ = Witness.`42`.T

def doSmth(value: Witness.`42`.T) = ???

In case 1) build.sbt should be
scalaOrganization := "org.typelevel"
scalaVersion := "2.12.3-bin-typelevel-4"
scalacOptions += "-Yliteral-types"

In case 2) build.sbt should be
scalaOrganization := "ch.epfl.lamp"
scalaVersion := "0.3.0-RC2"

and plugins.sbt
addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.1.5")

In case 3) build.sbt should be
scalaOrganization := "org.scala-lang"
scalaVersion := "2.12.3"
libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.2"

*or you can use Typelevel Scala and Shapeless at the same time.

Update. Since version 2.13.0 there are literal types in standard Scala
val x: 42 = 42
val x1: 42 = valueOf[42]

type Answ = 42

def doSmth(value: 42) = ???

https://github.com/scala/scala/releases/v2.13.0 (Language changes / Literal types)


text:
Q: Show mutiple tables on a query I'm currently storing tweets from twitter in a database and I'm storing the user fields in a separate table. I then have a foreign key which links the userid to the tweet. I'm wondering how I should show all of the information from both of the tables.

A: Use an inner join.
select *
from tweets inner join users on tweets.user_id = users.user_id

A: Select t.message, u.name, u.email
  From Tweets t, UsersInfo u
 Where t.userid = u.id

A: You don't give any schema info, so I've made assumptions.
select tweet, date, username from tweets
join user on user.id=tweets.userid;


text:
Q: Is it possible to develop a login xpages base on Lotus Notes Email Client Account? I would like to develop a web application using IBM Lotus Domino Designer 8.5.2.
The web application shall verify user's authentication base on user's Lotus Notes email account information.
More information about Lotus Notes in case it is helpful, users using Lotus Notes as email client, they check email using Lotus Notes. Their given email address like username@companyname.com
Here is my plan, the web application requires the user to enter the username and password to login.
The username and the password should be the same account as the user login to Lotus Notes for email checking, for example, to login to Lotus Notes email client, the username is testusername and the password is testpassword.
The user should enter the same username and the password to login to the web application  (that is testusername for username and testpassword
for password).
Before I post my question, I read the article in this website
http://www-10.lotus.com/ldd/ddwiki.nsf/dx/XPages_in_the_Notes_Client-Security
and I get confuse that should I have 1 or more database for the web application ?
But I just want the web application has a simple login.
Is it possible to develop a web application just use Lotus Notes Email Client account to login?
If so, I guess the validation should perform in xpages, is it correct?
I should be grateful if you would give advice or suggestion on this issue.
Thank you very much.
Yours sincerely,
beginner

A: The login process is a server based process and not based on the database directly.
First of all the Domino- server you try to access has to be configured to use a session based login, otherwise you are not able to use a login page and might be asked for your Login- Credentials multiple times in one sesssion.
Please ask your Domino- Administrator to do this.
Second: Usually there is a "domcfg.nsf" on the server to configure the login- forms. Without that you would just see an ugly yellow page with username and password- prompt.
Third: The users in the domino directory need to have an "Internet Password" set in their person document. This can be done manually or by synching the Notes ID password to the internet password using a policy (again: ask your admin, how it is configured in your environment)
Last (but not least): The acl of your application containing your XPage needs to have a proper ACL set (do not allow anonymous access).
If all of that requirements are met, you will be automatically prompted for a password when trying to accesss your XPage application, and after that be redirected to the reuqested page.
In a next step you can customize the Login page to fit the design of your XPage or even write a new login- page using XPages.
Security is by default built into domino, you just have to use it...


text:
Q: Accessing HttpServletRequest properties within a WebSocket @ServerEndpoint I need to access the HttpServletRequest properties to get the javax.servlet.request.X509Certificate which contains the X509Certificate array of certificates for TLS requests.
From a JAX-RS ContainerRequestFilter I can easily extract this from the ContainerRequestContext.getProperty(String property) method, but I can't find a way to get it from the WebSocket Session nor the HandshakeRequest, from which I can access the HttpSession instance but not the HttpServletRequest one.
Note: this is not a duplicate of Accessing HttpSession from HttpServletRequest in a Web Socket @ServerEndpoint since I need accesso to the HttpServletRequest (or equivalent to extract the TLS certificates), not HttpSession.
Since WebSocket is a superset of HTTP, I guess it should be possibile and hope the Java team had thought of a way to access the servlet properties, but I really couldn't find one. Anyone knows if this is possible at all?

A: Without hacking:

*

*Create servlet filter on URL pattern matching websocket handshake request.

*In filter, get request attribute of interest and put it in session before continuing chain.

*Finally get it from the session which is in turn just available via handshake request.

With hacking:

*

*Use reflection to find ServletRequest field in handshake request instance.

*Get its javax.servlet.request.X509Certificate attribute.
In other words:
public class ServletAwareConfigurator extends Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        ServletRequest servletRequest = getField(request, ServletRequest.class);
        X509Certificate[] certificates = (X509Certificate[]) servletRequest.getAttribute("javax.servlet.request.X509Certificate");
        // ...
    }

    private static <I, F> F getField(I instance, Class<F> fieldType) {
        try {
            for (Class<?> type = instance.getClass(); type != Object.class; type = type.getSuperclass()) {
                for (Field field : type.getDeclaredFields()) {
                    if (fieldType.isAssignableFrom(field.getType())) {
                        field.setAccessible(true);
                        return (F) field.get(instance);
                    }
                }
            }
        } catch (Exception e) {
            // Handle?
        }

        return null;
    }

}


text:
Q: Moment JS Date and time to timestamp in moment.js I am getting a text value and it is formatted like this : "9/19/2018 10:00 AM".
How would you go about turning this into an epoch timestamp using moment.js or just javascript?
EXAMPLE:
console.log(moment('4/17/2018 10:00 AM', 'mm/dd/yyyy hh:mm a').format('x'));

A: Use the date string to create a date Object and then use getTime() method of the Object.

date = new Date("9/19/2018 10:00 AM");
console.log(date.getTime())

A: normal js
new Date("9/19/2018 10:00 AM");

if you want to do with moment js
moment("9/19/2018 10:00 AM").unix()

A: The issue in your code is that you are using wrong tokens while parsing your input. Moment token are case sensitive and mm stands for 0..59 minutes, dd stands for day name (according locale) and there is no lowercase yyyy supported.
Use M for 1..12 month number, uppercase D or DD for day of month and uppercase YYYY for year as stated in moment(String, String) docs.
Your code could be like:

console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').format('x'));
console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Note that you can use both format('x') (returns a String) and valueOf() (returns a Number).
I suggest to use moment(String, String) over new Date() (Date.parse()) because this way you explicitly state how to parse you input (what would you expect for input like 1/2/2018? 1st of February or January 2nd?). See here a note about Date.parse behaviour

Somewhat surprisingly, these formats (e.g. 7/2/2012 12:34) are also unambiguous. Date.parse favors US (MM/DD/YYYY) over non-US (DD/MM/YYYY) forms.
These formats may be ambiguous to humans, however, so you should prefer YYYY/MM/DD if possible.


text:
Q: THREE.meshphongmaterial Not Working - Giving Black Color I am trying to use THREE.meshphongmaterial from this tutorial: http://solutiondesign.com/webgl-and-three-js-texture-mapping/
But it is not working and giving black color. Here is the jsfiddle for it: http://jsfiddle.net/8hrk7mu6/12/
Problem is in line 32:
var material = new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x0033ff, specular: 0x555555, shininess: 30 } );

Why is it not working? If I use THREE.MeshNormalMaterial, then it works.
var material = new THREE.MeshNormalMaterial();

Later, I want to use texture from an image in my code. That is not working either. Only THREE.MeshNormalMaterial is working. Why?

A: Turns out it is necessary to add light. Without light, meshphongmaterial gives black color.
So I had to add something like this:
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 1 ).normalize();
scene.add(light);

Got it from this link: https://github.com/mrdoob/three.js/issues/2766

A: Adding some ambient light to everything in the scene is the simplest solution:
scene.add(new THREE.AmbientLight(0x404040))

A: You will need to add some Ambient Light or Point Light since,
MeshPhongMaterial reacts to Light & hence is only visible in presence of Light, for best results/visibility use below code:
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);

const pointLight = new THREE.PointLight(0xffffff, 0.5);
pointLight.position.x = 2;
pointLight.position.y = 3;
pointLight.position.z = 4;

scene.add(ambientLight, pointLight);

A: Setting the emissive value was recommended by Terg's Three.js Learning QuickStart. The less lights you have the faster it renders.


text:
Q: Resolve relative ("~") paths without reference to the current Page? I am writing a generic library for use by all of my web projects. One of the functions is a permanent redirect as below:
public static void PermanentRedirect(string url, HttpResponse response, bool endResponse)
{
    url = //resolve url here. how?

    response.Status = "301 Moved Permanently";
    response.AddHeader("Location", url);

    if (endResponse) response.End();
}

How can I resolve the URL without having to pass the current page to get access to Page.ResolveUrl? Note, I can change the method signature, but I would prefer not to because I think it would overburden the API.
I have a couple overloads for this so my desired usage is:
WebUtility.PermanentRedirect("~/somewhere/somepage.aspx")

A: I believe you can use HttpRuntime.AppDomainAppVirtualPath as a direct replacement for tilde.
You can also use VirtualPathUtility.ToAbsolute, but it doesn't like query strings - so you have to parse them out (or, preferably, use UriBuilder).
Oh - and off-topic, but IMHO an extension method off HttpResponse would make syntax a bit easier.

A: This method should work:
url = VirtualPathUtiliy.ToAbsolute(url);

A: You can get the current page instance via HttpContext.Handler:
var page = HttpContext.Current.Handler as Page;
if (page != null)
{
     // Use page instance, f.e. page.Request.Url;
}

By the way, you don't need to pass the HttpResponse either:
HttpResponse response = HttpContext.Current.Response;

http://msdn.microsoft.com/en-us/library/system.web.httpcontext.response.aspx


text:
Q: Wordpress Blog on Subfolder of Ruby on Rails App Hosted on Heroku I'm having trouble with this. I currently have a wordpress blog on my subdomain, like this: www.blog.websitename.com. However I want to move it to www.websitename.com/blog.
This is where the problem lies because at www.websitename.com, I have a ruby on rails app that's hosted on Heroku. I haven't been able to find any instructions on how to do this.
Would love anyone's suggestions!

A: In your database you have to serach www.blog.websitename.com and replace it with www.websitename.com/blog.
There is a nice script for this I often use for this purpose:
https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
Download it, upload it into your wordpress folder and call it via webrowser.
Maybe, if you have a .htaccess file in your wordpress folder, you have to adjust the path on 2 lines:
From:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

To:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>


text:
Q: UISearchController Difference firstresponder and isActive when using the function
func updateSearchResults(for searchController: UISearchController) {

    if let searchBarText = searchController.searchBar.text {
        self.text = searchBarText
    }
    print("searchController firstResponder", searchController.isFirstResponder.description)
}

I get this output, although im clicking in the searchbar and it activates. Why is that?
searchController firstResponder false
searchController firstResponder false
searchController firstResponder false
searchController firstResponder false

When using the  searchController.isFirstResponder.description property it looks right. What's the difference between the two. Isn't the searchbar the first responder when clicking into that and the keyboard shows up?


text:
Q: Does Scale out in Azure web app service with enabled health-check count CPU on unhealthy instances? I have an Azure web app service with enabled Health-check feature and the following auto-scale configuration:
{
    "name": "Auto created scale condition",
    "capacity": {
        "minimum": 2,
        "maximum": 10,
        "default": 2
    },
    "rules": [
        {
            "metricTrigger": {
                "metricName": "CpuPercentage",
                "metricNamespace": "",
                "metricResourceUri": "[resourceId('Microsoft.Web/serverfarms', parameters('ServicePlanName'))]",
                "timeGrain": "PT1M",
                "statistic": "Average",
                "timeWindow": "PT10M",
                "timeAggregation": "Average",
                "operator": "GreaterThan",
                "threshold": 70
            },
            "scaleAction": {
                "direction": "Increase",
                "type": "ChangeCount",
                "value": "1",
                "cooldown": "PT5M"
            }
        }
    ]
}

The question: Does Azure count unhealthy instances for CPU loading while scaling up and down? I don't see this in official documentation and also I did some tests making one instance unhealthy but have got some unclear results.
So, let's imagine an unhealthy instance has 0% CPU usage and the healthy one has 90% CPU. So, totally on average we have (0%+90%)/2=45%. Will scale-out rule work in this case?
Thanks

A: The scale out logic does not look at whether your instances are healthy. Likewise, if an instance becomes unhealthy because of something like a dead lock in your code and causes the instance to reach 100% CPU usage, your scale out logic would trigger adding an additional instance, even though the increased CPU usage isn't being triggered by additional users.
To mitigate unhealthy instances quickly and automatically until you are able to resolve the issue within your code, we typically recommend customers turn on auto-heal and set it to restart the site process based on the parameters that you feel are occurring such as http errors. For more information on auto-heal, please see here.


text:
Q: How to force Jaxb to use restriction types for the following mapping
<xs:complexType name="ParentNode">
        <xs:sequence>
            <xs:element name="child" type="ChildNode"/>
        </xs:sequence>
</xs:complexType>

<xs:complexType name="ParentNodeRestriction">
    <xs:complexContent>
        <xs:restriction base="ParentNode">
            <xs:sequence>
                <xs:element name="child" type="ChildNodeRestriction"/>
            </xs:sequence>
        </xs:restriction>
        </xs:complexContent>
</xs:complexType>

Jaxb generates the following classes (approximately)
public class ParentNode {
    protected ChildNode child;
}

public class ParentNodeRestriction
    extends ParentNode
{
}

public class ChildNode {
}

public class ChildNodeRestriction
    extends ChildNode
{
}

Knowing that ParentNode is not used elsewhere than  ParentNodeRestriction, is it possible to force JAXB to generate the following class (hopefully without modifying the mapping):
public class ParentNodeRestriction
{
    protected ChildNodeRestriction child;
}

i.e. I need to have the most precise type for the child field.
ps : I am using jaxb2-maven-plugin version 2.2 with maven
Thank you

A: Using the xjb directive <xjc:treatRestrictionLikeNewType/> (as indicated by his name) generates classes for restrictions which do not inherit from the class corresponding to the parent mapping.
This solves the problem.
There seems to be a slight annoying consequence : elements with maxOccurs="0" are generated despite the <xjc:simple/> directive.
In fact, elements with maxOccurs="0" can be removed from the restriction definition.


text:
Q: Prove $\int_b^a [f(x)+f^{-1}(x)]dx=a^2-b^2$ So I recently came across the formula $$\int_b^a [f(x)+f^{-1}(x)]dx=a^2-b^2$$ which apparently came up in a final of the MIT integration bee, and is true when $a,b$ are fixed points of $f$. I was wondering how one would go about proving this formula? I have no clue how to even make a start!

A: Use the substitution $x=f(y)$ we get
$$
\int_a^bf^{-1}(x)\,dx=\int_a^byf'(y)\,dy=yf(y)|_a^b-\int_a^bf(y)dy=(b^2-a^2)-\int_a^bf(x)dx
$$

A: If $a$ and $b$ are fixed points of $f$, with $0 \le a \le b$, the points $(a, f(a))$ and $(b, f(b))$ lie on the line $y=x$. Then $\int_b^a f(x)$ and $\int_b^a f^{-1}(x)$ are the area of the region $([0, b] \times [0, b]) \setminus ([0, a] \times [0, a])$. The general case of $a \le b$ follows easily.


text:
Q: History/list of bounty questions opened by an individual user Thus far i have opened bounty for some questions... How can i view the history/list of questions that were offered bounty by me? I hope the question is clear....

A: There is now a bounty tab on the user profile page which shows all current and historical bounty activity for that user.

A: Jeff's answer points out that there's a new bounty tab on the profile. It's a lot more useful than the approaches from this ancient answer (one of which is no longer efficient or all that valid, so I've removed it), so direct your votes over there. ♪

If you are looking at your own bounties, then using the reputation audit as detailed here is the most efficient and accurate. Just look for all entries with a vote code of "8" in your reputation audit, the question IDs can then be used to find the specific questions.


text:
Q: How to protect from dangerous bash commands? When using bash with or without sudo there are many traps. For example when logged in as root between
rm -rf ~/bin

and
rm -rf /bin

there is just one character but this difference can make you quite unhappy.
To protect myself a little bit of such disasters I use this in my /etc/bash.bashrc (systemwide .bashrc):
if [ $UID -ne 0 ]; then
    # ask me before deleting
    alias rm='rm -i'
else
    # do not delete / or prompt if deleting more than 3 files at a time
    alias rm='rm -I --preserve-root'
fi

With this, I at least have to confirm deleting before running into disaster.
Maybe there are even more dangerous commands as rm...
What are the most dangerous bash-commands and to protect myself from day-to-day disasters?

A: First off, never use root to execute day-to-day commands.
That's the best way to actually expose yourself to disasters.
With that in mind, if you use sudo, you can actually limit commands AND the command options that a user can execute with sudo.
For example, in your sudoers file, you can limit using rm like so:
myuser ALL=(root)   NOPASSWD: rm -r

This would mean that myuser can only use sudo as root and can only execute rm with the -r option.
The sudoers file also support regex so you can really customize what can be executed while using sudo.
A good starting point...


text:
Q: Google map API JS get localization I need your help please,
I have a website and i need to add localization map in my website and get the localization user from it, how can i do it,
thanks,

A: Getting localization in Javascript is easily done within the browser or within the Google Map API.
The Browser GeoLocation can be used to determine location based on location services within the browser.  Instructions with code examples can be found at the Mozilla Developer Network Documentation.
For using the Google Maps API you can view their documentation at their tutorials page.
I actually use a combination of the two to return city/county/state for a user for a weather app that I put together.  The entire code can be found at my GitHub page but here is the code for GeoLocation.
function geoLocation() {
    var output = document.getElementById("out");

    if (!navigator.geolocation) {
        output.innerHTML = "
Geolocation is not supported by your browser
";
        return;
    }

    function success(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        //Google Maps API to return printed location as opposed to lat/lon coordinates.

        $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=YOUR-API-KEY', function(city) {

            var address = city.results[2].formatted_address;

After that you can use whatever you want with the data.


text:
Q: 'module' object has no attribute '__version__' during openstack /devstack installation I have tried updating pip but it didn't helped. How to get past this error.
+./stack.sh:main:1033                      create_keystone_accounts
+lib/keystone:create_keystone_accounts:372  local admin_tenant
++lib/keystone:create_keystone_accounts:373  openstack project show admin -f value -c id
Traceback (most recent call last):
  File "/usr/local/bin/openstack", line 7, in <module>
    from openstackclient.shell import main
  File "/usr/local/lib/python2.7/dist-packages/openstackclient/shell.py", line 32, in <module>
    from openstackclient.common import clientmanager
  File "/usr/local/lib/python2.7/dist-packages/openstackclient/common/clientmanager.py", line 293, in <module>
    'openstack.cli.base',
  File "/usr/local/lib/python2.7/dist-packages/openstackclient/common/clientmanager.py", line 264, in get_plugin_modules
    __import__(ep.module_name)
  File "/usr/local/lib/python2.7/dist-packages/openstackclient/network/client.py", line 16, in <module>
    from openstack import connection
  File "/usr/local/lib/python2.7/dist-packages/openstack/connection.py", line 68, in <module>
    from openstack import session as _session
  File "/usr/local/lib/python2.7/dist-packages/openstack/session.py", line 29, in <module>
    DEFAULT_USER_AGENT = "openstacksdk/%s" % openstack.__version__
AttributeError: 'module' object has no attribute '__version__'
+lib/keystone:create_keystone_accounts:373  admin_tenant=
+lib/keystone:create_keystone_accounts:1   exit_trap
+./stack.sh:exit_trap:474                  local r=1
++./stack.sh:exit_trap:475                  jobs -p
+./stack.sh:exit_trap:475                  jobs=
+./stack.sh:exit_trap:478                  [[ -n '' ]]
+./stack.sh:exit_trap:484                  kill_spinner
+./stack.sh:kill_spinner:370               '[' '!' -z '' ']'
+./stack.sh:exit_trap:486                  [[ 1 -ne 0 ]]
+./stack.sh:exit_trap:487                  echo 'Error on exit'
Error on exit
+./stack.sh:exit_trap:488                  generate-subunit 1481647878 224 fail
+./stack.sh:exit_trap:489                  [[ -z /opt/stack/logs ]]
+./stack.sh:exit_trap:492                  /home/tcs467518/devstack/tools/worlddump.py -d /opt/stack/logs
World dumping... see /opt/stack/logs/worlddump-2016-12-13-165502.txt for details
+./stack.sh:exit_trap:498                  exit 1

Tried reinstalling pip :
    /usr/local/bin/pip -V
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

A: i met the same issue on stable/mitaka version.
after upgraded openstacksdk to 0.9.5, the issue is gone.
https://bugs.launchpad.net/python-openstacksdk/+bug/1588823
https://review.openstack.org/#/c/325088/


text:
Q: What is it that prevents using a 3rd party SSD in a 2015 rMBP? I bought an Early 2015 MacBook Pro Retina model with the 128GB SSD and have been wondering what to do if I need more disk space.. then I found out that it's currently not quite possible to just stick any connector-wise compatible drive in place of current drive as an means of upgrading the storage.
OWC, Transcend etc sell nothing, Apple does not sell anything (at least not without installation at an ASP), however it seems eBay has some Far-East sellers that have some kind of adapters which allow for 3rd party SSDs to be attached, but they seem to have various limitations as some will not make the new drive bootable, some will boot, but do not support passwords etc leading to believe they just emulate some bit of the original drive but not all.
My question is - what is it exactly that causes this incompatibility? Is there some kind of white-list in the EFI firmware that allows only specific SSDs to work? Or is there perhaps some actual additional handshake/encryption/protocol that happens during the EFI boot that helps "to secure" the boot-up process to actually justify this incompatibility?

A: The reason for the "incompatibility" is simple: there is no SATA-based SSD in this Mac. Apple is transitioning away from SATA-Based SSD drives and moving towards PCIe based SSD drives.
I thought there were a couple of manufacturers that had upgrade parts for PCIe SSDs and a quick search for "MacBook Pro PCIe SSD" should yield some results for you.

A: Apple uses a proprietary PCI-e connection (Apple, remember?). However, since 10.13 and later, some NVMe drives are supported and a little pin adapter will make something like a Sabrent Rocket work just fine.


text:
Q: How to identify the last index of foreach loop using jquery This is my each function in this how can i identify the last index of the each loop
var mailtest = '';
$.each(data.getEmail, function (i) {
    $.each(data.getEmail[i], function (key, val) {
        if(key == 'personal_email'){
            mailtest += val+';';
        }
    });
});
alert(mailtest);

Because I am getting output like this, In this I dont want ; in last
Output :
test@gmail.com; test1@gmail.com; test2@gmail.com; test3@gmail.com;

Output I want :
test@gmail.com; test1@gmail.com; test2@gmail.com; test3@gmail.com

A: Very simple:
var mailtest = [];
$.each(data.getEmail, function (i) {
  $.each(data.getEmail[i], function (key, val) {
    if(key == 'personal_email'){
        mailtest.push(val)
    }
  });
});
console.log(mailtest.join(";"));

NOTE: If you had posted an example of the data, we could likely find a map that would get it in one line

A: You could use join().
 as long as you data structure is similar to this one

var data = {
 getEmail: [
  {
   personal_email: 'test@gmail.com'
  },
  {
   personal_email: 'test1@gmail.com'
  },
  {
   personal_email: 'test2@gmail.com'
  },
 ]
}
console.log(
  data.getEmail.map(a=>a.personal_email).join("; ")
)

A: I would suggest you use Array's methods, here's how:

*

*filter (.filter) the array first

*then map it (.map)

*finally join it into a string (.join)
Here's the code:
var mailtest = '';
$.each(data.getEmail, function(i) {
  mailtest += data.getEmail[i]
    .filter((key, val) => (key == 'personal_email'))
    .map((key, val) => val)
    .join(';')
});
alert(mailtest);

Or you could just remove the last character of your string:
mailtest.substring(0, mailtest.length - 1);


text:
Q: Calendar group by event in SharePoint I have calendar inside that I have created an event which starts from march (01/03/2016) to ends on May(29/05/2016).
I have created a calculated field "Month" which fetch month as a number like 3 for march and 5 for May. Then created a view and used group by "month". I can see that event which is from march (03) to May(05) is falling under March category only. however it should fall under April and May too.
Can someone help me on this?
Thanks in advance..!

A:
If you are using SharePoint 2010 then Recurring events will be stored
  as a single item with a rule attached to show all recurrences in the
  calendar view.
In your case, It is doing the same. That's why your event which is
  from march (03) to May(05) is falling under March category only.
The only way to have individual events out of a recurring event is to
  edit any single event in the calendar view and save them without
  modification. This will generate single events out of the recurring
  event.
The problem then is whenever you edit the series this events won't be part of the recurring event. The single events also won't be updated.

A: I just have had created calendar list and created additional column Month.
Month column formula is this =TEXT([Month column name],"m")
Than I created new View, regular/standard view and used Group by feature to group by month.

A: Grouping is working based on single selection not on multi selection.
And your scenario is something like one item grouped by March, April and May month. It is not possible.
You should create recurrence event with monthly category for specific date range. Open Current Events view from Calendar list. You can see recurrence items of each month.


text:
Q: Object/Array manipulation I'm getting an array of objects from a db query (nodejs, using Postgres w/ Knex) that looks like this: (minified version)
[
   {
    tvshow: 'house',
    airdate: 2017-02-01T00:00:00.000Z
   },
   {
    tvshow: 'big bang theory',
    airdate: 2017-02-01T00:00:00.000Z
   },
   {
    tvshow: 'simpsons',
    airdate: 2017-02-02T00:00:00.000Z
   },
   {
    tvshow: 'suits',
    airdate: 2017-02-02T00:00:00.000Z
   },
   {
    tvshow: 'sun',
    airdate: 2017-02-03T00:00:00.000Z
   },
   {
    tvshow: 'blacklist',
    airdate: 2017-02-03T00:00:00.000Z
  },
  {
    tvshow: 'something',
    airdate: 2017-02-03T00:00:00.000Z
  },
  {
    tvshow: 'homeland',
    airdate: 2017-02-03T00:00:00.000Z
  },
  {
    tvshow: 'american dad',
    airdate: 2017-02-04T00:00:00.000Z
  },
  {
    tvshow: 'games',
    airdate: 2017-02-05T00:00:00.000Z
  }
]

The query that returns this, limits the airdate field to 5 days. This means that whatever I do with it, it will always have 5 days.
My goal is to have the tvshows filtered by day.
Expected output example
{
    day1: [ 'house', 'big bang theory' ],
    day2: [ 'simpsons', 'suits' ],
    day3: [ 'sun', 'blacklist', 'something', 'homeland' ],
    day4: [ 'american dad' ],
    day5: [ 'games' ]
}

I've a working solution, but I think it could be improved. Here's what I'm doing atm. I'm using momentjs to compare dates. 'result' is the name of the query result (array of objects).
const obj = {};
let array = [];
let i = 0;
let currentDate = null;

result.forEach((element) => {
  if (currentDate !== moment(element.airdate).format('DD-MM-YYYY')) {
    if (currentDate !== null) {      // skip first iteration where currentDate is null
      i++;
      obj[`day${i}`] = array;     // new day => store previous day tvshow's array in the object
    }
    array = [];     // reset temporary array
  }
  array.push(element.tvshow);    // push tvshow to temporary array
  currentDate = moment(element.airdate).format('DD-MM-YYYY');   // update current date
});
obj[`day${i+1}`] = array;    // add last/5th day array to the object

A: I would try to avoid modifying variables inside the forEach callback, that are defined outside of it.
Here is a version with reduce, which stores all state in the reduce accumulator. At the end, you can extract the part that contains the result object. It assumes that the dates are ordered in ascending order, which you can take care of in your query:
result = result.reduce( (acc, {tvshow, airdate}) => {
    acc.i += acc.airdate !== airdate;
    acc.airdate = airdate;
    acc.obj[`day${acc.i}`] = (acc.obj[`day${acc.i}`] || []).concat(tvshow);
    return acc;
}, {i:0, obj: {}} ).obj;

let result = [
   {
    tvshow: 'house',
    airdate: '2017-02-01T00:00:00.000Z'
   },
   {
    tvshow: 'big bang theory',
    airdate: '2017-02-01T00:00:00.000Z'
   },
   {
    tvshow: 'simpsons',
    airdate: '2017-02-02T00:00:00.000Z'
   },
   {
    tvshow: 'suits',
    airdate: '2017-02-02T00:00:00.000Z'
   },
   {
    tvshow: 'sun',
    airdate: '2017-02-03T00:00:00.000Z'
   },
   {
    tvshow: 'blacklist',
    airdate: '2017-02-03T00:00:00.000Z'
  },
  {
    tvshow: 'something',
    airdate: '2017-02-03T00:00:00.000Z'
  },
  {
    tvshow: 'homeland',
    airdate: '2017-02-03T00:00:00.000Z'
  },
  {
    tvshow: 'american dad',
    airdate: '2017-02-04T00:00:00.000Z'
  },
  {
    tvshow: 'games',
    airdate: '2017-02-05T00:00:00.000Z'
  }
];

result = result.reduce( (acc, {tvshow, airdate}) => {
    acc.i += acc.airdate !== airdate;
    acc.airdate = airdate;
    acc.obj[`day${acc.i}`] = (acc.obj[`day${acc.i}`] || []).concat(tvshow);
    return acc;
}, {i:0, obj: {}} ).obj;

console.log(result);

I left out the formatting with moment, which is not the determining factor in this code. You can add it.


text:
Q: Using StickyGridHeaders StickyGridHeaders, but its not working as it should, or at least as I want.
So I got this list with other lists inside, and with that i create a header list(I use the original list) and a full items list (all the subitems), and the call the adapter like so:
List<CalendarDate.CalendarTvShowEpisode> lista=new LinkedList<CalendarDate.CalendarTvShowEpisode>();
for(CalendarDate l:response){
        lista.addAll(l.episodes);
    }
setListAdapter(new WeekCalendarAdapter(getActivity(), weekCalendar,lista));

Then i have my Adapter:
 public class WeekCalendarAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {

        private final List<CalendarDate> mListHeaders;
        private final List<CalendarDate.CalendarTvShowEpisode> lista;
        private LayoutInflater inflater;

        public WeekCalendarAdapter(Context context, List<CalendarDate> mList, List<CalendarDate.CalendarTvShowEpisode> lista) {
            this.mListHeaders = mList;
            this.lista=lista;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
           return lista.size();
        }

        @Override
        public Object getItem(int i) {
            return lista.get(i);
        }

        @Override
        public long getItemId(int i) {
            return lista.get(i).episode.firstAired.getDay();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.calendarweek_item_episode, parent, false);
            }

            AQuery aq= new AQuery(convertView);
            aq.id(R.id.imageViewCalendarEpisodeBackdrop).image(lista.get(position).episode.images.screen);
            aq.id(R.id.textViewCalendartext).text(lista.get(position).episode.firstAired.getDay()+"");

            return convertView;
        }

        @Override
        public int getCountForHeader(int header) {
            return mListHeaders.get(header).episodes.size();
        }

        @Override
        public int getNumHeaders() {
            return mListHeaders.size();
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.calendarweek_item, parent, false);
            }

            AQuery aq = new AQuery(convertView);
            SimpleDateFormat format = new SimpleDateFormat("E MM dd, yyyy");
            aq.id(R.id.textViewCalendarWeekDay).text(format.format(mListHeaders.get(position).date) + "");

            return convertView;
        }

The result I get is just a normal listview with all items ordered on below another, no gridview nor header.
What I'm a doing wrong?

A: Finally found out how to do it.
And the main problem is that it cant be a listfragment because, well listfragment has a listview. It has to be a Fragment and then your view need to have a com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView
So the code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.calendarweek_fragment, container, false);

        StickyGridHeadersGridView l = (StickyGridHeadersGridView) rootView.findViewById(R.id.listViewCalendar);
        mAdapter = new WeekCalendarAdapter(getActivity(), weekCalendar, lista);
        l.setAdapter(mAdapter);
return rootView;
}

And the View:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView
        android:id="@+id/listViewCalendar"

        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="160dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:gravity="left"
        android:background="@color/calendar_background"/>
</LinearLayout>

My adapter
public class WeekCalendarAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {

        private final List<CalendarDate> mListHeaders;
        private final List<CalendarDate.CalendarTvShowEpisode> lista;
        private LayoutInflater inflater;

        public WeekCalendarAdapter(Context context, List<CalendarDate> mList, List<CalendarDate.CalendarTvShowEpisode> lista) {
            this.mListHeaders = mList;
            this.lista = lista;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return lista.size();
        }

        @Override
        public CalendarDate.CalendarTvShowEpisode getItem(int i) {
            return lista.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.calendarweek_item_episode, parent, false);
            }

           //EDIT YOUR GRID ITEM HERE
            return convertView;
        }

        @Override
        public int getCountForHeader(int i) {
            return mListHeaders.get(i).episodes.size();
        }

        @Override
        public int getNumHeaders() {
            return mListHeaders.size();
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.calendarweek_item, parent, false);
            }
           //EDIT YOUR VIEW HEADER HERE

            return convertView;
        }
    }


text:
Q: requireSsl mvc attribute : working with returlUrl I have [requireSsl] on my accounts controller.
It appears to work for all actions except the login action.  I believe this is because the login action is called as follws:
    new { controller = "Account", returnUrl = HttpContext.Current.Request.RawUrl }

Account/Login?returnUrl...
Account/Login%3freturnUrl...

when changing to https the second line results in bad request.
EDIT: THE PROBLEM IS THAT THE "?" CHARACTER GETS CONVERTED TO "%3F". I tried also to do this with url rewirte in iis7 and the same thing. so what is the cause and how to fix?
UPDATE:  I did get HTTPS to work using IIS Rewrite, but not MVC as described above. I removed enable ssl and did it purely in iis. I still would like to know why it doesnt work in mvc.

A: It doesn't work because of what you pointed out: the ? character is getting encoded when it shouldn't. This is a bug.
The original RequireSslAttribute code:
UriBuilder builder = new UriBuilder
{
  Scheme = "https",
  Host = filterContext.HttpContext.Request.Url.Host,
  // gets encoded and shouldn't include the ?
  Path = filterContext.HttpContext.Request.RawUrl
};
filterContext.Result = new RedirectResult (builder.ToString ());

should probably be changed to something like
UriBuilder builder = new UriBuilder
{
 Scheme = "https",
 Host = filterContext.HttpContext.Request.Url.Host,
 Path = filterContext.HttpContext.Request.Path,
 Query = filterContext.HttpContext.Request.QueryString.ToString ()
};
filterContext.Result = new RedirectResult (builder.ToString ());


text:
Q: JavaScript DOM Error in Internet Explorer I'm receiving the following error on this line of code
select.up().appendChild(sw);

With error "SCRIPT438: Object doesn't support property or method 'up' "
This only happens in Internet Explorer...  Chrome, Safari, and Firefox all run the code fine.  I'm unable to find anything via Google searching for "select.up()". This code isn't my own and I'm not very adept with using DOM in Javascript.
Here is rest of the code:
<?php
$swatches = $this->get_option_swatches();
?>
<script type="text/javascript">
    document.observe('dom:loaded', function() {
        try {
            var swatches = <?php echo Mage::helper('core')->jsonEncode($swatches); ?>;

            function find_swatch(key, value) {
                for (var i in swatches) {
                    if (swatches[i].key == key && swatches[i].value == value)
                        return swatches[i];
                }
                return null;
            }

            function has_swatch_key(key) {
                for (var i in swatches) {
                    if (swatches[i].key == key)
                        return true;
                }
                return false;
            }

            function create_swatches(label, select) {
                // create swatches div, and append below the <select>
                var sw = new Element('div', {'class': 'swatches-container'});
                select.up().appendChild(sw);

                // store these element to use later for recreate swatches
                select.swatchLabel = label;
                select.swatchElement = sw;

                // hide select
                select.setStyle({position: 'absolute', top: '-9999px'})

                $A(select.options).each(function(opt, i) {
                    if (opt.getAttribute('value')) {
                        var elm;
                        var key = trim(opt.innerHTML);

                        // remove price
                        if (opt.getAttribute('price')) key = trim(key.replace(/\+([^+]+)$/, ''));

                        var item = find_swatch(label, key);
                        if (item)
                            elm = new Element('img', {
                                src: '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>swatches/'+item.img,
                                alt: opt.innerHTML,
                                title: opt.innerHTML,
                                'class': 'swatch-img'});
                        else {
                            console.debug(label, key, swatches);
                            elm = new Element('a', {'class': 'swatch-span'});
                            elm.update(opt.innerHTML);
                        }
                        elm.observe('click', function(event) {
                            select.selectedIndex = i;
                            fireEvent(select, 'change');
                            var cur = sw.down('.current');
                            if (cur) cur.removeClassName('current');
                            elm.addClassName('current');
                        });
                        sw.appendChild(elm);
                    }
                });
            }

            function recreate_swatches_recursive(select) {
                // remove the old swatches
                if (select.swatchElement) {
                    select.up().removeChild(select.swatchElement);
                    select.swatchElement = null;
                }

                // create again
                if (!select.disabled)
                    create_swatches(select.swatchLabel, select);

                // recursively recreate swatches for the next select
                if (select.nextSetting)
                    recreate_swatches_recursive(select.nextSetting);
            }

            function fireEvent(element,event){
                if (document.createEventObject){
                    // dispatch for IE
                    var evt = document.createEventObject();
                    return element.fireEvent('on'+event,evt)
                }
                else{
                    // dispatch for firefox + others
                    var evt = document.createEvent("HTMLEvents");
                    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
                    return !element.dispatchEvent(evt);
                }
            }

            function trim(str) {
                return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            }

            $$('#product-options-wrapper dt').each(function(dt) {

                // get custom option's label
                var label = '';
                $A(dt.down('label').childNodes).each(function(node) {
                    if (node.nodeType == 3) label += node.nodeValue;
                });
                label = trim(label);

                var dd = dt.next();
                var select = dd.down('select');
                if (select && has_swatch_key(label)) {
                    create_swatches(label, select);

                    // if configurable products, recreate swatches of the next select when the current select change
                    if (select.hasClassName('super-attribute-select')) {
                        select.observe('change', function() {
                            recreate_swatches_recursive(select.nextSetting);
                        });
                    }
                }
            });
        }
        catch(e) {
            alert("Color Swatches javascript error. Please report this error to support@ikova.com. Error:" + e.message);
        }
    });
</script>

Appreciate any insight anyone could give me!

A: I'm pretty sure up() is a PrototypeJS method, so i'm pretty sure you would need it to work.
http://prototypejs.org/api/element/up

A: I m also facing this problem. so, i comment
var sw = new Element('div', {'class': 'swatches-container'});
$(select).up().appendChild(sw);
select.setStyle({position: 'absolute', top: '-9999px'})

lines from function create_swatches
and paste it in function trim(str).
After this i did not error again.


text:
Q: Pattern matching doesn't work I wonder, why doesn't this work:
  def example(list: List[Int]) = list match {
    case Nil => println("Nil")
    case List(x) => println(x)
  }

  example(List(11, 3, -5, 5, 889, 955, 1024))

It says:
scala.MatchError: List(11, 3, -5, 5, 889, 955, 1024) (of class scala.collection.immutable.$colon$colon)

A: Because List(x) only matches lists with one element. So
def example(list: List[Int]) = list match {
  case Nil => println("Nil")
  case List(x) => println(x)
}

only works with lists of zero or one element.

A: As other posters have pointed out, List(x) only matches a list of 1 element.
There is however syntax for matching multiple elements:
def example(list: List[Int]) = list match {
  case Nil => println("Nil")
  case List(x @ _*) => println(x)
}

example(List(11, 3, -5, 5, 889, 955, 1024)) // Prints List(11, 3, -5, 5, 889, 955, 1024)

It's the funny @ _* thing that makes the difference. _* matches a repeated parameter, and x @ says "bind this to x".
The same works with any pattern match that can match repeated elements (e.g, Array(x @ _*) or Seq(x @ _*)). List(x @ _*) can also match empty lists, although in this case, we've already matched Nil.
You can also use _* to match "the rest", as in:
def example(list: List[Int]) = list match {
  case Nil => println("Nil")
  case List(x) => println(x)
  case List(x, xs @ _*) => println(x + " and then " + xs)
}

A: It doesn't work because List(x) means a list with exactly one element. Check it:
def example(list: List[Int]) = list match {
  case Nil => println("Nil")
  case List(x) => println("one element: " + x)
  case xs => println("more elements: " + xs)
}

example(List(11, 3, -5, 5, 889, 955, 1024))
//more elements: List(11, 3, -5, 5, 889, 955, 1024)
example(List(5))
//one element: 5


text:
Q: angular + bootstrap showing and hiding while preserving layout Is there a good way to add and remove elements without reflowing the page and causing all the elements to jitter about?
The angular directives ng-show and ng-hide don't preserve layout.
and bootstrap classes don't either

...

...

Is there a good way to add and remove elements without reflowing the page and causing all the elements to jitter about?

A: ng-hide and ng-show uses display:none
You need to add new property in CSS for visibility : hidden
 .element-hidden{
     visibility: hidden;
  }

And then provide the condition to ng directive - ng-class
e.g.
ng-class="{element-hidden : hideBox == true}"

where hideBox == true is the condition you want to check..

A: You're looking for the CSS visibility attribute which makes an item invisible, but still allows the element to take up space on the DOM.  There's no built-in Angular directive which will do this so you'll need to roll your own.
myApp.directive("visiblityOn", function(){
    return{
        restrict: "A",
        link: function(scope, element){
            scope.$watch('visibilityFlag', function(){
                element[0].style.visibility = scope.visibilityFlag ? "visible" : "hidden";
            });
        }
    }
});

and a corresponding controller that will work with your directive:
myApp.controller("myController", function($scope){

    $scope.visibilityFlag = true;

    $scope.changeVisibility = function(){
        $scope.visibilityFlag = !$scope.visibilityFlag;
    };

});

Example

A: @RahulPatil's answer is correct but somewhat inelegant. I would suggest to keep using ng-show/ng-hide because it's easier and more readable (i.e. keeps using the same pattern), and add an override in CSS for you particular items:
.keepInFlow.ng-hide {
   dislpay: block!important;
   visibility: hidden;
}

..

Angular's documentation also mentions overriding ng-hide


text:
Q: RegEx for replacing part of a string in R I am trying to do an exact pattern match using the gsub/sub and replace function. I am not getting the desired response. I am trying to remove the .x and .y from the names without affecting other names.
name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub(".x$|.y$", "", name)
new.name
[1] "compa"       "deriv"       "isConfirmed"

company has become compa.
I have also tried
remove = c(".x", ".y")
replace(name, name %in% remove, "")
[1] "company"    "deriv.x"    "isConfirmed.y"

I would like the outcome to be.
"company", "deriv", "isConfirmed"
How do I solve this problem?

A: Here we can have a simple expression that removes the undesired . and anything after that:
(.+?)(?:\..+)?

or for exact match:
(.+?)(?:\.x|\.y)?

R Test
Your code might look like something similar to:
gsub("(.+?)(?:\\..+)?", "\\1", "deriv.x")

or
gsub("(.+?)(?:\.x|\.y)?", "\\1", "deriv.x")

R Demo
RegEx Demo 1
RegEx Demo 2
Description
Here, we are having a capturing group (.+?), where our desired output is and a non-capturing group (?:\..+)? which swipes everything after the undesired ..

A: The dot matches any character except a newline ao .x$|.y$ would also match the ny in company
There is no need for any grouping structure to match a dot followed by x or y. You could match a dot and match either x or y using a character class:
\\.[xy]

Regex demo | R demo
And replace with an empty string:
name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub("\\.[xy]", "", name)
new.name

Result
[1] "company"     "deriv"       "isConfirmed"

A: In a regex, . represents "any character". In order to recognize literal . characters, you need to escape the character, like so:
name <- c("company", "deriv.x", "isConfirmed.y")
new.name <- gsub("\\.x$|\\.y$", "", name)
new.name

[1] "company"     "deriv"       "isConfirmed"

This explains why in your original example, "company" was being transformed to "compa" (deleting the "any character of 'n', followed by a 'y' and end of string").
Onyambu's comment would also work, since within the [ ] portion of a regex, . is interpreted literally.
gsub("[.](x|y)$", "", name)


text:
Q: Align 2 images in background in a div I would like to put 2 images as background image inside a div.
This is the code i put but i see only the second image.
#wrap-header {
  max-width: 100%;
  height: 400px;
  background-image: url("../assets/header_background.png"), url("../assets/circle_header_background.png");
  background-repeat: no-repeat;
  background-position: center bottom, center top;
}

I want to retrieve the effect of the one image under the other, or one image as first layer and the second up at the bottom.
I can't find a way. Could you pease help me ?

A: You can do this using the CSS selectors :after and :before
First, add the following to #wrap-header:
#wrap-header {
    position: relative;
    overflow: hidden;
    max-width: 100%;
    height: 400px;
}

And then use the selectors:
#wrap-header:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    height: 50%;
    width: 100%;
    background-image: url('image1');
    background-repeat: no-repeat;
    background-position: center
}

#wrap-header:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    height: 50%;
    width: 100%;
    background-image: url('image2');
    background-repeat: no-repeat;
    background-position: center;
}

A: You can simply do it with the background-size: 100% 50% where the first value of 100% indicates the width of the image, and the second one its height, which is set to 50% or always half of the #wrap-header's height:

#wrap-header {
  /*max-width: 100%; by default*/
  height: 400px;
  background-image: url('https://placeimg.com/1600/200/any'), url('https://placeimg.com/1600/201/any');
  background-repeat: no-repeat;
  background-position: bottom, top;
  background-size: 100% 50%;
}

A: This can be done with a help of pseudo elements :before and :after

#wrap-header {
  max-width: 100%;
  height: 400px;
}

#wrap-header:before {
  content: "";
  width: 100%;
  height: 100%;
  background-image: url("https://boutiqueme.com/static/4/generated/30-pattern-44-ff81c0.png");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}

#wrap-header:after {
  content: "";
  width: 100%;
  height: 100%;
  background-image: url("https://cdn.pixabay.com/photo/2016/04/12/00/04/hero-1323464_960_720.png");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

A: You can use :before and :after pseudo selector to achive this

/* Set #wrap-header to relative so that :before and :after does not goes outside */
#wrap-header {
  max-width: 100%;
  height: 400px;
  position: relative;
}

#wrap-header:before,
#wrap-header:after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

/* Set First Background Image */
#wrap-header:before {
  background: url("http://via.placeholder.com/850x450") center bottom no-repeat;
}

/* Set Second Background Image */
#wrap-header:after {
  background: url("http://via.placeholder.com/900x450") center top no-repeat;
  opacity: 0.3; /* Set transparency as per your requirement */
}


text:
Q: need help creating a dynamic columned table \NewDocumentCommand\foo{>{\SplitList{;}}m}
{
    \begin{table}
    \begin{tabular}{ \ProcessList{#1} c}
        \ProcessList{#1}{\additem}
    \end{tabular}
    \end{table}}
}

  \newcommand\additem[1]{#1 &}

Im trying to make a dynamic table that will take in as many args in the list and out put to the table with each item being a column.. having an issue with the number of columns and the number of & being inserted. any help would be greatly appreciated.
my issue is with predicting the number of columns in the table. and preventing the
! Package array Error:  Illegal pream-token (\ProcessList):c' used.`
or if i remove the processlist  i get
! Extra alignment tab has been changed to \cr.

A: It's unclear what this command would do, since a one row tabular is just a single line and so tabular is not needed at all: you'd get the required behavior by simply saying
\NewDocumentCommand{\foo}{>{\SplitList{;}}m}{%
  \begin{table}
  \centering
  \ProcessList{#1}{\additem}
  \end{table}
}

\newcommand{\additem}[1]{\mbox{\hspace{\tabcolsep}#1\hspace{\tabcolsep}}}

Complete example, with the same table typeset explicitly, in order to see that the output is exactly the same:
\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\foo}{>{\SplitList{;}}m}{%
  \begin{table}[htp]
  \centering
  \ProcessList{#1}{\additem}
  \end{table}
}

\newcommand{\additem}[1]{\mbox{\hspace{\tabcolsep}#1\hspace{\tabcolsep}}}

\begin{document}

\foo{abc;def;ghijkl;m}

\begin{center}
\begin{tabular}{*{4}{c}}
abc & def & ghijkl & m
\end{tabular}
\end{center}
\end{document}

For a more useful macro, here's a way:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\foo}{m}
 {
  \bob_make_table:n { #1 }
 }

\int_new:N \l_bob_colcount_int
\seq_new:N \l_bob_rows_seq
\seq_new:N \l_bob_temp_seq
\tl_new:N \l_bob_table_tl

\cs_new_protected:Npn \bob_make_table:n #1
 {
  \seq_set_split:Nnn \l_bob_rows_seq { \\ } { #1 }
  \int_zero:N \l_bob_colcount_int
  % count the number of columns
  \seq_map_inline:Nn \l_bob_rows_seq
   {
    \seq_set_split:Nnn \l_bob_temp_seq { ; } { ##1 }
    \int_compare:nT { \seq_count:N \l_bob_temp_seq > \l_bob_colcount_int }
     {
      \int_set:Nn \l_bob_colcount_int { \seq_count:N \l_bob_temp_seq }
     }
   }
  % produce the table
  \tl_set:Nn \l_bob_table_tl { \begin{tabular}{*{\l_bob_colcount_int}{c}} }
  \seq_map_inline:Nn \l_bob_rows_seq
   {
    \seq_set_split:Nnn \l_bob_temp_seq { ; } { ##1 }
    \tl_put_right:Nx \l_bob_table_tl { \seq_use:Nn \l_bob_temp_seq { & } }
    \tl_put_right:Nn \l_bob_table_tl { \\ }
   }
  % print the table
  \tl_use:N \l_bob_table_tl
  \end{tabular}
 }
\ExplSyntaxOff
\begin{document}

\foo{
  abc;def\\
  ghijkl;m;nopqrs;tu\\
  vz
}

\end{document}

Rows are separated by \\ and columns by ;.


text:
Q: HttpWebRequest Error on Server works Locally I have a shopping cart that acts as a general handler for different, disconnected parts of my application to allow users to purchase items. When the user removes an item from their cart, the cart then needs to inform the service that added the item. I'd hoped to use web services to accomplish this.
I am using an HttpWebRequest that looks like this:
        Dim serializer As New JavaScriptSerializer
        Dim req As HttpWebRequest
        Dim encoder As New System.Text.UTF8Encoding
        Dim jsonBytes As Byte()
        Dim stream As System.IO.Stream
        Dim result As String = ""
        Dim serialized As String
        Dim request As System.Web.HttpRequest = System.Web.HttpContext.Current.Request
        Dim resolvedService As String = ResolveUrl(request.Url.GetLeftPart(UriPartial.Authority) & Service)
        Dim Success As Boolean = False

        serialized = serializer.Serialize(PurchaseData)
        jsonBytes = encoder.GetBytes(serialized)

        req = WebRequest.Create(resolvedService.Trim)
        req.ContentType = "application/json; charset=utf-8"
        req.Method = "POST"
        req.UseDefaultCredentials = True
        req.ContentLength = jsonBytes.Length
        req.Timeout = "60000"

When I use this on my local computer, it works fine. But, when it's running on our host, it fails. If it is over https (which it should be), then I get "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." If it is not over https, then it just gives a 404. The requests to the service work through fiddler. There just seems to be an issue with them originating from the host server or something.
I've tried a number of different things and am totally stuck. I've heard it could be an issue with load balancing from my host, but I'm not sure what to do about that.
Does anybody know how I might proceed?
Thanks,
Mike


text:
Q: Points in the unit disk Suppose we have complex numbers $\alpha_1,..., \alpha_n$ that lie on the unit disk. Let $t_1,...,t_n$ be positive numbers such that $t_1 + ... + t_n =1 $. Then $\alpha_1 t_1 + ... + \alpha_n t_n $ lies in the unit disk.
Try
We have by hypothesis $|\alpha_i | < 1 $ for all $i = 1,...,n$. I was thinking about using Cauchy Schwarz inequality:
$$ |\alpha_1 t_1 + ... + \alpha_2 t_2 |^2 \leq ( |\alpha_1|^2 + ... | \alpha_n|^2)( |t_1|^2 + ... |t_n|^2 ) $$
But it seems this does not give me a good estimate. Is there another approach to solve this problem ?

A: stop thinking complex and start thinking planar geometry.
if you take two points inside the unit circle. The set of points of the form you give is the straight line between those points. So you are saying is that the unit disc is convex.
The general case follows by induction.

A: Using the triangle inequality and $|\alpha_i|<1$,
$$|\alpha_1 t_1 + \cdots + \alpha_n t_n| \leq |\alpha_1| t_1 + \cdots |\alpha_n |t_n < t_1 + \cdots t_n = 1$$

A: By induction on $n$. I denote the unit disk by $D$.
If $n=1$, this is trivial.
Suppose this holds for $n-1$ points. Now
$$\frac{t_1}{1-t_n} + \dots \frac{t_{n-1}}{1-t_n} = 1$$
so by inductive hypothesis
$$\frac{t_1}{1-t_n} \alpha_1+ \dots \frac{t_{n-1}}{1-t_n}\alpha_{n-1} \in D$$
and finally, since $D$ is convex
$$(1-t_n) \left( \frac{t_1}{1-t_n} \alpha_1+ \dots \frac{t_{n-1}}{1-t_n}\alpha_{n-1} \right) + t_n \alpha_n\in D$$
and this completes the proof.

A: Hint:
Try induction over $n$:
For $n = 1$ you have $t_1\alpha_1 = 1$ where $t_1 = 1$ and $\alpha_1$ lies on the unit disc.
Try proving it for $n=2$.
Then if it works for $n-1$ then let $\beta = t_1\alpha_1 + t_2\alpha_2 + \ldots + t_{n-1}\alpha_{n-1}$ and $u = t_1 + \ldots t_{n-1}$ then:
$u + t_n = 1$ and $\beta$ and $\alpha_n$ lie on the unit disc. (Using the induction hypothesis for $\beta$). This is essentially the same case as in $n=2$.

A: Try using induction on the number of points. Trivially true with one point and easily true with two (because the weighted sum is a point on the line segment joining the points, and the unit disk is convex). For $n > 2$, let $v = 1/(1-t_n)$. Then $$a_1t_1 + \cdots + a_nt_n = (a_1t_1v + \cdots + a_{n-1}t_{n-1}v)(1-t_n) + a_nt_n$$ By induction, the first term is a point on the disk, reducing the $n$-point problem to a 2-point problem, which you've already done.


text:
Q: Python list slicing not working correctly I have recently started learning python. After learning list slicing, I thought of trying it out. But when I am using -1, it's returning an empty list
numbers = [2, 3, 9, 5, 6, 0, 1]
# Slicing a list
print(numbers[1:5:-1])

gives,
[ ]
This video tells that -1 works:
Here
Can you guys tell me why is it like that?

A: If you specify indices so that the start comes after the end, you always get an empty slice:
>>> numbers = [2, 3, 9, 5, 6, 0, 1]
>>> numbers[5:1]
[]

Putting -1 on the end reverses the slice, so you need to reverse the indices as well if you're doing it as part of the same slice:
>>> numbers[::-1]
[1, 0, 6, 5, 9, 3, 2]
>>> numbers[5:1:-1]
[0, 6, 5, 9]

This is the same as if you took the reverse slice on its own and then sliced it with [1:5] afterward:
>>> numbers[::-1][1:5]
[0, 6, 5, 9]


text:
Q: MySQL Entity Framework 6 Update affecting all rows Code First I'm using Entity Framework 6 with MySQL.
Inserting is fine, I was able to insert a new record. but when I tried to update the newly created record. It updates all the rows.
Here is my code for saving.
    // This is the method I use every time I save a record.
    public async Task SaveAsync(User model)
    {

        if (model.Id != 0)
        {
            var original = GetOriginal(model.Id);

            if (model.Password == string.Empty)
            {
                model.Password = original.Password;
            }
            // The state is always modified if I'm updating the record.
            var state = Context.Entry(model).State;
        }

        await base.SaveAsync();
    }

When I save the record that I want to update, here is the Update Query. Entity Framework use the User_Update stored procedure but it's missing the where clause that's why the updates affects all the rows.
`User_Update`
-- Id: '6' (Type = Int32, IsNullable = false)
-- Username: 'test123' (Type = String, IsNullable = false, Size = 7)
-- Password: 'vZxTTTgLiQUxwchySt1e1o/I9XMWm4QW5pO6MpPGI0o=' (Type = String, IsNullable = false, Size = 44)
-- Email: 'test1@gmail.com' (Type = String, IsNullable = false, Size = 15)
-- FullName: 'test1' (Type = String, IsNullable = false, Size = 5)
-- CreatedAt: 'null' (Type = DateTime, IsNullable = false)
-- UpdatedAt: 'null' (Type = DateTime, IsNullable = false)
-- RoleId: '2' (Type = Int32, IsNullable = false)
-- Executing asynchronously at
-- Completed in 9 ms with result: 6

Updates:
Added the SaveCommand that executes the SaveAsync
        private async void SaveCommandExecute(object obj)
    {
        //var passwords = (Tuple<string, string>) obj;
        //var password = passwords.Item1;
        //var confirmPassword = passwords.Item2;

        var result = await DialogHelper.ShowAsync("Are you sure you want to continue?", "Confirmation",
            MessageDialogType.YesNo);

        if (result)
        {
            await UserWrapper.ValidateAll();

            if (!UserWrapper.HasErrors)
            {

                if (UserWrapper.Id == 0)
                {
                    UserWrapper.Password = DbHelper.CalculateHash(UserWrapper.FakePassword, UserWrapper.Username);
                }

                await _userRepository.SaveAsync(UserWrapper.Model);
                HasChanges = false;
                Id = UserWrapper.Id;
                SetTitle();
                ((DelegateCommand<object>)SaveCommand).RaiseCanExecuteChanged();

                await LoadAsync(UserWrapper.Id);
            }

        }

    }

Now my question, How I will tell EF to add the record id in the where clause?
PS: This logic is working perfectly fine with SQL Server Entity Framework. I'm not sure why it's not working in MySQL EF.
I also tracked if there any changes to the repository/current dbcontext, if there are any changes and no errors, I will enable the Save Button/Save Command.


text:
Q: How to: Assign a unique number to every entry in a list? What I want is to make tiles.  These tiles (about 30 of them) should have a fixed position in the game, but each time I load the game they should have random numbers that should affect their graphical appearance.
I know how to use the Random method to give a single tile a number to change its appearance, but I'm clueless on how I would use the Random method if I were to make a list storing the position of multiple tiles. How can you assign each entry in a list a unique random number?
I need this for my game where you're in a flat 2D map, generated with random types of rooms (treasure rooms, arena rooms etc.) that you are to explore.

A: Take a look at the Fisher-Yates shuffle. It's super easy to use and should work well for you, if I read your question right.

A: if you have something like this:
public class Tile
{
     public int Number {get;set;}
     ...
}

you can do it like this:
var numbers = Enumerable
  .Range(1, tilesList.Count)  // generates list of sequential numbers
  .OrderBy(x => Guid.NewGuid()) // shuffles the list
  .ToList();

for (int i = 0; i < tiles.Count; i++)
{
    tile[i].Number = numbers[i];
}

I know, that Guid is not a Random alternative, but it should fit this scenario.
Update: As long as answer was downvoted, I've wrote simple test, to check if Guids are not usable for shuffling an array:
var larger = 0;
var smaller = 0;

var start = DateTime.Now;

var guid = Guid.NewGuid();

for (int i = 0; i < 10000000; i++)
{
    var nextGuid = Guid.NewGuid();
    if (nextGuid.CompareTo(guid) < 0)
    {
        larger++;
    }
    else
    {
        smaller++;
    }

    guid = nextGuid;
}

Console.WriteLine("larger: {0}", larger);
Console.WriteLine("smaller: {0}", smaller);

Console.WriteLine("took seconds: {0}", DateTime.Now - start);

Console.ReadKey();

What it does, it counts how many times next guid is smaller than current and how many times is larger. In perfect case, there should be equal number of larger and smaller next guids, which would indicate, that those two events (current guid and next guid) are independent. Also measured time, just to make sure, that it is not too slow.
And got following result (with 10 million guids):

larger: 5000168
     smaller: 4999832
     took seconds: 00:00:01.1980686

Another test is direct compare of Fisher-Yates and Guid shuffling:
static void Main(string[] args)
    {
        var numbers = Enumerable.Range(1, 7).ToArray();
        var originalNumbers = numbers.OrderBy(x => Guid.NewGuid()).ToList();

        var foundAfterListUsingGuid = new List<int>();
        var foundAfterListUsingShuffle = new List<int>();

        for (int i = 0; i < 100; i++)
        {
            var foundAfter = 0;
            while (!originalNumbers.SequenceEqual(numbers.OrderBy(x => Guid.NewGuid())))
            {
                foundAfter++;
            }

            foundAfterListUsingGuid.Add(foundAfter);

            foundAfter = 0;

            var shuffledNumbers = Enumerable.Range(1, 7).ToArray();
            while (!originalNumbers.SequenceEqual(shuffledNumbers))
            {
                foundAfter++;
                Shuffle(shuffledNumbers);
            }

            foundAfterListUsingShuffle.Add(foundAfter);
        }

        Console.WriteLine("Average matching order (Guid): {0}", foundAfterListUsingGuid.Average());
        Console.WriteLine("Average matching order (Shuffle): {0}", foundAfterListUsingShuffle.Average());
        Console.ReadKey();
    }

    static Random _random = new Random();

    public static void Shuffle<T>(T[] array)
    {
        var random = _random;
        for (int i = array.Length; i > 1; i--)
        {
            // Pick random element to swap.
            int j = random.Next(i); // 0 <= j <= i-1
            // Swap.
            T tmp = array[j];
            array[j] = array[i - 1];
            array[i - 1] = tmp;
        }
    }

By "direct compare" I mean, that I'm producing shuffled sequence and try to shuffle again to get same sequence, and assume, that the more tries I need to produce same sequence, the better random is (which is not necessary mathematically correct assumption, I think it is oversimplification).
So results for small set with 1000 iterations to reduce error, was:

Average matching order (Guid): 5015.097
  Average matching order (Shuffle): 4969.424

So, Guid performed event better, if my metric is correct :)
with 10000 iterations they came closer:

Average matching order (Guid): 5079.9283
  Average matching order (Shuffle): 4940.749

So in my opinion, for current usage (shuffle room number in game), guids are suitable solution.

A: Make an array of 30 consecutive numbers, mirroring your array of tiles. Then pick an array-shuffling solution you like from, say, here for instance:
http://forums.asp.net/t/1778021.aspx/1
Then tile[23]'s number will be numberArray[23].


text:
Q: cocoapods pod setup --verbose not downloading I am trying to install cocoapods but however when I type pod setup --verbose it starts downloading for a little while and then it stops downloading and my internet connection is stable, I have tried to stop it and re-install it again but the same problem

amrs-Mac:~ amr$ pod setup --verbose
Setting up CocoaPods master repo
Cloning spec repo master from https://github.com/CocoaPods/Specs.git (branch master)
   $ /usr/bin/git clone https://github.com/CocoaPods/Specs.git master --progress
  Cloning into 'master'...
  remote: Counting objects: 1801035, done.
  remote: Compressing objects: 100% (453/453), done.
  Receiving objects:   3% (70783/1801035), 14.07 MiB | 419.00 KiB/s

I checked activity monitor networks and nothing is being downloaded
Is there any fix or can I install CocoaPods any other way?


text:
Q: On screen-brightness indicator not showing up I've just installed a new GNOME theme following a YouTube tutorial, but I'm having a problem with the on screen brightness indicator.
As you can see from the image below when I increase or decrease the brightness the indicator doesn't show up, but the same thing doesn't happen with the volume indicator.
Brightness indicator:

Volume indicator:

The theme I've installed is Qogir. The icon pack is Tela.


text:
Q: Swift Mailer error: Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted I was trying out some PHP scripts to send a mail to my gmail account. I am using Swift Mailer library. Here is my PHP code.
<?php
/// Swift Mailer Library
require_once 'swiftmailer-5.x/lib/swift_required.php';

// Mail Transport

$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
    ->setUsername('myemail@gmail.com') // Your Gmail Username
    ->setPassword('my_password'); // Your Gmail Password

// Mailer
try {
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance('New Mail')
    ->setFrom(array('myemail@gmail.com' => 'myemail')) // can be $_POST['email'] etc...
    ->setTo(array('myemail@gmail.com' => 'myemail')) // your email / multiple supported.
    ->setBody('Test Mail', 'text/html');

// Send the message
if ($mailer->send($message)) {
    echo 'Mail sent successfully.';
} else {
    echo 'I am sure, your configuration are not correct. :(';
}

} catch(Swift_TransportException $exception) {
    var_dump($exception);
}

?>

I have turned on Access for less secure apps in my Gmail account and the mail was sent once. But afterward its giving me this error.
Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted.

I did some research but was not able to nail down on an exact reason for this error.
Any help would be appreciated. Thanks!


text:
Q: ListView with dynamic pagination I need a ListView/CharmListView with dynamic pagination, loading dynamically from server. Is this possible?
My backend method already waits for start, page and limit url parameters.
Thanks!


text:
Q: Manage alerts of multiple local notifications fired in a single way? I need your help :(
Scenario: (using UILocalNotification in iOS SDK) if you see on your device several local notifications fired by your app, you have to respond to all the alerts. N fired notification require to tap on N alerts.
This is very annoying. In my app the notifications are closely related between each other, so I would like to find a way to "consume" all the fired alerts by tapping only one alert. Is there a way?
An (almost) solution: at the end of didReceiveLocalNotification (where you manage the single notification fired) if you cancel all the other notifications (via cancelAllLocalNotifications) and the other alerts disappear. But in this way you cancel all the notifications, so you need to re-schedule the notifications not-fired.
Is there a less painful solution?
Thanks in advance

A: I think you will need to create your own alert handler.  By this i mean, where you would normally throw an alert, call a method that will keep track of multiple alert like flags, and then when you could build in a timer that kicks off when the first alert is thrown and have it wait for other alerts.  If no other alerts are thrown say within 10 seconds, then activate the system alert with a message built by your method.  If multiple alert flags are thrown, then compile a composite message and then raise the alert with this composite message.


text:
Q: How to select all childnodes when a parent node is selected in treeview ? (When the treeview is used from usercontrol) I have a usercontrol which has only the Treeview control.
<asp:TreeView ID="Tree_Index"
Style="font-size: 11px; font-family: Tahoma; font-weight: bold; text-align: left;" runat="server" Width="10px"
EnableClientScript="False" ShowCheckBoxes="All" ShowLines="True">
</asp:TreeView>

From my aspx page i use this user control multiple times, inorder to show multiple treeview with different data in my aspx page.
I call the user control like below
Public Sub PopulateTreeview()
        Dim cph As ContentPlaceHolder = CType(Me.Master.FindControl("cphMain"), ContentPlaceHolder)
    Dim Treeview_Control As Controls_Deot_treecontrol

        Dim ds As DataSet = SPServiceModel.GetAllServiceCategorizationTypes()
        Dim dtRight As DataTable = ds.Tables(0)

        For i As Integer = 0 To dtRight.Rows.Count - 1
        Treeview_Control = CType(LoadControl("Deot/treecontrol.ascx"), Controls_Deot_treecontrol)
        Treeview_Control.ID = "Treecontrol_Right_" + i.ToString()
        Treeview_Control.SetCategoryID(dtRight.Rows(i)("id").ToString())
            cph.FindControl("pnl_right").Controls.Add(Treeview_Control)
        Next
End Sub

Say if there are 6 treeviews are there on my aspx page. I want to select all the child nodes of a parent node when a parent node is selected. The treeview will have three levels of node . So all the nodes inside the parent node should be selected for that particular tree.
How can i achieve this, because the ID is set by me in aspx page. How can i achieve this using javascript or jquery or codebehind of user control ?
Rendered HTML :

                	<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn0CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn0CheckBox">Clinics

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn1CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn1CheckBox">Respite Care Services

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn2CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn2CheckBox">Caregiver Training

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn3CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn3CheckBox">Psychiatric Rehabilitation Homes

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn4CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn4CheckBox">Befriending Service

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn5CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn5CheckBox">Polyclinics

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn6CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn6CheckBox">Caregiver Support Service

		<input type="checkbox" id="ctl00_cphMain_ctl03_Tree_Indexn7CheckBox" name="ctl00_cphMain_ctl03_Tree_Indexn7CheckBox">Helpline - Caregiver Helpline

                	<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn0CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn0CheckBox">Home Care

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn1CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn1CheckBox">Home Nursing

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn2CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn2CheckBox">Third Level 1

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn3CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn3CheckBox">Third Level 2

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn4CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn4CheckBox">Private Nursing Homes

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn5CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn5CheckBox">Personal Healthcare Assistant

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn6CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn6CheckBox">Home Medical

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn7CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn7CheckBox">Home Therapy - Physiotherapy

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn8CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn8CheckBox">Home Therapy - Occupational Therapy

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn9CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn9CheckBox">Social Day Care Services

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn10CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn10CheckBox">Community VWO Clinics

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn11CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn11CheckBox">Day Rehabilitation Services

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn12CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn12CheckBox">Community Wellness Clubs

		<input type="checkbox" id="ctl00_cphMain_ctl04_Tree_Indexn13CheckBox" name="ctl00_cphMain_ctl04_Tree_Indexn13CheckBox">Community Hospitals

                	<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn0CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn0CheckBox">Other Services

		<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn1CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn1CheckBox">Mobile Services

		<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn2CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn2CheckBox">Hospice Day Care

		<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn3CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn3CheckBox">Website - Disability Information Website

		<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn4CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn4CheckBox">Information & Referral Services

		<input type="checkbox" id="ctl00_cphMain_ctl05_Tree_Indexn5CheckBox" name="ctl00_cphMain_ctl05_Tree_Indexn5CheckBox">Ambulance Service (Non-Emergency)

A: you can simply use this code
$(document).ready(function() {
    $("div[id $= Tree_Index]").find("input[type=checkbox]:first").click(function() {
        $(this).closest("div").find(':checkbox').attr('checked', this.checked);
    });
});

js fiddle link is here


text:
Q: from 1000 to 2000 php mysql I'm trying to run a mysql query which selects all users from a table where the rank is from 5000 to 15000. Those two have been put into variables. Let me change this into code, it'll explain it better.
$user_rank = 10000 //this is actually a $row[''] pulled from a database
$rank_above = $user_rank + 5000;
$rank_below = $user_rank - 5000;

$fetch_users = mysql_query("SELECT * FROM users WHERE rank = '$rank_below' ?to? '$rank_above'");

However, I also want to make the result a LIMIT 1 random result, so that it only selects one random user from the users table. Am I even going about this the right way?
Any help much appreciated, thank you.

A: You can use the BETWEEN clause in mysql
$sql = "SELECT * FROM users WHERE rank BETWEEN  5000 AND 15000"

Example:
$sql = "SELECT * FROM users WHERE rank BETWEEN %d AND %d"
$sql = sprintf($sql,(int)$rank_above,(int)$rank_below); // sanitize user input

A: Try this:
SELECT * FROM users
WHERE rank BETWEEN $rank_below AND $rank_above
ORDER BY RAND()
LIMIT 1;


text:
Q: Mail not sending in mvc 3 i have posted my source that having porblem named
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 68.178.232.62:25
i have implemented by ref of
http://developmentfaction.blogspot.in/2013/03/sending-email-with-javascript-and-aspnet.html
please help me to solve this issue
thanks in advance :)
View Page
 @using (Html.BeginForm("Emailto", "Home", FormMethod.Post))
    {
@Html.TextBoxFor(a => a.Position, new { @readonly = "readonly", @id = "Position", @name = "Position" })
  <input type="text" value="" id="txtname" name="txtname" required />
  <input type="email" value="" id="txtemail" name="fromEmail"  required />
<input type="submit" id="btnApply" name="btnApply" value="Apply" />

Controller
[HttpPost, ValidateInput(false)]
        public ActionResult Emailto(string Position, string txtname, string fromEmail)

        {
            EmailManager.SendMessage(Position, txtname, fromEmail);
            return Redirect("Index");
        }

EmailManager
[System.Web.Services.WebMethod]
        public static void SendMessage(string Position, string txtname, string fromEmail)
        {
            const string SERVER = "relay-hosting.secureserver.net";
            const string TOEMAIL = "acb@gmail.com";
            MailAddress from = new MailAddress(fromEmail);
            MailAddress to = new MailAddress(TOEMAIL);
            MailMessage message = new MailMessage(from, to);

            message.Subject = "Position " + Position;
            message.Body = "Message from: " + Position + " at " +
                           fromEmail + "\n\n" + txtname;
            message.IsBodyHtml = false;
            SmtpClient client = new SmtpClient(SERVER);
            client.Send(message);
        }
    }

A: You don't seem to be supplying a password or port for the smtp.
var loginInfo = new NetworkCredential(email, password);
SmtpClient client = new SmtpClient(SERVER, 587);

                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = loginInfo;
                client.Send(mail);

Hope this helps


text:
Q: Beginner. Can someone teach me how to count the number of times the inner loop has been excecuted? Can someone teach me how to count the number of times the inner loop has been executed?
import java.util.*;
public class Lab8Ex5{
    public static void main(String[] args){
        int primeCount = 1;
        System.out.print(2);
        int num = 2;
        while (primeCount < 20){
            num++; // try next number
            boolean isPrime = true;
            for (int i = 2; i < num; i++){
                if(num%i==0) // divisible by i
                    isPrime = false; // not a prime
            }

            if (isPrime){
                primeCount++; // one more prime is found
                System.out.print(","+num);
            }
        }
        System.out.println("Done");
    }
}

The number of counts should be 2415. I know that int count = 0; for (...) count++ ; could be used.
However, I don't know where should I put that on.

A: You need to define a counter outside the loops.
Then you need to increment the counter inside the nested loop.
It will count the number of executions of the nested loop over the outer loop.
import java.util.*;
public class Lab8Ex5{
    public static void main(String[] args){
        int primeCount = 1;
        System.out.print(2);
        int num = 2;
        int counter = 0;   // Define the counter and init it
        while (primeCount < 20){
            num++; // try next number
            boolean isPrime = true;
            for (int i = 2; i < num; i++){
                counter++;     // Increment the counter in the inner loop
                if(num%i==0) // divisible by i
                    isPrime = false; // not a prime
            }

            if (isPrime){
                primeCount++; // one more prime is found
                System.out.print(","+num);
            }
        }
        // Print the value of counter
        System.out.println("Done in " + counter + " steps");
    }
}


text:
Q: Eclipse ADT Layout Editor: no Properties I have an odd problem: my layout editor is broken. The buttons in the first menu bar are missing and i can't get any properties on the right side. Also, if i add a View in the XML directly, the layout won't be refreshed until i close the layout editor and open the xml again. I have found some discussions about missing properties, but this doesn't really help as the additional properties screen don't fix the other problems.
I have already reinstalled ADT - without success.
Screenshot of a default layout without any custom views

A: If other solutions don't work, it might be interesting to be a bit more drastic: set up a new workspace and re-import your android project.
If that doesn't work => reinstall eclipse?


text:
Q: What happens with method-local, static variables when parent class is deleted? Assumed I have following static variable within a method:
void myClass::myFct()
{
   static int myvar=0;

   ...
}

The behaviour is clear, "myvar" is initialised only once and whenever it is changed during "..." on next call of myFct(), the last value of myvar can be seen but not the initial value.
Now my question: what happens when the class "myClass" is deleted and then created again? Does this affect "myvar" (means is it initialised again) or is it left untouched and also after deletion/construction of the parent class the last (modified) value can be seen there?
Thanks!

A:
what happens when the class "myClass" is deleted and then created again?

Nothing that changes myvar. It is left untouched. Note that this behavior is crucial: local, static data in a member function can't be tied to a particular class instance. Imagine multiple threads creating different instances of myClass, deleting it from time to time... how unpredictable and non-thread-safe would the behavior be if every deletion/creation causes a read to that variable?


text:
Q: Why this code is giving error? package geek;

public class Gfg {

    // constructor
    Gfg() {
        System.out.println("Geeksforgeeks");
    }

    Gfg a = new Gfg();

    public static void main(String args[]) {
        Gfg b;
        b = new Gfg();
    }
}

This program when run is giving
Exception in thread "main" java.lang.StackOverflowError
Why is it giving this error?

A: This is causing a StackOverflow because you're creating an instance of the class within the class itself. This leads to infinite recursion that tries to create infinite nested instances of Gfg.
Remove Gfg a = new Gfg(); as it serves no purpose.

A: The reason is the following line, which causes infinite recursion:
Gfg a = new Gfg();

This is executed whenever a Gfg is instantiated. Since this line will instantiate a new instance, the line will be called again.


text:
Q: Weird behavior in Rust with OpenCV I am trying Rust (ver 1.4.0) these days, and coding with opencv-rust library.
I wrote some code like this.
extern crate opencv;

use self::opencv::highgui;
use self::opencv::core::Mat;

fn main() {
    load("image/test4.jpg");
}

fn load(path: &str) {
    let src: Mat = highgui::imread(path, 1).unwrap();

    if src.empty().unwrap() {
        println!("Img load error");
    }
    else {
        println!("Img load success");
    }
}

When I run cargo run it shows Img load error.
However, when I added a println! at first line in load function like
fn load(path: &str) {
    println!("whatever");
    let src: Mat = highgui::imread(path, 1).unwrap();

    if src.empty().unwrap() {
        println!("Img load error");
    }
    else {
        println!("Img load success");
    }
}

It shows Img load success.
But when I change it to other code like let a: i32 = 1;, it shows Img load error again.
I have no idea what's going on.
System info:

*

*OS: Manjaro Linux

*Kernel: 4.3.0

A: This bug was reported and fixed. Version 0.2.2 should now work.


text:
Q: Using-declaration to move name to another namespace? Given:
namespace One {
  void foo(int x) {
    munch(x + 1);
  }
};

namespace Two {
  // ... see later
}

...
void somewhere() {
  using namespace Two;
  foo(42);
  ...

is there any difference between the following two variants:
a)
namespace Two {
  void foo(int x) {
    munch(x + 1);
  }
};

and b)
namespace Two {
  using One::foo;
};

EDIT: It's pretty clear that (a) duplicates the code which should never be a good idea. The question is more about overload resolution etc. ... what if there are other foos or munches in possibly other namespaces?

A: With a, they are actually different functions, but with b, the two functions are identical:
assert(&One::foo == &Two::foo);

This would rarely matter; a bigger concern is duplicating the logic.

A: As for the usage they are equivalent. As for code, in case a) you're duplicating the function foo() code. That is, both versions will make available the foo() function inside Two, but the a) case generates the code for foo twice, because the compiler doesn't have any hint in discovering it is the same function.