text:
Q: Bypass a Java error Is there a way that I can bypass an error message in Java ?
What if I get an error, but there is no viable way to change my program ? What if I suspect that I might get an error from a block of code, but I don't know when or if it will happen ? There's been a lot of times where I had to let something be in my code, but produced an error. For example, converting a string into a float with parseFloat().
Anyway to do this ?

A: I think you need a try...catch statement.
try {
    // parse your float here
} catch (NumberFormatException ex) { // parsing a float might throw a NumberFormatException
    // code in here will be executed if a NumberFormatException occurs
}

A: Yes you can handle runtime errors in Java.
Exception Handling
There are two ways to handle Exceptions.

*

*Throw out and ignore -
When an Exception occur inside a code of program simply throw it out and ignore that an exception occur(i.e.declare the methods as throws Exception).
Example:
void method()throws IOException{

 }

*Catch and handle -
If a code snippet is generating an Exception place it inside a try block. Then mention the way to handle the Exception inside the catch block.
Example for catch and handle:
try{
  double a= parseDouble("12.4a");
}catch(NumberFormatException e){
  System.out.println("cannot format");
}

Here try to convert 12.4a to double and store in a. Since 12.4a contains character a NumberFormatException will occur. you can handle it. In above code I just print a text. But you get printStackTrace:
e.printStackTrace;

You can add finally after catch block. read Orcale doc.

A: Yes, of course there is a way to do this, it is called Exception Handling.
Begin by reading about the Exception class, and the try catch and finally keywords.
Here is a starting point: https://www.tutorialspoint.com/java/java_exceptions.htm


text:
Q: BDD with cucumber: how to generate steps? I've an empty java gradle project:
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testCompile 'io.cucumber:cucumber-java8:5.4.0'
    testCompile 'io.cucumber:cucumber-junit:5.4.0'
}

Wrote a *.feature file:
Feature: All PIN variations
Scenario: *********************
    Given **************
    When ******************* ****
    Then  ************************

I've read from tutorials (a lot of them in the internet): I need to somehow generate steps. I'm using IntellijIdea, I wanna promote nothing, just what should I do? I guess I need to use some tool/plugin, so please just advise to me a direction where to search and best practices

A: The JetBrains documentation provides a bulletproof guide for this. If you've followed the setup properly, creating a step from a feature file is as simple as hovering over the step and pressing Option + Enter on your keyboard as also mentioned in their documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the folder name from a String containing the Absolute file path in android? Path name is : /storage/emulated/0/Xender/video/MyVideo.mp4
I am able to get last file name [MyVideo.mp4] from path using
String path="/storage/emulated/0/Xender/video/MyVideo.mp4";
String filename=path.substring(path.lastIndexOf("/")+1);

https://stackoverflow.com/a/26570321/5035015
Now i want to extract path [/storage/emulated/0/Xender/video] from this path.
I have one use of this path in my code so that i want to do this like this.
How can i do this?
Any help will be appreciated.

A: new File(path).getParentFile().getName() should work.
With regards to your current code, don't implement your own path parser. Use File.
Also note that this has nothing to do with Android specifically; this is a general Java question.


text:
Q: How to use EventEmitter in angular 8 Whenever I create EventEmitter it is throwing an error as

Expected 0 type arguments, but got 1.

statusUpdated = new EventEmitter<string>();

tried this:
statusUpdated = new EventEmitter<>;
statusUpdated = new EventEmitter<>();
statusUpdated = new EventEmitter<{}>();

A: You must import it from core
import {EventEmitter } from '@angular/core'

A: The proper definition would be:
statusUpdated:EventEmitter<string> = new EventEmitter();


text:
Q: Don't let the user leave the page? window.onbeforeunload = function() {
   return "Dont leave me";
   return;
};

So thats my HTML-Code(JavaScript) so far and its working.
Now there will be a pop up if you try to leave.
Is there any oppertunity to loop the user in this pop-Up when he clicks on leaving?

A: There is no way to prevent users from leaving the website.


text:
Q: Java Hibernate Error org.hibernate.hql.ast.QuerySyntaxException: unexpected token Hello I have a problem with the execution of a Query inside Java using Hibernate.
When I use this Query:
        Query query = dbSession.createQuery("SELECT activitydate, userid, sum(time) as homeofficeTime FROM Hours AS hours " +
               "WHERE (hours.comment ILIKE ANY(ARRAY['%homeoffice%', '%home office%']) OR " +
                        "remark ILIKE ANY(ARRAY['%homeoffice%', '%home office%'])) AND " +
                    "hours.activitydate BETWEEN :from AND :to " +
                        "AND userid = :user " +
                "GROUP BY activitydate, userid ORDER BY activitydate ");

        query.setLong("user", employee.getUserid());
        query.setCalendar("from", from);
        query.setCalendar("to", to);

I get this Error:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ILIKE near line 1, column 129 [SELECT activitydate, userid, sum(time) as homeofficeTime FROM com.thiesen.timesheet.sql.dbo.Hours AS hours WHERE (hours.comment ILIKE ANY(ARRAY['%homeoffice%', '%home office%']) OR remark ILIKE ANY(ARRAY['%homeoffice%', '%home office%'])) AND hours.activitydate BETWEEN :from AND :to AND userid = :user GROUP BY activitydate, userid ORDER BY activitydate ]

However when I use this Query:
        Query query = dbSession.createQuery("SELECT activitydate, userid, sum(time) as homeofficeTime FROM Hours AS hours " +
                   "WHERE hours.comment = 'test Homeoffice tst' AND " +
                        "hours.activitydate BETWEEN :from AND :to " +
                            "AND userid = :user " +
                    "GROUP BY activitydate, userid ORDER BY activitydate ");

        query.setLong("user", employee.getUserid());
        query.setCalendar("from", from);
        query.setCalendar("to", to);

It works and I get a Result back: [[Ljava.lang.Object;@7221ae50]
Both of the Query work if I test them inside Adminer and run the Querys there but for some Reason the first one wont work in my Project. Does Hibernate not know what to do with "ILIKE" or "LIKE" or the "Array[]" Part?


text:
Q: Как сгенерировать xml в javascript Нужна функция обратная $.parseXML - её я XML считываю.
Теперь нужно запись новую структуру, чтобы передать в этот вызов:
new XMLSerializer().serializeToString(Xml_2)

A: последовательный вызов:
childNodes
createElement
textContent или setAttribute
appendChild


text:
Q: Facebook Graph api Event crawling I am developing something like an event calendar at the moment and would like to pimp it up with a bit more "live" data. Therefore I want to get data from Facebook and I think the right way to do this is the Graph api.
But I really cant get it working. I would like to either:

*

*get all Events in a specific range from a Location (I don't think this is possible)

*or get all Events from a specific page

*or get all Data from a specific Event

But I don't get the API Documentation.
Do I need a Page API-Key or an Api API-Key. I don't even get the the Graph API Explorer to output any data.
When I want to crawl a Page I get
"(#10) To use 'Page Public Content Access', your use of this endpoint must be reviewed and approved by Facebook. To submit this 'Page Public Content Access' feature for review please read our documentation on reviewable features: https://developers.facebook.com/docs/apps/review.","
I know it sounds quite obvious but I just want to test a bit and get to know the api before I develop the app. I can't submit anything right now..


text:
Q: CSV writer displays each character in separate columns I have a .txt file with coordinates and earthquake magnitudes. I need to extract only 3 of the columns (latitude, longitude and magnitude) but the loadtxt in numpy module is not working. I wanted to convert the txt file into a csv file to see if I can extract the data I need... Here is what I have now. It returns a .csv file with each character printed as a separate row.
import csv

s = open('Sismos_24_4_17.txt',"r").read()
print(s)

sc = open('Sismos_24_4_17.csv',"rt")

in_txt = csv.reader(s, delimiter = '\t')

out_csv = csv.writer(open('Sismos_24_4_17.csv',"wt"))

out_csv.writerows([in_txt])

print(sc.read())

Here are a few lines of the .txt file:
Local   Fecha   Latitud     Longitud    Profundidad Magnitud    Referencia
24/04/2017 20:58:01 24/04/2017 23:58:01 -33.307     -71.769     20.6    4.3 Ml GUC  19 km al NO de El Tabo
24/04/2017 20:54:45 24/04/2017 23:54:45 -33.292     -71.934     28.4    4.6 Mw GUC  31 km al NO de El Tabo
24/04/2017 20:47:29 24/04/2017 23:47:29 -32.985     -72.008     25.8    3.2 Ml GUC  37 km al O de Valparaíso

And here are a few lines of the .csv file my code creates:
['L'],['o'],['c'],['a'],['l'],"['', '']",['F'],['e'],['c'],['h'],['a'],"['', '']",['L'],['a'],['t'],['i'],['t'],['u'],['d'],"['', '']","['', '']",['L'],['o'],['n'],['g'],['i'],['t'],['u'],['d'],"['', '']",['P'],['r'],['o'],['f'],['u'],['n'],['d'],['i'],['d'],['a'],['d'],"['', '']",['M'],['a'],['g'],['n'],['i'],['t'],['u'],['d'],"['', '']",['R'],['e'],['f'],['e'],['r'],['e'],['n'],['c'],['i'],['a'],[],['2'],['4'],['/'],['0'],['4'],['/'],['2'],['0'],['1'],['7'],[' '],['2'],['0'],[':'],['5'],['8'],[':'],['0'],['1'],"['', '']",['2'],['4'],['/'],['0'],['4'],['/'],['2'],['0'],['1'],['7'],[' '],['2'],['3'],[':'],['5'],['8'],[':'],['0'],['1']

How can I get it to separate each element with a comma!

A: You're not extracting the first 3 columns like you should. I'd recommend iterating over each line in the input, and concurrently writing to the out-file. You can use the with...as context manager to make this easy.
with open('Sismos_24_4_17.csv', "rt") as i, open('Sismos_24_4_17_2.csv', "wt") as o:
    r = csv.reader(i, delimiter='\t')
    w = csv.writer(o)
    for row in r:
        w.writerow(row[:3])

What's more, you should write your output to a separate file, with a different name.

A: You should add quoting to the csv.reader. I don't know why but for the first time when I was reading file via csv module the same occurred to me after adding the quoting to the csv.reader all is good
in_txt = csv.reader(s, delimiter = '\t', quoting=csv.QUOTE_NONE)
out_csv = csv.writer(open('Sismos_24_4_17.csv',"wt"), quoting=csv.QUOTE_NONE)

Worked for me try experimenting with it check the man page for csv library


text:
Q: Can i use a navigation drawer as a dropdown menu when i click on an item in a recyclerview? Im using a Navigation drawer as a dropdown when i select an item in my recyclerview, but im not sure if im supposed to use a navigation drawer as a dropdown list.
Everything works fine except i have some problem when i swipe between fragments, the drawer doesn't close.
Just want to know if it's okay to use a drawer this way.
NavigationView mNavigationView2;

        mNavigationView2 = rootView.findViewById(R.id.nav_view2);

        initRecyclerView();

        mNavigationView2.setBackgroundColor(getResources().getColor(R.color.color1));
        mNavigationView2.setItemIconTintList(null);

        mNavigationView2.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                final Dialog dialog;
                switch (item.getItemId()){
                    case R.id.ic_edit:
                    //code when edit is clicked in dropdown.
            return true;
        }
    });

A: Not clear about what you really want to achieve.
If i'm not wrong, you want to reuse the list of options (from res/menu) of navigation drawer in recyclerview dropdown options.
You may take a look at this:
https://developer.android.com/guide/topics/ui/menus


text:
Q: Magento - echo block within another block I have a CMS Page named Home, with the following code within the Design->Layout Update Xml
<reference name="content">
    <block type="core/template" template="homepage/home.phtml">
        <reference name="featured">
            <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
                <action method="setCategoryId"><category_id>2</category_id></action>
                <action method="setColumnCount"><count>5</count></action>
            </block>
        </reference>
    </block>
</reference>

and this within homepage/home.phtml

           // Promo Here

        <?php echo $this->getChildHtml('featured'); ?>

My main goal is trying to get the featured block inserted into the homepage/home.phtml template, but with the current layout xml in the CMS Page above it is not showing.
All help is greatly appreciated.

A: There are issue in xml files, i have modify ... the code
<reference name="content">
    <block type="core/template" template="homepage/home.phtml" >
            <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
                <action method="setCategoryId"><category_id>2</category_id></action>
                <action method="setColumnCount"><count>5</count></action>
            </block>
    </block>
</reference>

Rest of all same..

A: getChildHtml('featured'); ?> 'featured' is name of block not reference .If you want to call the block within template you will use the following block syntax
{{block type="catalog/product_list" name="featured" as="featured" template="catalog/product/list.phtml"}}

A: modify the code like that, I believe the name of the block "home_content" should be there.
<reference name="content">
    <block type="core/template" name="home_content" template="homepage/home.phtml" >
        <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
            <action method="setCategoryId"><category_id>2</category_id></action>
            <action method="setColumnCount"><count>5</count></action>
        </block>
    </block>
</reference>

I hope it will help you.


text:
Q: Copy and Paste a range from one worksheet to multiple worksheets I am trying to copy a range from one worksheet to about 600 more worksheets in the same workbook.
I have found some code that enables me to copy the range and paste it at the end of the next worksheet. The code below only pastes the range to 1 worksheet (Sheet3). But I am unable to figure out how to loop it to paste in all the other worksheets. How can I add a loop to the code below to to do so?
Sub copypaste()
Dim i As Long
With Sheets("Sheet3")
i = .Range("B" & Rows.Count).End(3).Row
Sheets("Cert").Range("A1:K27").Copy .Range("A" & i + 1)
End With
End Sub

A: If by 600 worksheets, you mean that you would like to copy to all the worksheets, then consider:
For Each WS In Worksheets
  With WS
  i = .Range("B" & Rows.Count).End(3).Row
  Sheets("Cert").Range("A1:K27").Copy .Range("A" & i + 1)
  End With
Next WS


text:
Q: Change position of entry title I've been unable to move the post entry title to under the post's image. Whenever I do this, the title moves under the content and appears just above the footer.
loop-single.php -
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<table id="post-<?php the_ID(); ?>" <?php post_class(); ?>

<?php the_title(); ?>

<?php the_subtitle(); ?>

<?php the_content(); ?>

Here is my site. What am I doing wrong?

A: If you're adding the image directly in the editor, then the_content() will always echo the image. Which means the title can only be above the blog post or below it. You should try adding the image as a featured image. Take a look at this link to see how to add featured image support, and how to use it-> http://codex.wordpress.org/Post_Thumbnails
Basically you need to add the code below to the functions.php file. This will turn on the featured images option.
add_theme_support('post-thumbnails');

Update the loop to include the featured image.
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<table id="post-<?php the_ID(); ?>" <?php post_class(); ?>

<?php
       //possible image sizes: thumbnail,medium,large,full

       the_post_thumbnail('full');

<?php the_title(); ?>

<?php the_subtitle(); ?>

      the_content();

  ?>

Go to your blog post edit page, look on the bottom right side for the "Set featured image" box. Add your image.


text:
Q: Implementation of skyline query or efficient frontier I know there must be an easy answer to this but somehow I can't seem to find it...
I have a data frame with 2 numeric columns.
I would like to remove from it, the rows, which have the property, that there exists at least one other row in the data frame, with both column values bigger than the ones in this row.
So if I have
    Col1 Col2
1     2    3
2     4    7
3     5    6

I would like to remove the first row, because the second one fulfills the property and keep only rows 2 and 3.
Thanks a lot!

A: Edit (2015-03-02): For a more efficient solution, please see Patrick Roocks' rPref, a package for "Database Preferences and Skyline Computation", (also linked to in his answer below). To show that it finds the same solution as my code here, I've appended an example using it to my original answer here.

Riffing off of Vincent Zoonekynd's enlightening response, here's an algorithm that's fully vectorized, and likely more efficient:
set.seed(100)
d <- data.frame(x = rnorm(100), y = rnorm(100))

D   <- d[order(d$x, d$y, decreasing=TRUE), ]
res <- D[which(!duplicated(cummax(D$y))), ]
#             x         y
# 64  2.5819589 0.7946803
# 20  2.3102968 1.6151907
# 95 -0.5302965 1.8952759
# 80 -2.0744048 2.1686003

# And then, if you would prefer the rows to be in
# their original order, just do:
d[sort(as.numeric(rownames(res))), ]
#            x         y
# 20  2.3102968 1.6151907
# 64  2.5819589 0.7946803
# 80 -2.0744048 2.1686003
# 95 -0.5302965 1.8952759

Or, using the rPref package:
library(rPref)
psel(d, high(x) | high(y))
#             x         y
# 20  2.3102968 1.6151907
# 64  2.5819589 0.7946803
# 80 -2.0744048 2.1686003
# 95 -0.5302965 1.8952759

A: Here is an sqldf solution where DF is the data frame of data:
library(sqldf)
sqldf("select * from DF a
 where not exists (
   select * from DF b
   where b.Col1 >= a.Col1 and b.Col2 >  a.Col2
      or b.Col1 >  a.Col1 and b.Col2 >= a.Col2
 )"
)

A: This question is pretty old, but meanwhile there is a new solution. I hope it is ok to do some self-promotion here: I developed a package rPref which does an efficient Skyline computation due to C++ algorithms. With installed rPref package the query from the question can be done via (assuming that df is the name of data set):
library(rPref)
psel(df, high(Col1) | high(Col2))

This removes only those tuples, where some other tuple is better in both dimensions.
If one requires the other tuple to be strictly better in just one dimension (and better or equal in the other dimension), use high(Col1) * high(Col2) instead.

A: That problem is called a "skyline query" by database administrators (they may have other algorithms) and an "efficient frontier" by economists.
Plotting the data can make it clear what we are looking for.
n <- 40
d <- data.frame(
  x = rnorm(n),
  y = rnorm(n)
)
# We want the "extreme" points in the following plot
par(mar=c(1,1,1,1))
plot(d, axes=FALSE, xlab="", ylab="")
for(i in 1:n) {
  polygon( c(-10,d$x[i],d$x[i],-10), c(-10,-10,d$y[i],d$y[i]),
  col=rgb(.9,.9,.9,.2))
}

The algorithm is as follows: sort the points along the first coordinate,
keep each observation unless it is worse than the last retained one.
d <- d[ order(d$x, decreasing=TRUE), ]
result <- d[1,]
for(i in seq_len(nrow(d))[-1] ) {
  if( d$y[i] > result$y[nrow(result)] ) {
    result <- rbind(result, d[i,])  # inefficient
  }
}
points(result, cex=3, pch=15)

A: In one line:
d <- matrix(c(2, 3, 4, 7, 5, 6), nrow=3, byrow=TRUE)
d[!apply(d,1,max)<max(apply(d,1,min)),]

     [,1] [,2]
[1,]    4    7
[2,]    5    6

Edit: In light of your precision in jbaums' response, here's how to check for both columns separately.
d <- matrix(c(2, 3, 3, 7, 5, 6, 4, 8), nrow=4, byrow=TRUE)
d[apply(d,1,min)>min(apply(d,1,max)) ,]

     [,1] [,2]
[1,]    5    6
[2,]    4    8

A: d <- matrix(c(2, 3, 4, 7, 5, 6), nrow=3, byrow=TRUE)
d2 <- sapply(d[, 1], function(x) x < d[, 1]) &
      sapply(d[, 2], function(x) x < d[, 2])
d2 <- apply(d2, 2, any)
result <- d[!d2, ]


text:
Q: Is this an N+1 problem and how do I fix it? I have a list of projects and a list of customers. A project can be for one customer and every customer can have many projects. So it's a simple 1:n relationship where the project is the owning side.
Simplified to the essential it is
@Entity
public class Project {
  @Id
  long id;

  @ManyToOne(optional = true)
  @JoinColumn(name = "customer", nullable = true, updatable = true)
  Customer customer;
}

@Entity
public class Customer {
  @Id
  long id;
}

When I load a list of projects, I want to retrieve the customers efficiently at the same time. This is not the case. There is one single query for the projects and then for every distinct customer that is encountered a separate query is issued.
So say I have 100 projects that are assigned to 50 different customers. This would result in one query for the projects and 50 queries for the customers.
This quickly adds up and for large project/customer lists our application gets rather slow. Also this is just one example. All our entities with relationships are affected by this behavior.
I already tried @Fetch(FetchMode.JOIN) on the customers field as suggested here but it does nothing and FetchMode.SUBQUERY is not applicable according to Hibernate:

org.hibernate.AnnotationException: Use of FetchMode.SUBSELECT not allowed on ToOne associations

How can I fix this problem?

A: If you are using Spring Data JPA to implement your repositories, you can specify lazy fetching in the JPA entities:
@Entity
public class Project {
  @Id
  long id;

  @ManyToOne(fetch = FetchType.LAZY, optional = true)
  @JoinColumn(name = "customer", nullable = true, updatable = true)
  Customer customer;
}

@Entity
public class Customer {
  @Id
  long id;
...
}

And add @EntityGraph to your Spring Data JPA-based repository:
@Repository
public interface ProjectDao extends JpaRepository<Project, Long> {

    @EntityGraph(
            type = EntityGraphType.FETCH,
            attributePaths = {
                    "customer"
            }
    )
    Optional<Project> findById(Long id);
...
}

My blog post at https://tech.asimio.net/2020/11/06/Preventing-N-plus-1-select-problem-using-Spring-Data-JPA-EntityGraph.html helps you preventing the N+1 select problem using Spring Data JPA and @EntityGraph.

A: Yes, it is a by-the-book example of the n+1 selects problem.
The approach I use in most cases is to make the association lazy and define a batch size.
Alternatively, you could use a JPQL query with [left] join fetch to initialize the association directly from the query result set:
select p from Project p left join fetch p.customer

A: Yes, it is a by-the-book example of the n+1 selects problem as @dragan-bozanovic said.
In Spring-Boot 2.1.3 @Fetch(FetchMode.JOIN) can be used to solve it:
  @ManyToOne(optional = true)
  @Fetch(FetchMode.JOIN)
  @JoinColumn(name = "customer", nullable = true, updatable = true)
  Customer customer;

Warning: If the relationship can be invalid, for example when marked with @NotFound(action = NotFoundAction.IGNORE), each invalid relationship will trigger another SELECT query.


text:
Q: Haskell appears to be ignoring the closing ')' in a function call inside a function I'm doing homework for a class on haskell, and we are building an interpreter. the first set of functions is to evaluate variables,
evalE (Var x) s        = subEv (Map.lookup x s)
where subEv (Just a)   = a
      subEv (Nothing)  = (IntVal 0)
evalE (Val v) s       = v
evalE (Op o e1 e2) s  = (evalE e1 s) 'o' (evalE e2 s)

So, the first two versions work fine, the issue is on the third evalE, the compiler keeps interpreting the (evalE e1 s) 'o' (evalE e2 s) as if the o and (evalE e2 s) are being given as arguments to the (evalE e1 s)
I can't figure out why it is ignoring the existence of the first closing parenthesis, and I'm new to haskell so I can't see where any syntax errors are in that line. But regardless, the compiler won't compile and says there are too many arguments to evalE, and I'm losing patience fast since it doesn't seem like anything should be wrong. Am I completely missing something from here?
On further testing, the same issue appears anywhere within the code for evalE that a function is called (even functions that are not recursive seem to be ignoring the ')' )

A: I assume that o is a two-argument function and you want to use it as an infix operator. Then you have to use backticks instead of single quotes (which are for character literals).
Try to change your last clause as follows:
evalE (Op o e1 e2) s  = (evalE e1 s) `o` (evalE e2 s)

To wrap up: foo 'f' bar means "call foo with character 'f' and bar as the parameters", while foo `f` bar means "apply f to foo and bar".
So the compiler's behaviour was perfectly correct.


text:
Q: sum of 2 number with object and method why am I getting these errors?
Undefined variable: num1
Cannot access empty property
class sum{
    public $num1=1;
public function fun($num2){
     return $this->$num1+$num2;
    }
}
$number = new sum();
echo $number->fun(3);

A: class sum{
   public $num1=1;
   public function fun($num2){
        return $this->num1+$num2;
          //removed $^^
   }
}
$number = new sum();
echo $number->fun(3);


text:
Q: VueJS and Webpack: Unit Testing error -- do I need the default HelloWorld component? I am using vue-cli with webpack for the first time and trying out the unit testing feature. However, I deleted the default HelloWorld.vue component because I didn't need that in my custom app. So, when running the following command in terminal I get a unit testing error:

$ npm run test

> vuetemplate@1.0.0 test D:\Users\myName\Desktop\vue-cli-webpacktemplate
> npm run unit

> vuetemplate@1.0.0 unit D:\Users\myName\Desktop\vue-cli-webpacktemplate
> jest --config test/unit/jest.conf.js --coverage

 FAIL  test\unit\specs\HelloWorld.spec.js
  ● Test suite failed to run

    Configuration error:

    Could not locate module @/components/HelloWorld (mapped as D:\Users\myName\Desktop\vue-cli-webpacktemplate\src\components/HelloWorld)

    Please check:

    "moduleNameMapper": {
      "/^@\/(.*)$/": "D:\Users\myName\Desktop\vue-cli-webpacktemplate\src\$1"
    },
    "resolver": undefined

Test Suites: 1 failed, 1 total

My question: I'd like to do unit testing on my app. Do I need to put that default HelloWorld component back in order to successfully do testing on my app? Or, is there a way to skip it? Not sure what to do here. Thanks.

A: Check if it is not referenced as an import on your AppComponent or any other component. Maybe on the tests.


text:
Q: Order sender file is not ovverriding My di.xml file is
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <preference for="Magento\Sales\Model\Order\Email\Sender\OrderSender" type="ABC\Listrak\Model\Order\Email\Sender\OrderSender" />
</config>

My class
namespace ABC\Listrak\Model\Order\Email\Sender;

class OrderSender extends \Magento\Sales\Model\Order\Email\Sender\OrderSender
{
    public function __construct(
            \Psr\Log\LoggerInterface $logger
    )
    {
        $this->logger = $logger;
    }

    public function send(Order $order, $forceSyncMode = false)
    {
        $order->setSendEmail(true);

        if (!$this->globalConfig->getValue('sales_email/general/async_sending') || $forceSyncMode) {
            if ($this->checkAndSend($order)) {
                $order->setEmailSent(true);
                $this->orderResource->saveAttribute($order, ['send_email', 'email_sent']);
                return true;
            }
        }

        $this->orderResource->saveAttribute($order, 'send_email');

        return false;
    }

}

But i get Error
Warning: Declaration of ABC\Listrak\Model\Order\Email\Sender\OrderSender::send(ABC\Listrak\Model\Order\Email\Sender\Order $order, $forceSyncMode = false) should be compatible with Magento\Sales\Model\Order\Email\Sender\OrderSender::send(Magento\Sales\Model\Order $order, $forceSyncMode = false) in C:\wamp64\www\huf\app\code\ABC\Listrak\Model\Order\Email\Sender\OrderSender.php on line 41

If someone can help with this
Thanks

A: Your Class file OrderSender.php content should like this.
namespace ABC\Listrak\Model\Order\Email\Sender;

use Magento\Sales\Model\Order;

class OrderSender extends \Magento\Sales\Model\Order\Email\Sender\OrderSender
{
    public function __construct(
            \Psr\Log\LoggerInterface $logger
    )
    {
        $this->logger = $logger;
    }

    public function send(Order $order, $forceSyncMode = false)
    {
        $order->setSendEmail(true);

        if (!$this->globalConfig->getValue('sales_email/general/async_sending') || $forceSyncMode) {
            if ($this->checkAndSend($order)) {
                $order->setEmailSent(true);
                $this->orderResource->saveAttribute($order, ['send_email', 'email_sent']);
                return true;
            }
        }

        $this->orderResource->saveAttribute($order, 'send_email');

        return false;
    }
}

I have added use Magento\Sales\Model\Order; after namespace ABC\Listrak\Model\Order\Email\Sender;.


text:
Q: Eclipse Installs .APK in the BIN Folder? Will not show up? [2013-05-07 13:06:56 - final_app] Performing sync
[2013-05-07 13:06:56 - final_app] Automatic Target Mode: Several compatible targets. Please select a target device.
[2013-05-07 13:07:02 - final_app] Uploading final_app.apk onto device '015d256464281611'
[2013-05-07 13:07:14 - final_app] Installing final_app.apk...
[2013-05-07 13:07:18 - final_app] Success!
[2013-05-07 13:07:18 - final_app] \final_app\bin\final_app.apk installed on device
[2013-05-07 13:07:18 - final_app] Done!

Hi I have been pulling my hair out for the past 24 hours I am a newbie and added Google Maps after this I'm not sure what the issue has been I can no longer launch the app on my Nexus 7 or the AVD it does not show up, I have got my API key etc. but now the app installs  \final_app\bin\final_app.apk and I can not launch it any more I selected Googles APi everything should function properly, how do I launch the app again there is no icon what so ever. Could it be my manifest?
ANDROIDMANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.final_app"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       <uses-library android:name="com.google.android.maps"/>
        <activity
            android:name="com.example.final_app.splash_screen"
            android:label="@string/app_name" ></activity>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        <activity android:name="MainActivity"></activity>
        <activity android:name=".activity_2"></activity>
        <activity android:name=".activity_3"></activity>
        <activity android:name=".activity_4"></activity>
        <activity android:name=".activity_5"></activity>
        <activity android:name=".MySQLiteHelper"></activity>
    </application>
</manifest>

In short, I want to: Launch my app as it no longer shows up or starts on both my android device or AVD.

A: I think I got your error, it was in the menifest file
<activity android:name="MainActivity"></activity>

it should be
<activity android:name=".MainActivity"></activity>

or follow this menifest file
 <application
    android:icon="@drawable/test"
    android:label="@string/app_name" >
    <activity
        android:name=".ABC"
        android:label="@string/app_name"   android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".welcome" android:theme="@style/Custom" android:label="@string/app_name"  android:screenOrientation="portrait">
    </activity>

it should work i guess,..


text:
Q: IndexError: list index out of range when assigning values to tuples from a for loop I am trying to create two sets of tuples to use as coordinates for the colour of the squares of a chessboard but I can't seem to get rid of the error: "IndexError: list index out of range".
Do you have an idea as to why it returns this error?
alpha = ["a","b","c","d","e","f","g"]

chessSquareBlack = []
chessSquareWhite = []

for i in range(8):
    for j in range(8):

        if ((i+1) % 2 == 0 and (j+1) % 2 != 0) or (i+1) % 2 != 0 and (j+1) % 2 == 0:
            chessSquareBlack.append(((alpha[i]),(j+1)))

        elif ((i+1) % 2 != 0 and (j+1) % 2 == 0) or (i+1) % 2 == 0 and (j+1) % 2 != 0:
            chessSquareWhite.append(((alpha[i]), (j+1)))

A: Your list alpha has a length of 7, but you are iterating up to 7. Since python starts indexing at 0, you get an IndexError.
Just change range(8) to range(7) and you are good.
However it should be said that in your second if statement for the white squares something is wrong with your conditions, as it is never actually opened as the condition is always false.

A: alpha = ["a","b","c","d","e","f","g"]

chessSquareBlack = []
chessSquareWhite = []

Instead of 7 or 8, you can check the length of the list "alpha" and use it in the for loop as below. This would be generic and hence you will not have to hardcode it everytime:
range(len(alpha))
for i in range(len(alpha)):
    for j in range(len(alpha)):
    #enter code here


text:
Q: Cypress with SystemJS I am attempting to create some basic tests to try out the new Cypress library. In my test I have cy.visit('http://mywebsite.com'); which is loading an AngularJS app that uses SystemJS.
If I understand Cypress correctly, I shouldn't have to do anything else and it will make sure the page is loaded before running anything else. However this doesn't seem to be working because the page is loaded, but SystemJS is still loading the modules.
How can I get Cypress to wait for all the SystemJS modules to load before running any more tests without using cy.wait(5000)?
EDIT
Thanks to Dwelle this is the solution that works for me. I wrap the initial System.import in a promise that gets resolved once the AngularJS app has been bootstrapped.
window.APP_READY = new Promise(function(resolve, reject) {
    System.import('app').then(function(app) {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['app']);
            resolve();
        });
    });
});

And then in the test
cy.visit('http://mywebsite.com').its('APP_READY');

A: Not familiar with SystemJS or your app, but if we assume you're doing some asynchronous work on load, you can set up some global property which indicates whether the app is ready or not.
// your main.js
let _appReadyResolver;
window.APP_READY = new Promise( resolve => _appReadyResolver = resolve );

// do some async setup
setTimeout(() => {

    _appReadyResolver();
});

Then, in your tests:
cy.visit("/")
    // by default will wait 4sec for APP_READY prop to exist on
    //  window object (unfortunately I don't know how to increase timeouts
    //  of `cy.its` command)
    // After that, it will wait indefinitely for your promise to resolve
    .its("APP_READY")

That being said --- if you're not doing any async setup in your app, but the main.js is simply being loaded asynchronously and it can take longer than 4sec, then I'd do this:
// index.js
<script>
  SystemJS.import('/js/main.js');
  window.APP_READY = new Promise( resolve => {
    let interval = setInterval(() => {
        if ( window.MAIN_READY ) {
            resolve();
            clearTimeout(interval);
        };
  }, 100 );
</script>

// main.js
window.MAIN_READY = true;

You'll want to strip the APP_READY logic from production build.

A: In theory, you can also solve this in a pure Cypress way.
If your page makes any request which indicates that your app is ready, you can make Cypress wait for it to complete before it proceeds. You might find this cleaner than the APP_READY work-around. Its just an opinion though, as this approach will fail if there are not requests you can trust to signal that your app is ready.
cy.server();
cy.route('**/api/getData').as('getData');
cy.visit('/home');
cy.wait('@getData');

Cypress best practices: Unnecessary-Waiting.
Cypress docs on wait Alias.


text:
Q: Find a real number a < 1 so that the events are independent. Let $X \sim \mathrm{Exp}(2)$. Find a real number $a < 1$ so that the events
$\{X \in [0, 1]\}$ and $\{X \in [a, 2]\}$ are independent.
I'm stuck on this one. So far I found $P(X \in [a, 2])$ and $P(X \in [0, 1])$. Where do I go from here?

A: Let $E=\{X\in[0,1]\}$ and $F=\{X\in[a,2]\}$. For $E$ and $F$ to be independent, we must have
$$
\mathbb P(E\cap F) = \mathbb P(E)\mathbb P(F).
$$
Now,
$$
\mathbb P(E) = \int_0^1 2e^{-2t}\ \mathsf dt = 1-e^{-2}
$$
and
$$
\mathbb P(F) = \int_a^2 2e^{-2t}\ \mathsf dt = e^{-2a}-e^{-4}.
$$
The product is then given by
$$
\mathbb P(E)\mathbb P(F) = \left(1-e^{-2}\right)\left(e^{-2a}-e^{-4}\right).\tag1
$$
Since this quantity is never zero, $E\cap F$ must be nonempty. For $a\in(0,1)$ we have $\mathbb E\cap F = \{X\in[a,1]\}$, and so
$$
\mathbb P(E\cap F) = \int_a^1 2e^{-2t} = e^{-2a} - e^{-2}.\tag2
$$
Equating $(1)$ and $(2)$, we have
$$
\left(1-e^{-2}\right)\left(e^{-2a}-e^{-4}\right) = e^{-2a} - e^{-2},
$$
and hence
$$
a = 2-\frac{1}{2} \log \left(1-e^2+e^4\right)\approx 0.06223.
$$


text:
Q: Dynamics CRM Plugin Shared variables - Object or Array We have a scenario where we need to calculate multiple fee components & share between Pre & Post stages of a Plugin. So we created the object like this.
class FeeCalculation
    {
        public string TotalFee { get; set; }
        public string FilingFee { get; set; }
        public string LegalFee { get; set; }
        public string RecordFee { get; set; }
    }

So far we have used single fee component & shared variable worked nicely. When tried to assign the whole object - the result is not fruitful.
context.SharedVariables.Add("fees", fcObject);

Is there a way to achieve this expected result?

A: The plugin infrastructure must be able to serialize/deserialize the objects that are in your SharedVariables collection. It has no knowledge of custom types like the FeeCalculation class and therefore cannot serialize it.
Use primitive types, common .NET types (e.g. a List of decimals should work) or CRM types (Entity, Money etc.). It's good to note that the SharedVariables collection is a key value pair collection. So, why not just add items to it with keys like "TotalFee", "FilingFee" etc?

A: I was trying to share an IEnumerable<Guid>, but collections like List did not work.
Of course you can always serialize to string, but your plugin code really shouldn't have to deal with serialization of common types.
After some trial and error, I ended up using arrays, i.e. Guid[].


text:
Q: File showing in Sources tab but not in Network I'm verifying that I'm using minified JavaScript in Chrome. I've cleared my cache and loaded the page. In the Sources tab I see:

But on the Network tab (note the filter) I see only:

I have not found the unminified angular.js referenced anywhere, and the Network tab does not show it as loaded. As far as I can tell I don't have any workspace folders added. Is this file actually being loaded? If so, how can I determine from where?

A: Found it - this is because of the Source Maps in DevTools feature. As a .map file named angular.min.js.map existed, Chrome loaded the original source file in addition to the minified one.


text:
Q: Tensorflow: How to Optimize the Prediction on GCloud-ML? I have a model published on GCloud-ML and it is working fine. I can do the Online predicitons and get the right results. My issue is the Performance. Each predict (inference) takes around 3.5 seconds and it is not good for my case. I'm using automatically scale and my bucket is US-Central. My images have around 100Kb and I'm in Brazil (in the GCloud Console I can see tha latency --> 1.5 seconds).
I already tried the optimazed_for_inference.py but it didn't work (I can't generate the saved_model from the optimazed graph. It is possible?).
I need to get the result at least in 2 seconds. My doubt is: Is it possible to do that?
or is it normal to get results in 3 / 4 seconds using gcloud-ml predict?
Thanks! Any ideas are well coming! If you need more information to help me, please add a comment!
Thanks again!


text:
Q: Kendo Splitter Nesting with Treeview I am getting the error:

Delegate 'System.Action' does not take 1 arguments

While creating a Splitter with Partial view rendered inside one of the panes of Splitter. The error is at Content property of the the pane. Please suggest me any changes to solve the problem
@(Html.Kendo().Splitter()
  .Name("vertical")
  .HtmlAttributes(new { style = "height:900px" })
  .Orientation(SplitterOrientation.Horizontal)
  .Panes(panes =>
  {
      panes.Add()
          .HtmlAttributes(new { id = "pane1" })
          .Resizable(true)
          .Size("300px")
          .Collapsible(false)
          .Content((@<text><div>@Html.RenderPartial("GetUsers", Model)</div></text>));
  })
)

A: with the information from the following link I am able solve my problem. When you have to nest container controls of kendo UI you need to create a helper method for nested content and call the helper method as cotent for container control.
Kendo widgets two level deep in Razor, inline markup blocks cannot be nested


text:
Q: Firing this function onClick i have this code:
The question is:
How can i fire this code onClick instead?
JS:
 $("input[type=radio],button").each(function () {
        var outputName = $(this).attr("data-midioutput");
        if (outputName) {
            var output = MidiUtil.getOutput(outputName);
            if (output) {
                var outputName = $(this).attr("data-midioutput");
                var midiChannel = $(this).attr("data-midichannel");
                if (!midiChannel)
                    midiChannel = 0;

                var cc = $(this).attr("data-midicc");
                var midiValue = $(this).attr("data-midivalue");

                if (outputName && cc) {
                    var output = MidiUtil.getOutput(outputName);
                    if (output) {

                        if ($(this).attr("type") == "number") {
                            this.oninput = function () {
                                    output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), $(this).val()]);

                            };
                            //Send initial value
                                output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), $(this).val()]);
                        }
                        else { //button
                            this.onclick = function () {
                                    output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), parseInt(midiValue, 10)]);
                            };
                        }

                    }
                    else {

                    }
                }
            }

        }
        else {

        }

    });

Which is automatically fired by buttons like this:
HTML:
<button class="1" data-midicc="19" data-midivalue="0" data-midichannel="00" data-midioutput="IAC 1" />

The question is:
How can i fire this code onClick instead?
Thanks!

A: Just changing the 'Jquery-each' statement to click event binding works for you well.
$("input[type=radio],button").on('click',function () {
        var outputName = $(this).attr("data-midioutput");
        if (outputName) {
            var output = MidiUtil.getOutput(outputName);
            if (output) {
                var outputName = $(this).attr("data-midioutput");
                var midiChannel = $(this).attr("data-midichannel");
                if (!midiChannel)
                    midiChannel = 0;

                var cc = $(this).attr("data-midicc");
                var midiValue = $(this).attr("data-midivalue");

                if (outputName && cc) {
                    var output = MidiUtil.getOutput(outputName);
                    if (output) {

                        if ($(this).attr("type") == "number") {
                            this.oninput = function () {
                                    output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), $(this).val()]);

                            };
                            //Send initial value
                                output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), $(this).val()]);
                        }
                        else { //button
                            this.onclick = function () {
                                    output.send([MidiUtil.eventTypes.MIDI_CC_CH1 + parseInt(midiChannel, 10), parseInt(cc, 10), parseInt(midiValue, 10)]);
                            };
                        }

                    }
                    else {

                    }
                }
            }

        }
        else {

        }
})


text:
Q: WordPress & Woocommerce with Dynamic Pricing unserialized string not parsing as array foreach The following serialized string is being pulled from the meta data of a Woocommerce product.
a:2:{s:17:"set_51fb76f97cc57";a:6:{s:15:"conditions_type";s:3:"all";s:10:"conditions";a:1:{i:1;a:2:{s:4:"type";s:8:"apply_to";s:4:"args";a:2:{s:10:"applies_to";s:5:"roles";s:5:"roles";a:1:{i:0;s:14:"trade_customer";}}}}s:9:"collector";a:1:{s:4:"type";s:7:"product";}s:4:"mode";s:5:"block";s:5:"rules";a:1:{i:1;a:4:{s:4:"from";s:0:"";s:2:"to";s:0:"";s:4:"type";s:14:"price_discount";s:6:"amount";s:0:"";}}s:10:"blockrules";a:1:{i:1;a:5:{s:4:"from";s:1:"*";s:6:"adjust";s:1:"1";s:4:"type";s:16:"fixed_adjustment";s:6:"amount";s:4:"8.37";s:9:"repeating";s:3:"yes";}}}s:17:"set_51fb76f97d6a2";a:6:{s:15:"conditions_type";s:3:"all";s:10:"conditions";a:1:{i:1;a:2:{s:4:"type";s:8:"apply_to";s:4:"args";a:2:{s:10:"applies_to";s:5:"roles";s:5:"roles";a:1:{i:0;s:19:"bulk_trade_customer";}}}}s:9:"collector";a:1:{s:4:"type";s:7:"product";}s:4:"mode";s:5:"block";s:5:"rules";a:1:{i:1;a:4:{s:4:"from";s:0:"";s:2:"to";s:0:"";s:4:"type";s:14:"price_discount";s:6:"amount";s:0:"";}}s:10:"blockrules";a:1:{i:1;a:5:{s:4:"from";s:1:"*";s:6:"adjust";s:1:"1";s:4:"type";s:16:"fixed_adjustment";s:6:"amount";s:5:"9.428";s:9:"repeating";s:3:"yes";}}}}

That's using Woocommerce with the Dynamic Pricing plugin.
I also have this function which I am writing in order to pull out the variable product data and display it on the site:
function mi_price_adjust(){
    global $post, $current_user, $user_roles;
    $meta = get_post_meta($post->ID);
    $curPrice = (float)$meta['_regular_price'][0];
    $variations = unserialize($meta['_pricing_rules'][0]);
    $user_roles = $current_user->roles;
    $theRoll = '';
    $thePrice = $curPrice;

    foreach($user_roles as $miroll){
        if(in_array($miroll, $user_roles)){
            $theRoll =  $miroll;
        }
    }

    if($theRoll != ''){
        foreach($variations as $curvar){
            $var_roll = $curvar['conditions'][1]['args']['roles'][0];
            $var_cost = (float)$curvar['blockrules'][1]['amount'];
            if($var_roll == $theRoll){
                $thePrice = $curPrice - $var_cost;
            }
        }

    }

    if($thePrice != $curPrice){
        return "".$curPrice."
You pay £$thePrice";
    }else{
        return  $thePrice;
    }

}

Everything is working fine apart from one thing. I am getting the following error:

Invalid argument supplied for foreach

The line in question is
foreach($variations as $curvar){

And the $variations variable is being populated using this:
$variations = unserialize($meta['_pricing_rules'][0]);

Which returns the serialized string at the top of this post.
Can anyone shed any light on why this might be happening and what we might be able to do to either fix it or circumvent it?


text:
Q: Access Report: Wrap Text Not Working I have a report with unbound textbox's in them. I populate these fields onLoad.
The problem, though, is that the if the text is too long, it will not wrap.  I have set Can Grow = Yes but this does not seem to work.
Is it due to the fact I am adding the string to the field OnLoad? If so, how can I overcome this and force the text to wrap? I would want the width to remain constant, but the height to grow.

A: Figured this out... I right clicked the text box and selected Size > To Fit...
I had the box big enough to accommodate a second line. It wouldn't ever word wrap until I made the change above. Can Grow and Can Shrink did nothing, but I left them selected.

A: I open report from code in design mode, make changes to control source of the text fields, save and close report and lastly open it in preview mode. The only way I get what I want.

A: I know this is an old post but I've been running into the same issue and haven't been able to figure out a solution until now.
One of the fields in print preview was getting cut off for me and despite my best efforts to make sure all the formatting settings were correct (i.e. Can Grow/Shrink: On) for both the detail section and the specific field. Again, this issue only happened in print preview, which meant the reports that were getting printed had the text cut off.
Solution:
I ended up realizing that all of the other text fields were set to Plain Text and the text field giving me the issue was set to Rich Text. I changed it to Plain Text and voila! It displayed everything without any issues.
My guess is that if you're having this issue, make sure all of the fields are set to the same property (Rich Text/Plain Text). Not sure why Access has trouble with this but I hope this solution helps someone else out.

A: The simple solution to this huge problem is listed below.

*

*Convert the property of the textbox from plain text to rich text.

*Set the text align property to distribute.

*Enable can shrink and can grow property of the text box. (Yes)

Done.

A: After a lot trial-and-error, the solution seems to be that the text box that you want to scroll must have enough height to show two vertical lines. A textbox that is only one line high will not scroll. (You must also have Can Grow set to 'Yes' for both the textbox and the detail section.)

A: You also have to have the CAN GROW of the section that the text box is in set to YES as well as the text box.


text:
Q: Displaying Google Play Achievements I have made a game, and when playing it the achievements show as a pop up in game when awarded.  And it appears to be working correctly, they're iterating when they're meant to, they're being awarded for completing set tasks as they're meant to.  But on the screen in "Play Games", it doesn't display them, and when you click on an achievement in the pop up, it doesn't let you view them.
Like so:

I want it to appear like:

What am I missing?  I've looked all over the developer console and can't find anything to make this change.

A: From the Google Play Games Service documentation, Make sure that you follow the instruction here that to show a player's achievements, call getAchievementsIntent() to get an Intent to create the default achievements UI. Your game can then bring up the UI by calling startActivityForResult
startActivityForResult(Games.Achievements.getAchievementsIntent(mGoogleApiClient),
        REQUEST_ACHIEVEMENTS);

In the following snippet, REQUEST_ACHIEVEMENTS is an arbitrary integer used as the request code.
Also from this SO question, make sure you publish the game in the developer console, to see the achievements in the activity
If this options adidn't work on you, then maybe AlexeyGorovoy is correct.

A: This might happen because you haven't publish your game in Game Services.
First publish game in google service which is situated in Google Play Developer Console.
Then your achievements tab will be created under your game in Play Games.


text:
Q: why 0, not Nothing in VB System.Data.DataTable The codes:
        Private m_log_dataTable As System.Data.DataTable = Nothing
        Private m_freq As String = Nothing
        Private m_r As Single = Nothing
        Private m_l As Single = Nothing
        Private m_c As Single = Nothing
        Private m_rp As Single = Nothing
        Private m_rs As Single = Nothing
        Private m_z As Single = Nothing
        Private m_esr As Single = Nothing
        Private m_dcr As Single = Nothing
        Private m_q As Single = Nothing
        Private m_d As Single = Nothing

...
    Private Sub LOG()
        Try
            m_freq = Nothing
            m_r = Nothing
            m_l = Nothing
            m_c = Nothing
            m_rp = Nothing
            m_rs = Nothing
            m_z = Nothing
            m_esr = Nothing
            m_dcr = Nothing
            m_q = Nothing
            m_d = Nothing
            m_value = Nothing
            m_unit = Nothing
            m_log_dataTable.Rows.Add(DateTime.Now, getDUT(), getMode(), m_freq, m_r, m_l, m_c, m_r, m_rs, m_z, m_esr, m_dcr, m_q, m_d)'Line1
            m_log_dataTable.Rows.Add(DateTime.Now, getDUT(), getMode(), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)'Line2
        Catch ex As Exception
            MsgBox("Exception when logging:" + ex.Message)
        End Try
    End Sub

Output:

Why line1 (in the above codes) write 0 to the datatable instead of Nothing?
What should I do?
Thanks

A: You need to use a Nullable type. Change all of your single types to single? and try it again.
Private m_r As Single? = Nothing
Private m_l As Single? = Nothing

// etc

As Gabor commented, you'll need to access the Value property or one of the other methods that are available to Nullable(Of T).
m_r.Value                 ' Access the underlying value

m_r.GetValueOrDefault()   ' Underlying value or, if none, default for the underlying type

m_r.GetValueOrDefault(3)  ' Underlying value or, if none, some default value you decide

A: Nothing in VB.NET equals to default(T) in C# (instead of null). Value types cannot be null therefore in db they are represented in columns with not null constraint.
You indeed should use Nullable(Of Single) (which is the same as Single?) for your fields.
But of course this is not enough. You should modify the columns in the database so that they will have null constraint instead of not null and the System.Data.DataTable should be configured the same way.

A: Coz The default value of Single is 0.You can use string column or you can define target datagridview's columns.
DataGridViewCellStyle1.Format = "N"
Column1.DefaultCellStyle = DataGridViewCellStyle1


text:
Q: "android.view.WindowManager$BadTokenException: Unable to add window" on buider.show() From my main activity, I need to call an inner class and in a method within the class, I need to show AlertDialog. After dismissing it, when the OK button is pressed, forward to Google Play for purchase.
Things work perfectly for most of the times, but for few users it is crashing on builder.show() and I can see "android.view.WindowManager$BadTokenException: Unable to add window" from crash log. Please suggest.
My code is pretty much like this:
public class classname1 extends Activity{

  public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.<view>);

    //call the <className1> class to execute
  }

  private class classNamename2 extends AsyncTask<String, Void, String>{

    protected String doInBackground(String... params) {}

    protected void onPostExecute(String result){
      if(page.contains("error"))
      {
        AlertDialog.Builder builder = new AlertDialog.Builder(classname1.this);
        builder.setCancelable(true);
        builder.setMessage("");
        builder.setInverseBackgroundForced(true);
        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){
            dialog.dismiss();
            if(!<condition>)
            {
              try
              {
                String pl = "";

                mHelper.<flow>(<class>.this, SKU, RC_REQUEST,
                  <listener>, pl);
              }

              catch(Exception e)
              {
                e.printStackTrace();
              }
            }
          }
        });

        builder.show();
      }
    }
  }
}

I have also seen the error in another alert where I am not forwarding to any other activity. It's simple like this:
AlertDialog.Builder builder = new AlertDialog.Builder(classname1.this);
    builder.setCancelable(true);

    //if successful
    builder.setMessage(" ");
    builder.setInverseBackgroundForced(true);
    builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton){
            // dialog.dismiss();
                   }
    });
    builder.show();
}

A: The possible reason is the context of the alert dialog. You may be finished that activity so its trying to open in that context but which is already closed.
Try changing the context of that dialog to you first activity beacause it won't be finished till the end.
e.g
rather than this.
AlertDialog alertDialog = new AlertDialog.Builder(this).create();

try to use
AlertDialog alertDialog = new AlertDialog.Builder(FirstActivity.getInstance()).create();

A: I had dialog showing function:
void showDialog(){
    new AlertDialog.Builder(MyActivity.this)
    ...
    .show();
}

I was getting this error and i just had to check isFinishing() before calling this dialog showing function.
if(!isFinishing())
    showDialog();

A: *

*first you cannot extend AsyncTask without override doInBackground

*second try to create AlterDailog from the builder then call show().
private boolean visible = false;
class chkSubscription extends AsyncTask<String, Void, String>
{

    protected void onPostExecute(String result)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(true);
        builder.setMessage(sucObject);
        builder.setInverseBackgroundForced(true);
        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                dialog.dismiss();
            }
        });

        AlertDialog myAlertDialog = builder.create();
        if(visible) myAlertDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0)
    {
        // TODO Auto-generated method stub
        return null;
    }
}

@Override
protected void onResume()
{
    // TODO Auto-generated method stub
    super.onResume();
    visible = true;
}

@Override
protected void onStop()
{
    visible = false;
    super.onStop();
}

A: android.view.WindowManager$BadTokenException: Unable to add window"

Problem :

This exception occurs when the app is trying to notify the user from
  the background thread (AsyncTask) by opening a Dialog.
If you are trying to modify the UI from background thread (usually
  from onPostExecute() of AsyncTask) and if the activity enters
  finishing stage i.e.) explicitly calling finish(), user pressing home
  or back button or activity clean up made by Android then you get this
  error.

Reason :

The reason for this exception is that, as the exception message says,
  the activity has finished but you are trying to display a dialog with
  a context of the finished activity. Since there is no window for the
  dialog to display the android runtime throws this exception.

Solution:

Use isFinishing() method which is called by Android to check whether
  this activity is in the process of finishing: be it explicit finish()
  call or activity clean up made by Android. By using this method it is
  very easy to avoid opening dialog from background thread when activity
  is finishing.
Also maintain a weak reference for the activity (and not a strong
  reference so that activity can be destroyed once not needed) and check
  if the activity is not finishing before performing any UI using this
  activity reference (i.e. showing a dialog).

eg.
private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    super();
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)
  }

  protected String doInBackground(String... params) {
    //web service call
  }

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
    {
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setCancelable(true);
        builder.setMessage(sucObject);
        builder.setInverseBackgroundForced(true);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){
            dialog.dismiss();
          }
        });

        builder.show();
      }
    }
  }
}

Update :
Window Tokens:

As its name implies, a window token is a special type of Binder token
  that the window manager uses to uniquely identify a window in the
  system. Window tokens are important for security because they make it
  impossible for malicious applications to draw on top of the windows of
  other applications. The window manager protects against this by
  requiring applications to pass their application's window token as
  part of each request to add or remove a window. If the tokens don't
  match, the window manager rejects the request and throws a
  BadTokenException. Without window tokens, this necessary
  identification step wouldn't be possible and the window manager
  wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time,
  the ActivityManagerService creates a special kind of window token
  called an application window token, which uniquely identifies the
  application's top-level container window. The activity manager gives
  this token to both the application and the window manager, and the
  application sends the token to the window manager each time it wants
  to add a new window to the screen. This ensures secure interaction
  between the application and the window manager (by making it
  impossible to add windows on top of other applications), and also
  makes it easy for the activity manager to make direct requests to the
  window manager.

A: I am creating Dialog in onCreate and using it with show and hide. For me the root cause was not dismissing onBackPressed, which was finishing the Home activity.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

I was finishing the Home Activity onBackPressed without closing / dismissing my dialogs.
When I dismissed my dialogs the crash disappeared.
new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                networkErrorDialog.dismiss() ;
                                homeLocationErrorDialog.dismiss() ;
                                currentLocationErrorDialog.dismiss() ;
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

A: I try this it solved.
 AlertDialog.Builder builder = new AlertDialog.Builder(
                   this);
            builder.setCancelable(true);
            builder.setTitle("Opss!!");

            builder.setMessage("You Don't have anough coins to withdraw. ");
            builder.setMessage("Please read the Withdraw rules.");
            builder.setInverseBackgroundForced(true);
            builder.setPositiveButton("OK",
                    (dialog, which) -> dialog.dismiss());
            builder.create().show();

A: In my case I refactored code and put the creation of the Dialog in a separate class. I only handed over the clicked View because a View contains a context object already. This led to the same error message although all ran on the MainThread.
I then switched to handing over the Activity as well and used its context in the dialog creation
-> Everything works now.
    fun showDialogToDeletePhoto(baseActivity: BaseActivity, clickedParent: View, deletePhotoClickedListener: DeletePhotoClickedListener) {
        val dialog = AlertDialog.Builder(baseActivity) // <-- here
   .setTitle(baseActivity.getString(R.string.alert_delete_picture_dialog_title))
...
}

I , can't format the code snippet properly, sorry :(

A: I got this error, but mine was coming from the Toasts, not a Dialog.
I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.
I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command                 Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

A: with this globals variables idea,
I saved MainActivity instance in onCreate();
Android global variable
public class ApplicationController extends Application {

    public static MainActivity this_MainActivity;
}

and Open dialog like this. it worked.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Global Var
    globals = (ApplicationController) this.getApplication();
    globals.this_MainActivity = this;
}

and in a thread, I open dialog like this.
AlertDialog.Builder alert = new AlertDialog.Builder(globals.this_MainActivity);

*

*Open MainActivity

*Start a thread.

*Open dialog from thread -> work.

*Click "Back button"  ( onCreate will be called and remove first MainActivity)

*New MainActivity will start. ( and save it's instance to globals )

*Open dialog from first thread --> it will open and work.

: )

A: Try this :
    public class <class> extends Activity{

    private AlertDialog.Builder builder;

    public void onCreate(Bundle savedInstanceState) {
                    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    super.onCreate(savedInstanceState);

                setContentView(R.layout.<view>);

                builder = new AlertDialog.Builder(<class>.this);
                builder.setCancelable(true);
                builder.setMessage(<message>);
                builder.setInverseBackgroundForced(true);

        //call the <className> class to execute
}

    private class <className> extends AsyncTask<String, Void, String>{

    protected String doInBackground(String... params) {

    }
    protected void onPostExecute(String result){
        if(page.contains("error")) //when not subscribed
        {
           if(builder!=null){
                builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton){
                    dialog.dismiss();
                        if(!<condition>)
                        {
                        try
                        {
                        String pl = "";

                        mHelper.<flow>(<class>.this, SKU, RC_REQUEST,
                        <listener>, pl);
                        }

                        catch(Exception e)
                        {
                        e.printStackTrace();
                        }
                    }
                }
            });

            builder.show();
        }
    }

}
}


text:
Q: Как выполнить запросы через определенный интервал между ними в Node.js? function checkPrice(url_item){

    var url = 'http://127.0.0.1:8080/'+url_item ;
    request(url, function(err, res, body){
            if(err){console.log(err)}
            else{
                console.log("body: "+body);
            }
        }
    )

}

var mas = new Array("1011935134_188530139", "991959905_0", "360454763_188530139", "1011934384_188530139", "310776726_0", "926978479_0");

mas.forEach(function() {setTimeout(checkPrice, 1000);});

Пишу парсер.
Удаленный сервер «отваливается» при 3-4 запросах в секунду.
Как задать интервал между запросами?
[2015-08-10 00:06:42.237] [DEBUG] server - req: /1011935134_188530139
[2015-08-10 00:06:42.238] [DEBUG] server - req: /991959905_0
[2015-08-10 00:06:42.239] [DEBUG] server - req: /360454763_188530139
[2015-08-10 00:06:42.239] [DEBUG] server - req: /926978479_0
[2015-08-10 00:06:42.240] [DEBUG] server - req: /1011934384_188530139
[2015-08-10 00:06:42.240] [DEBUG] server - req: /310776726_0

Как видно из лога, setTimeout результата не принесла.

A: Насколько я понял задачу, вы хотите выполнить несколько запросов к удаленному серверу из программы на node.js, сделав при этом паузу между запросами.
Ваш вариант не работает, потому что forEach сначала последовательно "заряжает" 5 setTimeout'ов, потом через 1 секунду они все срабатываются и генерят 5 практически одновременных запросов к серверу.
Чтобы починить вариант с setTimeout, вам нужно "вложить" их друг в друга, например:
var mas = new Array("1011935134_188530139", "991959905_0", "360454763_188530139", "1011934384_188530139", "310776726_0", "926978479_0");
(function fireRequestAndWait(i) {
  checkPrice(mas[i]);
  if(i >= mas.length) return;

  setTimeout(function() {
    fireRequestAndWait(i+1);
  }, 1000);
})(0);

Пример только для понимания, писать я бы так не рекомендовал.
Более промышленное решение (с учетом того, что вам наверное еще и результаты запросов интересны) - найти подходящую библиотеку, которая скроет эти некрасивости за нормальным API. Как пример (не зная вашей конкретной задачи), async#reduce.
В светлом будущем ES6 (или сейчас, если вы смело используете io.js) вы можете писать почти обычный последовательный код с помощью "генераторов" (пример утащил отсюда, co - еще одна библиотека):
function* waitAndDo(times) {
  for(var i=0; i<times; i++) {

    // Sleep
    yield function(callback) {
      setTimeout(callback, 1000);
    }

    // Do something here
    console.log('Doing a request');
  }
}

var co = require('co');

co(function* () {
  yield waitAndDo(10);
});


text:
Q: Proving that Lie groups are locally connected I'm trying to show that if $G$ is a Lie group, then it is locally connected, i.e., for any point $p$ in an open subset $U$ of $G$, there is a connected neighborhood $V$ of $p$ such that $V\subset U$. This is a step in my proof that the identity component of a Lie group is open, since I know that the connected components of a locally connected topological space are open.
My thought was to say let $U$ be an open subset of $G$ and let $g\in U$. Then letting $G_0$ be the connected component of the identity, since left-multiplication by $g$ is a smooth map from $G$ to itself, I know that $gG_0$ is a connected component of $G$ containing $g$. However, is $gG_0 \subset U$?

A: A Lie group is a manifold, thus it is locally connected.


text:
Q: Shiny App (using shinydashboard) : page goes weird after login I create a shiny application but I want users to login to access the application. Then I find a way to create the login page by this:
Starting Shiny app after password input. But I have a problem that my APP using the package "shinydashboard", and after login the page goes weird. I'm not familiar with HTML things. Does any one knows how to fix this problem?
Codes are below:
library(shiny)
library(shinydashboard)
Logged = FALSE;
my_username <- "test"
my_password <- "test"

ui1 <- function(){
tagList(
div(id = "login",
    wellPanel(textInput("userName", "Username"),
              passwordInput("passwd", "Password"),
              br(),actionButton("Login", "Log in"))),
tags$style(type="text/css", "#login {font-size:10px;   text-align: left;position:absolute;top: 40%;left: 50%;margin-top: -100px;margin-left: -150px;}")
)}

ui2 <- function(){
tagList(
dashboardPage(
  dashboardHeader(title = "MY Web APP"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("menu1", tabName = "menu1", icon = icon("bank"),
               badgeColor = "blue"),
      menuItem("menu2", tabName = "menu2", icon = icon("bar-chart"))
    )),
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "menu1",
              fluidRow(
                sidebarLayout(
                  sidebarPanel(
                    selectInput("pet1","PET:",c("dog","cat","pig"),selected = "dog"),
                    fileInput(inputId = "iFile", label = "Upload Excel:",
                              accept="application/vnd.ms-excel"),
                    actionButton("go","Go!"),
                    downloadButton('downloadData', 'Download')
                  ),

                  # Show a plot of the generated distribution
                  mainPanel(
                    tabsetPanel(
                      tabPanel("summary", tableOutput("summary1")),
                      tabPanel("Curve", plotlyOutput("curve1"))
                    )
                  )
                )
              )
      ),

      # Second tab content
      tabItem(tabName = "menu2",
              fluidRow(
                sidebarLayout(
                  sidebarPanel(
                    selectInput("pet1","PET:",c("dog","cat","pig"),selected = "dog"),
                    fileInput(inputId = "iFile", label = "Upload Excel:",
                              accept="application/vnd.ms-excel"),
                    actionButton("go","Go!"),
                    downloadButton('downloadData', 'Download')
                  ),

                  # Show a plot of the generated distribution
                  mainPanel(
                    tabsetPanel(
                      tabPanel("summary", tableOutput("summary1")),
                      tabPanel("Curve", plotlyOutput("curve1"))
                    )
                  )
                )
              )
      )
    )
  ),
  skin = "purple"
  )
 )
}

ui = (htmlOutput("page"))
server = (function(input, output,session) {

USER <- reactiveValues(Logged = Logged)

observe({
if (USER$Logged == FALSE) {
  if (!is.null(input$Login)) {
    if (input$Login > 0) {
      Username <- isolate(input$userName)
      Password <- isolate(input$passwd)
      Id.username <- which(my_username == Username)
      Id.password <- which(my_password == Password)
      if (length(Id.username) > 0 & length(Id.password) > 0) {
        if (Id.username == Id.password) {
          USER$Logged <- TRUE
        }
      }
    }
  }
}
})
observe({
if (USER$Logged == FALSE) {

  output$page <- renderUI({
    div(class="outer",do.call(bootstrapPage,c("",ui1())))
  })
}
if (USER$Logged == TRUE)
{
  output$page <- renderUI({
    div(class="outer",do.call(navbarPage,c(inverse=TRUE,ui2())))
  })
}
})
})

runApp(list(ui = ui, server = server))

After login the page should be like this:
enter image description here
Not like this:
enter image description here

A: The navbarPage function expect the title as the first argument, since you have only two arguments and one argument is already identified, the navbarPage takes the ui2() function as the title.
Just change
div(class="outer",do.call(navbarPage,c(inverse=TRUE,ui2())))
with
div(class="outer",do.call(navbarPage,c(title = "MY Web APP", inverse=TRUE,ui2())))


text:
Q: Where's the global inputrc file in AIX? I want to save my Readline settings globally for all bash users (it is installed on the system), but I cannot find the global configuration path, neither in /etc nor in /usr/etc. I also couldn't find it on the man pages myself.
I think there should be one if there's a local one in ~/.inputrc
Please help me with that.

A: "I think there should be one if there's a local one in ~/.inputrc"
According to documentation, this assumption is wrong. You can have ~/.inputrc for some users without the file /etc/inputrc.
Even worse, /etc/inputrc is read only if there is no .inputrc for a user.
Therefore, if you want to use global settings for all bash users, you have to :

*

*delete every ~/.inputrc

*create /${PREFIX}/etc/inputrc (where ${PREFIX} is the prefix readline was compiled with).

Source : http://www.linuxfromscratch.org/blfs/view/5.1/postlfs/inputrc.html


text:
Q: How to dynamically build multiple dimensional array in Java? Suppose I receive a number which we do not know before receiving it, say 5, then a series of numbers of length 5: 2,2,3,2,2.
Then, we build an array[2][2][3][2][2].
Is there a way to do this in Java?

A: Example of dynamic multi-dimensional array creation:
String input = "5 2 2 3 2 2";
Scanner sc = new Scanner(input);
int dimCount = sc.nextInt();
int[] dims = new int[dimCount];
for (int i = 0; i < dimCount; i++)
    dims[i] = sc.nextInt();
Object multiDimArray = java.lang.reflect.Array.newInstance(int.class, dims);

Now you just need to keep using java.lang.reflect.Array to manipulate it, since you don't know at compile-time how many dimensions it has.


text:
Q: Error When Instantiating an Object I am in the middle of (trying) to create a Class Library available for use in VB6/VBA. With some assistance received here I have now done the following:

*

*Created a Class Library Project in Visual Studio 2010 Express and put the code in a Class Module.

*Learned I needed this wonderful thing called an "Interface"... Made one of those:)

*I opened the project properties and went to "Assembly Information" and checked "Make COM Visible".

*I went to "Advanced Compile" options and targeted .Net 2.0 (it's very simple code).

*Removed all references expect for "System".

*Built the project (no warnings or errors) and copied the DLL out of the Bin folder into C:\Windows\System32\

*Ran RegAsm /tlb. Everything seemes just fine.

I popped open excel to run a quickie test and the TLB is available but I have two problems:

*

*I can see both the class and the interface in the Object Browser/Intellisense.

*When I try to create an instance of either object (Set obj = New MyObj)I get the error:

Automation error
  The system cannot find the file specified.

I can set a reference to the Object and the Intellisense can see it, I just get that error when I actually try to create the Object. Did I miss a step?

A: 7: Skip /tlb option of regasm it's a non-issue (not needed). Add /codebase


text:
Q: Get transactional email id by name Does someone know how do I get the id of an email by name set on backend? I have an email created in backend in transactional emails that I want to send it programatically, but the id of it may differ depending on the instance that I'm on (local, live, stage), and I can only provide the same name for it.
I have this:
Mage::getModel('core/email_template')->sendTransactional(
$templateId,
$sender,
$recepientEmail,
$recepientName,
$vars,
$store);

And I need to find out $templateId and I only know that I saved the mail with name "Tests".

A: Try calling: Mage::getModel('core/email_template')->loadByCode('Tests') if Tests is the name of the template you set up.
After that you can set the sender name, sender email etc and send it. Here is some sample code:
     $emailTemplate = Mage::getModel('core/email_template');
                    $emailTemplate->loadByCode($mailTemplate);
                    if(!$emailTemplate->getTemplateId()){
                        continue;
                    }
                    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
                    $mail = Mage::getModel('core/email')
                        ->setToName($customerName)
                        ->setToEmail($customerEmail)
                        ->setFromEmail(Mage::getStoreConfig('trans_email/ident_sales/email'))
                        ->setFromName(Mage::getStoreConfig('trans_email/ident_sales/name'))
                        ->setBody($processedTemplate)
                        ->setSubject($emailTemplate->getTemplateSubject())
                        ->setType('html');

         try {
                    $mail->send();
                } catch (Exception $error) {
                    Mage::log($error->getMessage(), null, 'auto_order_emails.log');
                    continue;
                }

$mailTemplate in above sample would be 'Tests' from your example.


text:
Q: Errors with unordered_map in C++? I was writing a program for a class using Visual C++ on my home computer, however, I tried to run it on school linux computers and I get these errors.
std::tr1::unordered_map <string, Word*> map;

Both of these errors appear on the line of code above
ISO C++ forbids declaration of 'unordered_map' with no type
expected ';' before '<' token
Originally I used hash_map but found out that could only be used in Visual C++
Thanks

A: GCC and MSVC define the TR1 extensions in different ways, because the TR1 standard is vague about how it should be supplied to the user. It simply specifies that there should be some compiler option to activate TR1.
Unlike MSVC, GCC puts the headers in a TR1 subdirectory. There are two ways to access them:

*

*Add a command-line option -isystem /usr/include/c++/<GCC version>/tr1. This is more conformant but appears to cause problems.

*Use conditional compilation:
#ifdef __GNUC__
#include <tr1/unordered_map>
#else
#include <unordered_map>
#endif

This exposes GCC's nonconformance: TR1 is not activated by setting an option, but instead by modifying the code.
There is a somewhat esoteric way around this: computed header names.
#ifdef __GNUC__
#define TR1_HEADER(x) <tr1/x>
#else
#define TR1_HEADER(x) <x>
#endif

#include TR1_HEADER(unordered_map)

This way, you only have to include things "once."


text:
Q: Expert system clips code return false value I have an expert system for diagnosing some disease.
It's coded in clips. But this code didn't run in clips and return false statement at the end of the run. I trace it again and again but I didn't notice what is the problem.
Here is some part of my code:
please help me.
sincerely.
`(deffacts init (start)) `
'(Defining defrule mainmenu '
'(start) '
'?ml <- (start) '
'=> '
'(printout t crlf crlf crlf crlf crlf crlf)'
'(printout t '
'"an expert system for diagnosis of some skin '
'disease" crlf crlf'
'"               Main Menu" crlf'
'"                ==========crlf crlf crlf'
'"         1-Skin rashes without fever" crlf crlf'
'"         2- Skin rashes with fever" crlf crlf'
'"         3- Skin infection " crlf crlf crlf'
'"         0- Quit the program " crlf crlf'
'"Type number of your choice then hit return key" crlf crlf'
'" Choice: ")'
'(bind ?response (read))'
'(if (eq ?response 1)'
'then (assert (type 0-1))'
'else'
'(if (eq ?response 2) then (assert (type 0-2)))'
'else '
'(if (eq ?response 3) then (assert (type 0-3)))'
'else'
'(if (eq ?response 0) then (assert (type quit)))'
'(printout t crlf)'
'(retract ?ml))'
'(Defining defrule user-quits'
'(type quit)'
'=>'
'(printout t "you have QUIT the program." crlf)'
'(halt))'
'((Defining defrule without'
'?p <- (type 0-1)'
'=>'
'(printout t crlf crlf crlf)'
'(retract ?p)'
'"printout t'
'"      Diagnosis of some skin desease " crlf crlf crlf'
'"      Skin rashes without fever menu" crlf'
'"      ==================================" crlf'
'crlf'
'"      1- red patches of skin , painful joints, " crlf'
'"         pitted nails, poorly controlled dandruff" crlf'
'crlf'

A: CLIPS> (deffacts init (start))
CLIPS>
(defrule mainmenu
   ?ml <- (start)
   =>
   (printout t crlf crlf crlf crlf crlf crlf)
   (printout t
    "an expert system for diagnosis of some skin disease" crlf crlf
    "               Main Menu" crlf
    "               =========" crlf crlf crlf
    "         1- Skin rashes without fever" crlf crlf
    "         2- Skin rashes with fever" crlf crlf
    "         3- Skin infection " crlf crlf crlf
    "         0- Quit the program " crlf crlf
    "Type number of your choice then hit return key" crlf crlf
    " Choice: ")
   (bind ?response (read))
   (switch ?response
      (case 1 then (assert (type 0-1)))
      (case 2 then (assert (type 0-2)))
      (case 3 then (assert (type 0-3)))
      (case 0 then (assert (type quit))))
   (printout t crlf)
   (retract ?ml)))
CLIPS>
(defrule user-quits
   (type quit)
   =>
   (printout t "you have QUIT the program." crlf)
   (halt))
CLIPS> (reset)
CLIPS> (run)

an expert system for diagnosis of some skin disease

               Main Menu
               =========

         1- Skin rashes without fever

         2- Skin rashes with fever

         3- Skin infection

         0- Quit the program

Type number of your choice then hit return key

 Choice: 0

you have QUIT the program.
CLIPS>


text:
Q: Insert query exception "No value given for one or more required parameters" Here i am adding 5 datas to the table(Registration), and it contains 6 six columns among that the ID is primary KEY indentity. But i am getting an exception that no value for one or more required parameters at "myCommand.ExecuteReader();" while trying to insert the other data columns.
public void SubmitClick(Object sender, EventArgs e )
{
    insertdata(FN.Text,LN.Text,DOB.Text,mailid.Text,username.Text);
}
public void insertdata(string fname, string sname, string dob ,string email ,string uname)
{

    //Connection string for the datbase
    string database = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\atchutharamkj\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\App_Data\Database3.accdb;Persist Security Info=True";
    OleDbConnection myConn = new OleDbConnection(database);
    string queryStr = @"Insert into Registration Values (fname , sname, dob , email, uname)";
    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    myCommand.Connection.Open();
    myCommand.ExecuteReader();
    myCommand.Connection.Close();

}

A: Your query is wrong and this way you are not passing anything to it.
Use parametrized queries like that:
public void SubmitClick(Object sender, EventArgs e )
{
    insertdata(FN.Text,LN.Text,DOB.Text,mailid.Text,username.Text);
}

public void insertdata(string fname, string sname, string dob ,string email ,string uname)
{
    string database = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\atchutharamkj\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\App_Data\Database3.accdb;Persist Security Info=True";
    OleDbConnection myConn = new OleDbConnection(database);

    string queryStr = @"Insert into Registration(FirstName,LastName,DOB,[E-Mail],Username ) Values (?, ?, ?, ?, ?)";

    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    myCommand.Parameters.AddWithValue("@fname", fname);
    myCommand.Parameters.AddWithValue("@sname", sname);
    myCommand.Parameters.AddWithValue("@dob", dob);
    myCommand.Parameters.AddWithValue("@email", email);
    myCommand.Parameters.AddWithValue("@uname", uname);

    myCommand.Connection.Open();
    myCommand.ExecuteNonQuery();
    myCommand.Connection.Close();
}

More about passing parameters to OleDB see MSDN.


text:
Q: Return Values for Single Row when when multiple rows are returned (LookupRows) I'm currently trying to figure out how to return values from a specified row when multiple results are returned:
For this case I'm going to show an example from ampscript.guide since my code is very similar:
%%[
var @rows, @row, @rowCount, @region, @rank, @i

set @region = AttributeValue("Region") /* value from attribute or DE column in send context */
set @region = "North" /* or a literal value */

set @rank = AttributeValue("Rank") /* value from attribute or DE column in send context */
set @rank = "1" /* or a literal value */

set @rows = LookupRows("LoyaltyMembers","region", @region, "rank", @rank)
set @rowCount = rowcount(@rows)

output(concat("region: ", @region))
output(concat("
rank ", @rank))

if @rowCount > 0 then

  for @i = 1 to @rowCount do

    var @emailAddress, @firstName, @rank
    set @row = row(@rows, @i) /* get row based on counter */
    set @firstName = field(@row,"firstName")
    set @emailAddress = field(@row,"emailAddress")

    ]%%

Row %%=v(@i)=%%, firstName: %%=v(@firstName)=%%, emailAddress: %%=v(@emailAddress)=%%

    %%[

  next @i ]%%

%%[ else ]%%

No rows found

%%[ endif ]%%

Output:
region: North
rank: 1
Row 1, firstName: Doug, emailAddress: doug@limedash.com
Row 2, firstName: Barb, emailAddress: barb@limedash.com

As you can see, multiple arguments are used in the LookupRows function and the proper result is displayed. - This roughly mimics my scenario.
However, in my case, when multiple rows are returned I want to only display values from one of the rows that I specify.
For instance, let's say that there is another column named size Doug's size is Large and Barb has no value for size.
How can I further specify the desired output? I've assumed adding the additional condition in the loop like so:
if @rowCount > 0 then

  for @i = 1 to @rowCount do

    var @emailAddress, @firstName, @rank
    set @row = row(@rows, @i) /* get row based on counter */
    set @firstName = field(@row,"firstName")
    set @emailAddress = field(@row,"emailAddress")
    set @size = field(@row,"size")
    ]%%

Row %%=v(@i)=%%, firstName: %%=v(@firstName)=%%, emailAddress: %%=v(@emailAddress)=%%

        %%[

      next @i ]%%

    %%[ elseif empty(@size) then /*Something here to just pull values from one row?*/]%%

    No rows found

    %%[ endif ]%%

But I am having trouble getting the syntax right and second-guessing the possibility of this being valid.
How can I do this when multiple rows are returned?

A: It is not 100% clear want you want to achieve and I see there are 2 different approaches:

*

*If you would want to always display only one row then it is better to check Lookup function with several field conditions and maybe even mix it with some IF-ELSE-ENDIF conditions as well.

*If you would want to conditionally reduce the number of displayed rows from the LookupRows function - it implies that the returned number of rows could be still more than 2 (where @size is not empty in your example). The code would be something like -

%%[
if @rowCount > 0 then

    for @i = 1 to @rowCount do

        var @emailAddress, @firstName, @rank
        set @row = row(@rows, @i) /* get row based on counter */
        set @firstName = field(@row,"firstName")
        set @emailAddress = field(@row,"emailAddress")
        set @size = field(@row,"size")
        ]%%

        %%[ IF NOT EMPTY(@size) THEN ]%%

Row %%=v(@i)=%%, firstName: %%=v(@firstName)=%%, emailAddress: %%=v(@emailAddress)=%%, size: %%=v(@size)=%%
        %%[ ENDIF ]%%

    %%[next @i ]%%

%%[ else ]%%

No rows found

%%[ endif ]%%

In your code, you could not do it because @size is not set up in the ELSEIF path. So you gotta limit the number of rows within the loop just before outputting them.


text:
Q: Jobs not executed in circle ci workflow I'm trying to cascade a series of tasking using the workflow syntax with circle ci. For some reason, only the build job seems to run - but my other jobs do not.
version: 2
jobs:
build:
docker:
  - image: circleci/node:latest
steps:
    - checkout
    - restore_cache:
        keys:
            - sfdx-version-41-local
    - run:
        name: Install SFDX
        command: pwd
    - save_cache:
        key: sfdx-version-41-local
        paths:
            - node_modules
auth:
    steps:
    - run:
        name: Authenticate
        command: ls -a
validate:
    steps:
    - run:
        name: Validate
        command:  mkdir whocares
clean:
    steps:
    - run:
        name: Remove Server Key
        when: always
        command: pwd

workflows:
 version: 2
 authenticate-and-deploy:
   jobs:
     - build
     - auth
     - validate
     - clean

Ideally, I want to make sure each step finishes with a non zero exit code before moving to next step. But I'm not sure the the subsequent steps after build are not being executed.
Thanks,

A: If you really wants all of these jobs for some reason, the Workflows config is missing requirements and each job is missing its executor. I also fixed indenting. You can do this:
version: 2
jobs:
  build:
    docker:
      - image: circleci/node:latest
    steps:
      - checkout
      - restore_cache:
          keys:
            - sfdx-version-41-local
      - run:
          name: Install SFDX
          command: pwd
      - save_cache:
          key: sfdx-version-41-local
          paths:
            - node_modules
  auth:
    docker:
      - image: circleci/node:latest
    steps:
      - run:
          name: Authenticate
          command: ls -a
  validate:
    docker:
      - image: circleci/node:latest
    steps:
      - run:
          name: Validate
          command:  mkdir whocares
  clean:
    docker:
      - image: circleci/node:latest
    steps:
      - run:
          name: Remove Server Key
          when: always
          command: pwd

workflows:
  version: 2
  authenticate-and-deploy:
    jobs:
      - build
      - auth:
          requires: build
      - validate:
          requires: auth
      - clean:
          requires: validate

A:

        Here is what I ended up doing:

    job-definition: &jobdef
    docker:
        - image: circleci/openjdk:latest-node-browsers
    steps:
        - checkout
        - restore_cache:
            keys:
                - sfdx-6.8.2-local
        - run:
            name: Print branch
            command: |
                echo $CIRCLE_BRANCH
                if [[$CIRCLE_BRANCH == 'master']];
                    then
                        echo "master";
                    else
                        echo "notMaster";
                fi

        - save_cache:
            key: sfdx-6.8.2-local
            paths:
                - node_modules
        - run:
            name: "Validate Build"
            command: |
                #node_modules/sfdx-cli/bin/run force:mdapi:deploy -d src/ -u $USERNAME -c --testlevel RunLocalTests
                echo CIRCLE_BRANCH
        - run:
            name: Push to Codecov.io
            command: |
                cp ~/tests/apex/test-result-codecoverage.json .
                bash <(curl -s https://codecov.io/bash)
        - store_artifacts:
            path: ~/tests
        - store_test_results:
            path: ~/tests

    version: 2
jobs:
  static-analysis:
    docker:
      - image: circleci/openjdk:latest
    steps:
      - checkout
      - restore_cache:
          keys:
            - pmd-v6.0.1
      - run:
          name: Install PMD
          command: |
              if [ ! -d pmd-bin-6.0.1 ]; then
                  curl -L "https://github.com/pmd/pmd/releases/download/pmd_releases/6.0.1/pmd-bin-6.0.1.zip" -o pmd-bin-6.0.1.zip
                  unzip pmd-bin-6.0.1.zip
                  rm pmd-bin-6.0.1.zip
              fi
      - save_cache:
          key: pmd-v6.0.1
          paths:
              - pmd-bin-6.0.1
      - run:
          name: Run Static Analysis
          command: |
              pmd-bin-6.0.1/bin/run.sh pmd -d ./src/ -R $RULESET -f text -l apex -r static-analysis.txt -no-cache
      - store_artifacts:
          path: static-analysis.txt
  build-enterprise:
     <<: *jobdef
     environment:
        SCRATCH_DEF: workspace-scratch-def.json
        URL: https://login.salesforce.com
        NAME: $PROD_USERNAME
  build-developer:
     <<: *jobdef
     environment:
        SCRATCH_DEF: developer.json
        URL: https://test.salesforce.com
        NAME: $EVANDEV_USERNAME
              workflows:
  version: 2
  test_and_static:
    jobs:
      - build-enterprise
      #- build-developer
      #- static-analysis

Two other thing I'm trying to do:
1. paramterize the build
2. run build on a PR


text:
Q: JSON schema rule to require property presence if it is mentioned in another property Having such JSON:
{
  "attribute_1": {
    "some_nested_attribute": {
      "other_attribute_reference": "attribute_2"
    }
  },
  "attribute_2": {
    ...
  }
}

attribute_1, attribute_X - the names are dynamic, it can also be blabla-something, I don't have a fixed property name list. I want to create a JSON schema validation, which would validate the presence of attribute_2 (or any other not predefined name) in the JSON if it was used in the nested other_attribute_reference. I know about if/else in JSON schema, but how would I use that when the property name is dynamic and can be almost anything?


text:
Q: JQuery observable Listing control Is there any free JQuery listing (you may call grid too) control which can be bind to an array as an observer such that whenever array data changes, listing control updates itself automatically eith array data?
thanks