text:
Q: Scala case option with empty list Let's set:
val l = List(("AA",473.3), ("BB",676.48), ("AA",685.45), ("GG",812.73))

I want to get the sum of all values that have "AA" in the tuple. It works quite well with this:
var totAA = l.collect{ case ("AA",v) => v }.sum

But if l is an empty list, I get this error:
cmd78.sc:1: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: Nothing
var totAA = l.collect{ case ("AA",v) => v }.sum
                            ^cmd78.sc:1: ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[B]
var totAA = l.collect{ case ("AA",v) => v }.sum

So I tried this:
var totAA = l.collect{ case List() => 0.0; case ("AA",v) => v }.sum

But I get the same error, a bit less verbose:
cmd78.sc:1: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: Nothing
var totAA = l.collect{ case List() => 0.0; case ("AA",v) => v }.sum
                                                ^

A: Your code works perfectly fine for both empty and non-empty lists.
Here the non-empty one:
val l = List(("AA",473.3), ("BB",676.48), ("AA",685.45), ("GG",812.73))
var totAA = l.collect{ case ("AA",v) => v }.sum
println(totAA) // output: 1158.75

Same for empty one:
val l = List.empty[(String, Double)]
var totAA = l.collect{ case ("AA",v) => v }.sum
println(totAA) // output: 0.0

Are you sure that you created an empty List[(String, Double)], and not an empty List[Nothing]? Nothing cannot be pattern-matched against ("AA", v), because it's obviously not a tuple. Nothing by definition cannot be pattern-matched against anything at all, because there are no values of type Nothing.


text:
Q: const& , & and && specifiers for member functions in C++ Recently I was reading through the API of boost::optional and came across the lines:
T const& operator *() const& ;
T&       operator *() & ;
T&&      operator *() && ;

I also wrote my own program  that defines member functions as const&, & and && (Note that I am not speaking about the return type, but the specifiers just before the semi-colons) and they seems to work fine.
I know what it means to declare a member function const, but can anyone explain what it means to declare it  const&, & and &&.

A: const& means that this overload will be used only for const, non-const and lvalue objects, such as:
const A a = A();
*a;

& means that this overload will be used only for non-const objects:
A a;
*a;

&& means that this overload will be used only for rvalue objects:
*A();

For more information about this feature of the C++11 standard you can read this post: What is "rvalue reference for *this"?

A: It is a member function ref-qualifiers; it is one of the features added in C++11. It is possible to overload non-static member functions based on whether the implicit this object parameter is an lvalue or an rvalue by specifying a function ref-qualifier (some details).
To specify a ref-qualifier for a non-static member function, you can either qualify the function with & or &&.
#include <iostream>
struct myStruct {
    void func() & { std::cout << "lvalue\n"; }
    void func() &&{ std::cout << "rvalue\n"; }
};

int main(){
    myStruct s;
    s.func();            // prints "lvalue"
    std::move(s).func(); // prints "rvalue"
    myStruct().func();   // prints "rvalue"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add empty entry to combobox bound to entity list I use a ComboBox which is bound to a List<> of Entities. How can I add a "Not selected" entry to the combobox? Adding null to the list results in empty combobox.

A: If you're binding to IEnumerable list of entities you can certainly add your empty object manually.
For example
var qry = from c in Entities
          select c;
var lst = qry.ToList();

var entity = new Entity();
entity.EntityId= -1;
entity.EntityDesc = "(All)";
lst.Insert(0, entity);

MyComboBox.DataSource = lst;
MyComboBox.DisplayMember = "EntityDesc"
MyComboBox.ValueMember = "EntityId"

A: You should use an empty string or other unique text pattern instead of null.
And then You can handle the Format event of the Combobox to intercept the <empty> and display an alternate text.
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
   e.Value = FormatForCombobox(e.ListItem);
}

private string FormatForCombobox(object value)
{
  string v = (string) value;
  if (v == string.Empty)
     v = "<no Selection>";
  return v;
}


text:
Q: Refuse to send email to specific recipients with Postfix So, right now I am halfway through trying to setup an outgoing-mail blacklist, by way of smtpd_recipient_restrictions.
The problem I am experiencing is that my test emails are being delivered when I am expecting them to be rejected by the system.
Here's the /etc/postfix/main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_recipient_restrictions =
        reject_unknown_recipient_domain,
        reject_unauth_destination,
        check_recipient_access hash:/etc/postfix/recipient_block

myhostname = hostname.domain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = hostname.domain.com, hostname.domain.com, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

My /etc/postfix/recipient_block (this was run through postmap afterwards)
personalemail@anotheroneofmydomains.com REJECT

And then, I'm sending the test email like so:
$ echo test | mail -s "test email, please ignore" personalemail@anotheroneofmydomains.com

Postfix has had its conf reloaded, has been restarted a couple times to try and troubleshoot, all to no avail.
A chunk from tailing the /var/log/mail.log file reads like so:
Sep 25 02:27:17 antares postfix/master[3024]: reload -- version 2.7.0, configuration /etc/postfix
Sep 25 02:27:27 antares postfix/pickup[3104]: C723018770: uid=1001 from=<obsidian>
Sep 25 02:27:27 antares postfix/cleanup[3110]: C723018770: message-id=<20110925092727.C723018770@hostname.domain.com>
Sep 25 02:27:27 antares postfix/qmgr[3105]: C723018770: from=<obsidian@hostname.domain.com>, size=388, nrcpt=1 (queue active)
Sep 25 02:27:28 antares postfix/smtp[3112]: C723018770: to=<personalemail@anotheroneofmydomains.com>, relay=ASPMX.L.GOOGLE.COM[74.125.47.26]:25, delay=0.35, delays=0.01/0.01/0.12/0.21, dsn=2.0.0, status=sent (250 2.0.0 OK 1316942848 j50si8227610yhe.128)
Sep 25 02:27:28 antares postfix/qmgr[3105]: C723018770: removed

...So, I'm stumped.  I don't see why the email isn't being rejected.

A: The problem is that the mail is sent via the pickup service (via sendmail inteface) and so it is an "outgoing" mail. For outgoing mail the smtpd_*_restrictions don't apply. These restrictions only apply for "incoming" mails that have been sent via SMTP.
Edit
There is even a solution provided by Victor Duchovni (Postfix maintainer): http://marc.info/?l=postfix-users&m=120155612332393&w=1

A: As @mailq says, the "mail" program does not inject messages via SMTP, the "smtpd_recipient_restrictions" only applies to messages received via SMTP.  So, for example, if you run this you should see it showing the reject:
printf 'ehlo hostname.domain.com\nmail from: <user@domain.com>\nrcpt to:' \
    '<personalemail@anotheroneofmydomains.com>\nquit\n' | nc localhost 25

This does an SMTP connection via "netcat" (usually called "nc"), and should demonstrate that the block is indeed in place.
Perhaps this is enough?  If not, the only way I can come up with to do a rejection for this remote address is to set up a transport that rejects messages sent to it, and then list that address in the transport table to be associated with the rejecting transport.


text:
Q: How to add product image via the woocommerce REST API? I am working with the Woocommerce REST API and need to add a product to the store.
It worked before. Now I have this error:
stdClass Object ( [errors] => Array (
  [0] => stdClass Object ( [code] =>
  woocommerce_api_invalid_remote_product_image
  [message] => Error getting remote image
  https://www.google.lt/images/srpr/logo11w.png ) ) )

Here is the documentation for adding a product via the WooCommerce REST API
 http://woothemes.github.io/woocommerce-rest-api-docs/#create-a-product
Here is my code:
$dataArray = array(
            'title' => 'xxxxxxxxxx',
            'description' => 'description1',
            'price' => '69',
            'sku' => 'sku2',
            'tags' => 'tag1, tag2, tag3',
            'color' => array('red', 'blue'),
            'size' => array('S', 'M'),
            'image' => 'https://www.google.lt/images/srpr/logo11w.png'
            );

public function addProduct($data)
{
    $wc_api = $this->_getClient();

    $newProductData = array(
        'product' => array(
            'title' => $data['title'],
            'type' => 'variable',
            'regular_price' => $data['price'],
            'description' => $data['description'],
            'sku' => $data['sku'],
            'tags' => [ $data['tags'] ],
            'images' => [ array('src' => $data['image'], 'position' => '0') ],
            'virtual' => true
        )
    );

    return $wc_api->create_product($newProductData);
}

I'm using this client to call the REST API
https://github.com/kloon/WooCommerce-REST-API-Client-Library
EDITED:
If I get image from wordpress where woocommerce is hosted then all is fine. But, if I use a link from another site then I get an error.

A: I had a similar issue and the error that cURL was generating inside WordPress which leads to woocommerce_api_invalid_remote_product_image was {"errors":{"http_request_failed":["SSLRead() return error -9806"]},"error_data":[]} which means, according to Asaph in https://stackoverflow.com/a/26538127/266531,

php is compiled with a version of cURL that uses Apple's Secure
  Transport under Yosemite and the target of the URL request doesn't
  support SSLv3 (which was probably disabled due to the POODLE
  vulnerability).

My guess is that you are experiencing errors with using SSL over cURL.
Have you tried it with an http link rather thank https?
If you can debug the server side, take a look at what's happening inside class-wc-api-products.php around line 1700. That's what's generating the error. You may be experiencing SSL errors.
If it is the same type of SSL issue, then your possible solutions are

*

*Use a non-secure image link (http instead of https), or

*Follow Asaph's steps to install PHP using OpenSSL instead of SecureSSL in his answer at https://stackoverflow.com/a/26538127/266531

A: In  Woocommerce REST API liblary You can also set option to dont validate SSL.
$options = array(
    'debug'           => true,
    'return_as_array' => false,
    'validate_url'    => false,
    'timeout'         => 60,
    'ssl_verify'      => false,
);


text:
Q: Can you have protocol extension for a specific generics type in Swift? Using protocol extensions, I can make any object conform to my own protocol as long as I provide an implementation for that. E.g. let's assume I create a protocol:
protocol Printable {
    // ... whatever ...
}

Now I can make Strings and Ints printable like that:
extension String: Printable {
    // ... whatever is required to satisfy protocol ...
}

extension Int: Printable {
    // ... whatever is required to satisfy protocol ...
}

This is a very cool way of programming as I now can feed Strings and Ints into whatever function I have that can deal with Printables.
Now if I have an Array of Printables, the whole Array is printable, so I try to do that:
extension Array<Printable>: Printable {
    // ... whatever is required to satisfy protocol ...
}

But the compiler doesn't like it.

Constraint extension must be declared on then unspecialized generic
type "Array" with constraints specified by a "where" clause.

For normal extensions that isn't a problem. I can just do this:
extension Array where Element: Printable {

}

This works as expected. Whatever I put into the extension above only applies to Arrays of Printable elements. But this will not make an Array of Printable elements conform to the Printable protocol itself. This is just a normal extension, not a so called "protocol extension".

A: You can do this in Swift 4.1
extension Array: Printable where Element: Printable {
    // ...
}


text:
Q: Как растянуть столбцы в qtableView чтобы они заняли все поле виджета вне зависимости от контекста Как растянуть столбцы в qtableView чтобы они заняли все поле виджета вне зависимости от контекста?
Еще охота автоматическое выравнивание при перемотки.
Версия qt 4.7.8

A: ui->table->horizontalHeader()->setStretchLastSection(true); // растянуть последнюю секцию (это свойство можно задать и просто в дизайнере)
ui->table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); // растянуть конкретную секцию

также можно растянуть и последнюю запись вертикально:
ui->table->verticalHeader()->setStretchLastSection(true);

при этом растяжение конкретной секции можно устанавливать только после того как таблица заполнена данными (иначе у нее будет отсутствовать horizontalHeader что приведет к исключению)

A: Для Qt5+ воспользуйтесь методом QHeaderView::setSectionResizeMode() с аргументом растяжки QHeaderView::Stretch:
qtableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

Для старых версий QHeaderView::setResizeMode(QHeaderView::Stretch);


text:
Q: Proper handling of events raised by child in MVVM parent I am simplifying a little here:
I have a tab control, and should like for individual tabs to have the power to create further tabs; siblings if you will. So I am calling the tab control the parent, and its tab pages the children.
Using MVVM, my tab control view model is something like this:
class ParentViewModel
{
    ObservableCollection<ChildViewModel> _pages;

    public ObservableCollection<ChildViewModel> Pages
    {
        get
        {
            if (_pages == null)
                _pages = new ObservableCollection<ChildViewModel>();
            return _pages;
        }
    }

    public ParentViewModel()
    {
        Pages.Add(new ChildViewModel());
    }
}

So I have a collection of ChildViewModel objects on my ParentViewModel.
This works a treat, and from inside the ParentViewModel I can of course easily add all the extra ChildViewModel objects I want to my collection and have it all nicely reflected in my Views.
What I want to do is allow a button press (for example) on a ChildView to result in the addition of another ChildViewModel to the collection on the ParentViewModel object.
I have read a lot about relay commands, routed commands, relativesource bindings, the dependancy injection pattern and so forth, but could someone tell me please the 'proper' (in an MVVM sense) way to achieve this, and exactly how it is best done. Thank you!

A: One of the ways I like to handle a situation like this is with Event Aggregating.
It is an ability added with Unity (if you aren't already using it)
Basically you add the Event Aggregator to your Dependancy Injections and then your Parent would subscribe as a listener to the event and your children would publish the event.
The nice part about this is that the children have no concept of who is listening and the parent just knows it has an event request to handle.  For more information you can go HERE!

A: You can use MVVM Lite Messenger class (or write you own):
And send a Message from a childe class to Parent class. See an example here.
create a message class:
public class AddNewChildMessage
{
  public string Data {get;set;} //any data you need to pass
}

In a ParrentViewModel's constructor:
Messenger.Default.Register<AddNewChildMessage>
(
     this,
     ( message ) => AddNewChild(message )
);

private void AddNewChild(AddNewChildMessage message)
{
  //do staf with message.Data if any
  Pages.Add(new ChildViewModel());
}

In a child view model:
Messenger.Default.Send<AddNewChildMessage>( new AddNewChildMessage() );

Adding childs is an example - you can add any logic you want.


text:
Q: Fetch date as date, not as number with BeautifulSoup I've found this other question to fetch a date when scraping a website.
However, the solution provided gives me a integer representation, when the desire ouput is a date.
Fetch date with BeautifulSoup

Prefered format: 09 de julio del 2019

from bs4 import BeautifulSoup

ec_editorial = requests.get("https://elcomercio.pe/opinion/editorial")

ec_editorial_scr = ec_editorial.content

data = """your html goes here"""
soup = BeautifulSoup(ec_editorial_scr)

for i in soup.findAll('time'):
        if i.has_attr('datetime'):
            print(i['datetime'])

prints
1560076500
1559990100
1559990100

A: Assuming 1560076500 are unix timestamps,
import datetime
time_stamp = 1559990100
converted_date = datetime.datetime.fromtimestamp(time_stamp / 1e3)
print(converted_date)
print(str(converted_date)

Output:
datetime.datetime(1970, 1, 19, 6, 49, 50, 100000)
'1970-01-19 06:49:50.100000'

A: Here (You can 'play' with the format string in order to get the exact output)
import time
import requests
from bs4 import BeautifulSoup

ec_editorial = requests.get("https://elcomercio.pe/opinion/editorial")
soup = BeautifulSoup(ec_editorial.content, 'html.parser')
for i in soup.findAll('time'):
    if i.has_attr('datetime'):
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(i['datetime']))))

output
2019-06-09 13:35:00
2019-06-08 13:35:00
2019-06-08 13:35:00
2019-06-07 13:35:00
2019-06-06 13:35:00
....

A: 1560076500, 1559990100 are epoch time, i.e. the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT).
Easiest way to convert those into string format are using Python time library.

*

*Convert the epoch integer value to localtime.

>>> date = 1560076500
>>> import time
>>> date = time.localtime(date)
>>> date
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=9, tm_hour=16, tm_min=5, tm_sec=0, tm_wday=6, tm_yday=160, tm_isdst=0)

*Use strftime() to format into string.

>>> time.strftime('%d %b %Y', date)
'09 Jun 2019'


text:
Q: How to connect Magento REST Api with OAuth Authentication in Android Application? Please Help me here i am searching from last two days but i didn't get the simple code for this.
I want to connect to My Magento Rest API using OAuth


text:
Q: How can we estimate number of zeros? Assume $a>0$ , $b>0$ and there exists a non-zero function $\phi(t)$ such that is the solution of $$y''+(a+b\cos 2t)y=0$$ and on $(-\pi/2,\pi/2)$ has $2n$ zero. How Floquet theory can help to prove that

$$(2n-1)^2\le a+b $$

Thanks

A: I solved it my self in this way:
We can prove that
Numbers of zeros of solution of $y''+g(x)y=0$ is less than the zeros of $y''+My=0$ which $0<g(x)<M$.
then every thing is obvious.


text:
Q: Why SlugField() in Django? Django has models.SlugField() which helps us to create some cool looking urls.
My question is why specifying it as a field
suppose I have this model
 class Blog(models.Model):
    title = models.CharField()

and if I want to add slug, I could just use
 class Blog(models.Model):
    title = models.CharField()

    def title_slug(self):
       return slugify(self.title)

in urls I could just use
(r'^blog/(?P<id>\d+)/(?P<slug>[-\w]+)/$', 'app.views.blog_view'),

and in views
def blog_view(request, id ,slug):
    get_object_or_404(Blog, pk=id)
    ...

urls will look like

example.com/blog/23/why-iam-here/

There are three things that makes me adopt this method

*

*Slug field does not comes with implicit uniqueness.

*get_object_or_404(Blog, pk=id) must be faster than get_object_or_404(Blog, slug=slug).

*Adding a slug field to existing models involves data migration.

so why SlugField()? , apart from the cost of dynamically generating slug, what are the disadvantages of above method ?

A: Why SlugField() in Django? Because:

*

*it's human friendly (eg. /blog/ instead of /1/).

*it's good SEO to create consistency in title, heading and URL.

The big disadvantage of your dynamically generated slug, accepting slugs in urls.py and not using the slug to get the right object? It's bad design.
If you supply and accept slugs, but don't check against them, then you have multiple URLs returning the same content. So /1/useful-slug/ and /1/this-is-a-bs-slug/ will both return the same page.
This is bad because it does not make life easy for humans. Your visitors have to supply an id and something that is redundant. Duplicated pages are search engines nightmare. Which page is the right one? Duplicated pages will end up with a low rank. See https://support.google.com/webmasters/answer/40349?hl=en (last p)
You can argue that you implement your own beautifully generated links consistently, but people and bots guess URLs all the time (see your logfiles). When you accept all slugs then humans and bots always guess right.
Also saving a slug to the db saves processing power. You generate the slug one time and reuse it. What will be more (in)efficient looking up the slug or generating it each time?
Slug fields in the admin are useful to give editors the opportunity to edit the slug. Maybe to supply extra information that is not in the title but still worth mentioning.
Bonus: To update migrated data:
from django.template.defaultfilters import slugify

for obj in Blog.objects.filter(slug=""):
    obj.slug = slugify(obj.title)
    obj.save()

A:
Slug field does not comes with implicit uniqueness.

There is no implicit uniqueness with a CharField. You need to specify unique=True if you want to ensure that each row is unique at the DB level. You must do this with both a CharField and a SlugField so no advantage to either

get_object_or_404(Blog, pk=id) must be faster than get_object_or_404(Blog, slug=slug).

There might be a very slight difference due to an index on your primary key, but it's probably negligible. This has nothing to do with using a CharField vs SlugField though - you have just created a different URL that takes an id and are using that to do the lookup.

Adding a slug field to existing models involves data migration.

Adding a CharField to an existing model also required a data migration so there is no advantage here.

SlugFields are simply CharField with an extra bit of validation. Look at the code. You are breaking Django's golden rule of DRY - don't repeat yourself.
Furthermore, if you just use a CharField you don't get any validation at the form level, so you can very easily create a "slug" that doesn't conform to the slugs validation, i.e. it might have spaces or characters that are not allowed in an URL.
Also with this approach, if you change your title, your URL has changed and now all your old links are dead. Having a slug field prevents this.
You are making more trouble for yourself here - just use the SlugField

A: I am making a multi-tenant calendar app. If the calendar urls were something like: /calendar/id/ where the ids were successive integers, then hackers could guess the ids and find out more about my business than I want. By using a url /calendar/slug/ it is much harder to find all the calendars.


text:
Q: Stringing together multiple page object files in Eclipse/Cucumber/Java I am having trouble stringing together multiple Page Object Files and step definitions.
I have imported the following, which is super heavily edited due to it being work code:
package <the package my step definition file is in>
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import <the other project my team created>.browsercapabilities.Browser;
import <the other project my team created>.Browsers;
import <a package a different step definition file is
in>.addNewContact.AddNewContactStepDefs;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import <the other project my team created>.webcomponents.WebButton;
import <my page objects package>.authenticationpages.CommandLoginPage;
import <my page object package>ThirdPageObjectFile;
import <my page object package>.SecondPageObjectFile;
import <my page object package>.FirstPageObjectFile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import cucumber.api.java.en.Then;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;

public class ThirdPageStepDefs extends BrowserBase {

private static final Logger LOG =
LoggerFactory.getLogger(ThirdPageStepDefs.class);
private WebDriver driver = mainBrowser().getDriver();
private Browser browser = Browsers.getBrowser();
private WebDriverWait wait = new WebDriverWait(driver,10);

LoginPage login = new LoginPage (browser);
SecondPageObjectFile contact = new SecondPageObjectFile (browser);
FirstPageObjectFile searchContact = new FirstPageObjectFile (browser);
ThirdPageObjectFile deal = new ThirdPageObjectFile (browser);

@Then("^I click the contacts icon$")
public void i_click_the_contacts_icon() throws Throwable {
    contact.get_contact_link().clickLink();
}

I was getting an initialization error when I ran the runner code saying that the runner could not instantiate an instance of my ThirdStepDefFile, i.e. "Failed to Instantiate Class "
My runner is working fine:
package <Utility package>.utilities;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;

@RunWith(Cucumber.class)
@CucumberOptions(
    features="src\\test\\resources\\<my feature folder>",
    plugin={"pretty", "html:target/cucumber-html-report",
"json:target/cucumber.json"},
    glue= "<My step def folder>",
    tags = "@<my tags>"
    )
public class ComUITestRunner extends AbstractTestNGCucumberTests {

}

I have many more lines in scenarios that I've commented out and since I was getting the initialization error, I edited to troubleshoot as following:
-Comment all methods out (green)
-Leave all methods in (red)
-Leave one method in (red)
When I have even one method that isn't commented out, then I get an error.
My project is a series of screens that a user has to get to in order to log in. The login screen, first screen, second screen, and third screen all have their own page objects. Eventually I want to abstract those screens out to a main project that all sub projects share as they'll be pre-conditions to everything else. Stringing these screens together seems to fail and I'm considering refactoring the whole thing.
Am also new to Java/Eclipse, so it's possible that I am not seeing the stack trace correctly. For instance, the bottom of my junit screen says "62 more" lines detailing the failure that I'm not able to see. I tried debugging to no avail and I clicked on the outline on the left hand side of the junit output and when I hovered over it, it says Test Class Not Found


text:
Q: SqlBulkCopy.WriteToServerAsync does not respect the `await` keyword. Why? SqlBulkCopy.WriteToServerAsync does not respect the await keyword. Why?
Here is my code:
public async Task UpdateDBWithXML(Action<Func<DataTable, Task>> readXmlInBatches, string hashKey, string hash)
{
    using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
    using (var bulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.UnderlyingTransaction))
    {
        //this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractorTemps]");

        bulk.DestinationTableName = "LegalContractorTemps";
        readXmlInBatches(async (DataTable table) =>
        {
            if (bulk.ColumnMappings.Count == 0)
            {
                foreach (DataColumn column in table.Columns)
                {
                    bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                }
            }

            await bulk.WriteToServerAsync(table);
        });

        await this.Context.Database.ExecuteSqlCommandAsync(
            "EXECUTE dbo.LegalContractorsDataSynchronize @hashKey, @hash",
            new SqlParameter("@hashKey", hashKey),
            new SqlParameter("@hash", hash)
        );

        transaction.Commit();
    }
}

In the readXmlInBatches parameter I pass the following function as an argument:
public void ReadXMLInBatches(Func<DataTable, Task> processBatch)
{
    int batchSize = 10000;
    var table = new DataTable();
    foreach (var col in columnNames)
    {
        table.Columns.Add(col);
    }

    using (var reader = new StreamReader(pathToXml, Encoding.GetEncoding(encoding)))
    using (var xmlReader = XmlReader.Create(reader))
    {
        string lastElement = null;
        DataRow lastRow = null;
        while (xmlReader.Read())
        {
            switch (xmlReader.NodeType)
            {
                case XmlNodeType.Element:
                    if (xmlReader.Name == "RECORD")
                    {
                        if (table.Rows.Count >= batchSize)
                        {
                            processBatch(table);
                            table.Rows.Clear();
                        }

                        lastRow = table.Rows.Add();
                    }
                    lastElement = xmlReader.Name;
                    break;
                case XmlNodeType.Text:
                    ReadMember(lastRow, lastElement, xmlReader.Value);
                    break;
            }
        }
        if (table.Rows.Count > 0)
        {
            processBatch(table);
            table.Rows.Clear();
        }
    }
}

I have in the XML something about 1.7 million records. After my program have read a few batches I am getting the error:

System.Data.RowNotInTableException: 'This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.'

I researched the source code of the SqlBulkCopy. And found the method which throws an error:
public Task WriteToServerAsync(DataTable table, DataRowState rowState, CancellationToken cancellationToken) {
            Task resultTask = null;
            SqlConnection.ExecutePermission.Demand();

            if (table == null) {
                throw new ArgumentNullException("table");
            }

            if (_isBulkCopyingInProgress){
                throw SQL.BulkLoadPendingOperation();
            }

            SqlStatistics statistics = Statistics;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                _rowStateToSkip = ((rowState == 0) || (rowState == DataRowState.Deleted)) ? DataRowState.Deleted : ~rowState | DataRowState.Deleted;
                _rowSource = table;
                _SqlDataReaderRowSource = null;
                _dataTableSource = table;
                _rowSourceType = ValueSourceType.DataTable;
                _rowEnumerator = table.Rows.GetEnumerator();
                _isAsyncBulkCopy = true;
                resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); //It returns Task since _isAsyncBulkCopy = true;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
            return resultTask;
        }

I noticed the field _isBulkCopyingInProgress and decided to check it while debugging. And I found out that when the error is thrown the field is true. How is that possible? I would expect the bulk insert to happen first (before the execution continues and the WriteToServerAsync will be called a second time)  since I add the await here: await bulk.WriteToServerAsync(table);.
What could I be missing?

A: You are passing an asynchronous function to ReadXMLInBatches, but it's execution isn't being awaited inside your method, therefore ReadXMLInBatches may terminate before all the calls to WriteToServerAsync have completed.
Try the following changes:
public async Task ReadXMLInBatchesAsync(Func<DataTable, Task> processBatch)
{
    //...
    await processBatch(table);
    //...
}

public async Task UpdateDBWithXML(Func<Func<DataTable, Task>, Task> readXmlInBatches, string hashKey, string hash)
{
    //...
    await readXmlInBatches(async (DataTable table) =>
    //...
}


text:
Q: Is there a way to get a list of defined languages in the project using ContentDelivery API in Kentico-Cloud? I need to get a list of available languages for given project. It would like to use content delivery api to achieve this. Is that possible ?

A: No, right now there is no direct support in the Delivery API, however, there are some options.
At first, you can utilize the Content Management API to list variants of the item or content type.
Secondly, you can create content type (and item) where you can list and maintain your languages and then request this item in your app.
At last, you can find Kentico Roadmap here and suggest/upvote requested feature(s).


text:
Q: Disable network connection using batch file I need to enable/disable network connections on windows with a batch file.

A: You can do this with Windows PowerShell. Here's a page with examples.
Probably you want to use the last one on that page.
Update
A little more searching reminded me about netsh, which is a more appropriate tool than either PowerShell or devcon:
netsh interface set interface "Local Area Connection " ENABLE
netsh interface set interface "Local Area Connection " DISABLE

I'm not sure which version of Windows you're using, but here's the netsh doc for XP to get you started.

A: You may use devcon (from MS).
Usage
  devcon disable *INTERFNAME

Here is a simple tutorial for your intended usage.
HTH!

A: netsh wlan connect ssid=*SSID HERE*name= network name HERE interface="Wireless Network Connection"
and
disconnect interface="Wireless Network Connection"
both actually work in windows 7


text:
Q: What are the kernels of ring homomorphisms that contain the polynomial $X^2+1$?
Let $\mathbb{R}[X]$ be the ring of polynomials over the field of real numbers.
Write down two ring homomorphisms $\mathbb{R}[X]\rightarrow\mathbb{C}$ whose kernels contain the polynomial $X^2+1$.

My attempt/thoughts:
I think that what the exercise requires us to do is to define two functions, say $\theta,\phi:\mathbb{R}[X]\rightarrow\mathbb{C}$, and then show that these functions are ring homomorphisms. Then we have to show that the kernel of each function contains the polynomial $X^2+1$, i.e. show that $X^2+1\in\ker\theta$ and $X^2+1\in\ker\phi$.
But I am struggling to think of such functions; I don't know how to derive them.
I would appreciate any hints/help.
Thank you.

A: Well, we know that in $\Bbb{C}$, there are two zeroes of $x^2+1$: $i$ and $-i$. Therefore, we can simply make $\theta$ the evaluation $f \rightarrow f(i)$ and $\phi$ the evaluation homomorphism $f \rightarrow f(-i)$. In both of these cases, when $f=x^2+1$, the homomophisms evaluate to $0$:
$$\theta(x^2+1)=i^2+1=-1+1=0$$
$$\phi(x^2+1)=(-i)^2+1=-1+1=0$$
Therefore, these evaluation homomorphisms are two ring homomorphisms from $\Bbb{R}[X]$ to $\Bbb{C}$ such that $x^2+1$ are in the kernel.


text:
Q: Hibernate sql named query with entities i need to build a sql query that returns a bean with inside an entity... i try to explain me with an example.
This is my bean that i want to get from the query:
public class EventiPerGiorno {

    private Eventi evento; // THIS IS AN ENTITY
    private Date primoSpettacolo; //SCALAR
    private int spettacoli; //SCALAR
...
}

and this is the xml query mapping:
<sql-query name="eventiPerGiorno">
    <return alias="evento" class="entity.Eventi"/>
    <return-scalar column="spettacoli" type="integer"/>
    <return-scalar column="primoSpettacolo" type="date"/>
    <![CDATA[
        select
            spettacoli.evento as {evento.id},
            count(spettacoli.id) as spettacoli,
            min(spettacoli.inizio) as primoSpettacolo,
        from ...
    ]]>
</sql-query>

But Hibernate says to me that it want ALL properties of Eventi in the select not only the primary key that is "evento.id". Why?


text:
Q: CompareValidator asp.net I inserted a comaper validator in my page linked with a text box to just get numbers as input.
Here's the code,
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="ContactNumber" Type="Integer" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="Input Only Numbers" SetFocusOnError="True" />

But when I input number like xxxx-xxxxxxx (i.e with a - in between) and then change the texbox, The error message just appears for a blink of an eye and vanishes.
Can anyone help in making it stay?
Or suggest any other way to just get numbers 0-9 input.
P.S: I have already applied
onkeypress="if(isNaN(String.fromCharCode(event.keyCode))) return false;"
on my textbox, but the problem occurred when client copy pasted the number with - in between.
Help guys!


text:
Q: Set column name for apply result over groupby This is a fairly trivial problem, but its triggering my OCD and I haven't been able to find a suitable solution for the past half hour.
For background, I'm looking to calculate a value (let's call it F) for each group in a DataFrame derived from different aggregated measures of columns in the existing DataFrame.
Here's a toy example of what I'm trying to do:
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': ['X', 'Y', 'X', 'Y', 'Y', 'Y', 'Y', 'X', 'Y', 'X'],
                'B': ['N', 'N', 'N', 'M', 'N', 'M', 'M', 'N', 'M', 'N'],
                'C': [69, 83, 28, 25, 11, 31, 14, 37, 14,  0],
                'D': [ 0.3,  0.1,  0.1,  0.8,  0.8,  0. ,  0.8,  0.8,  0.1,  0.8],
                'E': [11, 11, 12, 11, 11, 12, 12, 11, 12, 12]
                })

df_grp = df.groupby(['A','B'])
df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max())

What I'd like to do is assign a name to the result of apply (or lambda). Is there anyway to do this without moving lambda to a named function or renaming the column after running the last line?

A: Have the lambda function return a new Series:
df_grp.apply(lambda x: pd.Series({'new_name':
                    x['C'].sum() * x['D'].mean() / x['E'].max()}))
# or df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max()).to_frame('new_name')

     new_name
A B
X N  5.583333
Y M  2.975000
  N  3.845455

A: You could convert your series to a dataframe using reset_index() and provide name='yout_col_name' -- The name of the column corresponding to the Series values
(df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max())
      .reset_index(name='your_col_name'))

   A  B  your_col_name
0  X  N   5.583333
1  Y  M   2.975000
2  Y  N   3.845455

A: The accepted answer seems work for the current version of Pandas, but name is not one of the parameters of reset_index according to the documentation. There is a names argument, but it serves a different purpose IMO.
Since the output of apply is a series, we can simply use pandas.Series.rename() to achive the result.
df = pd.DataFrame({'A': ['X', 'Y', 'X', 'Y', 'Y', 'Y', 'Y', 'X', 'Y', 'X'],
                'B': ['N', 'N', 'N', 'M', 'N', 'M', 'M', 'N', 'M', 'N'],
                'C': [69, 83, 28, 25, 11, 31, 14, 37, 14,  0],
                'D': [ 0.3,  0.1,  0.1,  0.8,  0.8,  0. ,  0.8,  0.8,  0.1,  0.8],
                'E': [11, 11, 12, 11, 11, 12, 12, 11, 12, 12]
                })

df_grp = df.groupby(['A','B'])
df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max()).rename("your_col_name")


text:
Q: Angular8 Material, Grid with both headers and tiles. mat-grid-tile content not totally resizing Angular8 Material, Grid with both headers and tiles.
I am trying to learn how the grid system works in Angular Material. I am dynamically pulling in the components into a grid.  Right now, the grid list and tiles work as expected. The rendering of the components (Autocompelete etc, also work as expected). But the content of the tiles is off. The mat-figure portion. It's like they aren't totally aware that they are inside of tiles.
For example, if the page shrinks, the grid tiles are responsive and resize, but the content within the tile, looks like it is over the containing.  Also the sizes (font's widths) do not shrink.    I could probably fix this with just CSS but I want to understand why the grid-list isn't working.
I attached some screenshots. One is of the grid with a small screen resolution, showing how the fonts don't shrink (isn't that part of Angular Material?) and the other is how its allenter image description here rendering in the console.

import {Component, OnInit} from '@angular/core';

export interface ITile {
  color: string;
  cols: number;
  headerText: string;
  rows: number;
  text: string;
  componentName: string;
}

@Component({
  selector: 'app-forms',
  templateUrl: 'forms.component.html',
  styleUrls: ['forms.component.scss']
})
export class FormsComponent implements OnInit {
  tiles: Array<ITile>;

  setComponents() {
    this.tiles = new Array<ITile>();
    let components = [];
    components.push('autocomplete');
    components.push('checkbox');
    components.push('datepicker');
    components.push('formfield');
    components.push('input');
    components.push('radiobutton');
    components.push('select');
    components.push('slider');
    components.push('slidetoggle');
    console.log (components);

    components.forEach(component => {
      if (component === 'autocomplete') {
        const headerText = 'Auto Complete';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'checkbox') {
        const headerText = 'Checkbox';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'datepicker') {
        const headerText = 'Date Picker';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'formfield') {
        const headerText = 'Form Field';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'input') {
        const headerText = 'Input';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'radiobutton') {
        const headerText = 'Radio Button';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'select') {
        const headerText = 'Select';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'slider') {
        const headerText = 'Slider';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
      if (component === 'slidetoggle') {
        const headerText = 'Slide Toggle';
        this.setTile('#ccc', 4, headerText, 'example', 1, component);
      }
    });
  }

  setTile(color: string, cols: number, headerText: string, text: string, rows: number, componentName: string) {
    const tile = {
      color,
      cols,
      headerText,
      text,
      rows,
      componentName
    };

    this.tiles.push(tile);
    console.log(JSON.stringify(this.tiles));
  }

  ngOnInit(): void {
this.setComponents();
  }
}
<mat-grid-list cols="4" rowHeight="1:1" gutterSize="55px">

  <mat-grid-tile class="grid-tile"
                 [colspan]="2"
                 [rowspan]="1"
                 *ngFor="let tile of tiles"
                 [colspan]="tile.cols"
                 [rowspan]="tile.rows"
                 [style.background]="tile.color">
    {{tile.text}}
    <app-checkbox *ngIf="tile.componentName === 'checkbox'"></app-checkbox>

    <app-autocomplete *ngIf="tile.componentName === 'autocomplete'"></app-autocomplete>
    <app-checkbox *ngIf="tile.componentName === 'checkbox'"></app-checkbox>

    <app-datepicker *ngIf="tile.componentName === 'datepicker'"></app-datepicker>
    <app-formfield *ngIf="tile.componentName === 'formfield'"></app-formfield>

    <app-input *ngIf="tile.componentName === 'input'"></app-input>
    <app-radiobutton *ngIf="tile.componentName ==='radiobutton'"></app-radiobutton>

    <app-select *ngIf="tile.componentName === 'select'"></app-select>
    <app-slider *ngIf="tile.componentName ==='slider'"></app-slider>

    <app-sidetoggle *ngIf="tile.componentName === 'slidetoggle'"></app-sidetoggle>

    <mat-grid-tile-header>

 {{tile.headerText}}

    </mat-grid-tile-header>
  </mat-grid-tile>
</mat-grid-list>

A: I had the exact same problem. I ended up not using the material grid but angular flex grid.
https://tburleson-layouts-demos.firebaseapp.com/#/docs
Then you can use this layout grid:

    <mat-card fxFlex="50%" fxFill>

        {{tile.text}}
        <app-autocomplete *ngIf="tile.componentName === 'autocomplete'" class="spacing"></app-autocomplete>

    </mat-card>

    <mat-card fxFlex="50%" fxFill>

        {{tile.text}}
        <app-checkbox *ngIf="tile.componentName === 'checkbox'" class="spacing"></app-checkbox>

    </mat-card>


text:
Q: Copy a cell with its color - Excel I have a data sheet as below
COLA        COLB
ABC          10
             10
             15
XYZ          10
             15
             15

I copied it from another pivot where Col A groups to more than one value in Col B. Now I have used the below step to fill all the blank cells in Col A with value from the above cell,
Select Col A
Go to Special -> Select blanks -> OK -> Enter formula in cell A3 as "=A2" -> ctrl + Enter.
This has copied all the values from the cell above into all the blank cells in Col A.
But I want the blank cell to copy the color also from the parent cell if they are highlighted.
How can I do this in excel?
Cheers!!

A: try the code below
Sub test()
    lastrow = Range("B" & Rows.Count).End(xlUp).Row
    For i = 2 To lastrow
        If Cells(i, 1) = "" Then
            If Cells(i - 1, 1).Interior.ColorIndex > 0 Then
                Cells(i, 1) = Cells(i - 1, 1)
                Cells(i, 1).Interior.Color = Cells(i - 1, 1).Interior.Color
            Else
                Cells(i, 1) = Cells(i - 1, 1)
            End If
        End If
    Next i
End Sub


text:
Q: How to fix command not working multiple times I have a command ¬host which initiates a game. A person with the role Admin can use ¬cleargames to stop the games and delete the messages, via a variable Host.
However, if I run ¬host and then ¬cleargames it works. If I do it again, I get an error.
This is for a discord server using discord.py asyncio. I keep getting the error:

Command cleargames is already registered.

@client.command(pass_context=True)
async def host(ctx):
  host = "."
  if host == ".":
    host = ctx.message.author
    message = (f"__**Player List**__ \n \n{host.mention} (Host)")
    playerList = await client.say(message)
    @client.command(pass_context=True)
    @has_role("Admin")
    async def cleargames(ctx):
      command = ctx.message
      await client.delete_message(playerList)
      await client.delete_message(command)
      notfication = await client.say("Games cleared.")
      time.sleep(5)
      await client.delete_message(notification)
      host = "."

It should be able to carry out the ¬host and ¬cleargames command multiple times, without getting the error.

A: You can't have multiple versions of the same command.  When you try to run host a second time, it tries to register a command under the name cleargames again, which fails.
Instead, write two separate commands that share state through mutually accessed global variables.
playerList = None

@client.command(pass_context=True)
async def host(ctx):
    global playerList
    if playerList:
        return
    host = ctx.message.author
    message = (f"__**Player List**__ \n \n{host.mention} (Host)")
    playerList = await client.say(message)

@client.command(pass_context=True)
@has_role("Admin")
async def cleargames(ctx):
    global playerList
    if playerList:
        await client.delete_message(playerList)
        playerList = None
        await client.delete_message(ctx.message)
        notfication = await client.say("Games cleared.")
        await asyncio.sleep(5)
        await client.delete_message(notification)


text:
Q: how to get a random image on 1 imageView? how can I get a random image by just using 1 imageView?
here is my java code and it still does not work can someone please help me please.
public class Gameplay extends Activity
{

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

    final int[] images = {
            R.drawable.easy1, R.drawable.easy2};

    final ImageButton shuffle = (ImageButton) findViewById(R.id.imageView1);
    shuffle.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view)
        {
            Random generator = new Random();

            ImageView singleImageView = (ImageView) findViewById(R.id.imageView1);
            singleImageView.setImageResource(images[generator.nextInt(images.length - 1)]);
        }
    });

}

}

Thanks in advance

A: The code you have shown still have the solution for your question, your problem is how to get random images out of given array.
images[generator.nextInt(images.length - 1): this will get you random image everytime, show it on your image view.

A: Correct me if I'm wrong, but I think you're asking for one ImageView to appear on screen at a time, and you'd like to only allocate a single ImageView and replace the image with a random image at some time in your app.  For that, you can simply allocate a single image view (just put one imageView in your view) and use imageview.setImageResource as follows:
ImageView singleImageView = (ImageView) findViewById(R.id.single_image_view)
singleImageView.setImageResource(images[generator.nextInt(images.length - 1)];

A: In your case, generator.nextInt(images.length - 1) is equivalent with generator.nextInt(1) and therefore it always returns 0, since Random.nextInt(int)

returns:
  the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence

(http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int))


text:
Q: Missing identifier in project model (json) which exists in manifest I have two projects: one is for development and another one is for integration tests. Project for integration tests is created from the template of the development project. This template I export by means of the following URL: https://goodata.com/gdc/projects/myProjectId/model/view
However, even though I'm using the template of the development, the integration tests project misses one field, which is date dimension attribute.
Am I missing something here? Should I export not only the project model listed above, but something else?
Thank you in advance for any help,
Dani

A: The project model API support parameters which manage what is included in the response.
Please see API reference: https://help.gooddata.com/display/API/API+Reference#/reference/project-model/get-a-link-to-view-the-project-model/get-a-link-to-view-the-project-model
Try to include them and the missing attribute should appear.
Best,
Martin


text:
Q: Extracting a (sub)string from within parentheses I'm trying to extract text from within parentheses inside of a string. Example:
"John D Wilson(some text)"

I want to extract only some text from the string.
Here is the code I have so far:
temp = workingValue
rawname=split(temp)
dim value
Set myRegExp = New RegExp
myRegExp.IgnoreCase = True
myRegExp.Global = True

myRegExp.Pattern = "/\([a-z]+\)/"
msgbox temp
if myRegExp.Test(temp)then
value = myRegExp.Replace(temp,"")
msgbox value
else
msgbox "no match"
end if

A: By using a group you can extract the text between parentheses as a submatch. Your pattern won't work, though, because your sample text contains whitespace, but your pattern doesn't. Try something like this:
myRegExp.Pattern = "/\((.*?)\)/"
For Each m In myRegExp.Execute(temp)
  value = m.SubMatches(0)
Next

If IsEmpty(value) Then
  MsgBox "no match"
Else
  MsgBox value
End If

Regular expression breakdown:

*

*\(...\) matches the enclosing parentheses.

*.*? is a non-greedy match for any character except newlines.

*(...) is a capturing group, so the non-greedy match can be accessed as a submatch.

A: Your regex won't match the space in some text
Also, you need to put capture groups around just the text if you
want to separate/extract only that text.
One of these might work
\(([^()]+)\)
\(([a-z]+(?:\s+[a-z]+)*)\)/
\(([a-zA-Z\s]+)\)


text:
Q: Reconciling different expressions for Riemann curvature tensor [Note: I think this question is more suited to Physics SE rather than Math, since it refers to Carroll's notes and some equations might have inherent Physics-related assumptions
EDIT: This question has also been crossposted to Math SE. Link in comment.]
I'm reading Carroll's GR notes and I'm having trouble deciphering a particular expression for the Riemann curvature tensor. The coordinate-free definition is (eq. 3.71 in Carroll's notes):
$$R(X,Y)Z=\nabla_X\nabla_YZ-\nabla_Y\nabla_XZ-\nabla_{[X,Y]}Z\tag{3.71}$$
An index-based expression is also given (eq. 3.66 in Carroll's notes):
$$R^{\rho}_{\ \ \sigma\mu\nu}V^{\sigma}=[\nabla_{\mu},\nabla_{\nu}]V^{\rho}+T_{\mu\nu}^{\ \ \ \ \lambda}\nabla_{\lambda}V^{\rho}\tag{3.66}$$
I want to reconcile these two equations. A bit of background on the first equation, based on my reading of "Semi-Riemannian Geometry: The Mathematical Language of General Relativity" by Newman:
$R$ is a map from $\mathfrak{X}(M)^3$ to $\mathfrak{X}(M)$. The book doesn't really treat $R(X,Y)$ as a separate object (as far as I've read). (So far till the point I've read the book) $R$ is just treated as a map of 3 vector fields and with the weird notation $R(X,Y)Z$ instead of $R(X,Y,Z)$. Then there is a theorem showing that $R$ is multilinear in all its arguments and anti-symmetric in its first 2 arguments. And then the following assertion:

Let $(M,\nabla)$ be a smooth manifold with a connection, and let $(U,(x^i))$ be a chart on $M$. Then in local coordinates, $R(\partial/\partial x^{\mu},\partial/\partial x^{\nu})\partial/\partial x^{\sigma}$ can be expressed as: $$R\bigg(\frac{\partial}{\partial x^{\mu}},\frac{\partial}{\partial x^{\nu}}\bigg)\frac{\partial}{\partial x^{\sigma}}=R_{\ \ \sigma\mu\nu}^{\rho}\frac{\partial}{\partial x^{\rho}}$$

Based on the above, if $V\in\mathfrak{X}(M)$, then
$$R\bigg(\frac{\partial}{\partial x^{\mu}},\frac{\partial}{\partial x^{\nu}}\bigg)V=R\bigg(\frac{\partial}{\partial x^{\mu}},\frac{\partial}{\partial x^{\nu}}\bigg)V^{\sigma}\frac{\partial}{\partial x^{\sigma}}=V^{\sigma}R\bigg(\frac{\partial}{\partial x^{\mu}},\frac{\partial}{\partial x^{\nu}}\bigg)\frac{\partial}{\partial x^{\sigma}}=V^{\sigma}R_{\ \ \sigma\mu\nu}^{\eta}\frac{\partial}{\partial x^{\eta}}$$
Now if I act this on the $x^{\rho}$ coordinate function, I get $$\bigg(R\bigg(\frac{\partial}{\partial x^{\mu}},\frac{\partial}{\partial x^{\nu}}\bigg)V\bigg)(x^{\rho})=V^{\sigma}R_{\ \ \sigma\mu\nu}^{\eta}\frac{\partial}{\partial x^{\eta}}(x^{\rho})=V^{\sigma}R_{\ \ \sigma\mu\nu}^{\eta}\frac{\partial x^{\rho}}{\partial x^{\eta}}=R_{\ \ \sigma\mu\nu}^{\rho}V^{\sigma}\tag{1}$$
So far, so good. Now in the first equation (eq. 3.71), I can replace $X,Y$ by fields $\partial_{\mu},\partial_{\nu}$ respectively and $Z$ by $V$, then I can get the local coordinates for both sides by acting them on $x^{\rho}$, i.e. (AFAIK to make notation shorter, expressions like $\nabla_{\partial_{\mu}}$ are written as $\nabla_{\mu}$):
$$(R(\partial_{\mu},\partial_{\nu})V)(x^{\rho})=([\nabla_{\mu},\nabla_{\nu}]V)(x^{\rho})-(\nabla_{[\partial_{\mu},\partial_{\nu}]}V)(x^{\rho})=([\nabla_{\mu},\nabla_{\nu}]V)(x^{\rho})\tag{2}$$
Comparing (1) and (2), I get $$R_{\ \ \sigma\mu\nu}^{\rho}V^{\sigma}=([\nabla_{\mu},\nabla_{\nu}]V)(x^{\rho})\tag{3}$$
The above equation completely follows from (3.71). Now to reconcile (3.71) with (3.66), I have to show (comparing RHS of (3) and (3.66)):
$$([\nabla_{\mu},\nabla_{\nu}]V)(x^{\rho})=[\nabla_{\mu},\nabla_{\nu}]V^{\rho}+T_{\mu\nu}^{\ \ \ \ \lambda}\nabla_{\lambda}V^{\rho}\tag{4}$$
This is where I'm stuck. How do I go about proving eq. (4)? On the other hand, are eq.s (3.71) and (3.66) even meant to be reconciled (are they fundamentally the same equation?)
My assumption is that (3.66) is the index-based version of the coordinate-free equation (3.71). I'd appreciate any help or corrections!

A: Working in the abstract index notation,
$R(X,Y)V = [\nabla_X, \nabla_Y] V - \nabla_{[X,Y]}V$ boils down to
\begin{align}
   (R(X,Y)V)^A
   &= X^C\nabla_{C} (Y^D\nabla_{D}V^A)
      - Y^C\nabla_{C} (X^D\nabla_{D}V^A)
      - [X,Y]^C{\kern0.1em} \nabla_C V^A
   \,,\\
   &= \big({
         X^C \nabla_{C} Y^D
         {-}\, Y^C \nabla_{C} X^D
      }\big)(\nabla_{D}V^A)
      + X^C Y^D ([\nabla_{C},\nabla_{D}]V^A)
      - [X,Y]^C{\kern0.1em} \nabla_C V^A
   \,,\\
   &=
      (T(X,Y))^D {\kern0.1em} (\nabla_{D}V^A)
      + X^C Y^D ([\nabla_{C},\nabla_{D}]V^A)
   \,.
\end{align}
To recapitulate,
\begin{align}
   R^A{}_{BCD} V^B X^C Y^D
   &=
      ([\nabla_{C},\nabla_{D}]V^A) {\kern0.1em} X^C {\kern0.05em} Y^D
      +
      (\nabla_{D}V^A) {\kern0.1em} (T(X,Y))^D
   \,.
\end{align}
If we take $X^A = \partial^A{}_\rho$ and $Y^A = \partial^A{}_\sigma$, we find
\begin{align}
   R^\mu{}_{\nu\rho\sigma} V^\nu
   &=
   dx^\mu{}_A{\kern0.1em}
      R^A{}_{BCD} V^B \partial^C{}_\rho{\kern0.05em} \partial^D{}_\sigma
   \,,\\
   &=
   dx^\mu{}_A{\kern0.05em}
      ([\nabla_{C},\nabla_{D}]V^A){\kern0.1em} \partial^C{}_\rho{\kern0.05em} \partial^D{}_\sigma
      +
   dx^\mu{}_A{\kern0.05em}
      (\nabla_{D}V^A){\kern0.1em} (T(\partial_\rho,\partial_\sigma))^D
   \,,\\
   &=
   ([\nabla_\rho,\nabla_\sigma] V)^\mu
   +
   (\nabla_\lambda V)^\mu{\kern0.1em} T^\lambda{}_{\rho\sigma}
   \,,
\end{align}
where $\nabla_\mu := \nabla_{\partial_\mu}$.
Note that by "$\nabla_X V^\mu$" it really means $dx^\mu{}_A (\nabla_X V^A)$;
that's what I mean by $(\nabla_\lambda V)^\mu$ and $([\nabla_\rho,\nabla_\sigma] V)^\mu$.
I would say this identity is quite a tricky one. I also got really confused when I first encountered it. I believe abstract index notation helps. Where did the torsion come from? Roughly speaking, we can say $\nabla_X$ also differentiates $Y$ in $\nabla_X(\nabla_YV)$. The torsion term came from that contribution.

A: I  prefer the notation $\nabla_X$ to the apparently more explicit  $X^\mu\nabla_\mu$ because  in the presence of torsion  there is a dangerous ambiguity lurking in the notation $\nabla_\mu$.  To see this recall that the curvature definition
$$
 [\nabla_X,\nabla_Y]Z- \nabla_{[X,Y]}Z= {\bf R}(X,Y) Z
 $$
holds even when the connection has torsion.  Now  take $X\to \partial_\mu$ and $Y\to \partial_\nu$ {\it i.e./} $X^\lambda =\delta^\lambda_\mu$, $Y^\lambda =\delta^\lambda_\nu$ so that we are tempted to write
$$
 \nabla_{\partial_\mu}\stackrel{}{=}\delta^\lambda_\mu \nabla_\lambda\stackrel{?}{=} \nabla_\mu, \quad \nabla_{\partial_\nu}=\delta^\lambda_\nu \nabla_\lambda \stackrel{?}{=}\nabla_\nu.
 $$
Now,  remembering  that  $[\partial_\mu,\partial_\nu]=0$, our  curvature definiition gives us
$$
 [\nabla_\mu,\nabla_\nu] Z^\lambda \stackrel{?}{=} Z^\alpha{R^\lambda}_{\alpha \mu\nu}.
 $$
If, however, we include   a Christoffel  symbol ${\Gamma^\alpha}_{\nu\mu}$ when  $\nabla_\mu$ acts from the left on the index $\nu$ on $\nabla_\nu$ and similarly a ${\Gamma^\alpha}_{\mu\nu}$ when $\nabla_\nu$ is on the left and acting on the index $\mu$,  we  end up with
$$
 [\nabla_\mu,\nabla_\nu] Z^\lambda \stackrel{?}{=} Z^\alpha{R^\lambda}_{\alpha \mu\nu}- {T^\sigma}_{\mu\nu} \nabla_\sigma Z^\lambda.
 $$
Which is equation is correct?  With the last version, remembering that
$$
 \nabla_X Y-\nabla_Y X= [X,Y] + T(X,Y),
 $$ we can use Liebnitz rule to find
$$
 [X^\mu\nabla_\mu,Y^\nu \nabla_\nu]Z^\lambda  = (\nabla_X Y-\nabla_YX)^\sigma \nabla_\sigma  Z^\lambda +X^\mu Y^\nu (Z^\alpha{R^\lambda}_{\alpha \mu\nu}- {T^\sigma}_{\mu\nu} \nabla_\sigma Z^\lambda)\nonumber\\
 = Z^\alpha{R^\lambda}_{\alpha \mu\nu}X^\mu Y^\nu + [X,Y]^\sigma \nabla_\sigma Z^\lambda, \nonumber
 $$
which reproduces the curvature definition for general vector fields $X$, $Y$.  Both formul\ae\ are correct in their own ways. The  difference lies  in whether we regard the $\mu$ on $\nabla_\mu$ as a shorthand  label specifying   the basis  vector  $ \partial_\mu$, or as an index on the numerical  component of a covector.


text:
Q: Why is CKEditor refusing my custom tag? With a custom CKEditor plugin I am trying to insert a custom HTML tag, but the tag gets removed as soon as it is inserted into the editor. My plugin.js file:
CKEDITOR.plugins.add( 'tweet', {
    icons: 'tweet',
    init: function( editor ) {
        editor.addCommand( 'insertTweet', {
            allowedContent: 'tweet[:id]',
            requiredContent: 'tweet',
            exec: function( editor ) {
                console.log('inserting');
                editor.insertHtml( '<tweet :id="\'123\'" />' );  // also tried <tweet />
                // editor.insertHtml( '[tweet :id="\'123\'" /]' ); // this works
            }
        });

        editor.ui.addButton( 'tweet', {
            label: 'Insert tweet',
            command: 'insertTweet',
            toolbar: 'insert,0'
        });
    }
});

The way I am adding the plugin for Bolt CMS backend:
function run() {
    var extrasAdded = false;

    if (typeof(CKEDITOR) == 'undefined') return;

    CKEDITOR.plugins.addExternal('tweet', '/assets/plugins/tweet/plugin.js', '');

    CKEDITOR.on('instanceReady', function (event, instance) {

        if (extrasAdded === true) return;

        var config = event.editor.config;

        config.toolbar.push(
            { name: 'insert', items: [ 'tweet' ] }
        );
        config.extraPlugins += (config.extraPlugins ? ',' : '') + 'tweet';
        config.extraAllowedContent = 'tweet';  // also tried 'tweet[:id]'

        CKEDITOR.instances['body'].destroy();
        CKEDITOR.replace('body', config);

        extrasAdded = true;
    });
}

if (document.readyState!='loading') run();
else document.addEventListener('DOMContentLoaded', run);

Can someone smart see why my tag is rejected?

A: So it turns out that we don't need the allowedContent or requiredContent properties in the plugin.js script. What did the trick was to tweak the editor's HTML DTD rules. In my case I got a reference to the editor in the instanceReady callback and tweeked it like this:
// name = 'tweet'
editor.filter.allow(name + "[!*]", name, true);

CKEDITOR.dtd[name] = CKEDITOR.dtd;
CKEDITOR.dtd.$empty[name] = 1; // allow self-closing tag
CKEDITOR.dtd.$blockLimit[name] = 1;
CKEDITOR.dtd.$nonEditable[name] = 1;
CKEDITOR.dtd.$object[name] = 1;
CKEDITOR.dtd.$inline[name] = 1; // $block won't work!

You can also see a full gist of it.


text:
Q: Triggering clicks in GTM using virtual view and counting them as a event goal in GA I am having trouble tracking a click using Google Tag Manager.
I have set up a click event, and a click trigger. The click trigger's conditions are:     Click Class- Equals - next-step`
Screenshots:
This is how I created the tag. This is the trigger
Currently the problem is that the trigger is not firing.

A: Your problem is occuring because there are two different elements that are able to be clicked: next-step and ng-binding.
If you click on the text itself, it will have the class ng-binding.

Whereas, if you click anywhere else on the button, it will have the class next-step.

Because your ng-binding is not a unique attribute to fire this event from, I would create a DataLayer variable (lets call it Parent Node Class) with the following selector:
gtm.element.parentNode.className

This will return the className of the parent node, reletive to the element clicked. This means that users clicking on ng-binding will have the Parent Node Class of 'next-step'.
Using this, you can have two triggers for your tag.
1) Click Classes equals next-step

2) Parent Node Class equals next-step

Because triggers work with an 'or' condition, this means that if either of these results are satisfied, then it will fire the tag.


text:
Q: Adding Global passwords to Jenkins using groovy Im provisioning my Jenkins using groovy, I need to configure Jenkins.
To be specific Manage Jenkins - configure system
Like Global password, Gitlab configuration and  Project configuration.
I'm new to groovy I have very less knowledge on groovy.
It would be really helpful if anyone can share groovy script to configure Jenkins?!

A: this is a great idea , I just did the same when we upgrade to Jenkins 2.
here are some links :
https://pghalliday.com/jenkins/groovy/sonar/chef/configuration/management/2014/09/21/some-useful-jenkins-groovy-scripts.html
https://github.com/DotCi/jenkinsci-dotci-example/blob/master/configure-dotci.groovy
https://gist.github.com/vrivellino/97954495938e38421ba4504049fd44ea
BTW , you can install your plugins using CLI it will save you time in the future.
if you have specific question , let me know
Thanks , Mor


text:
Q: Add extra items in list comprehension I have this kind of list:
a = ['orange', 'apple', 'banana']

and from this I build another list of tuples using a simple list comprehension:
b = [(key, key.upper()) for key in a]

The result is something like this:
b = [('orange', 'ORANGE'), ('apple', 'APPLE'), ('banana', 'BANANA')]

Now I need to insert another tuple at the beginning (or at the end for example) of the newly generated b list: ('---', None).
The two easy solutions would be:
# Solution 1
b = [('---', None)] + b

# Solution 2
b.insert(0, ('---', None))

Question:
Is there a way to accomplish the same thing directly from the list comprehension construct?
Can something like this (pseudocode) could be possible in python?
b = [('---', None), (key, key.upper()) for key in a]

A: Premature optimization is the root of all evil
The operation you have identified is most likely not your bottleneck. Using a clever list comprehension which allows you to use one expression does not solve a problem relating to performance. Below is a demonstration with 3mio items in your list.
If you need to repeatedly add items to your list to the left, I recommend you use collections.deque. Note that deque has O(1) complexity for appendleft while lists have O(n) performance for insert(0, value).
from collections import deque

a = ['orange', 'apple', 'banana']*1000000

def l3v(a):
    return [('---', None), *((key, key.upper()) for key in a)]

def jpp(a):
    b = deque([(key, key.upper()) for key in a])
    b.appendleft(('---', None))
    return list(b)

def original(a):
    return [('---', None)] + [(key, key.upper()) for key in a]

def original2(a):
    b = [(key, key.upper()) for key in a]
    b.insert(0, ('---', None))
    return b

%timeit l3v(a)        # 1.35 s per loop
%timeit jpp(a)        # 1.23 s per loop
%timeit original(a)   # 1.17 s per loop
%timeit original2(a)  # 1.14 s per loop

A: Yes, by using generator comprehensions:
b = [('---', None), *((key, key.upper()) for key in a)]

Instead of using a generator comprehension, you could also use a list comprehension. The benefit of using generator comprehensions is that they don't create a new list, but hand out items one by one. If your list (a) is big, that can make an impact on memory use and/or performance.
Using the asterisk (the "splat operator") to unpack such a sequence is PEP 448 — Additional Unpacking Generalizations. It allows you to use the * not just in function calls, but in list, generator, and set comprehensions (the same applying to ** and dictionary comprehensions).

A: Try an if else with the list comprehension. Like below
b = [(a[i],a[i].upper()) if i < len(a) else ('---',None)  for i in range(len(a)+1)]

Hope it helps.
Happy Coding :)


text:
Q: Simple probability question involving "either...or..." statement Here is the  question :
A card is drawn from a standard deck of 52 cards.
Find the probability that the card is either a five
or a black card.  $[A] \frac4{
13}[B] \frac{15}{26}
[C] \frac{17}{52}
[D] \frac{7}{13} $
I thought you have 2 cards that are both five and black, they should not be included in  "either five  or black " case, the probability is $\frac{4+26-2-2}{52}=\frac{1}{2}$. However,  this is not one of the 4 choices. The only one that seems to be right is [D] $\frac{7}{13}$, in which case the two cards that are both 5 and black are included in the calculation. Should or shouldn't we include these two cards?


text:
Q: Debugging step in and step out is slower in VS2015 i am using VS2015 and developing a UWP project. when i try to debug my code by using breakpoint, it takes upto 2 second for debugging a single line. Whether i need to change any settings to make it faster?
Note: I tried to set the below options
1.Uncheck the option -> Enable Property evaluation and other implicit function calls.

2.Check the option -> Use Managed Compatibility code.

3.Check the option -> Automatically adjust visual experience based on client performance

I tried to set the above options, but still it makes slower while debugging. Is there any option will improve performance while debugging in VS2015

A: Please disable the symbols server under TOOLS->Options->Debugging->Symbols.
A blog also shared us some suggestions which could make debugging faster:
https://blogs.msdn.microsoft.com/visualstudioalm/2015/03/03/make-debugging-faster-with-visual-studio/


text:
Q: What is the correct declaration for SendMessage and how do I convert my code to use its parameters? I am confused by various declarations SendMessage.  How do I know which one is correct?
In my c# winforms application (Windows 7) I use the following;
public class NativeMethods
{
    [DllImport("user32.dll")]
    // Currently uses
    public static extern int SendMessage(IntPtr hWnd, uint wMsg, int wParam, int lParam);
    // Think I should probably be using
    // public static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);
}

but the code that calls SendMessage is
 NativeMethods.SendMessage(this.tv.Handle, 277, 1, 0);

How do I figure out what parameters to use so that I can switch to the other declaration?

A: Look at the header files or at the MSDN documentation, and then you need a bit of extrapolation.
In your case, the actual C prototype is:
LRESULT WINAPI SendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);

And the relevant typedefs are:
typedef unsigned int UINT;
typedef LONG_PTR LPARAM;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LRESULT;

So the correct C# declaration would be:
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg,
                                UIntPtr wParam, IntPtr lParam);

The IntPtr and UIntPtr have constructors that take a plain integer, so there is not problem to call it directly:
NativeMethods.SendMessage(this.tv.Handle, 277, new UIntPtr(1), IntPtr.Zero);

Actually, everything works as long as you respect the size of each of the parameters, but you have to be careful if you want your code to be portable between 32 and 64 bits.

A: Kirsten, this is an interop problem. Most C++ samples specify ints or uints for the parameters of SendMessage; the way C# would interpret the value doesn't really doesn't matter so long as

*

*the bit patterns you pass are correct

*the sizes are correct

*the marshalling is appropriate

There's actually quite a bit to come to grips with here, too much for a stack overflow answer. The words you need with google are "interop" and "marshalling".
You should also be aware that you may have problems sending messages cross-process unless the sender has elevated permissions. And SendMessage is synchronous. Are you sure you don't want PostMessage?


text:
Q: Why I should avoid loops in shells? The following link recommends against using loops in shells.
bash variables in for loop range
Why is this? Here is an example loop I just happened to be looking at when I
came across that answer:
find /etc/postinstall -name '*.sh' | while read script
do
  echo Running $script ...
  $script
  mv $script $script.done
done

A: Two application types come to my mind where shell loops are not considered to be the best approach. The first is data processing; many tools (like sed, awk, perl, etc.) do the loop implicitly and much more performant. The second is (like in your sample code), where some code is executed for a set of files, where find with the -exec switch can also already execute commands (also a shell) with less problems and overhead. There are probably more cases, but those two mentioned should already be enlightening. That said; shell loops are not inherently bad, or somesuch. Just take other options (like the two mentioned) into your consideration.

A: Shell is a terrible programing language, but it is very handy. I write a lot of shell scripts, and on occasion I use loops. I have a script that takes a couple hours to execute. It needs rewritten in something else. If you have a loop in your shell script it is an indicator that it might be time to start thinking about rewriting that script before it becomes completely unmanageable.


text:
Q: Editing external libraries in Android Studio I am using an image carousel library that I snagged off of github, but there are a few things I would like to change in the code. I have imported it using the compile 'com.theartofdev.edmodo:android-image-cropper:2.6.+' command. Is that code available for me to edit somehow? Or is it downloaded from github every time I run my code?

A: I solved this way. Fork library project. Then clone it (In Android Studio, File -> New -> Project from Version Control -> put the link of your repository that you forked and open it). Edit it and commit it to your master branch. Then push it to your master branch. And finally find snapshot version of that library. For example if you use JitPack. Go to jitpack.io website and search for your repository (forked version with your username). And there go to commits section and get latest version that you committed. And use that library dependency in your project instead of original repo.

A: For this you need to import it as lib and modify as you like:
To import the library to Android Studio, there are two methods that can work.
Method 1:

*

*Open your project in Android Studio

*Download the library (using Git, or a zip archive to unzip)

*Create a folder "subProject" in your project

*Copy and paste the FreemiumLibrary folder to your subProject folder

*On the root of your project directory create/modify the settings.gradle file. It should contain something like the following:

include 'MyApp', ':subProject:FreemiumLibrary'

*gradle clean & build/close the project and reopen/re-import it.

*Edit your project's build.gradle to add this in the "dependencies" section:

dependencies {
//...
    compile project(':subProject:FreemiumLibrary')
}

*Edit your App Activities to extend AdsFragmentActivity instead of Activity.

*Edit the library if you want to use it with ActionBarCompat
Method 2:

*

*Open your project in Android Studio

*Download the library (using Git, or a zip archive to unzip)

*Go to File > New > Import-Module and import the library as a module

*Right-click your app in project view and select "Open Module Settings"

*Click the "Dependencies" tab and then the '+' button

*Select "Module Dependency"

*Select "Freemium Library" (not Freemium Library Project)

*Modify your App Activities to extend AdsFragmentActivity instead of Activity.

*Modify the library if you want to use it with ActionBarCompat

A: My approach was similar to @Shailendra Madda's with some minor differences.
At first I downloaded/cloned the project in my PC. Let's say the library's name is 'VideoPlayer'.
I ensured that the module level gradle of VideoPlayer did not contain applicationId. I also ensured that it contained
  plugins {
      id 'com.android.library'
  }

instead of
  plugins {
    id 'com.android.application'
  }

Now the library is ready for import.
In order to import this library into my project, I went to File -> New -> Import Module.
From there, I selected the directory of VideoPlayer. The VideoPlayer project that I downloaded had four modules. In cases like this you can simply select the modules you want to import. I selected the module named core and clicked finish. [Note: instead of selecting VideoPlayer folder from the explorer, you can also select the 'core' folder].
After importing the module, go to File -> Project Structure (or Ctrl+Alt+Shift+S) and select dependencies. From modules section, select app (here, app is the name of my project's module) and then select the + icon in 'declared dependencies' section and select Module Dependency. From the new window, select the module you wish to add as dependency (in my case, it is 'core').
After you click Apply and/or OK, android studio will modify relevant gradle files, so you don't have to worrry about it. And the project will be added as a dependency in your project.
Check this page to learn more: https://developer.android.com/studio/projects/android-library


text:
Q: Internet Time tab has disappeared from the Date and Time applet of the Control Panel Previously, there was an Internet Time tab on the Date and Time applet of the Control Panel, wherein one could force a query of an internet time server and also type in a different server from the ones supplied. However, this tab has now disappeared, and I need to have it back. I should mention that this machine has never been part of a domain, since it seems that machines that are such do not have such a tab. I should be obliged to anyone who can help me restore the missing tab.
Windows 7 Home Premium
Service Pack 1

A: If your computer is not a domain member, the Windows Time service can be set to Manual startup mode and should ordinarily not be running.
Try just stopping the service to see if the additional tab returns. You may have to go as far as setting it to Manual startup and rebooting.

Additionally, the registry key HKEY\Software\Microsoft\Windows\CurrentVersion\DateTime\Servers needs to be configured correctly in order to make it work. In the screen shot below, there are six available time servers listed, but the (Default) value is empty.

The (Default) value needs to have something in it. Otherwise, the Internet Time tab will not show. Specifically, the (Default) value needs to have the name of one of the other values in this Servers key. It cannot have an invalid value. Using the screen shot again, a value of 6 would be invalid, because there is no corresponding time server labelled "6." On my machine, the (Default) value is 1, which means my computer gets time from time.windows.com.

A: It sounds like the computer thinks it is part of a Domain.  As you mentioned the internet time tab is disabled for domain environments.  The computer will sync with the domain controller and there isn't a way to have it sync to the internet in domains.
I think this article from Microsoft might help.  It provides a number of registry values that effect this area.
http://support.microsoft.com/kb/816042
Also, you might be able to run a few commands from command prompt to resolve this too:
w32tm /config /syncfromflags:MANUAL /manualpeerlist:time.nist.gov
w32tm /config /update

A: In previous versions of Windows, the Internet Time tab was not built-into the Date and Time applet,
but was added there by the Windows Time service. In Windows 7 I found weird things happening,
such as seeing the service running although it was set to Manual, or of seeing Internet Time displayed and time-sync done even when the service is disabled.
I'm starting to think that Windows 7 will start the service when time-sync is to be done,
no matter what is specified as its Startup type. I still don't know whether the Internet Time tab
is now built-in or is still being added there by the service on its first run.
It seems however likely to me that there is still some connection between the service
and the Internet Time tab, so that some corruption caused this mechanism to malfunction.
The Time service is defined in the registry at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time. In case that the problem is caused by registry corruption, I have posted this key's contents on pastebin for comparison. Do not import it blindly into the registry (or at least not before saving yours).
Otherwise, all I can suggest are general troubleshooting steps such as the System File Checker.

A: My computer is part of a Domain and the tab is not visible. If I disable the network card, then the tab can be seen/accessed. Re-enabling the NIC turns the tab invisible again.


text:
Q: I have a simple site and want to change my font-size when the mouse is over but this code don't work.Why? document.getElementById("change").onmouseover = function() {
  changeingFont();
};
document.getElementById("change").onmouseout = function() {
  normalFont();
};
function changeingFont() {
  document.getElementById("chnage").style.fontSize = "25px";
}
function normalFont() {
  document.getElementById("change").style.fontSize = "15px";
}

For code

I have hyperlinks in HTML(a tag) and when i hover the text with mouse the text have to be larger.And this doesn't work...I don't know why...May someone help me ?

A: The immediate answer was a typo, but I wanted to offer a little more to help you improve. You're overriding the onmouseover and onmouseout event handlers, but we could be a little nicer and use listeners:
const change = document.getElementById("change");
change.addEventListener("mouseover", () => changeFont());
change.addEventListener("mouseout", () => normalFont());

function changeFont() {
    change.style.fontSize = "25px";
}

function normalFont() {
    change.style.fontSize = "15px";
}


text:
Q: datatype text in mysql (Ruby on Rails) In development I used sqlite3 and I was writing a blog application. So for the blog articles, I had datatype text which worked fine. I was able to write really long articles, never had a problem. Switch over to production using MySQL and now my articles are getting truncated after around 250 characters.
Does anyone know what I need to do and/or change to get MySQL to behave like sqlite3 was, allowing really large bodies of text?
Thank you.
db/schema.rb:
ActiveRecord::Schema.define(:version => 20110307222323) do

  create_table "articles", :force => true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.string   "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "category_id"
    t.string   "url"
  end
end

A: May be you should replace
t.string   :body

with
t.text   :body

A: You must to change:
 t.text :body #change here

You can find more information about data type comparisons here


text:
Q: Add an element after a specific row in table I have a XML with ROW and ENTRY, But I need to add a ENTRY only after the first ROW.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl"?>

<TGROUP COLS="3">
<COLSPEC COLNAME="col1" COLWIDTH="5cm"/>
<COLSPEC COLNAME="col2" COLWIDTH="6.00cm"/>
<COLSPEC COLNAME="col3" COLWIDTH="5.91cm"/>

<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA><EMPHASIS>TA</EMPHASIS></PARA></ENTRY>
<ENTRY COLSEP="1" ROWSEP="1"><PARA><EMPHASIS>TB</EMPHASIS></PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA><EMPHASIS>TC</EMPHASIS></PARA></ENTRY>
</ROW>

<ROW>
<ENTRY COLSEP="1" MOREROWS="13" ROWSEP="1"><PARA>A</PARA></ENTRY>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>B</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>C</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A1</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>B1</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A2</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>B2</PARA></ENTRY>
</ROW>
<ROW>

<ENTRY COLSEP="1" ROWSEP="1"><PARA>A4</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A5</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A5<PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A6</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A6</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A7</PARA></ENTRY>
</ROW>

</TGROUP>

XSLT version 1.0
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="TABLE/*/ROW">
    <ENTRY>
      <xsl:apply-templates select="node()|@*"/>
    </ENTRY>
  </xsl:template>
    </xsl:stylesheet>

Desired Output:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl"?>

<TGROUP COLS="3">
<COLSPEC COLNAME="col1" COLWIDTH="5cm"/>
<COLSPEC COLNAME="col2" COLWIDTH="6.00cm"/>
<COLSPEC COLNAME="col3" COLWIDTH="5.91cm"/>

<ROW>
<ENTRY COLSEP="1" ROWSEP="1"><PARA><EMPHASIS>TA</EMPHASIS></PARA></ENTRY>
<ENTRY COLSEP="1" ROWSEP="1"><PARA><EMPHASIS>TB</EMPHASIS></PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA><EMPHASIS>TC</EMPHASIS></PARA></ENTRY>
</ROW>

<ROW>
<ENTRY COLSEP="1" MOREROWS="13" ROWSEP="1"><PARA>A</PARA></ENTRY>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>B</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>C</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY/>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A1</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>B1</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY/>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A2</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>B2</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY/>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A4</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A5</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY/>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A5<PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A6</PARA></ENTRY>
</ROW>
<ROW>
<ENTRY/>
<ENTRY COLSEP="1" ROWSEP="1"><PARA>A6</PARA></ENTRY>
<ENTRY COLSEP="0" ROWSEP="1"><PARA>A7</PARA></ENTRY>
</ROW>

</TGROUP>

The element ENTRY should only be added after the first ROW.

Thanks for your support.

A: Replace your temaplate <xsl:template match="TABLE/*/ROW"> with:
<xsl:template match="TBODY/ROW[position() > 1]">
    <xsl:element name="{name()}">
        <xsl:apply-templates select="@*"/>
        <xsl:element name="ENTRY"/>
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

Matches all TBODY/ROW with position greater than 1; Create the element ROW and copy his possible attributes. Create the Element ENTRY and go ahead with all childs of context-node.


text:
Q: Can JSF applications be configured to run without using internet connections? Is it possible to configure JSF applications to run without internet access after deploying to local server?
xmlns="http://www.w3.org/1999/xhtml
xmlns:h="http://xmlns.jcp.org/jsf/html

Would above XML namespaces pose any problem after deployment?

A: Those links don't require Internet access. They could just as well be gobbledygook. They're only there to provide a long enough namespace name so as to be unambiguous.

A: Those are not-followed URLs for naming, without validation AFAIK.
For other external XML/DTD links you can use XML catalogs, which for XHTML heavily speeds up things (HTML has enormous entities). There you map URLs to local files copied from those URLs.


text:
Q: Why does file_put_contents have permission issues when run from the browser? This question has been asked a couple of times up here, but I haven't found a solution yet. I have a Fedora 19 LAMP server and I just want to run the simple command: file_put_contents('test.txt', 'Hello there'); in order to confirm that my web server can use PHP to write data to files. I'm having trouble figuring out a proper permissions scheme. To start, just for development, Apache's document root is /var/www/html. This directory was originally owned by a user and group called www-data, but I changed the directory's group to the primary group of the owner of the httpd process, named apache. It is this owner that is active when PHP runs. I've confirmed this with the following:

As you see, the process owner is apache, the current direcory is /var/www/html/php-console. The directory is owned by www-data and members of the group apache have full access to it.
I have tried the following to get PHP to actually create a file in this location, but to no avail:
chmod 777 /var/www/html/php-console

chown apache /var/www/html/php-console
chgrp apache /var/www/html/php-console

cd /var/www/html; > test.txt; chmod 777 test.txt;

Nothing will work while this script is run from the browser. However, when I use file_put_contents with the PHP CLI, it works just like I would expect, provided that the user I'm entering commands as or its group has write permissions to this directory or test file.

So, from the command line, you see how www-data has read, write, and execute permissions to the folder I'm in. posix_getpwuid and posix_geteuid help you to find the owner of the Apache/PHP process, which in this case is the same as the user logged into the console. file_put_contents succesfully writes 8 bytes to the specified file. If I change the group or owner and group to something else, I get Permission denied, which absolutely makes sense.
If this works on the command line, then why not when I really want it to, i.e., while actually serving web pages???

A: Because you forgot to read the httpd_selinux(8) man page and give the directory the appropriate file context to allow the web server to write files there.


text:
Q: The relationship between the function and the conjugate Let $f:E\longrightarrow [-\infty,\infty]$ defined by
$$ f^*(y)=max_{x\in {E}}\{<y,x>-f(x)\}$$
is called the conjugate function of $f$.
where   $y\in{E^*}$ and $E,E^*$ are finite-dimensional real inner product vector spaces with inner product $<.,.>$ and norm $||.||$
Now, I want to know the relationship between the function and the conjugate function.
What is the relationship between the function diagram and the conjugate function diagram?


text:
Q: Получить кропп, меньше операций list($width, $height, $x, $y) = explode(':', explode('=', exec("ffmpeg -i {$vd} -ss 15 -t 30 -vf cropdetect -f null - 2>&1 | awk '/crop/ { print  $NF }' | tail -1"))[1]);

В целом та работает, получаю координаты кропа, единственное смущает - множество делений, explode.
Собственно вопрос в том, возможно ли иначе получить кроп, так же в каждую переменную запонить.
Операций бы поменьше хотя бы...


text:
Q: Is there a better way to persist a map with the value being a set? I'm looked a lot into being able to use Hibernate to persist a map like Map<String, Set<Entity>> with little luck (especially since I want it all to be on one table).
Mapping MultiMaps with Hibernate is the thing that seems to get referenced the most, which describes in detail how to go about implementing this using a UserCollectionType.
I was wondering, since that was written over four years ago, is there any better way of doing it now?
So, for example, I would like to have on EntityA a map like Map<String, Set/List<EntityB>>.
There would be two tables: EntityA and EntityB (with EntityB having a foreign key back to EntityA).
I don't want any intermediate tables.

A: The way how its done on my current project is that we transforming beans/collections to xml using xstream:
public static String toXML(Object instance) {
    XStream xs = new XStream();
    StringWriter writer = new StringWriter();
    xs.marshal(instance, new CompactWriter(writer));
    return writer.toString();
}

and then using Lob type in hibernate for persisting :
@Lob
@Column(nullable = false)
private String data;

I found this approach very generic and you could effectively implement flexible key/value storage with it. You you don't like XML format then Xstream framework has inbuilt driver for transforming objects to JSON. Give it a try, its really cool.
Cheers
EDIT: Response to comment.
Yes, if you want to overcome limitations of classic approach you are probably sacrifice something like indexing and/or search. You stil could implement indexing/searching/foreign/child relationships thru collections/generic entity beans by yourself - just maintain separate key/value table with property name/property value(s) for which you think search is needed.
I've seen number of database designs for products where flexible and dynamic(i.e. creation new attributes for domain objects without downtime) schema is needed and many of them use key/value tables for storing domain attributes and references from owner objects to child one. Those products cost millions of dollars (banking/telco) so I guess this design is already proven to be effective.
Sorry, that's not answer to your original question since you asked about solution without intermediate tables.

A: It depends :) When things are getting complex, you should understand what your application is doing.
In some situation, you may represent your Set as a TreeSet, and represent this TreeSet in an ordered coded String, such as ["1", "8", "12"] where 1, 8, 12 are primary keys, and then let's write code !
Obviously, it's not a general answer for, in my opinion, a too general question.


text:
Q: Draw Spectrogram STFT in C#, what function can I use? Assume that I have STFT (short time fourier transform) data, how would these can be displayed on the picture box as spectrogram of frequency vs time, what function in C# can I use ?

A: The WPF Sound Visualization Library isn't bad for this type of thing, although it doesn't have a spectrograph control.

*

*WPF Sound Visualization Library

*Codeplex project with source
While not a .NET implementation Audacity is open source.  So you may be able to poke around in there and see how they created their Spectrograph control

*

*Audacity Source
There is also some Matlab code here that should allow you to get to where you need

*

*Matlab code Stanford.edu


text:
Q: Python's dill one-time use of default argument in a defaultdict I'm trying to wrap my head around this odd problem that I'm facing. Let's say that we have a following instance of the defaultdict object:
import dill
from collections import defaultdict

a = 1
b = 2
default_value = a/b

dict_with_default = defaultdict(lambda: default_value)

dict_with_default['a'] = 1.2
dict_with_default['b'] = 3.5
dict_with_default['c'] = 0.25

Let's look how the dictionary looks like:
defaultdict(<function <lambda> at 0x7f860c97be18>, {'a': 1.2, 'b': 3.5, 'c': 0.25})

Before saving to a dill object I want to check if the dictionary works correctly - it does and 'd' is added:
print("d: ", dict_with_default['d'])

The dictionary looks like this now:
defaultdict(<function <lambda> at 0x7f860c97be18>, {'a': 1.2, 'b': 3.5, 'c': 0.25, 'd': 0.5})

Since I must save a dictionary to a file (in order to transfer it to a different script) I save it to a dill object:
with open('./pickles/simple_dict_dill.p', 'wb') as file:
    dill.dump(dict_with_default, file, protocol=dill.HIGHEST_PROTOCOL)

Let's now turn our attention to the different script I've mentioned:
import dill

with open('./pickles/simple_dict_dill.p', 'rb') as file:
    simple_dict_dill = dill.load(file)

print("a:", simple_dict_dill['a'])
print("d:", simple_dict_dill['d'])
print("e:", simple_dict_dill['e']) # gives error

The line print("e:", simple_dict_dill['e']) gives the following error even though absent key access is handled by the lambda: default_value:
NameError: name 'default_value' is not defined

I thought dill can serialize lambda functions but it turns out there's a problem with it.

A: I'm the dill author.  It's due to how a lambda is serialized when defined outside the global dictionary.  You can avoid this error in two ways:  (1) use the recurse setting, or (2) define the lambda in the global dict with no dangling pointers.
For example:
>>> import dill
>>> dill.settings['recurse'] = True
>>> from collections import defaultdict
>>> a = 1
>>> b = 2
>>> f = lambda: a/b
>>> d = defaultdict(f)
>>> d['a'] = 3
>>> d['b'] = 4
>>> dill.dumps(d)
b'\x80\x03ccollections\ndefaultdict\nq\x00cdill._dill\n_create_function\nq\x01(cdill._dill\n_load_type\nq\x02X\x08\x00\x00\x00CodeTypeq\x03\x85q\x04Rq\x05(K\x00K\x00K\x00K\x02KCC\x08t\x00t\x01\x1b\x00S\x00q\x06N\x85q\x07X\x01\x00\x00\x00aq\x08X\x01\x00\x00\x00bq\t\x86q\n)X\x07\x00\x00\x00<stdin>q\x0bX\x08\x00\x00\x00<lambda>q\x0cK\x01C\x00q\r))tq\x0eRq\x0f}q\x10(h\x08K\x01h\tK\x02uh\x0cNN}q\x11tq\x12Rq\x13\x85q\x14Rq\x15(h\x08K\x03h\tK\x04u.'

Then I cut-N-paste the string that's produced (instead of writing to a file... it's the same thing) into a new python session.
$ python
Python 3.6.9 (default, Jul  6 2019, 02:58:03)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> d = dill.loads(b'\x80\x03ccollections\ndefaultdict\nq\x00cdill._dill\n_create_function\nq\x01(cdill._dill\n_load_type\nq\x02X\x08\x00\x00\x00CodeTypeq\x03\x85q\x04Rq\x05(K\x00K\x00K\x00K\x02KCC\x08t\x00t\x01\x1b\x00S\x00q\x06N\x85q\x07X\x01\x00\x00\x00aq\x08X\x01\x00\x00\x00bq\t\x86q\n)X\x07\x00\x00\x00<stdin>q\x0bX\x08\x00\x00\x00<lambda>q\x0cK\x01C\x00q\r))tq\x0eRq\x0f}q\x10(h\x08K\x01h\tK\x02uh\x0cNN}q\x11tq\x12Rq\x13\x85q\x14Rq\x15(h\x08K\x03h\tK\x04u.')
>>> d
defaultdict(<function <lambda> at 0x101d8d048>, {'a': 3, 'b': 4})
>>> d['a']
3
>>> d['c']
0.5
>>>

IF you don't use the recurse setting, then you'd have to use:
>>> f = lambda: 1/2
>>> d = defaultdict(f)

when you create the defaultdict.
Of course, dill should be able to deal with the pointer references from a lambda better, but there are cases where it can't yet.


text:
Q: Remove kdewallet password without being prompted for wifi password I would like to boot my computer and it automatically connect to the wifi without typing in any passwords. I've found online how to disable the kdewallet using kwalletmanager and that works - but if I do that I'm prompted to enter the wifi password every time instead of the kdewallet password.
Is there a way to not have to type neither the kdewallet password nor the wifi password every time I turn on the computer?

A: According to Elder Geek in answer to a similar question from last year, "If that version of KDE has Network manager try opening network connections, go to the wireless tab and edit (or add) your wireless network info, making sure to check the box "available to all users." It won't ask for the wireless password again."