text:
Q: Webscraping Google Search Results Using Google API - Returns same result over and over again My problem
Hi everyone
I am attempting to develop my very first web scraper using the Google API and Beautiful Soup in Python.
The aim is for the scraper to ask the user for an input, do a normal Google search and return a number of results in a nicely formatted way.
My current code succeeds in retrieving the data, but it only returns 1 result. When I try to do a loop on the results, in just keeps giving me the same result over and over again.
What I actually want is for the script to iterate over the different results on e.g. first page of Google search results and return all of these results. I am quite new to coding and I am guessing it's somewhere in my loop that I am making the mistake, but I guess it could also be something in the API?
I would very much appreciate some help here. Also the formatting of the code might be horrible, feel free to critique it so I can better at writing nice code :D
current code is
import sys
import urllib.request
import urllib.parse
import re
from urllib.request import urlopen as ureqs
from bs4 import BeautifulSoup as soup
from googleapiclient.discovery import build

# Google Personal Search Engine information
my_api_key = <key>
my_cse_id = <id>

# Google Search
def google_search(search_term, api_key, cse_id, **kwargs):
    service = build('customsearch', 'v1', developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res

# Setting up so that user can input query
query = input("enter the query\n")

# Getting into printing the results
results = google_search(query, my_api_key, my_cse_id)

print("\n*********Google Search Results*********\n")

for i in results:
    print("Title == " +results['items'][0]['title'])
    print("Link ==" +results['items'][0]['link'])
    snippet = results['items'][0]['snippet'].replace('\n', "")
    html_snippet = results['items'][0]['htmlSnippet'].replace('\n', "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("
", "")
    html_snippet = html_snippet.replace(" …", ".")
    print("Description == " + snippet+html_snippet)

A: Your code is constantly iterating over the first element. This is because you are not using a i - loop local variable.
The for statement in Python can iterate over the elements of any sequence in the order they appear in the sequence (list or string). If you need to iterate over a sequence of numbers, the range() built-in function comes in handy.
I used the second option with the range() function, where the variable i was used as the iteration number, which corresponds to the indices in the resulting array of values and allows each iteration to output a new value at the index. The len() built-in function is used to count the number of elements in a sequence and return the number to the range() function, thus passing in how many times the loop should be iterated.
Below is a modified snippet of your code. I also added f-strings which is a more pythonic way of concatenating strings that looks cleaner:
# your code

for i in range(len(results)):
    print(f"Title == {results['items'][i]['title']}")
    print(f"Link == {results['items'][i]['link']}")
    snippet = results['items'][i]['snippet'].replace('\n', "")
    html_snippet = results['items'][i]['htmlSnippet'].replace('\n', "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("
", "")
    html_snippet = html_snippet.replace(" …", ".")
    print(f"Description == {snippet}{html_snippet}", end="\n\n")

A solution that does the same but using only the Beautiful Soup library:
# variant using only the Beautiful Soup library

for result in soup.select(".tF2Cxc"):
    title = f'Title: {result.select_one("h3").text}'
    link = f'Link: {result.select_one("a")["href"]}'
    description = f'Description: {result.select_one(".VwiC3b").text}'

    print(title, link, description, sep="\n", end="\n\n")

I decided to present an option using only the Beautiful Soup library, since your code uses a lot of libraries that you can do without. I also noticed that you manually remove the tags, although this can be done more easily by selecting the text of the .VwiC3b selector. This will ignore the inner tags and take their contents.

Also, make sure you're using request headers user-agent to act as a "real" user visit. Because default requests user-agent is python-requests and websites understand that it's most likely a script that sends a request. Check what's your user-agent.
Code and full example in online IDE:
import sys
import urllib.request
import urllib.parse
import re
from urllib.request import urlopen as ureqs
from bs4 import BeautifulSoup as soup
from googleapiclient.discovery import build

# Google Personal Search Engine information
my_api_key = <key>
my_cse_id = <id>

# Google Search
def google_search(search_term, api_key, cse_id, **kwargs):
    service = build('customsearch', 'v1', developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res

# Setting up so that user can input query
query = input("Enter the query:\n")

# Getting into printing the results
results = google_search(query, my_api_key, my_cse_id)

print("\n*********Google Search Results*********\n")

for i in range(len(results)):
    print(f"Title == {results['items'][i]['title']}")
    print(f"Link == {results['items'][i]['link']}")
    snippet = results['items'][i]['snippet'].replace('\n', "")
    html_snippet = results['items'][i]['htmlSnippet'].replace('\n', "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("", "")
    html_snippet = html_snippet.replace("
", "")
    html_snippet = html_snippet.replace(" …", ".")
    print(f"Description == {snippet}{html_snippet}", end="\n\n")

Output:
*********Google Search Results*********

Title == Coffee - Wikipedia
Link == https://en.wikipedia.org/wiki/Coffee
Description == Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain flowering plants in the Coffea genus. From the coffee fruit, ...Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain flowering plants in the Coffea genus. From the coffee fruit, ...

Title == Starbucks Coffee Company
Link == https://www.starbucks.com/
Description == More than just great coffee. Explore the menu, sign up for Starbucks® Rewards, manage your gift card and more.More than just great coffee. Explore the menu, sign up for Starbucks® Rewards, manage your gift card and more.

... other results

Using Beautiful Soup:
from bs4 import BeautifulSoup
import requests, lxml

query = input("Enter the query:\n")

# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
params = {
    "q": query,
    "hl": "en",  # language
    "gl": "us"   # country of the search, US -> USA
}

# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36",
}

html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")

for result in soup.select(".tF2Cxc"):
    title = f'Title: {result.select_one("h3").text}'
    link = f'Link: {result.select_one("a")["href"]}'
    description = f'Description: {result.select_one(".VwiC3b").text}'

    print(title, link, description, sep="\n", end="\n\n")

Output:
Title: Coffee - Wikipedia
Link: https://en.wikipedia.org/wiki/Coffee
Description: Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain flowering plants in the Coffea genus. From the coffee fruit, ...

Title: Starbucks Coffee Company
Link: https://www.starbucks.com/
Description: More than just great coffee. Explore the menu, sign up for Starbucks® Rewards, manage your gift card and more.

... other results

Alternatively, you can use Google Organic Results API from SerpApi. It`s a paid API with the free plan.
The difference is that it will bypass blocks from Google or other search engines, so the end-user doesn't have to figure out how to do it, maintain the parse, and only think about what data to retrieve instead.
Example code to integrate:
from serpapi import GoogleSearch
import os

query = input("Enter the query:\n")

params = {
  # https://docs.python.org/3/library/os.html#os.getenv
  "api_key": os.getenv("API_KEY"),  # your serpapi api key
  "engine": "google",               # search engine
  "q": query                        # search query
  # other parameters
}

search = GoogleSearch(params)  # where data extraction happens on the SerpApi backend
results = search.get_dict()    # JSON -> Python dict

for result in results["organic_results"]:
    print(result["title"], result["link"], result["snippet"], sep="\n", end="\n\n")

Output:
Coffee - Wikipedia
https://en.wikipedia.org/wiki/Coffee
Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain flowering plants in the Coffea genus. From the coffee fruit, ...

Starbucks Coffee Company
https://www.starbucks.com/
More than just great coffee. Explore the menu, sign up for Starbucks® Rewards, manage your gift card and more.

... other results

Disclaimer, I work for SerpApi.

A: You iterate through results, but you never use object i inside the loop. Instead you always display results['items'][0]'s result


text:
Q: Analogue $(document).on('event', 'selecton', function(){}); for JavaScript In jQuery there is the script
$(document).on('click', '#popup-pers .mfp-close', function(e){});,
is used if .mfp-close is virtual element that appear not by load the page, but by event, instead
$(#popup-pers .mfp-close).click();
I need the same analogue for JS. I use
pers_hide = querySelector('#popup-pers .mfp-close');

but browser sees just #popup-pers , not '#popup-pers .mfp-close'

A: For dynamically created elements on whom you want to assign a click event before they are inserted in the DOM - Assign the event to the parent delegator, and than query the Event Event.target.closest(selector) matches the desired dynamic child selector.
Here are two possible solutions/suggestions:
Create your own on() helper:

// DOM utility functions:
const el = (sel, parent) => (parent ||document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);

// On handler:
const on = (eventName, delegator, target, cbFn, opts) =>
  el(delegator).addEventListener(eventName, evt =>
    evt.target.closest(target) && cbFn(evt), opts);

// Task:

// 1. Assign events beforehand:
on("click", "#popup-pers", ".mfp-close", (evt) => {
  console.log(evt.target.textContent);
});

// 2. Insert element afterwards:
el("#popup-pers").append(elNew("button", {
  type: "button",
  className: "mfp-close",
  textContent: "CLICK"
}));
#popup-pers {
  background: gold;
  padding: 10px;
}

Assign the event when creating your elements
Otherwise assign the desired event handler function on Element creation, by using the onclick method (which is the only valid way that property should ever be used, and that's when creating new in-memory elements):

// DOM utility functions:
const el = (sel, parent) => (parent ||document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);

// Task:
// Insert element with click function assigned:

el("#popup-pers").append(elNew("button", {
  type: "button",
  className: "mfp-close",
  textContent: "CLICK",
  onclick() {
    console.log(this.textContent);
  }
}));
#popup-pers {
  background: gold;
  padding: 10px;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Given a Spring Data Rest URI, How Do you find the associated target repository? I'm building an application using Spring Data REST and implementing an interceptor pattern using a MappedInterceptor as suggested in this post. The interceptor works as expected and it intercepts @RestControllers.
Now, using the parameters available in the preHandle(…) method signature (these include: HttpServletRequest request, HttpServletResponse response, Object handler => can be casted to org.springframework.web.method.HandlerMethod), how can I access the RestRepository class or repository Method being invoked (the getMethod(), from the HandlerMethod class, works great with Concrete classes, but it does not work with Repository interfaces, it ends returning a RestAbstractController class that invokes the target repository through reflection)???
Why I need this?
Because, I´m doing a cross-cutting logic that needs to access the Repository interface to find a specific business annotation, if the annotation is present, some logic is done (like setting MDC special values, for example)...
Thanks...

A: The most flexible way to generically lookup and use Spring Data repositories is through the Repositories and RepositoryInvoker abstractions.
The former provides by-type lookup abilities of metadata about the repositories and the repositories themselves. The latter allows generic invocation of CRUD and query methods on those repositories. This additional abstraction is necessary as Spring Data repositories don't have to implement a special interface as long as they expose methods that are syntactically equivalent to the ones provided in Spring Data's CrudRepository.
The general way
If you know about the actual domain class you're trying to access the repository for you can get an instance of Repositories injected into your class. That one in turn allows you to lookup entity and repository information as well as the repository itself.
As the latter doesn't have to implement a dedicated interface mandatorily, Repositories.getRepositoryFor(…) only returns Optional<Object> which isn't too helpful if you want to actually do stuff on the repository. RepositoryInvokerFactory allows you to create RepositoryInvoker instances that allow you to invoke certain methods on a repository explicitly independent of way they're actually declared.
@Component
@RequiredArgsConstructor
class SomeComponent {

  private final Repositories repositories;

  public <T> void someMethod(Class<T> type) {

    … = repositories.getEntityInformation(type);

    RepositoryInvokerFactory factory = new DefaultRepositoryInvokerFactory(repositories);
    RepositoryInvoker invoker = factory.getInvokerFor(type);
    Optional<T> entity = invoker.invokeFindById(4711);
  }
}

Note, that a Repositories instance is available as Spring Bean if you use Spring Data REST. If you don't simply declare a bean for it. All it needs is a ListableBeanFactory.
Spring Data REST
With Spring Data REST in the picture on might get into the need to lookup the repository that's backing a particular path segment of the URI. That additional knowledge is encoded in RepositoryResourceMappings which can be used to find out about the domain type that's accessed:
RepositoryResourceMappings mappings = … // get injected

Optional<Class<?>> domainType = mappings.stream()
  .filter(metadata -> metadata.getPath().matches(pathSegment))
  .findFirst()
  .map(ResourceMetadata::getDomainType);

The discovered type can now be used to obtain the repository instance from Repositories. Spring Data REST also provides a preconfigured instance of RepositoryInvokerFactory that applies potentially registered custom EntityLookup instances. I.e. using that is preferred to creating an own one like shown above.


text:
Q: TikZ/PGF key filters : overriding color I'm trying to override the color key within a pic but not within the enclosing scope (That is the path/draw/fill instruction).
My objective is to be able to set the colour for a path and have this affect the pic as well. That is the pic might have a custom shading and I would like this shading to adopt the paths colour as a tint. One should, however, still be allowed to override the local colour for the pic.
The example shows how I think it should be coded based upon the documentation but the filter is not working as I'd expected. Within the example I create a local name space /tikz/example as originally the 'color' style was clobbering the /tikz/color key. Filtering also needs a family to work with.
My understanding of filtering is that one ought to create/register the filter, in this case tikz/example, and then activate it when necessary i.e. before and after pic actions is executed.
The output I expect to see is the backround block in white with a blue line, overlaid by the three smaller blocks each shaded in blue, red and green.
\documentclass[tikz]{standalone}

\usetikzlibrary{calc}

\tikzset{
 basis/.initial=1em,
 block/.is family,
 /tikz/pic actions/.install key filter=block,
 block/.pic={
  \draw[block/.activate family, pic actions, block/.deactivate family]
    let \n{basis}={\pgfkeysvalueof{/tikz/basis}} in
      (-\n{basis},-\n{basis}) rectangle  (\n{basis},\n{basis});
 },
 block/.cd,
 colour/.style={/tikz/top color   =#1!50!white,
                /tikz/bottom color=#1!50!black},
}

\begin{document}

\begin{tikzpicture}
\draw[color=blue]
     ( 0, 0) pic               {block}
     (-1,-1) pic[color=green]  {block}
      rectangle
      (1,1)  pic[color=red]    {block};
\end{tikzpicture}

\end{document}

A: Sorry but I do not understand why you need all this "block family".
Inside a picture the pic actions contains the current color settings, that are by default the path's one, but you can overwrite them inside the pic style.
\documentclass[tikz]{standalone}
\usetikzlibrary{calc}

\tikzset{
 basis/.initial=1em,
 block/.pic={
  \draw[pic actions]
    let \n{basis}={\pgfkeysvalueof{/tikz/basis}} in
      (-\n{basis},-\n{basis}) rectangle  (\n{basis},\n{basis});
 },
 colour/.style={top color   =#1!50!white,
                bottom color=#1!50!black},
}

\begin{document}

  \begin{tikzpicture}
    \draw[blue]
      ( 0, 0) pic                         {block}
      (-1,-1) pic[colour=green, draw=red] {block}
        rectangle
      (1,1)  pic[colour=red]              {block};
  \end{tikzpicture}

\end{document}


text:
Q: Wordpress 301 permanent redirect with exceptions I'd like to set a permanent redirect whenever someone visits myoldsite.com or its subpages to mynewsite.com  like that:

visit myoldsite.com go to mynewsite.com
visit myoldsite.com/subpage go to mynewsite.com (and NOT
  mynewsite.com/subpage)

I would also like to make exceptions to the above for wp-admin and wp-login subpages. I don't have server access to myoldsite Wordpress installation, so I can edit .htaccess file only through a Wordpress plugin. I would also like to make an exception for .htaccess if possible, in order to be able to reedit .htaccess via my 'Wordpress .htaccess plugin' once the redirect is done, so I can have the power to revert things back to default if necessary.
My .htaccess file:
# 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>

# END WordPress

A: In your htaccess plugin editor, add the following line in your rewrite rules:
RewriteCond %{REQUEST_URI} !^/wp-admin/
RewriteCond %{REQUEST_URI} !^/wp-login\.php
RewriteRule ^(.*)$ http://www.mynewsite.com/ [R=301,L]


text:
Q: SNMP Mib. Are the "qualified" descriptors used in practice According standard RFC 2578 3.2. IMPORTing Symbols:
Note that when symbols from "enterprise-specific" information modules
are referenced  (e.g., a descriptor), there is the possibility of
collision.  As such, if different objects with the same descriptor
are IMPORTed, then this ambiguity is resolved by prefixing the
descriptor with the name of the information module and a dot ("."),
i.e.,

    "module.descriptor"

(All descriptors must be unique within any information module.)

Of course, this notation can be used to refer to objects even when
there is no collision when IMPORTing symbols.

Everything seems to be clear, but...
i cannot find in standard where it can be used and i cannot find any mib that using "qualified" descriptors.
It seems that no one uses it. Is in real mib "qualified" descriptors used and how it used?

A: I made up some test cases for my compiler product, so post them here for your reference.
TEST1-MIB module who defines mytest as 9998.
TEST1-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9998 }

END

TEST2-MIB module who defines mytest as 9999.
TEST2-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9999 }

END

Then when TEST3-MIB module tries to import both, we need the prefix to determine which mytest would be used,
TEST3-MIB DEFINITIONS ::= BEGIN
IMPORTS
    mytest
        FROM TEST1-MIB
    mytest
        FROM TEST2-MIB;

mytest1 OBJECT IDENTIFIER ::= { TEST2-MIB.mytest 9999 }

END


text:
Q: Add class with opacity not working I have a div that loads with the following class.
I am removing and readding that class based off of a checkbox using the following jquery.
The issue is the opacity on the div is correct when the page loads, but when I check then uncheck (remove and add again) the class is added and the pointer events works but not the opacity. Does this have to do with the fact that this div has a form element in it? I have another div with just text elements in it and it works fine.
Here is the html of the non working div.

    $("#add_back").on("click",function(){
     if( $(this).is(':checked') ){
      console.log("checked");
      $(".back_lock").removeClass("disabledElememt");
     }else{
      console.log("unchecked");
      $(".back_lock").addClass("disabledElememt");
     }
    });
    .disabledElememt {
        pointer-events: none;
        opacity: 0.4;
    }

          <input id="add_back" type="checkbox">Unlock for 4.99

             Text Line 1
       <input type="text" id="back_txt_input_0" class="form-control text_element_input" placeholder="Text Line 1" value="Text Line 1">


text:
Q: Linear Algebra Matrix and Inverse I have 4x4 matrices:
$$A\begin{bmatrix}
3&1&3&-4\\
6&4&8&10\\
3&2&5&-1\\
-9&5&-2&-4
\end{bmatrix} =
\begin{bmatrix}
0&1&0&0\\
0&0&0&1\\
0&0&1&0\\
1&0&0&0
\end{bmatrix}
$$
and
$$\begin{bmatrix}
3&1&3&-4\\
6&4&8&10\\
3&2&5&-1\\
-9&5&-2&-4
\end{bmatrix}
B = \begin{bmatrix}
0&1&0&0\\
0&0&0&1\\
0&0&1&0\\
1&0&0&0
\end{bmatrix}$$
and I need to find $A^{-1}$ and $B^{-1}$.
Now, there's the long way of doing it (augmented matrix with identity on the right side and solving for A, then finding A inverse, B, then B inverse), but I thought this was too much work and there must be an efficient way of doing it.
I've noticed that the right side of the equation for both A[] and []B look like they are just another arrangement of identity matrix, which must provide some useful clue to this problem.
I have a gut feeling that we must do something with elementary row matrices but don't have a concrete idea to get me started..
Can anyone give me some insight or introduce efficient way of solving this question?
(Without determinant or long mechanical computation)
Thank you.

A: The right hand matrix is known as permutation matrix and its inverse is its transpose, i.e.
$$
P^{-1}=\begin{bmatrix}
0&1&0&0\\
0&0&0&1\\
0&0&1&0\\
1&0&0&0
\end{bmatrix}^T=\begin{bmatrix}
0&0&0&1\\
1&0&0&0\\
0&0&1&0\\
0&1&0&0
\end{bmatrix}=[e_2\: e_4\: e_3 \:e_1]=\begin{bmatrix}e_4'\\e_1'\\e_3'\\e_2'\end{bmatrix}
$$
where $e_i$ is elementary column vector and $e_i'$ is elementary row vector. Also $Ae_i$ is the $i$th column of $A$ and $e_i'A$ is the $i$th row of $A$.
So
$$
A^{-1}=\begin{bmatrix}
3&1&3&-4\\
6&4&8&10\\
3&2&5&-1\\
-9&5&-2&-4
\end{bmatrix}[e_2\: e_4\: e_3 \:e_1]=\begin{bmatrix}
1&-4&3&3\\
4&10&8&6\\
2&-1&5&3\\
5&-4&-2&-9
\end{bmatrix}
$$
And
$$
B^{-1}=\begin{bmatrix}e_4'\\e_1'\\e_3'\\e_2'\end{bmatrix}\begin{bmatrix}
3&1&3&-4\\
6&4&8&10\\
3&2&5&-1\\
-9&5&-2&-4
\end{bmatrix}=\begin{bmatrix}
-9&5&-2&-4\\
3&1&3&-4\\
3&2&5&-1\\
6&4&8&10
\end{bmatrix}
$$


text:
Q: IBM worklight WL.JSONStore.QueryPart(). Jsonstore error when i use an advance search, it shows that WL.JSONStore.QueryPart(). is not a function and it is not recognized as something existent, is it deprecated or i need to use it differently?
var queryPart1 = WL.JSONStore.QueryPart().like('category', 'abc')
var queryPart2 = WL.JSONStore.QueryPart().like('category', 'xyz');

  WL.JSONStore.get('Categories').advancedFind([queryPart1,queryPart2])

   .then(function(results){

                     })

.fail(function(errorObject) {
                        alert("fail" + errorObject);
                          });

A: Query parts and advancedFind are only supported on version 6.2 and above.


text:
Q: How do I fold Flutter Bloc in Android Studio? Is there a plugin or way I could fold code when using Bloc in Flutter using Android Studio
I want to be able to collapse this whole section
on<MyEvent>((event, emit) {
   /* A lot of code
   /* Which I want to collapse
});


text:
Q: Android games leaderboard broken while testing I have successfully integrated the Google Games API in my app, and now I can see my leaderboard and achievements as described here and here respectively.
However, when trying to submit a score using this code:
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.play_console_leaderboard_id), 100);

for some reason the leaderboard stops appearing. Actually it starts loading, and then directly disappears. This post seems to describe the same issue, however there is no solution posted.
I know that it has to do with the submitScore because when I create a new leaderboard, I can successfully open it and see the message that no one has reported any score. Then again, if I try to submit a score, the leaderboard again breaks.
Any hints / suggestions on that?
Thanks.
EDIT: I am starting to believe that for some reason it may have to do with the tamper protection from the Play Console. Although even when I tried to disable it, the problem still persists..
EDIT2: Do I have to publish my game so I can test the leaderboards? I know that it sounds weird.

A: After testing with the submitScoreImmediate, I saw that I got STATUS_CLIENT_RECONNECT_REQUIRED. Based on this post, I figured that I had to create another OAUTH client id, using my debug.keystore.
And this was true; when I created a release certificate-signed APK and tried it, everything worked.
Now, Google mentions here the following:

Note: If you are debugging your game using your debug certificate but
  have configured games services using your release certificate, you
  should add a second linked app using the same package name and your
  debug certificate's SHA1 fingerprint. This will allow you to sign in
  to the application whether it's signed with the debug or release
  certificates.

However, if I try to link a 2nd app with the same package, I CANNOT apply another SHA1 fingerprint, since the Approval button does not appear, and thus cannot provide my debug key.
Is there any help on this?


text:
Q: Backlight problems with 12.04 on my Acer Aspire 4736z How can I fix a bug that wouldn't let me turn the backlight on after it turns off automatically when I close the lid or when powersave settings kick in?
I also can't adjust the brightness of the screen through the Fn + Left/Right Arrow button combination, how can I make this work?
And one last thing, when I try to follow some of the fixes that are being suggested in forums, like editing the etc/x11/xorg.conf by using the terminal command sudo gedit, the file that I'm supposed to edit is totally blank. And when I look at the folder I didn't see a file "xorg.conf" but I saw "xorg.conf.failsafe" I tried creating a xorg.conf but I can't save the file. What shall I do in this kind of scenario, just in case the solution for my first 2 question requires sudo gedit? Thanks!

A: I installed Cairo Dock and there is an applet called Screen Luminosity that lets you use the Fn button for adjusting the brightness.
And I updated Ubuntu this morning and my other problems are gone. I hope this is for good. I'm getting fond of Ubuntu Linux.


text:
Q: What happens when you go to sleep mode in Windows 10 Title says it all, but specifically

*

*Does Wifi get turned off?

*How much CPU power is being reduced and how much battery is saved?

*Does the graphics card still run when on sleep mode?

A: 'Sleep mode' in a nutshell stops the CPU's clocking, so the CPU stops right where it is. The memory is still powered, and everything else does nothing.
When you wake the computer 'up', the clocking starts, and it moves right on.
Because the CPU does not react to interrupts while it 'sleeps' (except the 'wake-up' call), all external access it disabled, so no wireless, no internal clock updating, etc.

A:
What happens when you go to sleep mode in Windows 10

Below are a couple good references to the topic of the question as the title asks:

Shut down, sleep, or hibernate your PC
Sleep
This uses very little power, your PC starts up faster, and you're
  instantly back to where you left off. You don't have to worry that
  you'll lose your work because of your battery draining, because
  Windows automatically saves all your work and turns off the PC if the
  battery is too low. Use sleep when you're going to be away from your
  PC for just a little while—like when you're taking a coffee break.
source

Four Windows 10 Power Settings You Should Probably Change (Hibernation and Sleep)
Sleep stores the state of your computer in RAM, and so resumes much
  faster; you'll be up and running in two to five seconds in some cases.
  However, sleep uses a fair amount of battery power. So it makes sense
  to decide which of these you want to use and when. The default
  settings are, in my opinion, not ideal for most usage cases.
source

*

*Does Wifi get turned off

*How much CPU power is being reduced and how much battery is saved.

*Does the graphics card still run when on sleep mode

For the question about the Graphics Card and the WiFi, those are not operational in sleep mode until the PC wakes from the mode.
For the CPU question, that will depend on the sleep state you have configured, see these two resources for more detail on these states:

*

*System Power States

*System Sleeping States
For the Battery question that depends on many factors as well but see here for a good read:

*

*How Much Battery Life Does Sleep Mode Really Drain?

A: *

*yes, wifi is turned off (if your computer is not set up to be awaken remotely from network)

*cpu and battery consumption are very low (aprox. under 0,1%)

*no, grafics card is shut down
(fyi all jobs that you are running will be frozen till power on. even if you do a heavy cpu work like encoding of the movie)

A: my laptop has virus scans set up for 3 AM every day of the week.
However I often note that my AVG package tells me it has not done a scan for 10 or more days. My power setting is to put the computer to sleep when I close the lid.
Is that the problem?


text:
Q: Why does Windows Media Player sometimes fail to include the appropriate cookies in requests for content when it is being used via Internet Explorer? We have a site hosted in IIS6 that we built using the .NET 1.1 Framework. Users who go to this site use Internet Explorer exclusively and log into it using Forms authentication. Within the site, users can navigate to a specific page that has an iFrame embedded in it. This iFrame points to another virtual directory hosted on the same server, and this second virtual directory simply streams down the movie file. Assuming the user has Windows Media Player installed on their machine and has configured it so that Windows Media Player is the default movie player, when a user navigates to the page with the iFrame, Windows Media Player pops open a new window and the movie plays.
We very recently upgraded our software to use the .NET 3.5 framework. However, we have noticed that our movie file no longer plays. We instead get a message indicating that Windows Media Player cannot connect to the server.
I've gone ahead and done some investigation of the network traffic between the client and server machines by using Fiddler, and these are the steps that happen in the scenario where things work:
1) Internet Explorer makes a request to the server for the movie file. The request header contains cookies that are required for proper authentication and session identification.
*GET MYSITE HTTP/1.1
Accept: image/jpeg, image/gif, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, /
Referer: MYREFERRER
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2)
Accept-Encoding: gzip, deflate
Host: MYHOST
Connection: Keep-Alive
Cookie: a99fd71e-eb1b-4750-a391-5ad8cfe32068=800edb77-9649-4f93-9db9-98d678a3b166; ASP.NET_SessionId=uf1cr1bflwly0nmhbm1wnb55; EDDS=581A46E81C8DB0B475F1AFE00545F9B157A377BD31DF65BB2AEF7D1B293BDE9E178409FF251CF49F109FDC601C48F15A5FCDE1A29A18E6853357887698A01E7A2CC3690ECE98C464DE1359D796B60BE969F875EF08F638A04CDED78A309ACD6E9732F8C3751A2B0A411ADFA91B0AE567*
2) The server uses the cookies to authenticate the request from the user and then returns the movie. The status code of the return is a 200.
HTTP/1.1 200 OK
Date: Wed, 11 Aug 2010 21:30:55 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Content-Length: 3934146
Accept-Ranges: bytes
Content-Disposition: inline; filename = AS000006.wmv
Last-Modified: Tue, 10 Aug 2010 21:24:49 GMT
ETag: "MyExampleFileID"
Cache-Control: private
Content-Type: application/octet-stream
3) Windows Media Player makes a request to the server for the movie file. Again, the request header contains cookies. However, this time the request includes a Range request for bytes 8192-.
*GET MYSITE HTTP/1.1
Accept: /
User-Agent: Windows-Media-Player/12.0.7600.16415
Accept-Encoding: gzip, deflate
Range: bytes=8192-
Unless-Modified-Since: Tue, 10 Aug 2010 21:24:49 GMT
If-Range: "MyExampleFileID"
Connection: Keep-Alive
Host: MYHOST
Cookie: ASP.NET_SessionId=uf1cr1bflwly0nmhbm1wnb55; EDDS=581A46E81C8DB0B475F1AFE00545F9B157A377BD31DF65BB2AEF7D1B293BDE9E178409FF251CF49F109FDC601C48F15A5FCDE1A29A18E6853357887698A01E7A2CC3690ECE98C464DE1359D796B60BE969F875EF08F638A04CDED78A309ACD6E9732F8C3751A2B0A411ADFA91B0AE567; a99fd71e-eb1b-4750-a391-5ad8cfe32068=800edb77-9649-4f93-9db9-98d678a3b166*
4) The server uses the cookie information to authenticate the request from the user and then returns the document. The status code of the return is a 206.
HTTP/1.1 206 Partial Content
Date: Wed, 11 Aug 2010 21:30:57 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Content-Range: bytes 8192-3934145/3934146
Content-Length: 3925954
Accept-Ranges: bytes
Content-Disposition: inline; filename = AS000006.wmv
Last-Modified: Tue, 10 Aug 2010 21:24:49 GMT
ETag: "MyExampleFileID"
Cache-Control: private
Content-Type: application/octet-stream
When things don't work, it looks like this:
1) Internet Explorer makes a request to the server for the movie file. The request header contains cookies.
*GET MYSITE HTTP/1.1
Accept: image/jpeg, image/gif, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, /
Referer:MYREFERRER
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2)
Accept-Encoding: gzip, deflate
Host: MYHOST
Connection: Keep-Alive
Cookie: a99fd71e-eb1b-4750-a391-5ad8cfe32068=7ac4710e-1434-43c9-b521-bdf30328e2fb; ASP.NET_SessionId=glytwo55ztohig451qrf1355; EDDS=CFC5EAE69F6D6CDD0A1D53632F01629F8AC8F4901A6106DD26A0A9F4E1E0B0EC9D4B1B78FBEF5C504A54E6B1A43F576CD846ADD3D394DF257EBBF982BED5E99900116945191268E985ED923DAA78DF4FBD68B09FF3B4D14D7092FB846012E5F464D9EBC4BA834235839A397A4F00B548D353A1AB9B67F6F960E26FC655D19D4B89347DFA2BCC7101E2397AC7EB0F105025E5A21253C0E619E809C1D9B64E53E8*
2) The server uses the cookies to authenticate the request from the user and then returns the movie. The status code of the return is a 200.
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 3934146
Content-Type: application/octet-stream
Last-Modified: Wed, 11 Aug 2010 15:29:44 GMT
Accept-Ranges: bytes
ETag: "MyExampleFileID"
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
Content-Disposition: inline; filename = AS000006.wmv
X-Powered-By: ASP.NET
Date: Wed, 11 Aug 2010 21:36:45 GMT
3) Windows Media Player makes a request to the server for the movie file. The request does NOT contain any cookies. The server fails to authenticate the user and the movie doesn't get sent down.
*GET MYSITE HTTP/1.1
Accept: /
User-Agent: Windows-Media-Player/12.0.7600.16415
Accept-Encoding: gzip, deflate
Range: bytes=8192-
Unless-Modified-Since: Wed, 11 Aug 2010 15:29:44 GMT
If-Range: "MyExampleFileID"
Connection: Keep-Alive
Host: MYHOST*
So, at this point I know exactly why it isn't working. The request from Windows Media Player doesn't contain any cookies, so our server won't authenticate the request and send down the data. What I'm completely failing to understand is why those cookies aren't being used by Windows Media Player when it makes it's request.
All of the above requests were made from the same machine to two different sites, so I know that it isn't an issue with different versions Windows Media Player. I've reproduced the behavior on several different machines with different operating systems and different versions of IE, so it doesn't appear to be related to a specific machine. I've tried reverting back to IIS6 instead of using IIS7 for the new site, and that doesn't make a difference either. I'm left thinking it has to be something in my code, but I don't even know where to begin looking.
My question is: Does anyone really understand how Internet Explorer passes URL information to Windows Media Player and perhaps point me in the right direction to figure this out? My only other option at this point is to open up a ticket with Microsoft support... and to be frank, my experience with their support team has been less than optimal over the past few years. Any help would be GREATLY appreciated!
EDIT:
Using process explorer, I've been able to prove that IE is simply not providing cookie information to Windows Media Player now. I'm still no closer to understanding why, though.

A: After days of troubleshooting with 4 support engineers from Microsoft, we were had been no closer to understanding the issue. Then, one of the guys on my team stumbled across this link:
http://mvolo.com/iis-70-forms-authentication-and-embedded-media-players/
While the error message mentioned in the article isn't the one we're seeing, the solution he proposed resonated with me. We gave it a shot, and thankfully, it solved the issue.


text:
Q: How to call in C lua modules To simplify things, let's assume, that there are two Lua scripts, one program and one module, e.g:
sample.lua
local sample = {}
    sample.fun1 = function()
    end;
return sample;

I'm using it in program, like this:
program.lua
local sample = require("sample");
sample.fun1();

And now i'm trying to use the same module in C (first running lua program, what is important here), something like this:
luaL_dofile(luaState, "program.lua");
...
lua_getglobal(luaState, "sample");
lua_getfield(luaState,-1, "fun1");

or
luaL_dofile(luaState, "program.lua");
...
lua_getglobal(luaState, "sample.fun1");

But both versions causing crash. My question here: Is it possible to use somehow module, which was previously used in program? For this example it is of course nonsense, but my system is far more complicated and i need this functionality. Maybe some other approach to achieve this?


text:
Q: Changing rgb percentage color values with hexadecimal ones in a svg file using python I am trying to swap out all rgb(0%,0%,0%) to hex values inside a svg because the software I use doesn't support rgb values. I have figured out I can use webcolors to achieve the conversion. And I'm now trying to use re.sub to find the rgb values line-by-line and substitute them with hex using webcolors with the following exp:
exp = r'rgb\((?:(?P<red>\d{1,3}.?(?:\d{1,50})?)(?:\%\,?)(?P<green>\d{1,3}.?(?:\d{1,50})?)(?:\%\,?)(?P<blue>\d{1,3}.?(?:\d{1,50})?)(?:\%))\)'
However, I get value error whatever I try. Here is the code:
import re
from webcolors import rgb_percent_to_hex

exp = r'rgb\((?:(?P<red>\d{1,3}.?(?:\d{1,50})?)(?:\%\,?)(?P<green>\d{1,3}.?(?:\d{1,50})?)(?:\%\,?)(?P<blue>\d{1,3}.?(?:\d{1,50})?)(?:\%))\)'

with open('sample.svg', 'w') as f:
    for line in f:
        re.sub(exp, rgb_percent_to_hex(r'\g<red>',
                                       r'\g<green>',
                                       r'\g<blue>'), line))
f.close()

A: Apparently, you cannot run functions the way I initially thought with re.sub.
I managed it in the following way (here with a folder of svgs):
Setup
import re
import os
from webcolors import rgb_percent_to_hex

path = 'path/to/svgs'

# function that return hex color values from rgb
def cs(s): return rgb_percent_to_hex((s.group(1), s.group(2), s.group(3)))

# cobble up the svg files
svg_files = [f for f in os.listdir(path) if f.endswith('.svg')]

# There are probably more readable ones than this reg ex

exp = r'rgb\((?:(\d{1,3}.?(?:\d{1,50}\%)?)(?:\,?)(\d{1,3}.?(?:\d{1,50}\%)?)(?:\,?)(\d{1,3}.?(?:\d{1,50}\%)?)(?:))\)'
Then
# walking the files and making the change
for j in scaled_files:
    w = open(os.path.splitext(os.path.join(path, j))[0] + '_sub.svg', 'w')
    r = open(os.path.join(path, j))
    for l in r:
        w.write(re.sub(exp, cs, l))
    w.close()
    r.close()

You can just as easily do this with a single file with a few small changes.


text:
Q: redirect_uri facebook graph api with cakephp I need to share a page from my php website to user's facebook wall. If user is not logged into facebook, my website redirects to the facebook login page using
    $user = $facebook->getUser();
    if($user) {
        $result = $facebook->api(
            '/me/feed/',
            'POST',
            array('access_token' => $this->access_token, 'link'=>'google.com', 'message' => 'Test link')
        );
        $this->Session->setFlash('Your link has been succesfully posted on your wall');
        $this->redirect($this->referer());
    }else {
       $login_url_params = array(
          'req_perms' => 'publish_stream',
          'redirect_uri' => 'localhost/pictrail' //thts the same path I gave to my facebook app
       );
       $login_url = $facebook->getLoginUrl($login_url_params);
       header("Location: {$login_url}");
       exit();
    }

So, when the user is not logged into facebook .. it redirects to facebook for the user to log in, afterwards it redirects to localhost/pictrail regardless of the url i put in there. I want to redirect it to say localhost/pictrail/images/param ... how can i achieve this? I tried 'localhost/pictrail/images/99' but it didn't work. Everything works fine when the user is logged into facebook.

A: You cannot redirect from Facebook to localhost as it's not a valid address.
The way that I got around this, for development, was to edit my hosts file and replace the domain with my local ip.
www.example.com  127.0.0.1
Then you can redirect to www.example.com from your Facebook app and it will render your local development version.
Be sure to add this domain to your local server's vhost or similar.

Sorry I misread your question. To change the Facebook redirect url you need to change it in your Facebook app. So you'd have to pass a custom field through to Facebook and then tack it back on afterwards.
Have a look through this, https://developers.facebook.com/docs/authentication/server-side/


text:
Q: Missing or invalid 'android' section in rhobuild.yml: I am using RhoStudio to build a test application and it is giving me this error
Missing or invalid 'android' section in rhobuild.yml:

I tried googling it but I couldn't figure out the problem.

A: I think it's because you have to configure Android in build.yml file. That file is in the root folder of the proyect and is different of RhoBuild.yml since the last one configure variables for the Rho building environment and build.yml only configures the build of your app.
Try creating a blank app and locating that file in the root folder.


text:
Q: Calling variables in another module python I'm trying to access variables I created in one function inside another module in Python to plot a graph however, Python can't find them.
Heres some example code:
class1:
    def method1
        var1 = []
        var2 = []
    #Do something with var1 and var2
        print var1
        print var2
        return var1,var2

sample = class1()
sample.method1

here is class 2
 from class1 import *

 class number2:
     sample.method1()

This does as intended and prints var1 and var2 but I can't call var1 or var2 inside class number 2
FIXED EDIT:
Incase anyone else has this issue, I fixed it by importing this above class two
  from Module1 import Class1,sample

And then inside class2
      var1,var2 = smaple.method1()

A: The code you posted is full of syntax errors as Francesco sayed in his comment. Perhaps you could paste the correct one.
You don't import from a class but from a package or a module. Plus you don't "call" a variable unless it's a callable.
In your case you could just have :
file1.py :
class class1:
    def __init__(self): # In your class's code, self is the current instance (= this for othe languages, it's always the first parameter.)
        self.var = 0

    def method1(self):
        print(self.var)

sample = class1()

file2.py :
from file1 import class1, sample

class class2(class1):
    def method2(self):
        self.var += 1
        print(self.var)

v = class2()          # create an instance of class2 that inherits from class1
v.method1()           # calls method inherited from class1 that prints the var instance variable
sample.method1()      # same
print(v.var)          # You can also access it from outside the class definition.
v.var += 2            # You also can modify it.
print(v.var)
v.method2()           # Increment the variable, then print it.
v.method2()           # same.
sample.method1()      # Print var from sample.
#sample.method2()  <--- not possible because sample is an instance of class1 and not of class2

Note that to have method1() in class2, class2 must inherit from class1. But you can still import variables from other packages/modules.
Note also that var is unique for each instance of the class.


text:
Q: How to assign shortcut to play button when using Rider with Unity? Using Rider, I can debug my unity project but sometimes, I just want to run the project without debugging it. Is there any way to bind a shortcut to the play button (Play/Edit).
How could I do that with last version of Rider?

A: As you already know this is done using this button

And yes, you can assign a shortcut for that button!

*

*Open the File → Settings (CTRL + ALT + S)

*Go to Keymap → Plugins

*Scroll down to Unity Support and find the Play/Edit button

*Right click and select Add Keyboard Shortcut

*Add whatever appealing yet unused shortcut is availble (good luck finding one :P)

*Hit Ok and Save → Happy ;)


text:
Q: How can I have a restricted ssh user without totally limiting ssh access? I am working on making a new user with SSH access to my server for file sharing purposes via WinSCP. My goal was to restrict them to their home directory by having their default shell be rbash, but when I do this it won't let me connect to the server and it will stop at the "Connecting to Host..." message. I can connect with this user when the shell is set to the default shell. Is there a permission that I need to modify to get around this?
There is an entry in /etc/shells for rbash.
edit

A: Shell access typically requires shared system binaries and libraries. Limiting a user to only their home directory is unlikely to be usable (i.e. the user in question won't be able to do much).
If you  want the user to run a certain program, you could set their login shell to that program. Git does this with git-shell for example.
In general on a multi-user system, it is a good idea to make home directories not world readable (such as by setting an appropriate umask, or adjusting home directory permissions).

A: You can create /sshchroot/user/user. /sshchroot/user would be owned by root and writable by root only (as ChrootDirectory demands) and you would bind-mount /home/user to /sshchroot/user/user. This way the user does not even see the other home directories.
mount --bind /home/user /sshchroot/user/user # can be done in /etc/fstab

A: I was able to restrict the user by adjusting my .sshd_config as shown here. This step prevents them from going back into the system files. In addition, I changed the permissions of the other /home/user/ folders with chmod -R 700 /home/user/, which stops them from going into other home directories, while still having full descent access within their own.


text:
Q: how key exchanging happen in RSA for decrypting I want to implement the RSA encrypt/decrypt method in cipher in java in a code that does some treatment or changing to any data it receives and then sends it again, so I want this code to be able to:
- when it receives data, encrypt that data with RSA, I think this is easy, I saw many examples it generates a KeyPair and gets the public key then use the cipher to encrypt.
- when it receives data encrypted by RSA as i mentioned in decryption this is where I have a problem.. in all the examples I saw, it uses the private key generated in the encryption part to decrypt in cipher, but how can I do that if the two parties are separate?! how can the party how decrypt know the private key generated from the part how encrypt the data!
here is some code example I saw:
https://www.quickprogrammingtips.com/java/java-asymmetric-encryption-decryption-example-with-rsa.html

A:
how can I do that if the two parties are separate?! how can the party how decrypt know the private key generated from the part how encrypt the data

The sender needs to know the public key of the recepient upfront. The recepient needs to generate its keypair and provide the public key to the sender to encrypt data. The sender must as well make sure the public key is really from the intended recepient (that's why we use certificates)
If you see generating a keypair by an encrypting party, this is done only as an example to have a public key.


text:
Q: How to apply two different CSS style to the same div on the same page? My question is that how can I apply two different CSS style to the same div on the same page? I have a page which loads (an iframe which loads) two different images in it and both the images have a div element with the same id, I want to div to have different style from when the div loads once and different when it loads another time.
So how can achieve such a feat?
This is the div's HTML:

    More Information

This is the div's CSS:
#sa_moreinfo {
margin: 0px 0px 0px 840px;
float: left;
position: relative;
width: 135px;
}

Regards.

A: According to my comment above, Here is the detailed information.
Look at the following HTML.

     More Information

     More Information

Now using parent element you can apply #sa_moreinfo different styles like below.
 .test1 #sa_moreinfo {
   margin: 0px 0px 0px 840px;
   float: left;
   position: relative;
   width: 135px;
}
.test2 #sa_moreinfo {
   margin: 0px 500px 0px0px;
   float: right;
   position: absolute;
   width: 300px;
}

So that based on the parent element test1 and test2 it will apply different styles for the same id. But duplicating the ID is not a good practice.

A: OK, firstly do not use same IDs multiple times on one page and secondly try to style everything using classes. I would recommend you to add some extra class that would extend the other class on the second div, if you cannot do that use :nth-child selector. Btw avoiding iframes is not bad idea either.


text:
Q: Postgres calculated columns from joins I have the following table:
id | underlying | option_symbol | option_type | expiration_date | strike | mid |

I need to perform calculations on joined fields and use those calculated fields for further sorting.
Here is a try to what I mean:
SELECT  a.underlying,
a.expiration_date,
(a.strike - b.strike) as spread_profit,
(a.mid - b.mid) as spread_distance,
(spread_distance - spread_profit) as spread_max_loss,
(spread_profit / spread_max_loss) as spread_profit_ratio
FROM option_data a
JOIN option_data b ON a.underlying = b.underlying AND a.expiration_date = b.expiration_date
WHERE a.option_type = 'put'
AND b.option_type = 'call'
AND a.expiration_date <= '2017-10-31'
group by a.underlying, a.expiration_date order by spread_profit_ratio desc

What should be the right way to formulate this query?

A: You have to substitute the whole expressions, like
SELECT ...,
   (a.strike - b.strike) AS spread_profit,
   (a.mid - b.mid) AS spread_distance,
   (a.mid - b.mid - a.strike + b.strike) AS spread_max_loss,
   ((a.strike - b.strike) / (a.mid - b.mid - a.strike + b.strike))
      AS spread_profit_ratio
...

The same holds for the ORDER BY clause, but you can use the shortcut ORDER BY 6 to sort by the sixth SELECT list item.
If that is too cumbersome, you can use subselects:
SELECT underlying,
       expiration_date,
       spread_profit,
       spread_distance,
       spread_max_loss,
       spread_profit / spread_max_loss AS spread_profit_ratio
FROM (SELECT underlying,
             expiration_date,
             spread_profit,
             spread_distance,
             (spread_distance - spread_profit) AS spread_max_loss
      FROM (SELECT a.underlying,
                   a.expiration_date,
                   (a.strike - b.strike) as spread_profit,
                   (a.mid - b.mid) as spread_distance
            FROM ...
           ) sub_1
     ) sub_2
WHERE ...
ORDER BY spread_profit_ratio DESC;

It's your choice!


text:
Q: Ionic 1 App - Changing Tab Color I'm responsible for our university's freshman-week-app, which is build with Ionic 1. It has 5 Ttab-items, and I want to change the color of these tabs. I have used the custom.css file for that:
.tab-item.tab-item-active, .tab-item.active, .tab-item.activated, .tabs-md-tab-text-color-active, .tabs-md-tab-icon-color-active {
color: cyan;
background: #e72167; }

Now my Problem:
The Color changes...
[1] ...Work on iOS: https://i.stack.imgur.com/mXRvA.png
but
[2] ...don't work on Android: https://i.stack.imgur.com/4OuXr.png
I've googled for hours and tried several CSS attributes, but nothing works. Can anyone tell me a tab-color attibute that also works on Android, or a different solution? Thanks!

A: Please make sure you are not updating the css file of iOS folder only. To reflect changes on both platform you must change css of root folder and files. Changing on root level files automatically reflects for platform else only specific plaform will be updated respectively. When you type ionic serve command, this pushes the changes to the platform level. If root level don't have changes that you want that will update remaining platform. I hope that helps you

A: add style to .tab-item-active class like this
.tab-item-active{
  background:green;
}

see this codepen:http://codepen.io/edisonpappi/pen/aWvmjz


text:
Q: How can I send email reports to myself from my home server? One would think this is a dead simple thing, but apparently it isn't—or I just really suck at it.
Context: I have a little home server hosting things like task-managers (TaskWarrior), my website, my IRC bouncer, etc. I try to keep this server as secure as possible. Also, I would like to keep it well-maintained.
I thought it would be nice to receive some periodic/event-triggered emails from this server to detect possible security breaches, failed services and other problems. The actual implementation is irrelevant, I'd either just send myself the outputs of periodic maintenance scripts or perhaps grep some keywords out of logfiles.
The problem is that I am stuck at simply sending an email to my address. What I tried:

*

*I need an SMTP server to send the email, so I should just use my email service provider's, I guess (mailbox.org). This is how it turned out:

$ openssl s_client -connect smtp.mailbox.org:465
[...]
---
220 smtp2.mailbox.org ESMTP Postfix
HELO myhostname
250 smtp2.mailbox.org
MAIL FROM: me@myhostname
250 2.1.0 Ok
RCPT TO: me@mailbox.org
554 5.7.1 <my-ip:30920>: Client host rejected: Access denied

I am not sure if this has to do with having to authenticate on the server. I tried with smtp.gmail.com as well, but I got an 530-5.5.1 Authentication Required reply to my MAIL FROM there. However, I would rather like to avoid Google anyway.

*Supposing the failure is due to having to authenticate, I face another problem: sure, I could just tell my MTA (let's say dma or msmtp) my password for my mailbox.org account, it doesn't sound like a good idea. I am not experienced enough in setting up security to be certain my server won't be hacked easily. I know that once root access is gained I am done for, but I could still mitigate the damage by I don't know, not having my plaintext passwords scattered around the server? Normally, I keep them GPG-encrypted using password-store.

*Perhaps I should run my own SMTP server? I can't use my domain for that though, since I have set up mailbox.org with emails of my own domains, so my MX DNS records point to their servers. I don't really want to buy another domain just for this...

Summary & TL;DR
Is there some way to simply send emails to my own address provided by mailbox.org from my server without

*

*running and maintaining a complex SMTP server on my server

*having to expose sensitive information such as my passphrase on the server to log into the provider's SMTP server?

A: If you only want to send email to your mailbox.org account; you can set up your mail client to send mail directly into mailbox.org's MX servers. This will only allow you to send email to @mailbox.org accounts, not to the rest of the internet. This is because SMTP servers with the "MX" role, will not allow mail other than for their own destination (or at least, they shouldn't :) ).
Use mx1.mailbox.org as the SMTP server, on port 25, unauthenticated.
For example:
mtak@dc4:~$ telnet mx1.mailbox.org 25
Trying 2001:67c:2050:104:0:1:25:1...
Connected to mx1.mailbox.org.
Escape character is '^]'.
220 mx1.mailbox.org ESMTP Postfix
HELO dc4.mtak.nl
250 mx1.mailbox.org
MAIL FROM: test@mtak.nl
250 2.1.0 Ok
RCPT TO: postmaster@mailbox.org
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
Subject: Test email
This is a test email
.
250 2.0.0 Ok: queued as EBEE94F466
quit
221 2.0.0 Bye
Connection closed by foreign host.

A: Answering the part about sending emails with gmail not working since i have encountered the same problem:
To send emails using google's smtp you have to enable a setting called less secure apps otherwise it won't work, found in: google account, security, less secure apps.
After that you can use your favorite mail command, (mail, sendmail, sendemail, ssmtp ..), just remember to turn on tls option for that command.
Security wise, create an address specifically for that purpose and you are good.
If that is not good enough, you can enable two factor auth for your single purpose gmail account then generate an app password (also in account, security) and store that on your server and use it in place of the password (you can't use your password to send emails with 2FA enabled, you have to use an app password).
Example with sendemail command:
cat body.txt | sendemail -f "youremail@gmail.com" -u "subject" -t "receiver@domain.com" -s "smtp.gmail.com:587" -o tls=yes -xu "youremail@gmail.com" -xp "Account Password or App password if 2FA is enabled"


text:
Q: VMware virtual HD performance with Truecrypt on the host - Use 2 GB chunks? Configuration:
I am using VMware on a laptop computer, which is truecrypted as a theft precaution.
The VHDs are ceated as single growable files (i.e. not split in 2 GB chunks, no preallocation of whole VHD space.)
Host: Windows7 64bit.
Guests: Windows7 32bit and WindowsXP 32bit.
VMware version: VMware player 4.0.x.
Problem:
When using the VMs extensively, I often experience painful minutes of 100% I/O activity on the host HD. This of course slows everything down.
According to "Perfmon /res", the culpable host processes are system and "vmware-vmx.exe", ("system" consuming the lion share). There is big read AND write traffic, regardless of what I did in the VMs.
The problem seems to be worse with Windows7 guests that with WindowsXP clients.
Excluded causes:
Perfmon confirms that there is enough real RAM.
The antivirus on the host is configured to skip all file types which occur in the VM folders.
Q:
Are there any Truecrypt operations affecting the whole VHD file on the host, when I made a write-access to a small portion of the VHD from within the VM?
Would it therefore help to split the VHD files into 2 GB chunks?
Or is this a stupid thought because the Truecrypt ciphertext block size is just 16 bytes?
Any other idea out there?

A: You can safely presume that TrueCrypt has linear performance footprint because full disk encryption is implemented as a block-level driver.
VMware, on the other hand, is slow with dynamic volumes. I have seen similar effects with and without TC. So a possible solution would be to use fixed VHDs.


text:
Q: Delimiter Warning in shell Script with psql I get a Delimter Error in a Shell Script:
#!/bin/sh

result=`psql -d databasename -t -A <<EOF
SELECT COUNT(*) FROM schema.table
WHERE "column_name_x" = 'specific_value_x'
AND "column_name_y" = 'specific_value_y'
AND ("column_name_z" LIKE 'specific_z%' OR "column_name_za" LIKE 'specific_za%')
;`
EOF

echo $result
#EOF

The result of the Script is fine. But I get two warnings:
./filename.sh: line 13: warning: here-document at line 8 delimited by end-of-file (wanted `EOF')
./filename.sh: line 9: EOF: command not found

What is the problems here? Thank you!

A: You have the start of your here-doc inside of your command, but the EOF is outside of your command.
result=`psql -d databasename -t -A <<EOF
SELECT COUNT(*) FROM schema.table
WHERE "column_name_x" = 'specific_value_x'
AND "column_name_y" = 'specific_value_y'
AND ("column_name_z" LIKE 'specific_z%' OR "column_name_za" LIKE 'specific_za%')
EOF
`

The ; seems wrong here too (at least it threw an error for me).


text:
Q: Is there an R package for interpolated polar contour plots This R interpolated polar contour plot question is an excellent source for interpolated polar contour plots in R. Unfortunately, as explained in the this question, the PolarImageInterpolate function in earlier post has some bugs in it. My question is, is there a modified version of the function or a package or any other (ggpot?) way to do interpolated polar contour plots in R?
Here is a sample plot I made using the PolarImageInterpolate function. There are unusual values at the centre. It seems something is not right with the interpolation? Since akima interpolation does not allow NA`s in data, I removed them using  complete.cases. Is there a better option to manage NA's in interpolation?
inp <- read_csv("test.csv")
inp <- inp[complete.cases(inp),]

y = inp$Height * cos(inp$Theta)
x = inp$Height * sin(inp$Theta)
z = inp$Value

PolarImageInterpolate(x, y, z, points = F)

Data is here
Any help would be appreciated.


text:
Q: ERROR 1 (HY000): Can't create/write to file (Error code :13) Iam trying to create a mysql table in linux with changing data directory to another location. The selected forlder having full permission. But I got an error 'Can't create/write to file'. I googled and found that this error related to permission denied. I can change the owner permission of the folder to root using chown command. But it still showing the same error.
mysql> create table table123(Id int PRIMARY KEY, Name VARCHAR(20)) DATA DIRECTORY = '/home/test/Sample';

ERROR 1 (HY000): Can't create/write to file '/home/test/Sample/table123.MYD' (Errcode: 13)

When change the data directory location to /var/tmp/Sample, then the table become created.
Why the table not created in the location '/home/test/Sample' ???
Using ubuntu 10.04.
Permission of actual data directory is 700, owner : mysql, group : mysql

A: You should change owner of new location to mysql user (chown mysql.mysql /data/directory). In simple copy owner ond permision from actual data directory.
EDIT:
Set up permision on new data directory using chmod 755 /data/directory


text:
Q: Matrix of linear transformation w.r.t basis terminology What does it mean to find the matrix of a linear transformation with respect to a basis in the domain, and another in the codomain? In our notes we usually use the standard basis in the domain and a non-standard basis in the codomain. I assume the solution differs in we use a non-standard basis in the domain, but I'm not really sure how.
I'm probably not being very clear so I'll include an example.
Consider the basis $\beta = \{1,t,t^2\}$ for $P_2(\mathbb{R})$. Let $D: P_2(\mathbb{R}) \rightarrow P_2(\mathbb{R})$ be defined by differentation, $D(p)(t) = p'(t)$. Find the matrix $B_D$ of $D$ with respect to $\beta$ in the domain and $C = \{1+t, t-t^2, t^2\}$ in the codomain.
I know how to answer this question, but not really what it means. How would it differ if $\beta$ wasn't the standard basis? How do you do it with respect to two different bases?
Some clarification would be much appreciated, thanks!

A: An important point of abstract linear algebra is that "bases are arbitrary"; a "standard basis" is just for convenience and has no mathematical significance.  The way you answer this question doesn't change at all no matter what bases (standard or not) that you choose for the domain or codomain:

*

*Find the image, under $D$, of each element of the given basis for the domain.

*Write these images in terms of the given basis for the codomain.  This gives you a set of coordinates (real numbers, in your example) for each element in the image.

*Collect these coordinates into a matrix.


text:
Q: count number of missing values in netcdf file - R Is there a quick way to know how many missing values are in a netcdf file? Possibly using R.
Currently I have to
hum<-nc_open("rhum.sig995.2008.nc")
rhum<-ncvar_get(hum, "rhum")

then manually look up the missing value by typing 'hum' and copy it into this operation
sum(abs(rhum - 9.96920996838687e+36) < -9.96920996838687e+36)

Is there a more direct way, especially if I have to work with hundreds of files? I would like to avoid copying and pasting the missing value, and also I am not sure with what kind of precision the number should be handled.

A: My suggestion is to use the excellent raster package:
install.packages(raster)
library(raster)

r <- raster("rhum.sig995.2008.nc", var="rhum")

NAnum <- summary(r)[6]

A: The total number of missing data points for variable names "var" can be stored in a new additional variable using
ncap2 -s "nmiss=number_miss(var)" in.nc out.nc

or
ncap2 -s "nmiss=var.number_miss()" in.nc out.nc

If your data has a time dimension and you want to see the total number of missing points summed over the space dimensions, then you can see this with
cdo info in.nc


text:
Q: How to create Dynamic Charts with web api in angular 8 I am using canvas to create bar charts. I created a static chart but I need a dynamic chart. I need to fetch the data from the backend using web API.

A: this is for line chart and pie chart
<canvas baseChart [datasets]="lineChartData"
    [labels]="lineChartLabels" [options]="lineChartOptions"
    [colors]="lineChartColors" [legend]="lineChartLegend"
    [chartType]="lineChartType" [plugins]="lineChartPlugins">
</canvas>

<canvas baseChart [data]="pieChartData" [labels]="pieChartLabels"
        [chartType]="pieChartType" [options]="pieChartOptions"
        [plugins]="pieChartPlugins" [legend]="pieChartLegend"
        (chartClick)="chartClicked($event)">
</canvas>

.ts file
 ///line chart
    public lineChartData: ChartDataSets[] = []
    public lineChartLabels: Label[];
    public lineChartOptions: ( ChartOptions ) = { responsive: true, };
    public lineChartColors: Color[] = [
        {
            borderColor: 'black',
            backgroundColor: 'rgba(255,0,0,0.3)',
        },
    ];
    public lineChartLegend = true;
    public lineChartType = 'line';
    public lineChartPlugins = [];
    ///pie chart
    public pieChartOptions: ChartOptions = {
        responsive: true,
    };
    public pieChartLabels: Label[]// = [['Download Sales'], ['In Store Sales'], 'Mail Sales'];
    public pieChartData: SingleDataSet// = [300, 500, 100];
    public pieChartType: ChartType = 'pie';
    public pieChartLegend = false;
    public pieChartPlugins = [];
    chartJson = {}

in ngoninit you can call
 this.http.get( 'getGraphJSON' ).subscribe(( data ) => {
        this.chartflag = true
        this.lineChartData.push( data["linechartData"] );
        this.lineChartLabels = data["lineChartLabels"];
        this.pieChartLabels = data["pieChartLabels"];
        this.pieChartData = data["pieChartData"];

    } )

JSON:
{"pieChartLabels":["Nursing ","333999-Machinery Manufacturing","-Nursing Facilities","Social ","Electronic Product ","srvices","Social ","Professional, Scientific, and Technical Services","Repair and Maintenance","Transportation Equipment Manufacturing","Professional, Scientific, and Technical Services","Computer and Electronic Product Manufacturing","Crop Production","Publishing Industries (except Internet)","Machinery Manufacturing","Construction of Buildings"],"pieChartData":[83,57,42,41,37,33,33,33,12,12,9,9,4,3,3,3],"lineChartLabels":["Jun","Oct","Nov","Dec"],"linechartData":{"data":[1,2,5,423],"label":"Opportunity"}}


text:
Q: Spring batch job testing with jUnit always throwing me NullPointerException I'm trying to test a job in spring batch with jUnit and I don't know how to solve that error.
I have this class
ParametersValidatorService
@Service("parametersValidator")
public class ParametersValidatorService implements IParameterValidatorService {

/**
 * The Constant LOGGER.
 */
private static final Logger LOGGER = LoggerFactory.getLogger(ParametersValidatorService.class);

/**
 * Array con los parametros obligatorios.
 */
private static final String[] PARAMETROS_OBLIGATORIOS = new String[]{
        "val1", "val2", "val3", "val4", "val5", "val6", "val7"
};

/**
 * Array con los parametros que deben ser numericos.
 */
private static final String[] PARAMETROS_NUMERICOS = new String[]{
        "val1", "val2", "val3", "val4"};

/**
 * @param jobId:      the job id
 * @param parameters: input job parameters
 * ParametersValidatorException: manages exceptions related with input parameters.
 */
@Override
public void validate(final String jobId, final JobParameters parameters) throws ParametersValidatorException {
    try {
        validate(parameters);
    } catch (JobParametersInvalidException e) {
        throw new ParametersValidatorException(e);
    }
}

/**
 * @param parameters: input job parameters
 * JobParametersInvalidException: manages exceptions related with input parameters.
 */
@Override
public void validate(final JobParameters parameters) throws JobParametersInvalidException {
    validarParametros(parameters);
}

/**
 * Comprueba que los parámetros no estén vacíos y que los que tienen que ser numéricos, sean numéricos
 *
 * @param parameters: input job parameters
 * JobParametersInvalidException: manages exceptions related with input parameters.
 */
private void validarParametros(final JobParameters parameters) throws JobParametersInvalidException {

    List<String> numericParameters = Arrays.asList(PARAMETROS_NUMERICOS);
    String error = null;
    for (String validacion : PARAMETROS_OBLIGATORIOS) {

        if (StringUtils.isBlank(parameters.getString(validacion))) {
            error = "El parametro " + validacion + " es obligatorio";
        } else if (numericParameters.contains(validacion) && !StringUtils.isNumeric(parameters.getString(validacion))) {
            error = "El parametro " + validacion + " debe ser numerico";
        }
        if (error != null) {
            LOGGER.error(error);
            throw new JobParametersInvalidException(error);
        }
    }
}

}

I'm trying to test that with jUnit4 but I'm not able to execute it correctly. I've made this test
ParametersValidatorServiceTest
@RunWith(SpringJUnit4ClassRunner.class)
public class ParametersValidatorServiceTest {

//@Autowired
@Bean
public JobLauncherTestUtils jobLauncherTestUtils() {
    return new JobLauncherTestUtils();
}

@Test
public void testLaunchJobOK() throws Exception {

    JobParameters jobParameters = new JobParametersBuilder().addString("val1", "1")
                                                            .addString("val2", "Nombre de prueba")
                                                            .addString("val3", "61").addString("val6", "1")
                                                            .addString("val4", "RCVD").addString("val7", "43")
                                                            .addString("val5", "2017-05-10 10:48:42").toJobParameter

    JobExecution jobExecution = jobLauncherTestUtils().launchJob(jobParameters);
    Assert.assertEquals(ExitStatus.COMPLETED.getExitCode(), jobExecution.getExitStatus().getExitCode());

}

}

I'm always receiving a java.lang.NullPointerException as seen below
java.lang.NullPointerException
at org.springframework.batch.test.JobLauncherTestUtils.launchJob(JobLauncherTestUtils.java:152)
at com.bbva.kyob.respuestasob.services.impl.ParametersValidatorServiceTest.testLaunchJobOK(ParametersValidatorServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

When I do a debug of the test, I see that the parameters I'm entering are being collected and stored in the jobParameters so I don't know what's happening

A: If you think about it, there is no reference to any job in the ParametersValidatorServiceTest class right? So when you execute this statement:
JobExecution jobExecution = jobLauncherTestUtils().launchJob(jobParameters);

Which job should be launched? The job is actually a dependency of JobLauncherTestUtils. That's why it should be defined in your test context to be correctly autowired in JobLauncherTestUtils. For example, you can import a configuration class that contains its definition:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyJobConfiguration.class}) // contains the job bean under test
public class ParametersValidatorServiceTest {
   // ...
}

Hope this helps.


text:
Q: NIFI:cron scheuling pattern I want to run  my nifi processor  daily at 00:00 i use  expression like  this :0 0 * * *?  but it  throws  exception like this:

also  here is  several  subject i am interested in:

*

*can i  use cron on  groups   i have added

*2.can  i use any parameter (for  example i=2) whcih will  help me start and  stop processors in  evry 2  hours  after other processors
have  started( i want to use  any parameter
(in my case i ) which will start processor  after
several  hours other  processors  have started it's  work)

A: First of all the expression you have provided would not run daily at 00:00, it would run every hour. The third value in the expression is the hour value, and having it as the special character '*' means it runs every hour, replace this with '0' would change it to run at midnight.
So the new correct expression would be: 0 0 0 1/1 * ?
From what I can see from the expression you are providing it may be throwing the exception due to the spacing of the last value of the cron expression. The expression you provided, : "0 0 * * *?", does not have a space before the last question mark. This may cause an issue since the standard expected format is for all values to be separated by a space. Using the cron expression listed above should give you a valid trigger


text:
Q: Redux dispatch won't change my initialState Seems like dispatch is not working as it is supposed to be.
Here is my code.
Wrapper.js
...
const Wrapper = ({ action, variable }) => {
  useEffect(() => {
    action();
  }, []);

  return(
    <Text>{variable.toString()}</Text>
  );
};
...

Actions.js
export const action = () => dispatch => {
  dispatch({
    type: MY_TYPE,
    payload: true,
  });
};

Reducer.js
...
const initialState = {
  variable: false,
};

export default function(state = initialState, action) {
  switch(actions.types) {
    case MY_TYPE:
      return {
        ...state,
        variable: action.payload,
      };
    default:
      return state;
  }
}
...

When i do console.warn('test') inside my action function, i get the yellow message "test" so i assume that everything is fine with my code. But given the code above, in my <Text> i always get false

A: You have typo in your reducer. There is actions.types.
Should be action.type.
Also, I see you use function instead of object for an action. Make sure you have redux-thunk middleware applied and there is no problem with your connect hoc in Wrapper.js


text:
Q: "Fix" Angular UTC Dates I am building an Angular 2.x app that consumes a REST API for its data.  The API delivers some date information in JSON form:
  "punchDate": "2017-05-17T00:00:00",
  "timezone": "CST"

If I ask Angular to print punchDate to screen (in my timezone which is CST) it will show: May 16, 2017, 7:00:00 PM.
When that date gets assigned to a date picker it says the same, "May 16, 2017" when what the API really intended for me to do was have the date picker say "May 17, 2017".
The JSON response comes out of the API, into an Angular Service which converts it to a TypeScript interface, and that service get used throughout the app.
Class:
export interface Punch{
    punchDate: Date;
    timezone: string;
}

Service Method:
public get = (id: number): Observable<Punch> => {
    return this.http.get('/api/punch/' + id).map(res => res.json());
}

How do I get Angular to treat this date how the API intended?
Plunkr to demonstrate problem:
https://plnkr.co/edit/hYYRbyWLFBvzh4uGBJay

A: This might be something particular to your browser. they both say 17th when I run your code.


text:
Q: Separate Polymorphic Association table After reading the Ruby on Rails guides and a few of the stackoverflow responses to questions about polymorphic association I understand its use and implementation but I have a question about a specific use scenario. I have tags that can be associated with multiple topics, categories, images and other various models (which also have varying tags) but instead of placing the reference fields (foreign_id, foreign_type) within the tags table, I'd prefer to create a separate association table. Is this still possible using :polymorphic => true?
Something like this:
create_table :tags do |t|
  t.string :name
  t.remove_timestamps
end

create_table :object_tags, :id => false do |t|
  t.integer :tag_id
  t.references :tagable, :polymorphic => true
  t.remove_timestamps
end

If this isn't possible, I was planning on creating the same :object_tags table and using :conditions within the Tag model and other models to force the associations. Is there a rails way of doing this? Thanks! (working with rails 3.0.9 & ruby 1.8.7 <- because deployment server is still using 1.8.7)
UPDATE:
Thanks Delba! Answer is a working solution for HABTM polymorphism.
class Tag < ActiveRecord::Base
  has_many :labels
end

class Label < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
  belongs_to :tag
end

class Topic < ActiveRecord::Base
  has_many :labels, :as => :taggable
  has_many :tags, :through => :labels
end

create_table :tags, :timestamps => false do |t|
  t.string :name
end

create_table :labels, :timestamps => false, :id => false do |t|
  t.integer :tag_id
  t.references :taggable, :polymorphic => true
end

UPDATE: Because I need bi-directional HABTM, I ended up going back to creating individual tables.

A: Yes, and from your description you couldn't have the tagable columns on your tag anyhow since they can have multiple tagable things and vice versa .  You mentioned HABT, but you can't do anything like has_and_belongs_to, :polymorphic => true as far as I know.
create_table :object_tags, :id => false do |t|
  t.integer :tag_id
  t.integer :tagable_id
  t.string  :tagable_type
end

Your other tables don't need any columns for object_tags, tags, or tagable.
class Tag < ActiveRecord::Base
  has_many :object_tags
end

class ObjectTag < ActiveRecord::Base
  belongs_to :tagable, :polymorphic => true
  belongs_to :tag
end

class Topic < ActiveRecord::Base
  has_many :object_tags, :as => :tagable
  has_many :tags, :through => :object_tags
end


text: Q: Supremum of upper semicontinuous (usc) functions The supremum of finitely many usc functions is usc. I'm wondering when/if the supremum of infinitely many bounded usc functions could be usc? Any hint, examples, or counterexamples?


text:
Q: Passing STATIC_URL to file javascript with django Which is the best solution to pass {{ STATIC_URL }} to javascript files?
I'm working with django and python.
Thanks in advance.
Regards.

A: I think this complements the commentary of  @Yuji 'Tomita' Tomita, as a full setup.
this worked for me.
This is how i did the full setup of django compressor for using STATIC_URL in django js file.
https://github.com/jezdez/django_compressor
pip install django_compressor

Add 'compressor' to your INSTALLED_APPS setting:
INSTALLED_APPS = (
    # other apps
    "compressor",
)

To test compression in Debug mode, in settings.py:
COMPRESS_ENABLED = True

In case you use Django's staticfiles contrib app (or its standalone counterpart django-staticfiles) you have to add Django Compressor's file finder to the STATICFILES_FINDERS setting, for example with django.contrib.staticfiles:
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

Enable the TemplateFilter in settings.py after installing to parse your js or css files via the template engine.
COMPRESS_JS_FILTERS = [
    'compressor.filters.template.TemplateFilter',
]

Now any JS within {% compress js %} blocks will be parsed by the django template language...
{% load compress %}

{% compress js %}
    <script src="/my_script.js" type="text/javascript"></script>
{% endcompress %}

// my_script.js

alert('{{ STATIC_URL|escapejs }}');

A: Using a global javascript variable with the static url value is more simple :
<script language="javascript">var STATIC_URL = "{{ STATIC_URL|escapejs }}";</script>
<script src="{{ STATIC_URL }}js/myfile.js"></script>

Then, you can simply use the static url by calling STATIC_URL in myfile.js :
html = '<img src="'+STATIC_URL+'/icons/flags/tn.gif">';

A: django-compressor lets you do this as well as optimize your site by condensing all of your required JS or CSS into one file and optimizing file size.
UPDATE: By default, compressor will convert relative urls into absolute urls using STATIC_URL. If you download the development version, it comes with a django template engine parser which lets you use all django template code directly in your CSS files, such as the {% static %} tag.
https://github.com/jezdez/django_compressor
Enable the TemplateFilter in settings.py after installing to parse your js or css files via the template engine.
COMPRESS_JS_FILTERS = [
    'compressor.filters.template.TemplateFilter',
]

Now any JS within {% compress js %} blocks will be parsed by the django template language...
{% compress js %}
    <script src="/my_script.js" type="text/javascript"></script>
{% endcompress %}

// my_script.js
alert('{{ STATIC_URL|escapejs }}');

You asked for the best way -- I think this is the best. Certainly better than serving dynamic files.


text:
Q: Sorting an array of objects on both ascending and descending order on same click I have an array of objects:
var arr = [{
  title: "finance",
  book: "book1"
},
{
  title: "nature",
  book: "book2"
},
{
  title: "programming",
  book: "book3"
}]

HTML:
TITLE

Right now I have implemented a basic sorting logic below
JAVASCRIPT(AngularJS controller):
self.sortTitle = function () {
    self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
}

This JavaScript function is currently sorting it in ascending order only based on title. How do I write a logic that sorts it on either order, i.e. click1 should sort it in ascending and click2 should reverse and set it in descending? Basically reversing the sort everytime it is clicked.

A: You can create a property on self like isAscending and default to true or false (whatever you want initially) based on which sort order will be executed and flip isAscending every time the sort fn runs.
self.isAscending = true;

self.sortTitle = function () {
 if(self.isAscending){
   self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
 }else{
   self.arr= self.arr.sort((a, b) => (a.title > b.title) ? -1 : 1);
 }
 self.isAscending = !self.isAscending;
}

A: It probably would make sense to have a reusable function you can call to do the sorting for you which also accepts a direction parameter:

var arr = [{ title: "finance", book: "book1" }, { title: "nature", book: "book2" }, { title: "programming", book: "book3" }]

let sortBy = (arr, p, o=1) => [...arr].sort((a,b) => a[p].localeCompare(b[p]) * o)

console.log(sortBy(arr, 'title'))
console.log(sortBy(arr, 'title', -1))
console.log(sortBy(arr, 'book'))
console.log(sortBy(arr, 'book', -1))

You can replace the last param to deal with asc/desc if you need to.
Also since you are comparing strings the recommended way is to use String.localeCompare simply due to the amount of options it supports which almost always come in handy (sorting book10 vs book1 for example)

A: You just need to maintain sort type somewhere so that you can toggle it.
There's lots of variants, but something simple like this should work:
const ascendingComparator = (a, b) => (a.title > b.title) ? 1 : -1;
const descendingComparator = (a, b) => (a.title > b.title) ? -1 : 1;

self.sortTitle = function (type) {
  if (type === "ascending") {
    self.arr = self.arr.sort(ascendingComparator);
    type = "descending";
  } else {
    self.arr = self.arr.sort(descendingComparator);
    type = "ascending";
  }
}

A: Add a variable to your function and change the conditional
self.sortTitle = function (sortOrder) {
    if (sortOrder === 'asc') {
        self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
    } else { //desc
        self.arr= self.arr.sort((a, b) => (a.title  sort(a,b, sortArrayAsc));
}

// ToDo: You can writte this nicer
self.sort = function (a, b, ascending) {
    if(ascending) {
        return a.title > b.title ? 1 : -1;
    } else {
        return a.title > b.title ? -1 : 1;
    }
}


text:
Q: Unix command to cut between strings my file:
Informatica(r) PMCMD, version [10.2.0 HotFix2], build [1911.0401],  Workflow run status: [Failed]

Output I need is Failed
Output I am getting is 10.2.0 HotFix2
Command used:
grep "Workflow run status:" test.txt | cut -d'[' -f2 | cut -d']' -f1

If Workflow run status: comes in any field, my objective is to search Workflow run status: and then print the status of the field. Because Workflow run status: can come in any line or field

A: cut -d'[' -f2 gets you the second [ delimited field. In
Informatica(r) PMCMD, version [10.2.0 HotFix2], build [1911.0401],  Workflow run status: [Failed]
<---------- field 1 ---------> <------ field 2 ------> <------------ field 3 -----------> <field 4>

You'd rather want the fourth field if its Failed you want. However, using sed to extract the part after Workflow run status would make more sense:
sed -n 's/^.*Workflow run status: \[\([^]]*\)\].*$/\1/p' < file

Or as the original tags on your questions suggest you're on a GNU system, get GNU grep to extract it with:
grep -Po 'Workflow run status: \[\K[^]]*' < file

Those would extract the part in Workflow run status: [there] without having to rely on how many [s there were on the line.

A: awk -F "[,:]" '{for(i=1;i<=NF;i++){if($i ~ /Workflow run status/){gsub(/[\[\]]/,"",$(i+1));print $(i+1)}}}' filename

 output

 Failed


text:
Q: Access to ARKit – iOS App Rejected Guideline 2.5.1 Our iOS app rejected with following reason.

Guideline 2.5.1 - Performance - Software Requirements
During review, we were prompted to provide consent to access the ARKit. However, we were not able to locate any features in your app that use the ARKit.
Next Steps
If your app does not include any features that use the ARKit, please remove access to the ARKit from your app.
If your app does include features that use the ARKit, please reply to this message in Resolution Center to provide information on how to locate them.

We aren't using any ARKit framework in our app. We also checked whether any dependencies are using ARKit. But, none of them add ARKit. So, I can't figure out how ARKit consent is coming up during review.
FYI, We are using front/back camera for taking profile picture of the user. Also, we set

*

*'NSCameraUsageDescription',

*'UIRequiredDeviceCapabilities' to 'armv7',

*'NSFaceIDUsageDescription',

*'NSLocationAlwaysAndWhenInUseUsageDescription',

*'NSMicrophoneUsageDescription'

etc in info.plist for permission text.
Any kind of help will be appreciated.
Thanks

A: ①. It seems you used ARKit template when created application. Try to use arm64 value instead of armv7, and delete arkit value if you have this one in info.plist.
Take into consideration these two values are compulsory when using ARKit.
<key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
        <string>arkit</string>
    </array>

②. Check if there are any guard statement in AppDelegate.swift file like this:
guard ARWorldTrackingConfiguration.isSupported else {
    fatalError("ARKit is not available on this device.")
}

③. If you're 100% sure your app doesn't have any ARKit features just contact AppStore team to discuss the issue.

P.S.
@MilanKamilya suggested you may potentially use any CocoaPod with dependency on ARKit. To find out whether you have such a dependency or not, use in Terminal the following command executed from macOS root directory (works in both bash and zsh):
grep -r ARKit ./


text:
Q: How can I specify a custom APK filename when publishing a MAUI app? When publishing a MAUI app for iOS, I can either use
<IpaPackageName>IPA.ipa</IpaPackageName>

in the project file or add -p:IpaPackageName=IPA.ipa to the dotnet publish command to change the filename of the distribution package. I didn't find much documentation but it's obvious once you change it in the project properties:

What is the equivalent setting for Android? I can't find a way in the UI to change the APK filename.

A: In visual studio
1.Go to project Properties by right clicking the android project; Switch to tab Android - Manifest; You will see the Application package name just as follows, then you can modify the name of it.
2.Go to Android Manifest.
You said that changes the application identifier as well. It seems to be the default setting. About it, you can refer to Configure the app module.
Some relevant cases about "change the package name", you can check Is it possible to change the package name of an Android app on Google Play? and Changing the package name of an upgraded Android application


text:
Q: CodeIgniter com Blade? Estou começando a estudar CI e como usei um pouco de Laravel para facilitar estava tentando colocar o Blade, segui este tutorial. Segui a risca o tutorial, mas retorna esses erros:

Como resolver esses problemas?

A: O problema é mudança de versão, o arquivo blade.php criado na pasta application\libraries deve conter o seguinte código, mediante configuração obtida no seu próprio github: XiaoLer/blade, diferente do que está no tutorial, pois é antiga e a versão foi alterada, exemplo das alterações:
<?php defined('BASEPATH') or exit('No direct script access allowed');
class Blade
{
    private $factory;
    public function __construct()
    {
        $path = [APPPATH . 'views/'];
        $cachePath = APPPATH . 'cache/views';
        $file = new \Xiaoler\Blade\Filesystem;
        $compiler = new \Xiaoler\Blade\Compilers\BladeCompiler($file, $cachePath);
        $compiler->directive('datetime', function($timestamp) {
            return preg_replace('/(\(\d+\))/',
                    '<?php echo date("Y-m-d H:i:s", $1); ?>', $timestamp);
        });
        $compiler->directive('now_datetime', function() {
            return '<?php echo date("Y-m-d H:i:s", '.(strtotime('now')).'); ?>';
        });
        $resolver = new \Xiaoler\Blade\Engines\EngineResolver;
        $resolver->register('blade', function () use ($compiler) {
            return new \Xiaoler\Blade\Engines\CompilerEngine($compiler);
        });
        $this->factory = new \Xiaoler\Blade\Factory($resolver,
                            new \Xiaoler\Blade\FileViewFinder($file, $path));
        $this->factory->addExtension('tpl', 'blade');
    }
    public function view($path, $vars = [])
    {
        echo $this->factory->make($path, $vars);
    }
    public function exists($path)
    {
        return $this->factory->exists($path);
    }
    public function share($key, $value)
    {
        return $this->factory->share($key, $value);
    }
    public function render($path, $vars = [])
    {
        return $this->factory->make($path, $vars)->render();
    }

}
e nas views criadas deve seguir a nomenclatura blade.php exemplo:

*

*index.blade.php

*home.blade.php
para funcionar.
Para chamar o comando no seu controller:
class Welcome extends CI_Controller
{
    public function test()
    {
        $data['message'] = 'message 1';
        $this->blade->view('test_message', $data);
    }
}

a view seguindo a nomenclatura de nome ficando assim: test_message.blade.php
Outro ponto a observar é a criação da pasta de cache application\cache\views, como exemplo da figura logo abaixo:

Observação: só o arquivo blade.php deve ser modificado, o resto continua igual do tutorial.
Referencias:

*

*github: XiaoLer/blade

*Laravel - Blade Templates


text:
Q: Is there no way to use GCP TCP load balancing and IPv6 for a http/https website? I have a website all set up and ready to go in a Docker environment behind an NGINX proxy. I've configured SSL to the website works with http and https, and the website is working over IPv4.
Now I need to add IPv6 support. It seems I can't attach an IPv6 address directly to my VM, I have to create a load balancer. I don't want to use the HTTP(S) load balancer, because that would involve re-doing my whole setup, configuring new certificates for the LB, routines for renewing them etc.
So I've tried creating TCP load balancing, and it was fairly straight-forward for IPv4. However, when I try to create an IPv6 TCP load balancer, I'm forced to create a multi-region/global load balancer. When configuring a global load balancer, I have to select TCP port from a dropdown, and port 80 is not one of the options.
Is it impossible to set up a website working with HTTP, HTTPS, IPv4 and IPv6 using TCP load balancing in GCP? Do I really have to configure a HTTP(S) load balancer?

A: Only global GCP load balancers offer IPv6 termination at this moment.
HTTP(S), SSL proxy and TCPproxy load balancers accept IPv6 connections from clients and then proxy those connections to the backend instances using IPv4.
You will find details here.
SSL Proxy load balancer supports ports 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, and 5222.
TCP Proxy load balancer supports the following ports: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222.
Load balancing on port 80 is only provided by the HTTP(S) load balancer.
So in your case, if you want to use port 80 for IPv6 termination, the only option in GCP is to use the HTTP load balancer.

A: Support for HTTP and HTTPS with IPv6 requires the HTTP/S Load Balancer today.