text:
Q: angular-ui-router Gone Wrong I have tried this multiple times to no avail. Here is my set-up:
Angular: 1.5.7
angular-ui-router: 0.3.1
Here are my files:
/demo
  /node_modules
    (module files)
  -index.html
  -route1.html
  -route1.list.html
  -route2.html
  -route2.list.html

Here are the file contents:
index.html
<!doctype html>

    <title>AngularJS ui-router Demo</title>
    <link href="<path to bootstrap css file>" rel="stylesheet" />

        Quick Start

Route 1

Route 2

The route1.html, route1.list.html, route2.html and route2.list.html are all simple H1 tag titles with a P tag of dummy text, nothing special.
This code structure was modified from the original AngularJS ui-router examples.
There doesn't seem to be anything wrong with the code. If anyone notices any bug or gremlin, please advise.
Thanks!

A: The problem is here:
var myapp = angular.module('myapp', ['ui-router']);

The module name is ui.router, so change it to:
var myapp = angular.module('myapp', ['ui.router']);


text:
Q: Pasting Excel Data to Only Matching Values I'm struggling to find an answer to my problem. My problem is that I have a column of unique identifiers (Excel File A). On a separate excel file (Excel File B) I have the same unique identifiers but some are missing or are not relevant in this file.
I need to take the data in Excel File B and match them to Excel File A. But I can't simply copy and paste because they're not in the same order and some are missing.
How do I solve this?

A: =Vlookup('Excel File A!A1','Excel File B!A:A',1,FALSE)

Vlookup
1. First Part = What your looking for
2. Second Part = Column you are looking in
3. Third Part = Column number to look in
4. Fourth Part = FALSE means EXACT MATCH

First Workbook

Second Workbook

Formula

Result

A: You will need to follow a few steps:

*

*insert =match(symbol, List looking at,0) in the column that you
are looking to try to filter

*go to the data tab an select filter

*click on the drop down and unselect #NA (and any you don't want to
copy)

*select all of the filtered results and copy them

*paste them where you would
like.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Left join using a temporary column I want to do left join on two tables but the second table doesn't have required column.
So a temporary column (concat of two column values in second table) is needed in order to do the left join.
select a.name, a.number, b.id, b.sub_num
from tableA a left join
     tableB b
     on a.number = (select concat(id,'-',Cast(sub_num as varchar)) as tempcol from tableB);

Obviously this shows error:

SUBQUERY_MULTIPLE_ROWS: Scalar sub-query has returned multiple rows.

But I don't need this tempcol to show in the main query nor save it as new column in any tables here.
What is the better way to do left join on temporary column?

A: You don't need a subquery for the join.  Just use the expression:
select a.name, a.number, b.id, b.sub_num
from tableA a left join
     tableB b
     on a.number = concat(id, '-', sub_num);

If you like, you can use a subquery:
select . . .
from tableA a left join
     (select b.*, concat(id, '-', sub_num) as tempcol
      from tableB b
     ) b
     on a.number = b.tempcol;


text:
Q: Priority queue with two priority values As it is good known, elements which are inserted to the priority queue have a value which determines its priority. For example if I have five elements A,B,C,D,E with priorities (let's call this priority values priorityI):
A = 10, B = 5, C = 1, D = 3, E = 2.
But how can I write a priority queue where I can define two priority values, I mean:
if two elements has the same value of priorityI, then value priorityII decides which element should be taken first, like for example:
element A has priorityI = 3, and prioriotyII = 5
element B has priorityI = 3, and prioriotyII = 1

then first element B will be taken from the queue first.

A: Starting from Python2.6, you can use Queue.PriorityQueue.
Items inserted into the queue are sorted based on their __cmp__ method, so just implement one for the class whose objects are to be inserted into the queue.
Note that if your items consist of tuples of objects, you don't need to implement a container class for the tuple, as the built in tuple comparison implementation probably fits your needs, as stated above (pop the lower value item first). Though, you might need to implement the __cmp__ method for the class whose objects reside in the tuple.
>>> from Queue import PriorityQueue
>>> priority_queue = PriorityQueue()
>>> priority_queue.put((1, 2))
>>> priority_queue.put((1, 1))
>>> priority_queue.get()
(1, 1)
>>> priority_queue.get()
(1, 2)

EDIT:  As @Blckknght noted, if your priority queue is only going to be used by a single thread, the heapq module, available from Python2.3, is the preferred solution. If so, please refer to his answer.

A: The usual way to do this is to make your priority value a tuple of your two priorities. Python sorts tuples lexographically, so it first will compare the first tuple item of each priority, and only if they are equal will the next items be compared.
The usual way to make a priority queue in Python is using the heapq module's functions to manipulate a list. Since the whole value is compared, we can simply put our two priorities along with a value into a single tuple:
import heapq

q = []  # the queue is a regular list

A = (3, 5, "Element A")  # our first item, a three-tuple with two priorities and a value
B = (3, 1, "Element B")  # a second item

heapq.heappush(q, A)  # push the items into the queue
heapq.heappush(q, B)

print(heapq.heappop(q)[2])  # pop the highest priority item and print its value

This prints "Element B".


text:
Q: Which gives a more accurate location? Which of these two methods is the more accurate one in determining user location?
// First
[locationManager startUpdatingLocation]

// Second
[locationManager startMonitoringSignificantLocationChanges]

A: According to the Apple CoreLocation documentation, startUpdatingLocation is more accurate. From the documentation:

You start standard location services by calling the startUpdatingLocation method. This service is most appropriate for applications that need more fine-grained control over the delivery of location events. Specifically, it takes into account the values in the desiredAccuracy and distanceFilter property to determine when to deliver new events. This is most appropriate for navigation applications or any application where high-precision location data or a regular stream of updates is required.

Contrast this with startMonitoringSignificantLocationChanges, which, according to the documentation, is more coarse and less accurate:

For applications that do not need a regular stream of location events, you should consider using the startMonitoringSignificantLocationChanges method to start the delivery of events instead. This method is more appropriate for the majority of applications that just need an initial user location fix and need updates only when the user moves a significant distance. This interface delivers new events only when it detects changes to the device's associated cell towers, resulting in less frequent updates and significantly better power usage.

You can control the accuracy of the location updates by using the desiredAccuracy property of the CLLocationManager class.

A: The first will give you updates in the desiredAccuracy set on the CLLocationManager class.  Also note that the distanceFilter is also important.
The significant location changes only gets fired if you move a "significant" distance, meaning very few updates.
Find the documentation here: http://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html


text:
Q: ImportXML query giving internal error I have just wrote my first ImportXML function to fetch the products like this.
I want to fetch all h3 elements. But its showing import internal error.
=ImportXML("https://www.google.com/products?q=ipod+nano","//h3")

I tried this query also to give all the h3 elements with class r, but its still showing the same error?
=ImportXML("https://www.google.com/products?q=ipod+nano",
                "//h3[@clsass='r')")

A: As pointed out by @MarcusRickert already, HTTPS pages might be a problem. Use HTTP versions of them:
=IMPORTXML("http://www.google.com/search?tbm=shop&q=ipod+nano&gws_rd=ssl", "//h3")

The result is (clipped):
Apple iPod Nano (6th Generation) - 8 GB - Graphite
Apple iPod Nano (3rd Generation) - 4 GB - Silver
Apple iPod Nano (4th Generation) - 8 GB - Pink
Apple iPod Nano (PRODUCT) RED (7th Generation) - 16 GB - Red
Apple iPod Nano (2nd Generation) - 4 GB - Silver
Apple iPod Nano (5th Generation) - 8 GB - Black
Apple iPod Nano (4th Generation) - 8 GB - Silver
Apple iPod Nano (7th Generation) - 16 GB - Space Gray
Apple iPod Nano (5th Generation) - 16 GB - Black
Apple iPod Nano (2nd Generation) - 4 GB - Green
.....

Do the same with your second query. Again, credit goes to Marcus for spotting two errors in your XPath expression. Try to be more careful with writing those expressions! Especially the clsass instead of class should be easy to catch if you look twice at your code.
=IMPORTXML("http://www.google.com/search?tbm=shop&q=ipod+nano&gws_rd=ssl", "//h3[@class='r']")

Result:
Apple iPod Nano (7th Generation) - 16 GB - Slate
Apple iPod Nano (6th Generation) - 8 GB - Graphite
Apple iPod Nano (3rd Generation) - 4 GB - Silver
Apple iPod Nano (4th Generation) - 8 GB - Pink
Apple iPod Nano (PRODUCT) RED (7th Generation) - 16 GB - Red
Apple iPod Nano (2nd Generation) - 4 GB - Silver
Apple iPod Nano (5th Generation) - 8 GB - Black
Apple iPod Nano (4th Generation) - 8 GB - Silver
Apple iPod Nano (7th Generation) - 16 GB - Space Gray
Apple iPod Nano (5th Generation) - 16 GB - Black
Apple iPod Nano (2nd Generation) - 4 GB - Green
Apple iPod Nano (3rd Generation) - 8 GB - Pink
Apple iPod Nano (PRODUCT) RED Special Edition (2nd Generation) - 4 ...
Apple iPod Nano (1st Generation) - 2 GB - White
Apple iPod nano (PRODUCT) RED Special Edition (6th Generation) - 8 ...
Apple iPod Nano (PRODUCT) RED Special Edition (3rd Generation) - 8 ...
Apple iPod Nano (PRODUCT) RED Special Edition (5th Generation) - 8 ...
Engraved Apple iPod Nano 16GB - 8th Gen
Apple 16GB iPod nano (Blue) Brand new
Apple iPod Nano (3rd Generation) - 8 GB - Green


text:
Q: Maven build zip file from generated resources How I can build zip file from generated resources?
Trying to generate a zip file for all generated files under target. Not sure where the problem is:
assembly:
<id>resources-bundle</id>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
    <fileSet>
        <outputDirectory>${project.basedir}/</outputDirectory>
        <directory>${project.basedir}/</directory>
        <includes>
            <include>**/target/dependency/**.properties</include>
        </includes>
    </fileSet>
</fileSets>

pom entry:
<plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.5.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <phase>validate</phase>
                    <id>archive</id>
                    <configuration>
                        <appendAssemblyId>true</appendAssemblyId>
                        <formats>
                            <format>zip</format>
                        </formats>
                        <descriptors>
                            <descriptor>assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>
            </executions>
        </plugin>

error I'm facing:
Failed to create assembly: Error creating assembly archive test-libs: You must set at least one file.

Any help much appreciated!
Thanks

A: Resolved!
assembly.xml::
        <fileSet>
        <outputDirectory>resources/</outputDirectory>
        <directory>${project.basedir}/target/dependency/</directory>
        <includes>
            <include>**/**.properties</include>
        </includes>
    </fileSet>

pom.xml:
<execution>
                    <id>pack-resources</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <appendAssemblyId>true</appendAssemblyId>
                        <formats>
                            <format>zip</format>
                        </formats>
                        <descriptors>
                            <descriptor>assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>

Thanks


text:
Q: Segmentation fault (core dumped) when calling LdapConnection.SendRequest(SearchRequest req) at System.DirectoryServices.Protocols on Ubuntu 18.04.4LTS When I try to get user information from Active Directory, LdapConnection.SendRequest(SearchRequest req) causes :
Segmentation fault (core dumped)
on an Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-147-generic x86_64).
If I remove the line
searchRequest.TimeLimit = new TimeSpan(0, 1, 0);
LdapPal.SearchDirectory method returns LdapError.TimeOut (-7). and throws :
System.DirectoryServices.Protocols.LdapException: The LDAP server returned an unknown error.
   at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)
   at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request)
   at ConsoleApp16.Program.GetUserDetailsFromLdap(String username) in D:\source\repos\ConsoleApp16\ConsoleApp16\Program.cs:line 47

Below code works without any problem on a Windows.
Verifying username and password by LdapConnection.Bind(new NetworkCredential(username, password, domainName)) works without any problem.
Below is the code:
    private static string _baseDn = "OU=org1,DC=org1,DC=com,DC=tr";
    private static LdapConnection _con = new(new LdapDirectoryIdentifier("org1.com.tr"), new NetworkCredential("#Username", "#Password", "#DomainName"));
    static void Main(string[] args)
    {
        _con.AuthType = AuthType.Basic;

        Console.ReadLine();
        Console.WriteLine("Hello World!");

        Console.WriteLine(TryLoginUser(@"#Username", "#Password","#DomainName"));

        Console.WriteLine(GetUserDetailsFromLdap(@"#Username").Email);
    }

    private static bool TryLoginUser(string username, string password, string domainName)
    {
        try
        {
            _con.Bind(new NetworkCredential(username, password, domainName));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
        return true;
    }

    private static LdapUser GetUserDetailsFromLdap(string username)
    {
        var searchFilter = $"(&sAMAccountName={username.Split('@')[0]})";

        var searchRequest = new SearchRequest(_baseDn, searchFilter, SearchScope.Subtree, new string[] { "mail", "givenName", "sn", "sAMAccountName" });
        searchRequest.TimeLimit = new TimeSpan(0, 1, 0);

        try
        {

            var response = (SearchResponse)_con.SendRequest(searchRequest);
            if (response?.ResultCode == ResultCode.Success)
            {
                var result = response?.Entries[0];
                return new LdapUser()
                {
                    Email = result.Attributes["mail"][0].ToString(),
                    FirstName = result.Attributes["givenName"][0].ToString(),
                    LastName = result.Attributes["sn"][0].ToString(),
                    UserName = result.Attributes["sAMAccountName"][0].ToString()
                };
            }
            else
            {
                return null;
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }
}

public class LdapUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
}

Configuration
System.DirectoryServices.Protocols version 5.0.0
Runtime : Microsoft.NETCore.App 5.0.7
Target Runtime : portable
Deployment Mode: Portable
Update
When using 6.0.0-preview.7.21377.19 version of System.DirectoryServices.Protocols without SearchRequest.TimeLimit property causes :
System.DirectoryServices.Protocols.LdapException: The search filter is invalid.
   at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)
   at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request)
   at ConsoleApp16.Program.GetUserDetailsFromLdap(String username) in D:\source\repos\ConsoleApp16\ConsoleApp16\Program.cs:line 47

private static LdapConnection _con = new(new LdapDirectoryIdentifier("org1.com.tr"));

bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);

var searchFilter =isWindows?$"(&sAMAccountName={username.Split('@')[0]})": $"(&(objectCategory=person)(objectclass=user)(sAMAccountName={username.Split('@')[0]}))";

If I set the searchFilter conditional to operating system, method executes successfully most of the time, even if I don't set credentials for LDAPConnection object.
However randomly it continues to throw
System.DirectoryServices.Protocols.LdapException: The LDAP server returned an unknown error.

A: When I set LdapConnection.SessionOptions.ProtocolVersion to 3, everything worked as expected on Linux also.


text:
Q: Ideal in $\mathbb{Z}[x]$ Is the set of polynomials $a_0+a_1x+\ldots+a_nx^n$, where $2^{k+1}$ divides $a_k$,
an ideal in $\mathbb{Z}[x]$? How should I think about this?

A: Can you se what happens when you multiply an element of that set by a polynomial; by $x$ for example?
Another approach, your set contains the constant $2$; if it were an ideal, it should contain all polynomials divisible by $2$. Does it?


text:
Q: Show next database values on button click I have made a quiz, but instead of showing all of the questions at once I want to show them 1 by 1. So question 1 is shown first and when the answer is submitted question 2 is shown etc. The questions and multiple choice answers are shown on the page from the database with sql statements. But I can't seem to manage it to show the questions after each other.The way the databasebase is setup is, there is a question with 4 options and a correct answer column. I want to show the question and the 4 options that go with that question. This is the code I use to show all the questions with the answers from the database, it would be nice if someone could help me with a way to show them one by one:
<?php
$conn = mysqli_connect("127.0.0.1", "root", "", "kinderboekenweek");

$sql = "SELECT * FROM questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

      $i =0;
     while($row = $result->fetch_assoc()) {

         echo " Vraag: ". $row["vraag"].

         "

 <input type='button' class='btn btn-default' name='Optie".$i."' value=".$row['optie1']." id='optie1".$i."'>
".

         "
 <input type='button' class='btn btn-default' name='Optie".$i."' value=". $row["optie2"]." id='optie2".$i."'>
 ".

         "
 <input type='button' class='btn btn-default' name='Optie".$i."' value=". $row["optie3"]." id='optie3".$i."'>
".

         "
 <input type='button' class='btn btn-default' name='Optie".$i."' value=". $row["optie4"]." id='optie4".$i."'>
".

         "

";
         $i++;
     }
} else {
     echo "0 results";

}


text:
Q: Exibir opção selecionada em select com JS Eu tenho um trecho de código onde eu desejo pegar o valor da option selecionada, com JavaScript, e dar um alert com esse valor. Entretanto, toda vez ele dá o valor como undefined. Eu fiz uma linha para colocar em um input também, só para testar, e não funcionou.
Aqui está o código:

$("select[name='estado']").change(function() {
    var estado = document.getElementsByTagName("estado").value;
    document.getElementById("teste").setAttribute("value", estado);
    alert('estado ' + estado);
});
<select id="txt-model" class="field-50" name="estado">
    <option value="">Selecione um Estado</option>
    <option value="AC">Acre</option>
    <option value="AL">Alagoas</option>
    <option value="AP">Amapá</option>
    //... O resto dos estados
</select>

<input type="text" id="teste" name="teste">

A: O target no seletor não está correto, uma forma é obter o valor direto pelo evento do elemento:

$("select[name='estado']").change(function() {
    var estado = this.value;
    alert('estado ' + estado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="txt-model" class="field-50" name="estado">
    <option value="">Selecione um Estado</option>
    <option value="AC">Acre</option>
    <option value="AL">Alagoas</option>
    <option value="AP">Amapá</option>
    //... O resto dos estados
</select>

<input type="text" id="teste" name="teste">

Um pouco sobre seletores.


text:
Q: How to update the global sass variable from a mixin
Note: Please Don't Mark it as duplicate, many like myself, are waiting for the answer. we've searched everywhere.

1) I have a global variable $global_var_bg defined as blue color in the scss file of a component.
2) I have a mixin function in the component's scss file which accepts the $theme argument, which is passed while the global theme changes for the app.
3) Inside the mixin function I change the global variable $global_var_bg.
4) Then access the global variable $global_var_bg inside an scss class.
5) finally I assign the class to a div element in the component.html, expecting $global_var_bg to be the modified background_color inside the mixin function.
6) but, its still $global_var_bg

Help me to solve this problem,
Note: I don't want to move the class inside the mixin function.

@import '~@angular/material/theming';

$global_var_bg: blue; //define a global variable

@mixin dashboard-component-theme($theme) {

  $background: map-get($theme, background);

  //modify the global variable inside the mixin function

  $global_var_bg: mat-color($background, background) !global;
}

//access the global variable inside a class
.some-class {
  background-color: $global_var_bg;
}
<!-- set the background color of the div -->
<!-- which I expect to be the theme's backround color -->
<!-- but still blue-->

<div class="some-class"> random text </div>

A: When dealing with theming not based on CSS Variables you could do:
Example using function map
//  –––––––––––––––––––––––––––––-
//  _theme.colors.scss
//  –––––––––––––––––––––––––––––-
//  default theme
$theme: light !default;

//  theme colors
$theme-colors: (
    light: (
       text: black,
       back: white
    ),
    dark: (
       text: white,
       back: black
    )
);

// color function returning the color value
// based on color name and theme
@function color($name, $theme: $theme){
    @return map-get(map-get($theme-colors, $theme), $name);
}

//  –––––––––––––––––––––––––––––-
//  _my.component.scss
//  –––––––––––––––––––––––––––––-
@import '_theme.colors.scss';

.class {
    color: color(text);       // black (using the default light theme)
    background: color(back);  // white (using the default light theme)
}

.class {
    color: color(text, dark);       // white (using the passed dark theme)
    background: color(back, dark);  // black (using the passed dark theme)
}

//  switching global theme will take effect in all
//  classes after the point of change
$theme: dark;

.class {
    color: color(text);       // white (using the now default dark theme)
    background: color(back);  // black (using the now default dark theme)
}

Example using theme mixin
//  –––––––––––––––––––––––––––––-
//  _theme.colors.scss
//  –––––––––––––––––––––––––––––-
//  default theme
$theme: light !default;

 @mixin theme($theme: $theme){

    @if $theme == light {
        $color-text: silver !global;
        $color-back: white !global;
    }
    @if $theme == dark {
        $color-text: black !global;
        $color-back: white !global;
    }

    //  passed content (classes)
    @content;
}

//  –––––––––––––––––––––––––––––-
//  _my.component.scss
//  –––––––––––––––––––––––––––––-
@import '_theme.colors.scss';

@include theme {
    .class {
        color: $color-text;       // black (using the default light theme)
        background: $color-back;  // white (using the default light theme)
    }
}

@include theme(dark) {
    .class {
        color: $color-text;       // white (using the passed dark theme)
        background: $color-back;  // black (using the passed dark theme)
    }
}

//  switching global theme will take effect in all
//  classes after the point of change
$theme: dark;

@include theme {
    .class {
        color: $color-text;       // white (using the now default dark theme)
        background: $color-back;  // black (using the now default dark theme)
    }
}

Note!
Changing theme at a global level could cause unforeseen problems (like when changing import order) – why you can chose not to expose it by defining the default inside the function and mixin
@function color($name, $theme: light){ ... }
@mixin theme($theme: $theme: light){ ...}


text:
Q: How to visualize categorical variables using ggplot2? I executed the code below to visualize my categorical variable:
p3 <- ggplot(combi %>%
               group_by(Item_Type) %>%
               summary(count = n())) +
  geom_bar(aes(Item_Fat_Content, count), stat = "Identity", fill = "coral1") +
  xlab("") +
  geom_label(aes(Item_Fat_Content, count, label = count), vjust = 0.5 ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  ggtitle("Item Type")

It threw me an error stating:

Error: data must be a data frame, or other object coercible by
  fortify(), not an S3 object with class table

A: As Pogibas commented:

*

*substitute  summary to summarize. Please see the code below (with the combi data frame simulation);

*check the data you are providing into aesthetics (I put left_join to make a code executable).

Please see the code below:
library(ggplot2)
library(dplyr)
n <- 10
m <- 3
combi <- data.frame(
  Item_Type = sample(letters[1:m], n, replace = TRUE),
  Item_Fat_Content = abs(rnorm(n))
)

ggplot(combi %>%
               group_by(Item_Type) %>%
               summarise(count = n()) %>% left_join(combi)) +
  geom_bar(aes(Item_Fat_Content, count), stat = "Identity", fill = "coral1") +
  xlab("") +
  geom_label(aes(Item_Fat_Content, count, label = count), vjust = 0.5 ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  ggtitle("Item Type")

Output:


text:
Q: $E S^1$ not homotopy equivalent to finite dimensionsl $S^1$-CW-Complex I am trying to proof, that the universal $S^1$-bundle $ES^1$ is not homotopy equivalent, to a finite dimensional $S^1$-CW-Complex.
I think, I might assume, it is, so in $X_n=X$ at some step, and then showing, that $\pi_n(X) \neq 0$, because there is a free action of $S^1$, but I am stuck explaining why this holds, so any hints are highly welcome.


text:
Q: Custom Response code and response message in restfull and SOAP services I'm developing Web services restful and SOAP Services, I'm wondering what if I use custom response code and custom response message included in response body and the http response status code in most cases will be returned as (200 ok) so it will be easier to handle errors, I'm wondering if that way is acceptable

A: Use appropriate status codes for appropriate errors. Both SOAP and REST should use 4xx and 5xx where they make sense. If you are looking for a good standard response type for REST, go for application/problem+json, for SOAP use SOAP's standards.
Clients for each should still behave correctly if they get a HTTP error, but don't support/understand the response body.

A: In HTTP, the definition of a status-line is found in RFC 7230
status-line = HTTP-version SP status-code SP reason-phrase CRLF

reason-phrase turns out to not be particularly important; clients are expected to ignore the reason phrase when processing an HTTP response.

The rest of the response message is to be interpreted in light of the semantics defined for that status code

The status code is an important piece of metadata in the transfer of documents over a network domain; general purpose clients use it to understand the nature of the HTTP response so that they can do intelligent things.
(Among the intelligent things: automatically following redirects, retrying requests with authentication credentials attached, cache invalidation).
There's a lot of code out on the internet that you don't control, that understands standardized HTTP semantics.  When you fail to respect the standardized semantics, you introduce a risk that some other code will misunderstand your responses; when that happens, the blame lies squarely with your implementation, not the client.
Expressed another way: violating the standard doesn't make things "easier"; what it does is move around where the work needs to be done.  Abiding the standard is doing your fair share of the work; offloading your share of the work onto your clients is rude.

That said, if you look carefully, there are plenty of spaces where you will find that people do deliberately violate the standards (I see this when working on health checks).  The dreadful consequences of violating the standard are not guaranteed.


text:
Q: How to Store Ad Campaign Rules in a database to Query Efficiently? I have a MySQL table like below which contains thousands of advertising campaigns.
+---------+--------------+------------------+--------------+-------------------+---------------------+
| int: id | string: name | json: countries  | json:regions | json: platforms   | json: browsers      |
+---------+--------------+------------------+--------------+-------------------+---------------------+
| 1       | Uber Android | ["US","UK","DE"] |              | ["Android"]       |                     |
+---------+--------------+------------------+--------------+-------------------+---------------------+
| 2       | Game X       | ["US"]           |              | ["Android","iOS"] | ["Chrome","Safari"] |
+---------+--------------+------------------+--------------+-------------------+---------------------+
| 3       | Game Y       |                  |              | ["Android"]       |                     |
+---------+--------------+------------------+--------------+-------------------+---------------------+

In this table, an empty column means it supports all options (e.g. an empty country means the campaign is available for all countries). So basically when I get a visitor, I can extract user details like country code, region, platform, browser and I want to find all suitable ad campaigns matching to user.
So my question is what's the best approach to store this data for querying for each visitor to get the list of all matching campaign IDs?


text:
Q: Integral of product of Legendre polynomial $P_n(x)$ and shifted Legendre polynomial $\widetilde{P}_m(x)$ Does the integral
$$C_{n,m}\equiv\int_0^1P_n(x)\widetilde{P}_m(x)dx$$
have any closed answer? $P_n(x)$ is the Legendre polynomial of order $n$. $\widetilde{P}_m(x)\equiv P_m(2x-1)$ is called the shifted Legendre polynomial.
For what $n$ and $m$, $C_{n,m}$ would vanish?

A: Write $P_n(x)$ in an explicit form 1:
$$P_n(x)=\frac{1}{2^n}\sum_{k=0}^{[n/2]}{(-1)^k\binom{n}{k}\binom{2n-2k}{n}x^{n-2k}}$$
Write $\widetilde{P}_m(x)$ in an explicit form 1:
$$\widetilde{P}_m(x)=(-1)^m\sum_{j=0}^{l}{(-1)^j\binom{m}{j}\binom{m+j}{j}x^j}$$
Multiply and rearrange:
$$P_n(x)\widetilde{P}_m(x)=\frac{(-1)^m}{2^n}\sum_{k=0}^{[n/2]}{(-1)^k\binom{n}{k}\binom{2n-2k}{n}}\sum_{j=0}^{l}{(-1)^j\binom{m}{j}\binom{m+j}{j}x^{n-2k+j}}$$
Integrate:
$$C_{n,m}\equiv\int_0^1P_n(x)\widetilde{P}_m(x)dx=\frac{(-1)^m}{2^n}\sum_{k=0}^{[n/2]}{(-1)^k\binom{n}{k}\binom{2n-2k}{n}}\sum_{j=0}^{l}{(-1)^j\binom{m}{j}\binom{m+j}{j}\int_0^1x^{n-2k+j}}dx,$$
$$\int_0^1x^{n-2k+j}dx=\frac{1}{n-2k+j+1}x^{n-2k+j+1}\Big|_0^1=\frac{1}{n-2k+j+1},$$
solution:
$$\bbox[border:1px solid black]{
C_{n,m}=\frac{(-1)^m}{2^n}\sum_{k=0}^{[n/2]}{(-1)^k\binom{n}{k}\binom{2n-2k}{n}}\sum_{j=0}^{l}{\frac{(-1)^j}{n-2k+j+1}\binom{m}{j}\binom{m+j}{j}}
}$$


text:
Q: use load balancing with wso2esb I use From Wso2 esb And Load Balancing Concept with sevices, but i have an error this is my code:
 <proxy xmlns="http://ws.apache.org/ns/synapse" name="MultiAdd" transports="https,http" statistics="disable" trace="disable" startOnLoad="true">
 <target>
  <inSequence>
     <log level="full"/>
     <log level="full" category="FATAL"/>
     <property xmlns:tem="http://tempuri.org/" name="AParam" expression="//tem:SumSerVise/tem:a" scope="default" type="INTEGER"/>
     <property xmlns:tem="http://tempuri.org/" name="BParam" expression="//tem:SumSerVise/tem:b" scope="default" type="INTEGER"/>
     <log level="custom">
        <property name="AParam" expression="$ctx:AParam"/>
        <property name="BParam" expression="$ctx:BParam"/>
     </log>
     <payloadFactory>
        <format>
           <p:SumSerVise xmlns:p="http://tempuri.org/">
              <!--Exactly 1 occurrence-->
                 <s:a xmlns:s="http://tempuri.org/">$1</s:a>
                 <!--Exactly 1 occurrence-->
                    <s:b xmlns:s="http://tempuri.org/">$2</s:b>
                 </p:SumSerVise>
              </format>
              <args>
                 <arg expression="$ctx:AParam"/>
                 <arg expression="$ctx:BParam"/>
              </args>
           </payloadFactory>
           <log level="full"/>
           <send receive="SeqOne">
              <endpoint>
                 <address uri="http://D-N-PC-12071:8280/services/Add"/>
              </endpoint>
           </send>
        </inSequence>
        <outSequence>
           <log level="full"/>
           <send/>
        </outSequence>
     </target>
     <publishWSDL>
        <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="http://tempuri.org/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://tempuri.org/">
           <wsdl:types>
              <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
                 <s:element name="SumSerVise">
                    <s:complexType>
                       <s:sequence>
                          <s:element minOccurs="1" maxOccurs="1" name="a" type="s:int"/>
                          <s:element minOccurs="1" maxOccurs="1" name="b" type="s:int"/>
                       </s:sequence>
                    </s:complexType>
                 </s:element>
                 <s:element name="SumSerViseResponse">
                    <s:complexType>
                       <s:sequence>
                          <s:element minOccurs="1" maxOccurs="1" name="SumSerViseResult" type="s:int"/>
                       </s:sequence>
                    </s:complexType>
                 </s:element>
              </s:schema>
           </wsdl:types>
           <wsdl:message name="SumSerViseSoapIn">
              <wsdl:part name="parameters" element="tns:SumSerVise"/>
           </wsdl:message>
           <wsdl:message name="SumSerViseSoapOut">
              <wsdl:part name="parameters" element="tns:SumSerViseResponse"/>
           </wsdl:message>
           <wsdl:portType name="ServiceSoap">
              <wsdl:operation name="SumSerVise">
                 <wsdl:input message="tns:SumSerViseSoapIn"/>
                 <wsdl:output message="tns:SumSerViseSoapOut"/>
              </wsdl:operation>
           </wsdl:portType>
           <wsdl:binding name="ServiceSoap" type="tns:ServiceSoap">
              <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
              <wsdl:operation name="SumSerVise">
                 <soap:operation soapAction="http://tempuri.org/SumSerVise" style="document"/>
                 <wsdl:input>
                    <soap:body use="literal"/>
                 </wsdl:input>
                 <wsdl:output>
                    <soap:body use="literal"/>
                 </wsdl:output>
              </wsdl:operation>
           </wsdl:binding>
           <wsdl:binding name="ServiceSoap12" type="tns:ServiceSoap">
              <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
              <wsdl:operation name="SumSerVise">
                 <soap12:operation soapAction="http://tempuri.org/SumSerVise" style="document"/>
                 <wsdl:input>
                    <soap12:body use="literal"/>
                 </wsdl:input>
                 <wsdl:output>
                    <soap12:body use="literal"/>
                 </wsdl:output>
              </wsdl:operation>
           </wsdl:binding>
           <wsdl:service name="Service">
              <wsdl:port name="ServiceSoap" binding="tns:ServiceSoap">
                 <soap:address location="http://localhost/SumServices/Service.asmx"/>
              </wsdl:port>
              <wsdl:port name="ServiceSoap12" binding="tns:ServiceSoap12">
                 <soap12:address location="http://localhost/SumServices/Service.asmx"/>
              </wsdl:port>
           </wsdl:service>
        </wsdl:definitions>
     </publishWSDL>
     <description></description>
  </proxy>

and this is my sequence:
<sequence xmlns="http://ws.apache.org/ns/synapse" name="SeqOne">
<log level="full"/>
<property xmlns:ns="http://org.apache.synapse/xsd" xmlns:m0="http://tempuri.org/" name="CParam" expression="//m0:SumSerViseResponse/m0:SumSerViseResult" scope="default" type="INTEGER"/>
<log level="custom">
  <property xmlns:ns="http://org.apache.synapse/xsd" name="CParam" expression="$ctx:CParam"/>
</log>
<payloadFactory>
  <format>
     <p:MultiService xmlns:p="http://tempuri.org/">
        <!--Exactly 1 occurrence-->
           <s:z xmlns:s="http://tempuri.org/">$1</s:z>
        </p:MultiService>
     </format>
     <args>
        <arg xmlns:ns="http://org.apache.synapse/xsd" expression="$ctx:CParam"/>
     </args>
  </payloadFactory>
  <log level="full"/>
  <send>
     <endpoint>
        <loadbalance algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
           <endpoint name="mt">
              <address uri="http://D-N-PC-12071:8280/services/MultiService/MultiService"/>
           </endpoint>
           <endpoint name="KR">
              <address uri="http://D-N-PC-12071:8280/services/Multi/MultiService"/>
           </endpoint>
        </loadbalance>
     </endpoint>
  </send>
</sequence>

when use load balancing one of services return value 0 and other return correct value

A: i found my problem was in define endpoint kr and mt that wasnt correct
my parameters in multiservice should be compatible with source
parameters in mt was named "z"
       <endpoint name="mt">
          <address uri="http://D-N-PC-12071:8280/services/MultiService/MultiService"/>
       </endpoint>

but parameters in kr was named "a"
       <endpoint name="KR">
          <address uri="http://D-N-PC-12071:8280/services/Multi/MultiService"/>
       </endpoint>


text:
Q: Example ad tag for Google Interactive Media Ads I'm trying to figure out how to use the Google IMA to show ads in videos on Android. The SDK is available from https://developers.google.com/interactive-media-ads/docs/sdks/googleandroid
While the example app does work the example ad tag URL that is provided with it does not work. Without a tag URL ads cannot be shown and it is very difficult to build and experiment with the API without one. I've been trying to search for an example ad tag URL that works but I've not been successful.
The add tag URL provided with the Android example (as well as with the HTML5 example) is:
http://ad.doubleclick.net/pfadx/AngelaSite;kw=html5linearnonlinear;sz=300x300;ord=5036130;dcmt=text/xml
For those who have adblock enabled:
ad[dot]doubleclick[dot]net/pfadx/AngelaSite;kw=html5linearnonlinear;sz=300x300;ord=5036130;dcmt=text/xml
That leads into server side error:
error on line 1 at column 31: AttValue: " or ' expected

Does anyone know where I could get a working tag URL?

A: The sample tag at http://ad.doubleclick.net/pfadx/AngelaSite;kw=html5linearnonlinear;sz=300x300;ord=5036130;dcmt=text/xml
has been reactivated. It should work now.


text:
Q: wso2is - Adding new keystore I'm trying to set up a new keystore in wso2is, I follow the 2 guides :

*

*https://docs.wso2.com/display/ADMIN446/Creating+New+Keystores

*https://docs.wso2.com/display/Carbon443/Configuring+Keystores+in+WSO2+Products
In the https://docs.wso2.com/display/Carbon443/Configuring+Keystores+in+WSO2+Products it says to change keystore in sec.policy, but the file doesn't exist in IS 5.2.0
Although the guide don't talk about theses files, where the default keystore seem to be used :

*

*conf/identity/EndpointConfig.properties

*conf/security/secret-conf.properties

*conf/security/cipher-text.properties

I have a webapp calling wso2is, the keystore has been added in the JVM using -Djavax.net.ssl.trustStore=/path/to/newkeystore.jks -Djavax.net.ssl.trustStorePassword=mypassword
When calling oauth2 endpoint (https://myinternaldomain:9443/oauth2/token) I got this error :

TID: [1] [] [2017-01-10 13:30:14,505] @tenant1.com [1] [IS] INFO
  {org.wso2.carbon.core.deployment.DeploymentInterceptor} -  Deploying
  Axis2 service: wso2carbon-sts {tenant1.com[1]} TID: [1] [] [2017-01-10
  13:30:14,536] admin@tenant1.com [1] [IS]ERROR
  {org.wso2.carbon.core.deployment.DeploymentInterceptor} -  Error while
  updating wso2carbon-sts in STSDeploymentInterceptor
  java.io.IOException: Keystore was tampered with, or password was
  incorrect
          at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:780)
          at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56)
          at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)
          at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70)
          at java.security.KeyStore.load(KeyStore.java:1445)
          at org.wso2.carbon.core.util.KeyStoreManager.getKeyStore(KeyStoreManager.java:146)

I did not change anything regarding keystore in the axis2.xml because all information regarding the keystore are commented.
All other endpoints (soap enpoints) are working fine with SSL, and everything works fine with localhost and default wso2carbon.jks
but I cannot make oauth2/token endpoint work with a new jks.
Thanks for your input, ideas.
Regards

A: I got it working by adding the public key in the java default keystore
keytool -import -v -alias certalias -file newkeystore.pem -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit
and by doing the following configuration which should definitely be in the wso2is keystore configuration documentation !
http://xacmlinfo.org/2014/11/05/how-to-changing-the-primary-keystore-of-a-tenant-in-carbon-products/


text:
Q: Can anyone help me make sense of all these Java versions? I am taking a Java programming class for school and the book required is for Java 5 SCJP Exam 310-055. I looked it up, I don't think that SE 5 is even supported anymore. Is this bad? The instructor says if I pass the Java Certification and show proof I can skip the class and get an instant A, but if it's outdated I don't know how I can even do this?
I am also confused about the way Java handles the different versions. What the hell does Java 2 mean? Is Java 5 actually Java 2 version 5? What does SE 5 mean and how different is it from SE 6? I also see EE, what's the difference between SE and EE? What is the most up to date version of Java right now? Does JDK just mean SDK for Java? I am so confused.
Somebody needs to be slapped?
Edit: Just found out there is also a Java ME? D:

A: Most of these questions are answered in these Wikipedia pages:

*

*Java Platforms - SE, EE, ME

*Java SE version history

*Java EE version history
From a language perspective, Java 5.0 and 6 are virtually identical.  The differences between these two versions are in the area of the runtime libraries, and in performance related aspects of the platform.  I think your instructor has made a good call.

A:
I looked it up, I don't think that SE 5 is not even supported anymore.

You don't have to worry about this. Most books you read on SE 5 will still be relevant. You should concentrate on SE 6 though IMHO.

What does Java 2 mean? What does SE 5 mean and how different is it from SE 6?

Java 2 = SE n = Java 1.n where n >= 2 && n < 6. (I hope thats a fun way to say it rather than a confusing way ...)
Basically Java 1.2 and newer versions are Java 2.
SE 5 is Java 1.5
SE 6 is Java 1.6

A little more clarification:

Java 1.1 | Java 1.2 | ... | Java 1.5 | Java 1.6 |

         |           Java 2          |

         |          | ... | Java SE5 | Java SE6 |

         |          | ... |  Java 5  |  Java 6  |

You can see the difference between SE 5 and 6 here.

A: The most recent version is Java 6 (aka 1.6) with Java 7 being developed, if I remember correctly.
SE means Standard Edition, whereas EE means Enterprise Edition. It's just a different set of standards and libraries but both complement each other (i.e. you can't normally use EE without SE).
As for the exam: I prepared for the Java 5 SCJP and did the Java 6 SCJP. That was no problem since between Java 5 and 6 there were only additions in the standard library (part of SE ;) ), no real changes in the language itself (as opposed to the changes from 1.4 to 5, except for the version name).

A: Java SE 6 is 98% the same as Java SE 5.0. The differences are subtle and you could program for years and never need to know what they are. (BTW There was no Java 5 or "SE 5")
If you are an expert in Java 5.0, that would more than qualify you to use Java 6.
I wouldn't worry about "Java 2 SE" as this an old marketing name which doesn't apply to any recent version of Java.
Java SE 5.0 is not provided free by Oracle, but you can get paid for support for it and previous versions.
Java SE 6 is provided free.

A: J2SE stands for Java 2 standard edition and is normally for developing desktop applications, forms the core/base API.
J2EE stands for Java 2 enterprise edition for applications which run on servers, for example web sites.
J2ME stands for Java 2 micro edition for applications which run on resource constrained devices (small scale devices) like cell phones, for example games.

 Standard Edition (standard version) includes J2SE which constitute the core of the Java language.
  For example: Database connectivity, interface definitions, input / output, Network Programming

Enterprise Edition (Enterprise Edition) J2EE included in the J2SE category, and also includes for the development of enterprise-class applications category.
  For example: EJB, servlet, JSP, XML, Service Control
Micro Edition (miniature version) J2ME includes J2SE part in the category for the consumer electronics products of software development.
  For example: Xiaowei, smart cards, mobile phone, PDA, set-top boxes
Their scope is: J2SE included in the J2EE, J2ME includes J2SE core categories, but add a number of new proprietary class

A: Java SE is the basic run-of-the-mill Java plus the set of standard libraries.  (Standard Edition.)  It comes in two flavours: the JRE (Java Runtime Environment) which is what you need to run Java programs and the JDK (Java Development Kit) which is what you need to make Java programs.  (The latter has the compiler, for example, among other tools.)  The current version of Java SE is 6 (although 7 is coming Real Soon Now™.  Java 5 is well past its end of life and shouldn't be used for any new development.
Java EE is, basically, a huge application framework for enterprise applications built on top of Java SE.  You need a Java SE implementation to run a Java EE implementation.  The current version of Java EE is 6 but Java EE 5 is still in use and supported.
Java ME is a stripped down Java SE.  It's targeted at small devices with (relatively) limited resources like mobile phones and the like.  There's also a Java Card which is targeted at even more restrictive environments (and, if memory serves, actually modifies the language to do it).
That's it in a nutshell, but now the confusion...
Naming in the Java world has been powerfully confusing as Sun-now-Oracle has changed directions like a sailor after a major bender in a port dive.  Java was just plain Java up to and including version 1.1.  So it was Java 1.0, Java 1.1 (and, of course, JDK 1.0, JDK 1.1).  Then Sun decided to signal that Something Big Was Happening™ for release 1.2 and renamed it to Java2.  So Java2 was actually Java 1.2.  This was also the beginning of the "SE" thing because they wanted to distinguish between the Java2 Platform Standard Edition (J2SE), Java2 Platform Enterprise Edition (J2EE) and the Java2 Platform Mobile Edition (J2ME).  The JDK version was still 1.2, but the branding was Java2.
Then when the JDK 1.3 came out, confusingly it was still called Java2, but now version 1.3.  So you had J2SE 1.3.  This remained true up to and including J2SE 1.4.  Then Sun changed things AGAIN.  Now you have Java2 Standard Edition 5.0 as the branding name.  The internal developer version was still only 1.5, but the external branding had changed.  This changed yet again for the next release which was called Java SE 6 (dropping the "2" part of the brand).  So in one major release and six minor releases the way Java has been branded has changed three or four times.
The same thing happened with EE.  The first version of Java EE was Java2 Enterprise Edition 1.2 (J2EE 1.2) to coincide with the Java2 1.2 thing.  This naming scheme was kept up to and including J2EE 1.4 when suddenly the brand was changed to Java EE 5.  This was then later updated to Java EE 6 (the most current release).
I'm not up to speed at all on Java ME or Java Card so you'll have to puzzle those out yourself, but basically from what I've gathered its as confusing as the SE/EE suite or possibly even more so.
Good luck!


text:
Q: Python Xlib issue I have a small python app using the Xlib package. I am not sure how to create a window/app properly to be managed by a window manager. Everytime I set the DISPLAY to xorg, the window is automatically created and mapped. However, the X11 window manager denies the mapping, but the window is still shown. It doesn't respond to keyboard input but will still change the cursor once the mouse moves into the window.
self.screen = display.Display().screen()
self.window = self.screen.root.create_window(
                    10, 10, 100, 100, 1,
                    self.screen.root_depth,
                    background_pixel=self.screen.white_pixel,
                    event_mask=X.ExposureMask | X.KeyPressMask)
self.window.map()

If I create an app/frame with WXPython the mapping works correctly, however, I am unable to set the X11 Font cursors in wxpython ... this is why I'm using Xlib.
So ... I either need a way to set the X11 font cursors in wxPython or a way to properly setup the self.window above in XLib.


text:
Q: filestream - open excel file read only fails I read an excel file (.xlsm; password-protected) with a vb.net application. I use the following interfaces:

*

*System.IO.filestream

*Syncfusion.XlsIO (NuGet)

That works, but I want to open it in ReadOnly-Mode, so that any other people can use this file with MS Office (write, save, ...).
Code:
Imports Syncfusion.XlsIO

Private SyncEE As Syncfusion.XlsIO.ExcelEngine
Private SyncWB As Syncfusion.XlsIO.IWorkbook

Private SyncFS As System.IO.FileStream

Public Sub new

 SyncEE = New ExcelEngine
 SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
 SyncEE.Excel.DefaultVersion = ExcelVersion.Excel2016

 SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelParseOptions.Default, openReadOnly, password)
 SyncWB.Unprotect(password)
 SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelOpenType.Automatic)

 ' read....

'discard
 SyncWB.Close()
 SyncWB = Nothing

 SyncEE.Dispose()
 SyncEE = Nothing

 SyncFS.Dispose()
 SyncFS = Nothing

End Sub

I tried it step by step and found out that i block the file at row:
SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

and I release the file at the 'discard' rows.
Blocking means that no one can edit and save the excel-file manually in MS Excel while I read it.

A: Greetings from Syncfusion.
You are blocking the file on loading the file using FileStream, as mentioned by you and you are discarding the FileStream object only at the end of your entire program. You can discard the FileStream object immediately after loading it into a workbook object so that others can use the file with MS Office (write, save, …) while you are reading it. Hence, we have modified your code as below to achieve your requirement.
Code snippet:
Private Sub new

    SyncEE = New ExcelEngine
    SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    SyncEE.Excel.DefaultVersion = ExcelVersion.Excel2016

    SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelParseOptions.Default, openReadOnly, password)

    'Discard FileStream
    SyncFS.Dispose()
    SyncFS = Nothing

    ' read....

    'discard
    SyncWB.Close()
    SyncWB = Nothing

    SyncEE.Dispose()
    SyncEE = Nothing

End Sub

Note: I work for Syncfusion.
Regards,
Shamini


text:
Q: Detecting text with ARSKView and Vision I have a view controller with an ARSKView whose ARSession I configure like this:
let configuration = ARWorldTrackingSessionConfiguration()
arskView.session.run(configuration)

In its associated SKScene I have this method implementation:
override func update(_ currentTime: TimeInterval) {
    guard let arskView = self.view as? ARSKView else {
        return
    }

    if let currentFrame = arskView.session.currentFrame {
       let capturedImage = currentFrame.capturedImage
       var requestOptions: [VNImageOption : Any] = [:]

       if let cameraData = CMGetAttachment(capturedImage, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
          requestOptions = [.cameraIntrinsics : cameraData]
       }

       let request = VNDetectTextRectanglesRequest { [weak self] (request, error) in
          self?.detectTextHandler(request: request, error: error)
       }
       request.reportCharacterBoxes = true

       let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: capturedImage, orientation: 6, options: requestOptions)

       do {
          try imageRequestHandler.perform([request])
       } catch {
          print(error)
       }
    }
}

Then, some logic to draw rectangles wrapping the detected text. I found such logic in this article, where ARKit and thus ARSKView are not used, but AVCaptureSession and AVCaptureVideoPreviewLayer instead. When you run that example, the camera has better quality and text boxes are more accurately drawn than when I run my project using ARKit and ARSKView.
I need to use ARKit with SpriteKit, but when I move the camera close to texts they are shown blurred, and in general the boxes wrapping words are drawn quite misplaced.
Is there any way I could improve this?


text:
Q: Optimising a [large] look-up table within a loop, in R I would really appreciate any help in optimising the code below. For the number of iterations I need to run, it currently takes way to long.
Basically, I'm looking for the optimal set of model parameters for estimating a variable of interest. I'm simulating a set of model parameters and a variable of interest, using each of them (in a loop) to model the signal of interest, then compare each of the modeled signal to the observed signal, and where they are minimised select one of the (simulated) values we're trying to predict. Then, a RMSE function is used to select which set of model parameters offers the smallest error compared to the observed values.
Many Thanks
Code
#Empty variable
 est_hold <- NULL

# Model Parameters (simulated and/or estimated via NLS earlier)
    beta <- seq(0.001,0.2,0.01)
    sig.g <- seq(0.028, 0.038,length.out = 20)
    sig.v <- seq(0.6, 0.8,length.out = 20)
    params <- data.frame(rbind(beta,sig.g,sig.v))

# Simulated variable of interest (Dependant variable)
sim_var <- seq(1,100,0.1)

# Observed signal (Independant variable)
obs_sig <- seq(0.0001,0.8,length.out = 100000)

# Observed variable of interest (Dependant variable)
obs_var2 <- seq(1,100,length.out = 100000)

min.func <- function(x) {sim_var[which.min(x)]}

system.time({
  for(c in 1:ncol(params)){

    # Modelled signal (Independant)
    model_var <- params[2,c]*exp(-params[1,c]*sim_var)+params[3,c]*(1-exp(-params[1,c]*sim_var))

    # Calculate difference between each modelled value (using simulated params) and each observed value
    diff <- t(apply(as.data.frame(model_var),1,"-",obs_sig))
    diff <- abs(diff)

    # Apply function, to select a simulated dependant value where differences are minimised
    est <- apply(diff,2,min.func)
    rm(diff)

    est_hold <- cbind(est_hold,unlist(est))

  }})

# RMSE function, to calculate RMSE between observed dependant variable and the modelled dependant variable (using simulated params)
rmse.fun = function(x){sqrt(sum((obs_var2-x)^2)/length(obs_var2))}

# Apply the RMSE function to the matrix of modelled values
# (where each column represents modelled values using each of the simulated params)
sim_rmse <- apply(est_hold,2,rmse.fun)

# Find the position of the lowest RMSE
ind <- which.min(sim_rmse)

#Use this position to subset the parameters (...and continue with script/modelling)
final_params <- params[ind]


text:
Q: Further question on Logarithm product integral How to perform $\int_0^1 \frac{\left(a_0\log(u)+a_1\log(1-u)+a_{2}\log(1-xu)\right)^9}{u-1} du $?
Method tried:
Intgration-by-parts
Series expansion
change of variable $\log(u)=x$
But I still can't work out.
One may use Mathematica, but it returns this integral just as your input.
The answer maybe some series of PolyLog and Single(multi-) zeta function.


text:
Q: Blank data from GET call in python requests when adding in a dataframe I'm using a GET request which runs successfully and provides me necessary details.
I'm trying to use parts of this resultant data from the GET call in an existing pandas dataframe by adding new columns.
Problem is I'm able to get the response data, but the dataframe is filled with just blank values.
However I'm able to see the data populated in my dataframe when I'm debugging the code
For index in range(Len(df)):
     Some API calls
     df.loc[index,"column"]= resultant_json["data_of_interest"]
df.to_csv('output.csv')

In the above code, if I'm debugging, the values from the API calls are populated in the dataframe. If I'm executing my code dataframe is not filled.
P.S: my code is restricted for sharing. Please let me know if you need more information

A: In of the API calls, I was using a response data as a parameter for another GET request which wasn't getting set because of the shorter execution time.
So used
time.sleep(3)
before the GET request.


text:
Q: azure sql - create index, does DB have to be offline? New to Azure SQL. Simple example to ask question.
Table Cars.
Want to add an non clustered index to Cars table.
Takes a long time, say 30 min during staging test deploy.
When upgrading production Azure SQL, can we leave the database online while building a table index? During this time while the table is building, can applications send inserts/updates to this table?
Or do we need to take the production DB offline for 30 to build this index?

A: You should absolutely be able to access the table while the index builds. Now, depending on your service tier in Azure, you might be using a lot of your resources to build this index, and that might impact user access, but otherwise, no. The index will build, but access to the table will continue.

A: Yes, leave online and inserts and updates happen while indexing occurs in the background. See Guidelines for online index operations

A: You can consider take advantage of the resumable online index creation feature to distribute the time needed to create the index over many hours, assigning one or two minutes (or X seconds) every X minutes of time to create the index. For more information, please read this resource.
ALTER INDEX test_idx on test_table PAUSE

ALTER INDEX test_idx on test_table RESUME


text:
Q: Parsing list of desired files python I have folders that contain netCDF files, which are named according to the hour of data they contain (i.e. S20160307T000000.nc through S20160308T000000.nc in one folder). I am combining multiple netCDF files into one, which I have done with:
import netCDF4
import numpy
import xarray
import glob
import os

files = sorted(glob.glob('/path/to/date/file/0307', recursive = True))

ds = xarray.open_mfdataset(files,concat_dim=['time'],
                       combine='nested',parallel=True)

varss = ['vbins', 'height', 'secs', 'snr', 'snc', 'Ze', 'vel', 'Zec']

ds[varss]

ds[varss].to_netcdf('/save/to/same/path/S20160307T120004_combined.nc')

However, I would like to combine files from 1200 UTC one day to 1200 UTC to next day. These data are located in 2 separate folders. How can I  parse the list of desired files out from the total files and then feed it to the xarray function?
Thank you!


text:
Q: How to optimize and clean these loops? I'm writing a project with Laravel.i have a loop with a lot of condition like this:
  foreach ($transactionsGroupBys as $transactionsGroupBy) {

        if ($this->checkExistSettlement($transactionsGroupBy, Carbon::today())) {
            $this->setErrorLog('This settlement has already been created', $transactionsGroupBy);
            continue;
        }

        try {

            if ($this->doChunk()) {

                $transactions = $this->getTransactions($transactionsGroupBy);
                $maxAmountSettle = $this->configRepository->find('transaction_chunk:PUBLIC')->value;
                $transactionChunk = app(ChunkTransaction::class)->chunk($transactions, $maxAmountSettle);

                foreach ($transactionChunk as $chunk) {
                    $transactionsIds = collect($chunk->transactions)->pluck('id')->toArray();
                    $settlements[] = $this->insertSettlement($chunk->transactions_group_by, $transactionsIds)->toArray();
                    $this->setInfoLog("Created $counter/$countSettlements settlement", $chunk->transactions_group_by);
                }

            } else {

                $transactions = $this->getTransactions($transactionsGroupBy, ['id']);
                $transactionsIds = $transactions ? collect($transactions)->pluck('id')->toArray() : [];

                $settlements[] = $this->insertSettlement($transactionsGroupBy, $transactionsIds)->toArray();
                $this->setInfoLog("Created $counter/$countSettlements settlement", $transactionsGroupBy);
            }

            $counter += 1;

        } catch (\Exception $exception) {
            $this->setErrorLog($exception->getMessage());
            continue;
        }

    }

i am checking $this->doChunk() and if true, run other loop. i feel this code is very Complicated and i have duplicated code. i need new pattern for Solve this problem.

A: No, it's ok.
One point that can be corrected is - remove try {} catch {} block and rewrite it using Laravel ExceptionHandler.
Other way is split this method and put every branch in big if statement into separate methods, then rewrite if to thernary operator.
Also you can rewrite foreach with array_reduce to reduce the complexity of the code, in relation to "counter"


text:
Q: JSF form is not submitted Please check this form the form data is submitted but setAttendancedata method is working..
but classname, sectionname, date is not set in variable ..
xhtml:
 <p:panel header="Attendance Entry" style="margin-top:10px">
        <p:growl id="msgs" showDetail="true" />

        <h:form id="attendance">
            <h:panelGrid id="detail" columns="10" styleClass="grid"
                cellspacing="10" cellpadding="40">

                <h:outputText value="Date: " />
                <h:outputText value="" id="popupDate">
                    <f:convertDateTime pattern="yyyy-mm-dd" />
                </h:outputText>
                <p:calendar value="#{StudentAttendanceComponent.date}"
                    id="popupCal" />

                <h:outputText value="Class :" />

                <p:selectOneMenu id="classname"
                    value="#{StudentAttendanceComponent.classname}">
                    <f:selectItem itemLabel="Select Class Name" itemValue="" />
                    <f:selectItems value="#{PreferencesClassComponent.classnames}" />
                </p:selectOneMenu>

                <h:outputText value="Section :" />

                <p:selectOneMenu id="sectionname"
                    value="#{StudentAttendanceComponent.sectionname}">
                    <f:selectItem itemLabel="Select Section Name" itemValue="" />
                    <f:selectItems value="#{PreferencesSectionComponent.sectionnames}" />
                </p:selectOneMenu>

                <p:commandButton ajax="false" immediate="true" value="Go"
                    action="#{StudentAttendanceComponent.setAttendanceData}"
                    update="msgs" icon="ui-icon-check"></p:commandButton>

            </h:panelGrid>
        </h:form>

Model:
@Scope("session")
@Component("StudentAttendanceComponent")
public class StudentAttendanceComponentImpl implements
        StudentAttendanceComponent {

    /**
     * Data type variable that provides CRUD operations for StudentAttendance
     * entities
     *
     */
    @Autowired
    StudentMasterService studentMasterService;

    private Date date = new Date();

    private String[] attData;

    private StudentAttendance studentattendance;

    private String classname;
    private String sectionname;

    private List<StudentAttendance> studentAttendances;

    @Autowired
    private StudentAttendanceDAO studentAttendanceDAO;

    /**
     * Service injected by Spring that provides CRUD operations for
     * StudentAttendance entities
     *
     */
    @Autowired
    private StudentAttendanceService studentAttendanceService;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getSectionname() {
        return sectionname;
    }

    public void setSectionname(String sectionname) {
        this.sectionname = sectionname;
    }

    public void setAttendanceData() {
        // TODO Auto-generated method stub
        System.out.println(classname+sectionname);
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
                "Filter Data", "Class " + classname + ", section " + sectionname+", date " + getDate().getDate());
        FacesContext.getCurrentInstance().addMessage("msgs", msg);

    }

A: The problem you have is, that you set the immediate="true" attribute within your p:commandButton. Because of this attribute, several JSF Lifecycles are skipped.
Check these links:

*

*http://docs.oracle.com/javaee/1.4/tutorial/doc/JSFIntro10.html

*http://balusc.blogspot.co.at/2006/09/debug-jsf-lifecycle.html#AddImmediateTrueToUICommandOnly

*http://balusc.blogspot.co.at/2006/09/debug-jsf-lifecycle.html#WhenShouldIUseTheImmediateAttribute


text:
Q: Google and Yahoo OpenID Endpoint Are https://www.google.com/accounts/o8/id and https://me.yahoo.com are Google's and Yahoo's OpenID Endpoint or the URL's to which I must send the discovery request, which in response will have the OpenID Endpoints?

A: They are discovery url's, not endpoints.

A: Yeah, that format doesn't work, and Yahoo no longer has any documentation on it apparently.


text:
Q: Proof by induction, utilizing inductive assumption Show that for every natural number $n$ there exist integers $x,y$ such that
$$4x^2 + 9y^2\equiv 1\pmod{n} $$
The base case is trivial, since 1 divides anything. Assume the claim holds for some $k\in\mathbb{N}$, must show that the claim holds for $k+1$. We must find some $x', y'$ such that $4x'^2 + 9y'^2\equiv 1\pmod{k+1}$. My idea was to utilize the property:
$$\forall t\neq 0 (a\equiv b\pmod{n}\Longleftrightarrow ta\equiv tb\pmod{tn}) $$
Since  for $k$ the claim holds we have
$$4x^2+9y^2\equiv 1\pmod{k}\Longleftrightarrow (k+1)(4x^2+9y^2)\equiv k+1\pmod{k(k+1)} $$
but I don't know how to proceed (nor if this even leads anywhere), how to better apply the inductive assumption.
To elaborate:
I can do the following:
$$(4x^2 + 9y^2)k + (4x^2 + 9y^2-1) \equiv k\pmod{k(k+1)}\Longrightarrow 4x^2 + 9y^2 + z\equiv 1\pmod{k+1} $$
the inductive assumption provides that $4x^2+9y^2-1$ is divisible by $k$, but the result is not in a convincing form.
Alternative ideas for constructing proof in question are also welcome, of course.

A: (This is not a complete answer; merely some initial observations.)
You'll probably struggle to induct on $n$ like that. After all, knowing that $n \vert m$ (some integer $m$) tells you almost nothing about what $n+1$ divides.
Notice that $4x^2 + 9y^2 = ||2x+3y i||^2$ so it is necessary and sufficient to be able to find $x, y$ such that $$||2x+3yi||^2 \equiv 1 \pmod{n}$$
Consider $2x+3iy$ and $2\alpha + 3i\beta$.
If we multiply those together, we get $$4x\alpha -9y \beta + 6 (\alpha y+\beta x)i$$
This is of the form $2r + 3is$ if and only if $y$ or $\beta$ is even; and in that case, $s$ is also even.
Therefore if we can find $2x+3iy, 2\alpha + 3 i \beta$ such that $4x^2+9y^2 \equiv a \pmod{n}$ and $4\alpha^2+9\beta^2 \equiv b \pmod{n}$, with either $y$ or $\beta$ even, then we can find $4r^2+9s^2 \equiv ab \pmod{n}$ with $s$ even.
This is a kind of closure property which might be helpful, although it is no use in the case that $n$ is even, because then the left-hand side would always be even and the right-hand side always odd, so the "closed set" is in fact empty.
It solves the question in the case that $n$ is odd, though.
Indeed, if $n$ is odd, then for some $c \in \mathbb{N}^{>0}$ we have $4^c \equiv 1 \pmod{n}$.
Letting $x=1, y=0$ yields $4x^2+9y^2 = 4$, and we can just use the closure result above $c$ times.
Although after all this work, this is equivalent simply to putting $$x = 2^{c-1}, y=0$$
Similarly, if there is $d$ such that $9^d \equiv 1 \pmod{n}$, then we can set $$x=0, y=3^{d-1}$$
That holds if and only if $n \not \equiv 0 \pmod{3}$.
Therefore the only remaining case is when $n$ is divisible by $6$.
Letting $x=y=1$, we get $13$, so if there is $c$ such that $13^c \equiv 1 \pmod{n}$ then we are likewise done.
But this happens iff $n \not \equiv 0 \pmod{13}$.
Therefore the only remaining case is when $n$ is divisible by $6 \times 13 = 78$.


text:
Q: Android studio : How to add end/closing tag automatically in layout xml file Where can I find the setting for automatically adding the closing tag in layout XML in Android Studio? For example, if I select TextView from suggestions, it should automatically close it with /> .

I used to get the ending tag automatically, but after updating Android Studio, I am not getting it anymore. I tried searching in Editor > Code Style > XML, but didn't find any relevant setting.

I am on Android Studio 3.5 RC 3.

A: Could it be this one?

Insert closing tag on tag completion and Auto-close tag on typing </ ?
For what is worth, mine closes automatically.

A: I've both AD 3.4.2 and 3.5 RC 3 installed on my system. XML issues like this are only happening on 3.5+ versions. I've looked up at open issues and came to know that 3.5 causing many issues like No auto tags after completion, hangs/freezes during autocompletion and many more.

A: The base problem: Observe the current code style (Schema) it's got changed from default style to project style when you rebuild your project, I don't know why this happened!
A proper fix for this, is setting the current style to Default IDE:


text:
Q: Игнорирование стилей в Android При применении стилей многие их параметры почему-то игнорируются.
<LinearLayout
android:id="@+id/regionColumn"
android:layout_width="170dp"
android:layout_height="match_parent"
android:orientation="vertical">
 <TextView
   android:id="@+id/regionHeader"
   style="@style/AppTheme.TableHeaderTextView"
   android:layout_width="80dp"
   android:text="@string/region" />

</LinearLayout>

Например, при добавлении в такой контейнер TextView со стилем, игнорируются все отступы и высота.
Сам стиль:
<style name="AppTheme.TableTextView">
    <item name="android:textSize">8pt</item>
    <item name="android:paddingTop">10dp</item>
    <item name="android:paddingBottom">10dp</item>
    <item name="android:paddingLeft">10dp</item>
    <item name="android:paddingRight">10dp</item>
    <item name="android:layout_height">80dp</item>
</style>

Почему так происходит и как решить эту проблему?
P.S. TableHeaderTextView - это заголовок столбца. TableTextView - обычная ячейка таблицы.

A: Разобрался сам.
Нужно отступы указывать в LayoutParams, иначе они игнорируются.
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 20, 20, 30);
textView.setLayoutParams(params);


text:
Q: Glove Model Taking lots of time to give n similar words I have a list of token and i am trying to find the top 10 similar word for each token but Glove model is taking a lot of time to return similar word.My code is:
class GloveModel:
    def __init__(self):
        self.embedding_dict={}
        with open("glove.6B.50d", 'r', encoding="utf-8") as f:
            for line in f:
                values = line.split()
                word = values[0]
                vector = np.asarray(values[1:], "float32")
                self.embedding_dict[word] = vector

    def find_closest_embeddings(self,token):

        return sorted(self.embedding_dict.keys(), key=lambda word: spatial.distance.euclidean(self.embedding_dict[word],token))

    def analyze(self,final_token):
        summary_txt_token=[]
        result=[]
        for i in final_token:
            if i in self.embedding_dict:
                temp=self.find_closest_embeddings(self.embedding_dict[i])[0:10] ##TOp ten similar word from the token
                summary_txt_token.extend(temp)

        summary_txt_token=list(set(summary_txt_token))
        return summary_txt_token
summary_obj=GloveModel()
final_token=summary_obj.analyze(final_token)


text:
Q: Display SP Online list data as report in Excel Web Access Webpart I have a SP Online list and I want to present this data as a report using Excel Web Access.
First is it possible to sync a SP Online list data to an excel file uploaded to SP document library as a report? If so how?

A: You can follow the steps below to add connection to a SP Online list and upload the excel file to a SP Online library. The data in the workbook will refresh automatically if the refresh control is enabled. After that, you can display the data using Excel Web Access web part.

*

*Create a excel file in client.

*Get external data from ODate Date Feed.

*Link to https://tenant.sharepoint.com/<site>/_vti_bin/listdata.svc.

*Select the lists which you want to display and click Next.

*Enter the information such as file name for this data connection and click Finish.

*View this data as a table in the workbook.

*Edit this data connection properties, set the refresh control to refresh data when opening the file or other refresh options as you want.

*Save the file and upload the file to a SP Online library.

*Display the data using Excel Web Access web part.


text:
Q: How to pass Data between Tabs in Xamarin forms Prism based-app Say I have TabbedPage with two pages :
 <TabbedPage ... x:Class="MyApp.Views.MyTabbedPage" ... >
 <TabbedPage.Children>
   <local:PageA/>
   <local:PageB/>
 </TabbedPage.Children>
</TabbedPage>

How I can Pass Data from PageA to PageB (From PageAViewModel to PageBViewModel)
I implemented INavigationAware interface and try to use OnNavigationTo(...) but  without success! OnNavigatedTo(...) never be called, OnNavigatedTo will be invoked on the TabbedPage and only the SELECTED TAB.
I wonder if there is a solution for passing data each time I switch from tabA to tabB ?
MORE INFOS
Say that I have a list of a customer in the PageA, do some filtering, I want to pass the filtered list of a customers to the PageB to do more actions
How I can perform this using prism?
Thanks in advance


text:
Q: weird shell script error: invalid option return: usage: return [n] This programme checks if a certain book title exist by matching user input of book title and book author.
function removebook_option()
{
    echo -n "Title : "
    read title_input2

    echo -n "Author: "
    read author_input2

    checkexist $title_input2 $author_input2
    error=$?
    echo "$error"

    if [ $error != -1 ];then
        #removebook
            echo "New book title $title_input removed successfully"
        else
        echo "Book does not exist"

    fi

}

function checkexist()
{
   counter=0

   for x in ${title[@]}
   do

    for y in ${author[@]}
    do
        if [  $x == $1 ] && [ $y == $2 ];
        then
            error=$counter
                return "$error"
        fi
    done
    counter=$((counter+1))
   done

   error=-1
   return "$error"

}

title=(foo1 foo2)
author=(bar1 bar2)
removebook_option

I am getting a very weird error , where function checkexist() returns 2 instead of -1 when there isnt a match which happens when returning value error=-1

line 43: return: -1: invalid option return: usage: return [n]

EDIT : For reasons unknown , i can only return values from 0-255 , does anyone know how to return negative values??
You can try to input incorrect data to see the weird error
I need help resolving this issue thanks!!!!

A: You're getting this error:
line 43: return: -1: invalid option return: usage: return [n]

This is because the -1 is interpreted as an option. Use this, -- means 'end of options':
return -- -1

which returns with 255.

Working solution:
#!/bin/bash

function removebook_option()
{
    echo -n "Title : "
    read title_input2

    echo -n "Author: "
    read author_input2

    error="$(checkexist "$title_input2" "$author_input2")" # <--
    echo "$error"

    if [[ "$error" != NOT_FOUND ]]; then # <--
        #removebook
        echo "New book title $title_input removed successfully"
    else
        echo "Book does not exist"
    fi

}

function checkexist()
{
   counter=0

   for x in "${title[@]}" # <--
   do
        for y in "${author[@]}" # <--
        do
            if [[  $x == $1 ]] && [[ $y == $2 ]]; # <--
            then
                error=$counter
                echo "$error" # <--
                return
            fi
        done
        ((counter++)) # <--
   done

   error=NOT_FOUND # <--
   echo "$error"
   return
}

title=(foo1 foo2)
author=(bar1 bar2)
removebook_option

Edits marked with  # <--
This works by instead of returning an integer value, it echoes it (writes to screen). Usually, this would print to the terminal however the $( ... ) syntax captures the printed output, and assigns it to error in removebook_option(). This allows 'returning' any string, I've made it return a sentinel value of NOT_FOUND if not found.
Notes:

*

*Array expansion should be wrapped with double quotes: "${author[@]}" and "${title[@]}"

*Use [[ ... ]] instead of [ ... ].


text:
Q: Is selection/sample bias immediately caused when I don't exclude data? I'm running a multinomial logistic regression on 8 independent variables for 180 observations in Stata (version 11). The dependent variable is categorical with 7 outcome categories, categories 1-6 (solving strategies for a household with a resource conflict) and category 0 (no solving strategy because the household doesn't encounter any resource conflicts).
I was advised to exclude the observations of category 0. My questions are

*

*what happens, if I keep the sample as it is - will my regression results be biased?

*what the trade-off between selection/sample bias and data exclusion is, because in the latter case, the sample will be reduced more than half.

*if a simple way around sequential/nested logit (nlogit)exists, as a solution to this problem (I tried it but I guess it exceeds my Stata skills and my expectations on the this estimation).


text:
Q: Hide a Control Box in Excel I have some radio buttons in Excel (2011 Mac), and they are grouped by a Group Box.
I want to make the Group Box invisible. I searched on the internet and found that I could do that with VBA by entering:
ActiveSheet.GroupBoxes.Visible = False

in the VBA window that corresponds to the relevant worksheet. I did that but there seems to be no difference. Do I have to do something else to activate the change?

A: Try to call it out specifically by name
ActiveSheet.Shapes("Group Box 1").Visible = False

Make sure Application.ScreenUpdating = True e.g.
Sub hidethings()
Application.ScreenUpdating = False
ActiveSheet.Shapes("Group Box 2").Visible = False
Application.ScreenUpdating = True
End Sub

If you have a bunch that you want to hide you can do something like this -
Sub tellme()
Dim thing As Shape
For Each thing In ActiveSheet.Shapes
 If thing.FormControlType = xlGroupBox Then
   thing.Visible = msoFalse
 End If
Next
End Sub

A: It sounds like you've entered one line of VBA code but have not placed it in a subroutine that can be executed. Hence, what you've done has no effect.
Try the following:

*

*Open the VBA editor pane by pressing Alt+F11.

*In the window that opens insert a new module by clicking through Insert > Module.

*In the text box that appears, paste the following:

Sub HideBoxes()
ActiveSheet.GroupBoxes.Visible = False
End Sub

*Place the cursor anywhere inside the code and press F5 to execute the code.
This should hide any group boxes on the active sheet.


text:
Q: How do you send a user to your app's settings from iPhone/iPad? Is there a way to launch the iPhone/iPad's settings from within your app?

A: There is no way to do this. What apps usually do is recreate the same view the user would see if they opened the settings and then display that in-app.

A: Check this out:  It is a framework to display the apps's settings in both places, or just just on the app using the same type of display as the settings pane.


text:
Q: Can Hibernate automatically recognize an entity type? I'm creating project using Hibernate and Spring Data JPA. I have one superclass named Product (with fields like price etc) and some specialized subclasses like Memory, Processor with specialized fields (different for all classes). All products have separate tables.
My question is: can i use all products polimorphically - like
  productRepository.update(product)

and will hibernate automatically detect type od product (so it can save object to appropriate table)?
I used
@MappedSuperclass and @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

annotations in my Product class - is this enough?

A: Hibernate inheritance mapping support is suitable for this scenario. In your example, you don't have to call:
productRepository.update(product);

unless you want to attach a detached entity.
What might be a problem is that you need concrete entity Spring Data repositories. So you can't have a productRepository but a memoryRepository and processRepository instead.
So you can get a Memory entity:
Product memory = memoryRepository.findOne(1L);

If you modify the attached entity in the same Hibernate Session, the dirty checking mechanism will synchronize changes with the database.
If the entity is sent to an HTTP Session and merged back in another transaction then you need to use the actual repository:
memoryRepository.save(memory);

You can have your repositories extend an interface giving the supported entity class and then use an automatic scanning mechanism to have a Map<Class, CrudRepository>, so that based on the product type, you can fetch the associated repository.


text:
Q: Django/Python: generate pdf with the proper language I use Pisa/xhtml2pdf in my Django apps to generate pdf from an HTML source. That is:

*

*I generate the HTML file formatted with all 'printing' stuffs (e.g. page-breaks, header, footer, etc.)

*I convert this HTML into pdf using Pisa

This process is ok but it is slow (expecially when dealing with long tables) and I must use HTML/CSS according to Pisa features/limitations.
The question is: is this the right way to generate pdf from a web application (i.e. create HTML and then convert it to pdf) or there is a more direct way, that is "write" the pdf with a more suitable language?

A: I think generating a pdf from html with libraries like Pisa or http://weasyprint.org/ is the simplest approach. because it takes care of inserting images, css, barcode (on pisa) ... etc
If you want to write the pdf yourself take a look at Reportlab but it will take much longer to implement. In both cases i suggest to always generate the pdf in the background with celery or python-rq for optimization.

A: Pisa is known having various issues - especially with long tables. In general one should avoid using PISA. Other options are:

*

*using Reportlab directly

*z3c.rml (Reportlab template language clone)

*commercial alternatives:

*

*PrinceXML

*PDFreactor

The general rule when it comes to PDF production: you get what you pay for.
Converters like Pisa or Apache FOP are half-baked solutions that work for simple cases but suck in general.

A: You can also use the QT webkit rendering engine to create PDFs from HTML with http://code.google.com/p/wkhtmltopdf/ and django-wkhtmltopdf.
The advantage is that you can write the HTML and CSS as you would normally for WebKit. This works well if you are outputting an existing web page but may be less appropriate if generating PDFs from scratch.

A: WeasyPrint author here. The point of using HTML/CSS to generate PDF (vs. using a lower-level PDF library directly.) is to get automatic layout. It lets you specify high-level constraints like h1 { page-break-after: avoid } and let the layout engine figure it out, rather than specifying the absolute position of everything. The former is much more maintainable when you make changes to your documents.
Some tools like rst2pdf have their own stylesheet syntax, but that's just a bad way of re-inventing CSS.
But yes, dumping complex stylesheets made for screen might not give great results. It's better to build the stylesheets with print in mind, or even use completely different stylesheets with @media print in CSS or <link media="print"> in HTML.


text:
Q: adding limit to my sequelize query is throwing an error this works properly
        let data=await db.company.findAll({
            include:{model:db.user,as:'users'},
            where:{'$users.id$':7}
        });

but as soon as i add limit below, it throws an error
        let data=await db.company.findAll({
            limit:10,
            include:{model:db.user,as:'users'},
            where:{'$users.id$':7}
        });

here's the error when i execute the one with limit.
{
name: "SequelizeDatabaseError",
parent: {
message: "The multi-part identifier "users.id" could not be bound.",
code: "EREQUEST",
number: 4104,
state: 1,
class: 16,
serverName: "LAPTOP-5ED24571",
procName: "",
lineNumber: 1,
sql: "SELECT [company].*, [users].[id] AS [users.id], [users].[username] AS [users.username], [users].[name] AS [users.name], [users].[address] AS [users.address], [users].[active] AS [users.active], [users].[email] AS [users.email], [users].[phone] AS [users.phone], [users].[job_role] AS [users.job_role], [users].[time_zone] AS [users.time_zone], [users].[country] AS [users.country], [users].[currency] AS [users.currency], [users].[induction] AS [users.induction], [users].[createdAt] AS [users.createdAt], [users].[updatedAt] AS [users.updatedAt], [users].[userRoleId] AS [users.userRoleId], [users->user_company_mm].[id] AS [users.user_company_mm.id], [users->user_company_mm].[userId] AS [users.user_company_mm.userId], [users->user_company_mm].[companyId] AS [users.user_company_mm.companyId], [users->user_company_mm].[createdAt] AS [users.user_company_mm.createdAt], [users->user_company_mm].[updatedAt] AS [users.user_company_mm.updatedAt] FROM (SELECT [company].[id], [company].[name], [company].[address], [company].[city], [company].[country], [company].[state_region], [company].[logo], [company].[numberOfLocations], [company].[numberOfEmployees], [company].[audience_builder], [company].[creator_user_id], [company].[tags], [company].[createdAt], [company].[updatedAt] FROM [company] AS [company] WHERE [users].[id] = 7 ORDER BY [company].[id] OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY) AS [company] LEFT OUTER JOIN ( [user_company_mm] AS [users->user_company_mm] INNER JOIN [user] AS [users] ON [users].[id] = [users->user_company_mm].[userId]) ON [company].[id] = [users->user_company_mm].[companyId];"
}

Any idea why this is happening? thank you

A: I'm not necessarily familiar with sequelize.js. But looking at your query statement, you have a WHERE condition in your sub query limiting it to [Users].[Id] = 7. But this doesn't exist in this part of your query context.
...
FROM
(SELECT [company].[id],
[company].[name],
[company].[address],
[company].[city],
[company].[country],
[company].[state_region],
[company].[logo],
[company].[numberOfLocations],
[company].[numberOfEmployees],
[company].[audience_builder],
[company].[creator_user_id],
[company].[tags],
[company].[createdAt],
[company].[updatedAt] FROM [company] AS [company]
/* HERE --> */ WHERE [users].[id] = 7 ORDER BY [company].[id] OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
)
AS [company] LEFT OUTER JOIN
( [user_company_mm] AS [users->user_company_mm] INNER JOIN [user]
AS [users] ON [users].[id] = [users->user_company_mm].[userId]) ON [company].[id] = [users->user_company_mm].[companyId]

But why the query is structured as so, I can't tell. That would be something for how you've configured it/how sequalized works.


text:
Q: Django uninstalled after installing django-debug-toolbar in docker container, how to install it without un installing django? I was trying to install django debug toolbar in my container using
[shub@debian teamwave](task-details-api)$ docker exec -it teamwave_backend_1 pip install django-debug-toolbar Collecting django-debug-toolbar   Downloading https://files.pythonhosted.org/packages/01/9a/3db232bd15882d90d3c53de1f34ce0a522327849593c9198899713267cfe/django_debug_toolbar-1.11-py2.py3-none-any.whl (201kB)
    100% |████████████████████████████████| 204kB 426kB/s  Collecting sqlparse>=0.2.0 (from django-debug-toolbar)   Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Collecting Django>=1.11 (from django-debug-toolbar)   Downloading https://files.pythonhosted.org/packages/61/cb/e3c6bfccdf23c48dd4ce014b96178aa048b9450739eaa5f11d4d23d9d5d6/Django-1.11.23-py2.py3-none-any.whl (6.9MB)
    100% |████████████████████████████████| 7.0MB 544kB/s  Requirement already satisfied: pytz in /usr/local/lib/python2.7/site-packages (from Django>=1.11->django-debug-toolbar) (2015.2) Installing collected packages: sqlparse, Django, django-debug-toolbar   Found existing installation: sqlparse 0.1.15
    Uninstalling sqlparse-0.1.15:
      Successfully uninstalled sqlparse-0.1.15   Found existing installation: Django 1.8.18
    Uninstalling Django-1.8.18:

I have tried running the container and installing the django
Starting teamwave_backend_1 ... done
Attaching to teamwave_backend_1
backend_1  | Traceback (most recent call last):
backend_1  |   File "manage.py", line 8, in <module>
backend_1  |     from django.core.management import execute_from_command_line
backend_1  | ImportError: No module named django.core.management
teamwave_backend_1 exited with code 1

I later fixed my django by docker-compose build but I want django-debug-toolbar too.
This is my docker-compose.yml
version: '3'

services:
  db:
    image: postgres:10-alpine
    environment:
      - POSTGRES_PASSWORD=dsdbadmin
      - POSTGRES_DB=tm_v1.1
    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
  backend:
    build: .
    volumes:
      - .:/backend
    ports:
      - "8000:8000"
    depends_on:
      - db
      - redis
  redis:
    image: redis:4-alpine

volumes:
  pgdata:

And this is my Dockerfile
FROM python:2
ENV PYTHONUNBUFFERED 1
WORKDIR /backend
ADD req.txt /backend/
RUN pip install --upgrade pip
RUN pip install -r req.txt
ADD . /backend/

ENTRYPOINT ["python", "manage.py", "runserver", "0.0.0.0:8000"]

EXPOSE 8000

I use docker-compose up to run my containers

A: installing the latest version from django-debug-toolbar will install Django-1.11.23 and uninstall older Django versions .
you may try to find the correct django-debug-toolbar for Django-1.8


text:
Q: Definite Integration by parts how do I code
Integrate[u[x] D[v[x], x], {x, a, b}]

to return the following straightforward undergraduate result?
u[b] v[b] - u[a] v[a] - Integrate[v[x] D[u[x], x], {x, a, b}]

A: Use WolframAlpha
WolframAlpha["integration by parts (mathematical problem)", \
{{"FormulasPod:FamousMathProblem", 1}, "Content"}]

A: There's a resource function, based on the the internal utility ResourceFunctionHelpers`IntegrateByParts:
ResourceFunction["IntegrateByParts"][
 u[x] D[v[x], x], {x, a, b}]

ResourceFunction["IntegrateByParts"][
 u[x] D[v[x], x], {x, a, b}, "Grid"]