text:
Q: How to fix indentation / tab issue on Spyder I'm trying to get the python shell to display this print statement without the large gap at the backslash. I have already tried going into Source > Fix indentation.
    print('\nAverage median \
           income in {:2s}: ${:<10,.2f}'.format(state, income))

Average median        income in MI: $51,601.37

Any guidance helps, thanks!

A: Try removing the tab before 'income' in ur code print('\nAverage median \income in {:2s}: ${:<10,.2f}'.format(state, income))

A: This is not a Spyder problem. It's your code. I think your backslash was intending to separate a line of code across two lines, but the backslash must be outside of your string, otherwise you're just escaping a space inside a string. If you must keep the code separated on two lines while preserving indentation, simply close your quotes and reopen them, keeping the backslash outside the quotes:
print('\nAverage median ' \
       'income in {:2s}: ${:<10,.2f}'.format(state, income))

Average median income in MI: $51,601.37


text:
Q: FlutterFire - Where to get verification code # through email on FirebaseAuth im new on using FIrebase
With major update, FlutterFire added new methods
NEW: Added support for applyActionCode().
NEW: Added support for checkActionCode().
NEW: Added support for verifyPasswordResetCode().

And on documentation https://firebase.flutter.dev/docs/auth/usage/
User user = FirebaseAuth.instance.currentUser;
if (!user.emailVerified) {
   await user.sendEmailVerification();
}

//Firebase will send an automated email to the user with a unique code.
//This code can then be entered via the applyActionCode() method.
//You can first check whether the code is valid by using the checkActionCode() method:

await user.sendEmailVerification(); this only sends verification links to user email to verify. Not a verification CODE.
What should i do to receive that code through email? So I can use the method verifyPasswordResetCode().. Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting records from a table based on a filter field and Between but also having the OR logic for multiple rows I have a this table, where I store multiple ids and an age range (def1,def2)
CREATE TABLE "template_requirements" (
  "_id" INTEGER NOT NULL,
  "templateid" INTEGER,
  "def1" VARCHAR(255),
  "def2" VARCHAR(255),
  PRIMARY KEY("_id")
)

Having values such as:
templateid | def1 | def2
-------------------------------
100        | 7    | 25
200        | 40   | 90
300        | 7    | 25
300        | 40   | 60

As you see for templateid 300, we have an or logic: age between 7 and 25 or age between 40 and 60.
I want to get all the template ids that are not for a certain age like 25...
What's the problem?
If I run a query like this one:
SELECT group_concat(templateid)
 FROM template_requirements
where 1=1 and '25' not between cast(def1 as integer)
                       and cast(def2 as integer)

it returns 200, 300, which is wrong, as the 300 matched on row 40 to 60, but shouldn't be included in the result as we have a condition with same templateid 7 to 25 that fails the not beetween stuff.
How would be the correct query in SQLite, I would like to keep the group_concat stuff.

A: You might try EXCEPT:
sqlite> select group_concat(templateid)
          from (select templateid from template_requirements
                except
                select templateid from template_requirements
                 where 25 between cast(def1 as integer) and cast(def2 as integer));

... show me those "templateid"s except those which have an age range encompassing 25.
Or how about a similar WHERE NOT IN:
sqlite> select group_concat(distinct templateid)
          from template_requirements
         where templateid not in
                 (select templateid from template_requirements
                   where 25 between cast(def1 as integer) and cast(def2 as integer));

Both are fairly "colloquially accurate" SQL representations of what you're trying to do...

A: I think i'ts not sqlite but the query, try this:
SELECT templateid
FROM template_requirements

/*You want this values*/
WHERE '25' not between cast(def1 as integer) and cast(def2 as integer)

/*You don't want results with this values (with this you should eliminate 300)*/
AND templateid NOT IN (
  SELECT templateid
  FROM template_requirements
  WHERE '25' between cast(def1 as integer) and cast(def2 as integer)
  )


text:
Q: Use findstr to Search a Sub Directory for a String? I can use the following to search for text files that contain the word "string" from the Windows Command Prompt:
C:\>findstr /spin /c:"string" *.txt

What if I want to search a sub-directory? The following doesn't work:
C:\>findstr /spin /c:\Users\My Name\Desktop"string" *.txt

Is it possible to search a specific sub path using findstr? I know I can do the following, but I'm trying to avoid having to change directories first:
C:\Users\My Name\Desktop>C:\>findstr /spin /c:"string" *.txt

A: Your question appears to me quite bit vaguely formulated. Read program documentation in any doubt (findstr /? or http://ss64.com/nt/findstr.html in this case).
findstr /spin /c:"string" "c:\Users\My Name\Desktop\*.txt"


text:
Q: How to display 3 boxes in the same line? I am trying to design a page using CSS and I need to display three boxes in the same line.
I used three div's and have added float:left to the first, margin-left:8cm; to the center and float:right to the right.
The left and center box are perfectly displayed but the right one goes to the next line. I even tried adding margin-left:16cm; , it still goes down by a line.
Can someone help?

A: Simply use float:left; on all three elements, and they will line up next to each other.

A: float:right floats the block element right of the next block element, not the previous one.
If you want to preserve the order of the
 elements in your DOM, you should set both the first and the second as float:left and set the left margin of the third one to accomodate for the space taken by the first two.
Alternatively, you can put the
 elements in first, third, second order and keep your current styles.

A: An alternative that does not mess with your markup, and does not require a margin that depends on the other divs' width is to float the first two divs left, and float the last right. So long as the added widths of the divs fits within the parent element it should display as three columns.

One

Two

Three

#one, #two, #three { width: 33.3%; }
#one, #two { float: left; }
#three { float: right; clear: none; }

The clear:none in the third div makes this work in IE 6 & 7.

A:

A:

.whateveritiscalled {
  display: inline-block;
 }

just simply


text:
Q: Create image based off a SWF (flash) element on the page? PHP/Jquery/Javascript/HTML/FLASH Is there anyway to take take a "screenshot", "save" or "capture" the active SWF element on a page as an image? I'd like for users to be able to simply click a button on my page, instead of having to need to manually take a screenshot of the entire page and then crop the image to show only the SWF element.
I found a Jquery method, although I am unsure if it could work with SWF files. It basically captures an area of an Image element on the page and allows you to save that as a separate image. What I would need however, is to capture the SWF as the image instead. Note: I do not have access to the SWF code so I cannot achieve this using Actionscript or anything like that -it has to be purely done with PHP and Javascript.
Thanks for any ideas :)

A: I don't think that there is a way to do this from Javascript, but if you host those swf files on your own server you could create a wrapper swf which loads the swfs you want to screenshot dynamically and then draws them into a BitmapData object.
The snapshot process inside of the swf can be triggered from Javascript via ExternalInterface, after that you can either serialize the raw pixels or use a PNG or JPEG encoder inside the wrapper swf to convert the bitmapdata to a image file and then send that data back to Javascript via ExternalInterface. Or you use the FileReference class in the swf to save the image file directly on the user's hard drive - one caveat in this is though that in order to trigger the save process the user will have to click a button inside the swf (that's a security feature).
There is one more prerequisite and that is that the swfs that you load into the wrapper have to be hosted on the same domain as the wrapper swf, otherwise the security sandboy will not allow to take a bitmap snapshot of it.

A: Look at ByteArray.getPixels(0,0,stage.stageWidth,stage.stageHeight) or var b;BitMap = BitMapData(stageW,stageH).draw(stage), depending on your needs. Note that the above two lines are not proper code, just the correct object and function names written in shorthand and from my head.


text:
Q: Decimal precision when copy excel numbers to clipboard I'm writing a MatLab programm under windows 7 x64 that takes the clipboard, with mixed data copied from Microsoft Excel, and import it directly to MatLab into a single char array.
When I use str = clipboard('paste') in MatLab, all text data copied from excel are fine, but the numerical data copied loss some decimal places.
For example, if the cell A1 contains the number 2113.12389881239, but it only displays the value 2113.123899 due to cell formating, then 2113.123899 is copied from excel to MatLab instead of the real cell value 2113.12389881239.
I would like to know how to copy the exact cell value stored in Excel not the value displayed.
Thanks in advance.

A: Given the following value: .1234567, formatted with all from 1-7 decimal places, I get the following results when I copy-paste to another program (notepad):
0.1
0.12
0.123
0.1235
0.12346
0.123457
0.1234567

Assuming you want to copy one number at a time, I used this macro:
Sub FormattedCopy()

    Dim oldFormat, copyString As String

    oldFormat = Selection.NumberFormatLocal

    Selection.NumberFormatLocal = "@"

    Selection.Copy

    MsgBox ("Please paste your data")

    Selection.NumberFormatLocal = oldFormat

End Sub

The message box serves to 'pause' the process, because changing the number format back will clear the clipboard. When I paste any value, it properly displays in notepad as 0.1234567
You can do this with a range of values if you save the range of number formats in an array and feed it back as I did above with for loops.


text:
Q: Will a single XSLT file solve this issue - continuation..? This question is connected with this post of mine - Will a Single XSLT file solve this issue..or...?
Below is my XML file -
<CVs>
 <CV>
  <Name>ABC</Name>
  <Address></Address>
  <Introduction></Introduction>
  <CompSkills>Java, XSLT, XPATH, XML, Oracle, VB.NET</CompSkills>
  <Experience>
    <Profile></Profile>
    <Duration></Duration>
    <Info></Info>
  </Experience>
  <Experience>
    <Profile></Profile>
    <Duration></Duration>
    <Info></Info>
  </Experience>
  <Experience>
    <Profile></Profile>
    <Duration></Duration>
    <Info></Info>
  </Experience>
<CV>
<CV>
 <Name>XYZ</Name>
 <Address></Address>
 <Introduction></Introduction>
 <CompSkills>Java, XSLT, XPATH, XML, JSP, HTML</CompSkills>
 <Experience>
   <Profile></Profile>
   <Duration></Duration>
   <Info></Info>
 </Experience>
 <Experience>
   <Profile></Profile>
   <Duration></Duration>
   <Info></Info>
 </Experience>
 <Experience>
   <Profile></Profile>
   <Duration></Duration>
   <Info></Info>
 </Experience>

Below is my XSLT file - (well Dimitre gave this answer, but now its mine ;) )
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pName" select="'XYZ'"/>

 <xsl:template match="node()|@*" name="identity">
   <xsl:copy>
     <xsl:apply-templates select="node()|@*"/>
   </xsl:copy>
 </xsl:template>

 <xsl:template match="CV">
   <xsl:if test="$pName = Name or $pName='*'">
     <xsl:call-template name="identity"/>
   </xsl:if>
 </xsl:template>

</xsl:stylesheet>

The above XSLT will extract matching <Name> which is passed from Java.
Now I need to know how can i modify this XSLT, so that if I pass Oracle as a parameter, then
those who have Oracle in <CompSkills> would get listed. Oracle will be one of the CompSkills..
Thanks in advance - John

A: XPath 1.0, easy way: contains function, e.g.:
<xsl:if test="contains(CompSkills, $pSkill)">

A: You can do this by using contains().
This modified version of your stylesheet will pull the CV if the Name matches the pName param or if CompSkills contains the pSkill param.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="pName" select="'XYZ'"/>
  <xsl:param name="pSkill" select="'Oracle'"/>

  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="CV">
    <xsl:if test="$pName = Name or $pName='*' or
                  contains(CompSkills,$pSkill)">
      <xsl:call-template name="identity"/>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>


text:
Q: How can i print recutsive calls with Decorator I have a basic fib function and I want to create a Decorator in order to print the calls fib does
I want to print the calls without change the recursive function
for example:
for n = 5: # Thats the general idea
    fib(5)
    fib(4), fib(3)
    fib(3), fib(2), fib(2), fib(1)
    fib(2), fib(1), fib(1), fib(0), fib(1), fib(0), fib(0), fib(-1)

def print_call_params(function):
    def rec(params):
        if params:
            print(f"{function.__name__}({params})")
            function(params)

    return rec

@print_call_params
def fib(n):
    if n < 3: return 1
    return fib(n-1) + fib(n-2)

The end goal is to create a file where I can see the Tree that was created by the recursion

A: I think the problem is a missing return:
def print_call_params(function):
    def rec(params):
        if params:
            print(f"{function.__name__}({params})")
            return function(params) #<- need to return
    return rec

Also, I think the if params: is superfluous.


text:
Q: cmake problems with MSBuild.exe I have problems with cmake on Windows 10.  I pruned things to the smallest example that will generate the same errors.  I run cmake from the Windows command prompt (the same problem occurs with the git bash command-line interpreter, of the Visual Studio command prompt
).  My CMakeLists.txt contains three lines:
cmake_minimum_required(VERSION 3.1)

project(DEBUG bogus)

I run cmake this way:
cmake -G "Visual Studio 15 2017 Win64" .
A MSBuild.exe window pops up briefly with an error message, but I can't read it.  It's gone too fast.
The command-line window displays this error message:
CMake Error at CMakeLists.txt:3 (project):

  Failed to run MSBuild command:

    C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/MSBuild/15.0/Bin/MSBuild.exe

  to get the value of VCTargetsPath:

-- Configuring incomplete, errors occurred!

See also "C:/Users/tmpuser/Desktop/SDK/dependencies/DEBUG/CMakeFiles/CMakeOutput.log".

The executable for MSBuild.exe does indeed exist.  The CmakeOutput.log file contains:
The system is: Windows - 10.0.17763 - AMD64

Does anyone know what is wrong?


text:
Q: Microsoft Access 2007: save relative directory path in database table I created a table with column "Directorypath" and a form with an input field for "Directorypath". When I create new database entry with the form and write something in the "Directorypath"-field (form-mode), the input is correctly stored in my table.
But in this field I want to store the relative path from my directory, so I wrote "=[Application].[CurrentProject].[Path]" (form-edit-mode). In the form-mode the path in the inputfield is shown correct but when I want to save the new entry, every other fields are saved but the "Directorypath"-field is empty (in database).
What should I do to save the path in database? My field has the fieldtype "text".
Hope anyone could help me!


text:
Q: Setting up Symfony 3 with NetBeans 8 I am not able to setup Symfony 3.0 with NetBeans 8.
Here is what I have done:
NetBeans IDE: Tools -> Options -> PHP -> Framework & Tools -> Symfony 2/3 -> symfony2/3

In the installer textbox, I gave the path to the symfony.zip file.
When I create a new PHP project with the Symfony framework, I get the following error:

I am not able to begin with the Symfony project.


text:
Q: How do I sample N items from a list ensuring the samples are as similar as possible to each other? Is there anyway to sample 6 numbers without replacement this list of 12 numbers
(490,   700,    850,    1220,   505,    650,    930,    810,    800,    960,    1130,   1480)

ensuring that the average is as close as possible to the remaining 6 numbers?
In this case is the average the best method of making sure that the two samples are as similar as possible? (Maybe something like a Density curve)?

A: My first thought was that a hierarchical cluster analysis using a method that minimizes variability would be the best approach (e.g., Ward's method).  However, this doesn't constrain to a solution with a fixed number of clusters (or more appropriately, a fixed number of items within a fixed number of clusters, such as a half-half split).
So, I would propose a less elegant sampling approach to find the "best" split sample with the desired criteria.  Randomly sample different splits of the 12 values (into equal groups of 6 each); calculate the difference of the standard deviations for each group; retain the split that gives the lowest value.  If you sample over a larger enough number of iterations, you should be able to find a reasonably good solution.
Here's the code I applied to your data:
vals <- c(490, 700, 850, 1220, 505, 650, 930, 810, 800, 960, 1130, 1480)

set.seed(1234)

min.abs.diff <- abs(diff(sd(vals[1:6]),sd(vals[7:12])))
best.split <- c(rep.int(0,6),rep.int(1,6))
for(ctr in 1:2000) {
    grp <- sample(c(rep.int(0,6),rep.int(1,6)),12)
    sd.diff <- abs(diff(aggregate(vals~grp,data.frame(vals,grp),sd)[,2]))
    min.abs.diff <- min(min.abs.diff,sd.diff)
    if(sd.diff == min.abs.diff && ctr>50) {
        print(ctr)
        print(grp)
        best.split <- grp
        }
}

aggregate(vals~grp,data.frame(vals,grp=best.split),sd)
vals[which(best.split==0)]
vals[which(best.split==1)]

This resulted in the following:
  grp     vals
1   0 283.7898
2   1 283.9674

And the groups were:
700  850  930  800 1130 1480
490 1220  505  650  810  960

I hope this helps with your project.  And, I hope that if there is a more elegant way to cluster the data to achieve minimum differences in variability for fixed sample sizes...I'd very much like to see that.


text:
Q: how to order values a dataframe from high to low in python myDataTradeSWE = myDataTrade[(myDataTrade['from']=='SWE') & (myDataTrade['Year']<2015)]
myDataTradeSWE.head(10)

this is the code of the data frame and the data it returns the "VAL" column is the one i need to order from high to low.

A: If you want to sort the entire DataFrame:
out = myDataTradeSWE.sort_values(by='VAL', ascending=False)

If you want to sort only VAL:
out = myDataTradeSWE['VAL'].sort_values(ascending=False)


text:
Q: Is this still considered as inheritance? Is this an ok coding practice? I'm currently re-doing Tim Buchalka's OOP Master Challenge exercise where the task is to make a Hamburgerclass that has the basic fields like name, breadRoll, price, meat etc; and to make an inherited class called Healthy Burger where it would have it's own specific fields that would distinguish it (having a different bread roll, more additions).
Tim firstly made all of the additions and prices for every addition in to a separate field (and also made methods for every single addition to set them). Like this:
private String addition1;
private String additionPrice1;
private String addition2; etc...

Where as I preferred to make a String[] and pre-defined every addition into a String array. Like this:
    private String[] additions = {"lettuce","tomato","carrot","dressing","onion","ginger"};
    private double[] additionPrice = {0.3,0.4,0.5,0.6,0.7,0.8};

I had an idea in mind that the user that is going to create a Hamburger class, has to have constrained input and an easier way of creating the Hamburger object, without invalid inputs.
So I made my constructor like this:
 public Hamburger(String name) {

    this.name=name;
    breadRollSelection();
    baseMeatSelection();
    this.totalPrice = basePrice;
}

breadRollSelection(); and baseMeatSelection(); both contain loops that print out the String[] for types of bread rolls and meats, where user would input using Scanner:
public void breadRollSelection() {
    System.out.println("Pick a bread roll: ");
    if(this.name.equalsIgnoreCase("Healthy Hamburger")) {
        this.breadRoll=breadRolls[2];//healthy bread roll
        System.out.println(breadRoll + " has been chosen with the price of "+breadRollsPrice[2]);
        this.basePrice += breadRollsPrice[2];
    } else {
        for (int i = 0; i < 2; i++) {
            System.out.println(i + " " + breadRolls[i] + " with the price of: " + breadRollsPrice[i]);
        }
        Scanner scan = new Scanner(System.in);
        int choice = scan.nextInt();
        this.breadRoll = breadRolls[choice];
        this.basePrice += breadRollsPrice[choice];
    }
}

Where as in the Healthy Burger class, I only did this:|
public class HealthyBurger extends Hamburger {

private String breadRoll="Bread Roll Diet";
public HealthyBurger() {
    super("Healthy Hamburger");
}

So when I create a HealthyHamburger ham = new HealthyHamburger(); object, when accessing breadRollSelection() method, it already knows that a child object is calling it. I would override it in the child class, but I don't have access to the String[] breadRoll, unless I make them protected (if that is ok to do here).
And with addAddition(); method, which is quite larger, I used the name of the burger as a condition which additions should be added:
  public void addAddition(){
        int additionLimit=0;
        boolean q=true;
        if(this.name=="Basic") {
            while (q) {
                for(int i=0;i<4;i++){
                    System.out.println(i+" "+additions[i]+ " with the price of: "+additionPrice[i]);
                }
                Scanner scan = new Scanner(System.in);
                int choice = scan.nextInt();
                choice -= 1;
                System.out.println(additions[choice] + " chosen!");
                this.totalPrice += additionPrice[choice];
                System.out.println(this.totalPrice + " is the price after this addition!");
                additionLimit += 1;

                if (additionLimit == 4) {
                    System.out.println("No more additions");
                    q = false;
                    break;
                }
                System.out.println("Press 0 to exit or 1 if you want more additions!");
                int choice1 = scan.nextInt();
                if (choice1 == 0) {
                    q = false;
                }
            }
        }
        if(this.name=="Healthy Hamburger"){
            while (q) {
                for(int i=0;i<additions.length;i++){
                    System.out.println(i+" "+additions[i]+ " with the price of: "+additionPrice[i]);
                }
                Scanner scan = new Scanner(System.in);
                int choice = scan.nextInt();
                choice -= 1;
                System.out.println(additions[choice] + " chosen!");
                this.totalPrice += additionPrice[choice];
                System.out.println(this.totalPrice + " is the price after this addition!");
                additionLimit += 1;

                if (additionLimit == 6) {
                    System.out.println("No more additions");
                    q = false;
                    break;
                }
                System.out.println("Press 0 to exit or 1 if you want more additions!");
                int choice1 = scan.nextInt();
                if (choice1 == 0) {
                    q = false;
                }
            }
        }
    }

My question is, if it's ok to use the parent class like this, where it would know which child is accessing it and is it ok if I use the constructor this way?

A: Your instincts are good, as far as having the sense that something is off here. This is a little bit subjective, but there are some guidelines and design patter descriptions I can offer you to help figure it out.
Firstly, the red flags that this is an anti-pattern:

*

*Too many if blocks

*Too much nesting, i.e. loops inside of ifs

*And yes, a parent class that's given an awareness of its child.

Some of that can be solved by just breaking the larger function up into smaller ones, but a parent class is supposed to be abstract by nature. As soon as you find it necessary to give it more contextual awareness, that's a sign you're using the wrong pattern.
Now, what to do about it.
I believe you're looking for a 'compositional' pattern as opposed to traditional inheritance. Specifically, the one you're probably looking for is the Decorator Pattern. As a matter of fact, the classic example use-case for the Decorator pattern is the construction and pricing of various types of coffee at a cafe, conceptually not far off at all from your hamburger example.
The gist of it is, each component of the thing you're trying to make is its own separate class. Rather than inherit from eachother. So you start with a base-"Hamburger" class, or a base-"VegiBurger". (And there's no reason they can't still inherit from an abstract "Burger" class.) Then, using Dependency Injection, give that base-object to an ingredient instance, then give that ingredient object to the next one, and so on.
Each component is responsible for its own pricing, and its own attributes, and what you end up with is a series of object wrappers that look a bit like the layers of the onions you may be putting on your burger. Now the trick is, each of them implements the same interface. And that interface guarantees the existence of something like a "getTotal" method. And each individual "getTotal" definition would be designed to tap into that of the object initially given to it, so that calculation runs through all the layers.
What this does for you is alleviate any assumptions that the structure needs to make about what a burger entails. Ingredients and prices can be added or modified without having to modify anything else.

A: You're violating several principles of object-oriented programming here:

*

*A constructor cannot wait for user input. Any input/output (other than diagnostic messages) should be handled as far up in the call chain as possible, i.e. in the main program or one of the functions it calls directly. The constructor must get all the necessary input from its arguments.

*The Open/Closed Principle: the base class should not have to be modified every time you add a subclass. Here, breadRollSelection depends on knowing about the existence of HealtyBurgers.

A: One thing you might consider doing is to get the bits where you ask for user input out of the Hamburger class. You could transfer all that to an OrderCounter class.
The builder pattern seems to be a good fit for creating Hamburger objects, which have a lot of (optional) "additions". In Item 2 of Effective Java, 3rd ed., Joshua Bloch suggests the same for creating Pizza objects, which similarly have a lot of toppings. If we were to adopt his approach,
public abstract class Hamburger {

    final Set<Addition> additions;
    final BreadRoll breadRoll;

    abstract static class Builder<T extends Hamburger.Builder<T>> {
        protected EnumSet<Addition> additions = EnumSet.noneOf(Addition.class);
        protected BreadRoll breadRoll;

        public T addAddition(Addition addition) {
            additions.add(Objects.requireNonNull(addition));
            return self();
        }

        public T breadRoll(BreadRoll breadRoll) {
            this.breadRoll = breadRoll;
            return self();
        }

        abstract Hamburger build();

        protected abstract T self();
    }

    abstract double getPrice();

    Hamburger(Hamburger.Builder<?> builder) {
        additions = builder.additions.clone();
        breadRoll = builder.breadRoll;
    }
}

and
public class HealthyBurger extends Hamburger {

    public static class Builder extends Hamburger.Builder<HealthyBurger.Builder> {

        @Override
        public HealthyBurger build() {
            return new HealthyBurger(this);
        }

        @Override
        protected HealthyBurger.Builder self() {
            return this;
        }
    }

    HealthyBurger(Builder builder) {
        super(builder);
    }

    @Override
    double getPrice() {
        double priceOfAdditions = additions.stream().mapToDouble(Addition::getPrice).sum();
        double priceOfBreadRoll = breadRoll.getPrice();
        return priceOfAdditions + priceOfBreadRoll;
    }
}

And, finally, here are our Addition and BreadRoll enums:
public enum Addition {
    LETTUCE(0.3), TOMATO(0.4), CARROT(0.5), ONION(0.6);

    private final double price;

    Addition(double price) {
        this.price = price;
    }

    public double getPrice() {
        return price;
    }
}

and
public enum BreadRoll {
    KAISER(1.0), PRETZEL(1.1), SLICED(1.2), DIET(1.3);

    private final double price;

    BreadRoll(double price) {
        this.price = price;
    }

    public double getPrice() {
        return price;
    }
}

Creating a HealthyBurger looks like this:
HealthyBurger healthy = new HealthyBurger.Builder()
                .breadRoll(BreadRoll.DIET)
                .addAddition(Addition.TOMATO)
                .addAddition(Addition.ONION)
                .build();

Ask the user for a hamburger type, and create a builder for that type. Then use the builder to create the object as you get inputs for roll type, meat type, and additions.


text:
Q: How to violate a foreign key in oracle Hi people I have the following relationship:
ALTER TABLE Role ADD CONSTRAINT ACTOR_ROLE_FK FOREIGN KEY (actorID) REFERENCES Actor (actorID);

What query can I construct to test if this working correctly
Thanks I would like it to be tested from a UPDATE command thanks
please not this is not the same as my previous question as I am asking how to violate a Foreign Key
Thank you for your kind help

A: INSERT INTO Role (actorID) VALUE(X)
-- replace X with a number that doesn't exist in the Actor table

A: Try to add a row in Role whose actorID does not exist in table Actor.

A: Update Role
set actorID = '99'
where actorid = '00069'

This assumes that the actor table has actorid = '00069' and that it does not have actorid = '99'


text:
Q: Structural error property type should be equal to one of the allowed values allowedValues: string, number, boolean, integer, array in Swagger editor I'm using springfox 2.9.2 and want test my swagger JSON as YAML in https://editor.swagger.io/
I have property with @ApiParam annotation type: object
@ApiParam(value = "metadata file")

protected Object metadataFile;

but when I test my generated json on swagger editor I got this error:

Structural error at ---.parameters.5.type should be equal to one of
the allowed values allowedValues: string, number, boolean, integer,
array Jump to line ---

there is way to allowed property type object in this section?
the section that trigger the problem
paths:
:
post:

  parameters:

      name: metadataFile
      in: query
      description: ...
      required: false
      type: object

A: Swagger documentation (go to the bottom of the page): https://swagger.io/docs/specification/2-0/describing-parameters/
"Can I have an object as a query parameter?
This is possible in OpenAPI 3.0, but not in 2.0."


text:
Q: python function arguments I have a Python function that inputs a string and should output a path along with doing some other operations within the function.
So the function looks like this, where testcase is the input and path should be returned:
def generate_testcase(testcase,path)
    path=os.path.join(os.getcwd(), testcase)
    return path

The function is a part of a package "regress" and is being called/used as:
import regress
testcase='xyz'
regress.main.generate_testcase(testcase,path)
print path

Now I am getting an error that I have not defined path
NameError: name 'path' is not defined

A: The issue occurs because in your main script where you are calling - regress.main.generate_testcase(testcase,path) , you have not defined path yet. And that is exactly what the error tells you as well.
In Python, you do not need to pass in the argument that you need to return. You are not doing anything with the path variable passed in as argument, I am guessing you think its needed as path is returned from the function, but its not. Just remove it from the parameter list and then in the main script, make it so that path recieves the return value of the function. Example function -
def generate_testcase(testcase)
    path=os.path.join(os.getcwd(), testcase)
    return path

Example main script -
import regress
testcase='xyz'
path = regress.main.generate_testcase(testcase)
print path


text:
Q: What is the difference between '->' (arrow operator) and '.' (dot operator) in Objective-C? In Objective-C what is the difference between accessing a variable in a class by using -> (arrow operator) and . (dot operator) ? Is -> used to access directly vs dot (.) isn't direct?

A: -> is the traditional C operator to access a member of a structure referenced by a pointer. Since Objective-C objects are (usually) used as pointers and an Objective-C class is a structure, you can use -> to access its members, which (usually) correspond to instance variables. Note that if you're trying to access an instance variable from outside the class then the instance variable must be marked as public.
So, for example:
SomeClass *obj = …;
NSLog(@"name = %@", obj->name);
obj->name = @"Jim";

accesses the instance variable name, declared in SomeClass (or one of its superclasses), corresponding to the object obj.
On the other hand, . is (usually) used as the dot syntax for getter and setter methods. For example:
SomeClass *obj = …;
NSLog(@"name = %@", obj.name);

is equivalent to using the getter method name:
SomeClass *obj = …;
NSLog(@"name = %@", [obj name]);

If name is a declared property, it's possible to give its getter method another name.
The dot syntax is also used for setter methods. For example:
SomeClass *obj = …;
obj.name = @"Jim";

is equivalent to:
SomeClass *obj = …;
[obj setName:@"Jim"];

A: The arrow, ->, is a shorthand for a dot combined with a pointer dereference, these two are the same for some pointer p:
p->m
(*p).m

The arrow notation is inherited from C and C has it because the structure member accessing operator (.) binds looser than the pointer dereferencing operator (*) and no one wants to write (*p).m all the time nor do they want to change the operator precedence to make people write *(p.m) to dereference a pointer inside a structure. So, the arrow was added so that you could do both p->m and *s.p sensibly without the ugliness of the parentheses.

A: When you use the arrow operator ptr->member it's implicitly dereferencing that pointer. It's equivalent to (*ptr).member. When you send messages to an object pointer, the pointer is implicitly dereferenced as well.


text:
Q: Comparison test to prove $\frac{1}{p!}<\frac{1}{2^{p-1}}$ I'm trying to show $\frac{1}{p!}<\frac{1}{2^{p-1}}$ for $p>2$
I notice that the right hand side of the inequality represents a geometric sequence. I can compute its infinite sum but how do I show the left hand side is smaller?

A: Computing the geometric sum $\sum_{p=1}^\infty \frac{1}{2^{p-1}}$ is irrelevant to proving this inequality. Note that it is equivalent to proving $$2^{p-1}<p!$$ for $p>2$. You should prove this inequality with induction. The base case of $p=3$ should be straightforward. For the induction step, you can multiply the inequality  $2^{k-1}<k!$ by $2$, and then use the fact that $2<k+1$ to quickly see that $2^k< (k+1)!$. Once you've done that, you know the inequality will hold for all $k \in \Bbb{N}$ where $k>3$, and you can flip the inequality back to get the result you are after.

A: Prove by induction the equivalent statement $n!>2^{n-1}$ for $n>2$.

First, show that this is true for $n=3$:
$3!>2^{3-1}$
Second, assume that this is true for $n$:
$n!>2^{n-1}$
Third, prove that this is true for $n+1$:
$(n+1)!=n!\cdot(n+1)>\color{red}{n!}\cdot2>\color{red}{2^{n-1}}\cdot2=2^n$

Please note that the assumption is used only in the part marked red.

A: hint: $2^{p-1} = 2\cdot 2\cdots2 < 2\cdot 3\cdot (2\cdot 2) \cdot 5\cdot 6\cdots p$


text:
Q: How do you get total directory size in the same function that is getting all file sizes? (Python) I am using the following function to get all file sizes in a system from the target directory down.
def get_files(target):
    # Get file size and modified time for all files from the target directory and down.
    # Initialize files list
    filelist = []
    # Walk the directory structure
    for root, dirs, files in os.walk(target):
        # Do not walk into directories that are mount points
        dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs)
        for name in files:
            # Construct absolute path for files
            filename = os.path.join(root, name)
            # Test the path to account for broken symlinks
            if os.path.exists(filename):
                # File size information in bytes
                size = float(os.path.getsize(filename))
                # Get the modified time of the file
                mtime = os.path.getmtime(filename)
                # Create a tuple of filename, size, and modified time
                construct = filename, size, str(datetime.datetime.fromtimestamp(mtime))
                # Add the tuple to the master filelist
                filelist.append(construct)
    return(filelist)

How can I modify this to include a second list containing directories and the total size of the directories?  I am trying to include this operation in one function to hopefully be more efficient than having to perform a second walk in a separate function to get the directory information and size.
The idea is to be able to report back with a sorted list of the top twenty largest files, and a second sorted list of the top ten largest directories.
Thanks for any suggestions you guys have.

A: I output the directories in a dictionary instead of a list, but see if you like it:
def get_files(target):
    # Get file size and modified time for all files from the target directory and down.
    # Initialize files list
    filelist = []
    dirdict = {}
    # Walk the directory structure
    for root, dirs, files in os.walk(target):
        # Do not walk into directories that are mount points
        dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs)
        for name in files:
            # Construct absolute path for files
            filename = os.path.join(root, name)
            # Test the path to account for broken symlinks
            if os.path.exists(filename):
                # File size information in bytes
                size = float(os.path.getsize(filename))
                # Get the modified time of the file
                mtime = os.path.getmtime(filename)
                # Create a tuple of filename, size, and modified time
                construct = filename, size, str(datetime.datetime.fromtimestamp(mtime))
                # Add the tuple to the master filelist
                filelist.append(construct)
                if root in dirdict.keys():
                    dirdict[root] += size
                else:
                    dirdict[root] = size
    return(filelist, dirdict)

If you want the dirdict as a list of tuples, just do this:
dirdict.items()

A: I have more than a few scripts laying around which does this type of thing, I just uploaded 'bigfiles.py' to github http://github.com/sente/sys-utils/blob/master/bigfiles.py
It doesn't compute total cumulative directory sizes but it could be modified without too much trouble.
I have other code lets sum total directories sizes at a given depth, like:
In [7]: t = build_tree_from_directory('/scratch/stu/')

In [8]: pprint.pprint(walk_tree(t,depth=0))
{'name': 'ROOT', 'size': 6539880514}

In [9]: pprint.pprint(walk_tree(t,depth=0))
{'name': 'ROOT', 'size': 6539880514}

In [10]: pprint.pprint(walk_tree(t,depth=1))
{'children': [{'name': 'apache2-gzip', 'size': 112112512},
              {'name': 'gitnotes', 'size': 897104422},
              {'name': 'finder', 'size': 3810736368},
              {'name': 'apache2', 'size': 1719919406}],
 'name': 'ROOT'}

In [12]: pprint.pprint(walk_tree(t,depth=2))
{'children': [{'children': [{'name': 'vhost', 'size': 103489662}],
               'name': 'apache2-gzip'},
              {'children': [{'name': '2', 'size': 533145458},
                            {'name': 'notes.git', 'size': 363958964}],
               'name': 'gitnotes'},
              {'children': [{'name': 'gzipped', 'size': 3810736368},
                            {'name': 'output.txt', 'size': 0}],
               'name': 'finder'},
              {'children': [{'name': 'sente_combined.log', 'size': 0},
                            {'name': 'lisp_ssl.log', 'size': 0},
                            {'name': 'vhost', 'size': 1378778576},
                            {'name': 'other_vhosts_access.log', 'size': 0},
                            {'name': 'ssl_error.log', 'size': 0},
                            {'name': 'ssl_access.log', 'size': 0},
                            {'name': 'sente_test.log', 'size': 0}],
               'name': 'apache2'}],
 'name': 'ROOT'}

The FS is only crawled once but the tree needs to be walked once it's created in order to get the full sizes, if you start at the leaf nodes and work your way towards the root you can compute every dir's total size most efficiently.


text:
Q: C# GhostScript convert multiple PDFs to PostScript Can anyone suggest how to merge multiple PDF files into a single PostScript file when using GhostScript with C#
Using the command line works and merges the two input PDF files to a single PostScriptFile:
gswin32c.exe -dNOPAUSE -dBATCH -sDEVICE=ps2write -sOutputFile=outfile.ps Infile1.pdf Infile2.pdf

I cannot get it to work in C# though:
params.Add("-q");
params.Add("-dQUIET");
params.Add("-dNOPAUSE");
params.Add("-dBATCH");
params.Add("-P-");
params.Add("-dPARANOIDSAFER");
params.Add("-dNOPROMPT");
params.Add("-sDEVICE=ps2write");
params.Add("-dLanguageLevel=3);
params.Add("-dASCII85DecodePages=false");
params.Add("-sOutputFile=outfile.ps");
params.Add("InFile1.PDF inFile2.PDF");

I did try it with a comma between the output file names as well.
Any suggestions would be greatly appreciated. Thanks, Mike

A: I would start with something like this:
params.Add("-ignored");
params.Add("-q");
params.Add("-dQUIET");
params.Add("-dNOPAUSE");
params.Add("-dBATCH");
params.Add("-dPARANOIDSAFER");
params.Add("-dNOPROMPT");
params.Add("-sDEVICE=ps2write");
params.Add("-dLanguageLevel=3");
params.Add("-dASCII85DecodePages=false");
params.Add("-sOutputFile=outfile.ps");
params.Add("-f");
params.Add("C:\fullpath\InFile1.PDF");
params.Add("C:\fullpath\inFile2.PDF");


text:
Q: parallel "short circuit" approval / rejection I need parallel approval of different people.
The job is approved if they all approve, or rejected if at least one rejects (usual AND logic).
How do I model that as soon as there is one rejection we should not wait for the answer of the other people?
Thanks!


text:
Q: Test Class for a simple Apex Class I am trying to write a test class for a simple Apex Class which sets the status of the Case to be Closed like below
public class updateCaseRecord {
     @AuraEnabled
    public static void updateCheck(String caseId){
        List<Case> records = [select id,Status from Case WHERE Id = :caseId];
        for (Case record : records)
        {
            record.Status = 'Closed';
        }
        update records;
    }
}

The test class I have written so far is like below I have created a test account,contact and a case.
@IsTest
public class updateCaseRecordTest {
@IsTest(SeeAllData=true) static void testIsUpdateCheck() {
    ID parentRecType = '012U0000000PqA9IAK';
    ID csRecType     = '012U0000000QGv4IAG';

    Account pa = new Account(Name='Test Parent Account', recordTypeId=parentRecType);
    insert pa;

    Account testAccount = new Account(Name='test', Industry='Biotech',Territory__c='EUR',BillingCity='Test',BillingCountry='Germany',ParentId=pa.id);
    insert testAccount;

    Contact c = new Contact(LastName='Test',LeadSource='Customer Service',AccountId=testAccount.Id);
    insert c;

    Case newCase = new Case();
    newCase.Subject = 'testStatusClosed';
    newCase.Status = 'New';
    newCase.Category__c = 'Inquiry';
    newCase.Sub_Category__c = 'Other';
    newCase.AccountId = testAccount.Id;
    newCase.ContactId = c.id;
    newCase.recordTypeId=csRecType;
    insert newCase;

     ApexPages.standardController std = New ApexPages.standardController(newCase);

updateCaseRecord uC = new updateCaseRecord();
uC.updateCheck(std);
}}

I get the error like Method does not exist or incorrect signature: void updateCheck(ApexPages.StandardController) from the type updateCaseRecord. How  can I test the apex class and can have the assertion statement. I am writing first time test scripts and I am kind of lost. Any help is greatly appreciated

A: In your class updateCheck method is static. you can't invoke static method from an instance of the class in Apex. It should be invoked from a class:
instead of
updateCaseRecord uC = new updateCaseRecord();
uC.updateCheck(std);

should be
updateCaseRecord.updateCheck(newCase.Id);

you don't need any standard controller,  as for VF controller.

I recommend you to read Get Started with Apex trailhead, not hardcode ids and if possible not to use SeeAllData=true in tests


text:
Q: Why does cd default to ~? When you type cd, it basically does the same thing as cd ~. Why?
I'm wondering if it's just a hard-coded behavior or if bash is expanding the command or something.

A: That is the POSIX specified behaviour. Not bash-specific.


text:
Q: How Can I Change the VirtualBox VM that Docker is Connected To? When I start up the Docker Quickstart Terminal, it automatically stands up a virtual machine in VirtualBox called "default", and connects to it. I have a second VM running boot2docker, however, that I would like to use instead of the "default" one (let's call it "myVM").
I would like to change the Docker Terminal's connection over to myVM, so that I can issue commands like "docker images" or "docker ps" without having to specify the IP address, port etc. (so I don't have to do something like "docker -H 192.168.99.105:2376 blah"). How can I go about accomplishing this?

A: To connect your shell to the new myVM machine.
eval $(docker-machine env myVM)

This sets environment variables for the current shell that the Docker client will read which specify the TLS settings. You need to do this each time you open a new shell or restart your machine.


text:
Q: Unable to upload files from disk to server using FileReader I am working on a form for uploading files from a local disk within the react component. After uploading the file, it should be sent to the server using the POST request, where it is processed using express-fileupload to upload to the server. The server responds that the request is too large:

PayloadTooLargeError: request entity too large

Here is the component:
import React, { Component } from 'react';
import axios from 'axios';

class FileUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sendImage: null
    };
    this.openFile = this.openFile.bind(this);
    this.sendFile = this.sendFile.bind(this);
  }
  onChange = (e) => {
    var file = e.target.files[0];
    var reader = new FileReader();
    reader.onloadend = () => {
      this.setState({ sendImage: reader.result })
    }
    reader.readAsDataURL(file);
  }
  openFile(e) {
    this.refs.fileUploader.click();
  }
  sendFile = () => {
    axios.post(this.props.API_URL + "upload/news", { data: this.state.sendImage })
      .then(res => {
      })
  }
  render() {
    return (
      <>
        <button className="xbutton" onClick={this.sendFile} >Upload</button>
        <button className="xbutton" onClick={this.openFile} >Open</button>
        <
          input
          type="file"
          name="sampleFile"
          ref="fileUploader"
          defaultValue=""
          onChange={e => this.onChange(e)}
        />
      </>
    );
  }
}

export default FileUpload;

Please tell me what the error is, and is it possible to upload files using these tools?
Thanks!


text:
Q: Python/Arcpy Crashing I am running a fairly large script where I export to a PDF. Now I added an export to Excel along with export to PDF from the same MXD. The Python window says python.exe has stopped working, ends then says restarts. I never had python crash on me before I added the export to Excel feature. can this be a memory issue?
I ran the file from the command prompt and got this error or whatever you want to call it. Not sure what it means exactly
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'GpMetadataFunctions, Version=10.2.0.0, Culture=ne
eyToken=8fc3cc631e44ad86' or one of its dependencies. The system cannot find the file specified.
File name: 'GpMetadataFunctions, Version=10.2.0.0, Culture=neutral, PublicKeyToken=8fc3cc631e44ad86'
   at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackC
kMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean fo
)
   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIn
   at System.Reflection.Assembly.Load(String assemblyString)
   at GetManagedType(Char* _assembly, Char* _path, Char* _className)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

*i do not save or close the mxd
*my code is very large so if anyone needs any more information I can provide it
export to excel code
        in_excel = fc
        out_excel = "C:path\\{}{}.xls".format(table['County'],table['MunName'])
        arcpy.TableToExcel_conversion(in_excel, out_excel)

this is my export to PDF code
        table['zoom'] = arcpy.mapping.Layer("UnionLayer")
        arcpy.SelectLayerByAttribute_management(table['zoom'])
        df.extent = table['zoom'].getSelectedExtent()
        df.scale = df.scale * 1.1
        arcpy.RefreshActiveView()
        PDFMap = arcpy.mapping.ExportToPDF(mxd, table['County']+" "+table['MunName']+" "+"Zoom Out")

The script always crashes on the second iteration right before the export to excel. the first iteration it works fine. the export to excel occurs before the export to PDF.
UPDATE
Instead of using the table to excel conversion I used a search cursor to extract the info i wanted and tried writing to a csv and I encountered the same problem. The answer does not seem to be in my code. Has anyone ever encountered a similar error? I have found this post https://geonet.esri.com/thread/61030 which alludes to the same message I get..the person on the post says "I had to copy GpMetadataFunctions.dll and MetadataTranslator.dll to the Global Assembly Cache (GAC) directory."


text:
Q: preg_replace only works on a few The code below is supposed to convert bbcode to HTML for my application, using the Laravel package.  I rebuilt the array to use my database instead.
https://github.com/golonka/BBCodeParser
The problem is that it converts a majority of the input, but not all.
A example is:
[code]html[/code] -> works
/\[code\](.*?)\[\/code\]/s

[notice]html[/notice] -> doesn't work
/\[notice\](.*?)\[\/notice\]/s

Code to populate the array:
    $temps = DB::table('bbcodes')->get();

    foreach($temps as $temp) {
        $this->parsers[$temp->name] = [
            'pattern' => $temp->pattern,
            'replace' => $temp->replace,
            'content' => $temp->content
        ];
    }
    $this->enabledParsers = $this->parsers;


text:
Q: Using a single sed call to split and grep This is mostly by curiosity, I am trying to have the same behavior as:
echo -e "test1:test2:test3"| sed 's/:/\n/g' | grep 1

in a single sed command.
I already tried
echo -e "test1:test2:test3"| sed -e "s/:/\n/g" -n "/1/p"

But I get the following error:
sed: can't read /1/p: No such file or directory

Any idea on how to fix this and combine different types of commands into a single sed call?
Of course this is overly simplified compared to the real usecase, and I know I can get around by using multiple calls, again this is just out of curiosity.
EDIT: I am mostly interested in the sed tool, I already know how to do it using other tools, or even combinations of those.
EDIT2: Here is a more realistic script, closer to what I am trying to achieve:
arch=linux64
base=https://chromedriver.storage.googleapis.com
split="<Contents>"
curl $base \
    | sed -e 's/<Contents>/<Contents>\n/g' \
    | grep $arch \
    | sed -e 's/^<Key>\(.*\)\/chromedriver.*/\1/' \
    | sort -V > out

What I would like to simplify is the curl line, turning it into something like:
curl $base \
 | sed 's/<Contents>/<Contents>\n/g' -n '/1/p' -e 's/^<Key>\(.*\)\/chromedriver.*/\1/' \
 | sort -V > out

A: Here are some alternatives, awk and sed based:
sed -E "s/(.*:)?([^:]*1[^:]*).*/\2/" <<< "test1:test2:test3"
awk -v RS=":" '/1/' <<< "test1:test2:test3"
# or also
awk 'BEGIN{RS=":"} /1/' <<< "test1:test2:test3"

Or, using your logic, you would need to pipe a second sed command:
sed "s/:/\n/g" <<< "test1:test2:test3" | sed -n "/1/p"

See this online demo. The awk solution looks cleanest.
Details
In sed solution, (.*:)?([^:]*1[^:]*).* pattern matches an optional sequence of any 0+  chars and a :, then captures into Group 2 any 0 or more chars other than :, 1, again 0 or more chars other than :, and then just matches the rest of the line. The replacement just keeps Group 2 contents.
In awk solution, the record separator is set to : and then /1/ regex is used to only return the record having 1 in it.

A: This might work for you (GNU sed):
sed 's/:/\n/;/^[^\n]*1/P;D' file

Replace each : and if the first line in the pattern space contains 1 print it.
Repeat.
An alternative:
sed -Ez 's/:/\n/g;s/^[^1]*$//mg;s/\n+/\n/;s/^\n//' file

This slurps the whole file into memory and replaces all colons by newlines. All lines that do not contain 1 are removed and surplus newlines deleted.

A: echo -e "test1:test2:test3"  | sed -En 's/:/\n/g;/^[^\n]*2[^\n]*(\n|$)/P;//!D'

*

*sed -n doesn't print unless told to

*sed -E allows using parens to match (\n|$) which is newline or the end of the pattern space

*P prints the pattern buffer up to the first newline.

*D trims the pattern buffer up to the first newline

*[^\n] is a character class that matches anything except a newline

*// is sed shorthand for repeating a match

*//! is then matching everything that didn't match previously

So, after you split into newlines, you want to make sure the 2 character is between the start of the pattern buffer ^ and the first newline.
And, if there is not the character you are looking for, you want to D delete up to the first newline.
At that point, it works for one line of input, with one string containing the character you're looking for.
To expand to several matches within a line, you have to ta, conditionally branch back to label :a:
$ printf "test1:test2:test3\nbob3:bob2:fred2\n"  | \
    sed -En ':a s/:/\n/g;/^[^\n]*2[^\n]*(\n|$)/P;D;ta'
test2
bob2
fred2

A: An alternative to the really ugly sed is: grep -o '\w*2\w*'
$ printf "test1:test2:test3\nbob3:bob2:fred2\n"  | grep -o '\w*2\w*'
test2
bob2
fred2

*

*grep -o: only matching

Or: grep -o '[^:]*2[^:]*'

A: This is simply NOT a job for sed. With GNU awk for multi-char RS:
$ echo "test1:test2:test3:test4:test5:test6"| awk -v RS='[:\n]' '/1/'
test1

$ echo "test1:test2:test3:test4:test5:test6"| awk -v RS='[:\n]' 'NR%2'
test1
test3
test5

$ echo "test1:test2:test3:test4:test5:test6"| awk -v RS='[:\n]' '!(NR%2)'
test2
test4
test6

$ echo "foo1:bar1:foo2:bar2:foo3:bar3" | awk -v RS='[:\n]' '/foo/ || /2/'
foo1
foo2
bar2
foo3

With any awk you'd just have to strip the \n from the final record before operating on it:
$ echo "test1:test2:test3:test4:test5:test6"| awk -v RS=':' '{sub(/\n$/,"")} /1/'
test1


text:
Q: How to alias a command containing both apostrophes and quotation marks? As a result of my previous question I decided to
alias groe= ?vim -c 'normal "+p1Gdddd"' -c ':%s/\n/' -c 'normal"gVGgJy"' -c'q!'?
I cant find out how to substitute '?s' in my example to make it work.
Already tried question marks and apostrophes. Any Ideas would be appreciated. Thx

A: "Inside" single quotes you could have a single quote by closing the outer single quote, then add an escaped single quote and re-open the outer single quotes, like
echo 'It'\''s ugly.'

In other words all ' will become '\'' plus outer single quotes.
Your alias would look like that:
alias groe='vim -c '\''normal "+p1Gdddd"'\'' -c '\'':%s/\n/'\'' -c '\''normal"gVGgJy"'\'' -c'\''q!'\'''

Or you could use C-style escapes $'...' where you have to escape single quotes only once but also escape character in \n:
echo $'It\'s a newline: \\n'
alias groe=$'vim -c \'normal "+p1Gdddd"\' -c \':%s/\\n/\' -c \'normal"gVGgJy"\' -c\'q!\''

A: Make it a shell function, so you can lose the outer quotes.
groe() {
  vim -c 'normal "+p1Gdddd"' -c ':%s/\n/' -c 'normal"gVGgJy"' -c'q!' "$@"
  }

That should call vim with the arguments -c, normal "+p1Gdddd", -c, :%s/\n/, -c, normal"gVGgJy", -cq!. The "$@" at the expands to the parameters you gave to the function, so groe foo.txt should work.

A: On MacOS I found that placing the following line in my .bash_profile gave me an alias that only setup my useful alias upon later usage of the logr command:
alias logr="alias r='java -jar LogUtil.jar -gui'"

I used double quotes "" around the entire logr alias that gets created for all new shells, but then the r alias only becomes available once I issue the logr command.


text:
Q: For...in statement Objective-C I am studying Objective-C and I came across this "for...in" statement. I searched for it but i still don't get how it works. Could someone explain to me in a noob-friendly how this statement works?

A: See fast enumeration documentation.
Basically you'd have, usually, an array, and you can obtain each item in the array with a handy loop instead of using NSEnumerator or an integer count variable. It makes your code much cleaner to ask for each NSString in your array rather than to have to assign to a variable using objectAtIndex for each pass of your loop.
Compare:
for (NSString *string in myArray)
{
    // do stuff...
}

To:
for (int i = 0; i < [myArray count]; i++)
{
    NSString *string = [myArray objectAtIndex:i];
    // Do stuff...
}


text:
Q: How to control an Installed Program on Windows with python I'm fairly new to Python, and am still in the process of learning it.  I just want to know if the following is possible, and if anyone could give me a few pointers on where to start.
I have ~6,000 audio files that need to be processed - reduce noise, normalize, and finally, compress - to reduce the size without losing quality.  I want to do this through Audacity, which has these actions under the "Effects" menu.  I was wondering if I could use Python to automate the work for the ~6000 files, or if a better alternative exists (maybe through Windows command prompt?).
Any kind of information to help steer me in the right direction would be greatly appreciated.  Thanks in advance.


text:
Q: PCA working so good when I compress array from 20000 to 100 I have an array of sizes (100, 200) and their value ranges from (-2.5,2.5) of each pixel, and I have 1000 such images. I want to compress the image to 100 pixels from 200000(100, 200), so I'm using PCA for it. Here's my code:
pca = PCA(100)

lower_dimensional_data = pca.fit_transform(a) #a is my data

approximation = pca.inverse_transform(lower_dimensional_data)

It's working well when I invert it and get back the original image. Am I doing something wrong here? I'm surprised as it's inverting back so well, which means there's so much information even in 100 size array.
Can someone tell me If I'm doing something wrong or understanding something wrong?
Sample image:

A: You're doing nothing wrong and a lot of things right. Your images are not complex in the theoretical sense. I can see from the example image that the pixel values do not oscillate drastically. Kolmogorov complexity can be more easily explained with strings.
Your image is more like "AAAaaaaaaaaaaaBBBBbbbbbbbbbb" which though long is easy to compress (3As10as4Bs etc)
compared to say "AzF34dsvWrr" which is much shorter but more complex.


text:
Q: Joomla 3.4.3 - configuration.php not writable Using MariaDB, Apache, PHP 5.4.x, RHEL 7
How do I allow configuration.php to be written to?
Installed Joomla several times, always ending up with the configuration.php file not writable.  I proceeded, copied the config content and created a new php file, placed it where Joomla lives, opened up the permissions, changed to apache:apache, still nothing.   I've referenced several articles, notably this one:
Installing Joomla 3 Error: Your configuration file or directory is not writable
I have also tried creating an empty configuration.php file and placing it in the joomla root, opening up permissions - didnt work.
My current state of installation is configuration.php file in place, but unable to remove the installation directory via the web installer (assuming because I shoehorned the config file into place and still not being writable).
I've tried several permissions setups then attempting to remove the install directory without success.  Manually removing the install directory via rm -r only yields a totally inaccessible site forcing me to wipe my joomla files, databases, and install again. Thanks in advance.

A: The first thing I would do is check what user php runs at on your server, and compare this with ownership of your site files.
Create user.php file at the root of your domain with
<?php echo exec('whoami'); ?>

then open that file with your broser. This will give you the name of the user that php runs as on your server. It may be apache but it may not.
Compare this user with the ownership of config.php and your site installation as a whole.
If you upload a new Joomla site via SFTP and follow the standard browser instal steps, permissions shouldn't be a problem. If you are say uploading a zip file and using a terminal connection and SSH, make sure your SSH connection is the same user as the php user on your server.
Good luck!

A: Working with my server guy - found out that several sebool settings were keeping Apache from doing what it needed to do.  Going one step further, we identified that sebool commands needed to be ran to allow httpd_can_sendmail in order to use the Sendmail feature.  Hope this helps someone out there.
The command that seemed to do the trick was sudo chcon -R -t httpd_sys_rw_content_t /var/www/html

A: In our case, problem was with CentOS permissions. So if Joomla is installed on CentOS powered server, you need to change config file (/etc/selinux/config) to look like this:
[root@host2a ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

Actually, you only set SELINUX to permissive.
Hope this helps.
p.s. Solution works for RedHat too.


text:
Q: cakephp retrive data from one table excluding the associated tables I am struggling with a basic problem. i am using cake php 2.5. i try to apply the find query in the company model and receiving all the data from companies and with its associations, but i only want to receive the data from company table and want to exclude the data from rest of relationships, can anyone help me with this. below are my queries.
    $this->loadModel('Company');
    $fields=array('id','name','logo','status');
    $conditions=array('status'=>1);
    $search_companies =    $this->Company->find('first',
    compact(array('conditions'=>$conditions,'fields'=>$fields)));
    print_r($search_companies);die();
    echo json_encode($search_companies);die();

A: With out seeing your data output, I am just going to take a stab at the problem.
Inside your $search_companies variable you are getting a multidimensional array probably with the other values of the other tables.
Why not just select the one array:
$wantedData = $search_companies['Company'];
// The key Company (which is the model) should be the data you are wanting.

A: Try setting model's recursive value to -1
$this->Company->recursive = -1;
$search_companies =    $this->Company->find('first',
  compact(array('conditions'=>$conditions,'fields'=>$fields)));

With this you will not fire the joins queries and therefore you only retrieve model's information.

A: Cakephp provide this functionality that we can unblind few/all associations on a any model. the keyword unbindModel is used for this purpose. inside the unblindModel you can define the association type and model(s) name that you want to unblind for that specific association.
$this->CurrentModelName->unbindModel(array('AssociationName' => array('ModelName_Youwwant_unblind')));


text:
Q: Javascript + Convert "" to actual bold font I am using the jTwitter plugin to get Twitter feeds. I am using it combined with a function that makes the links in the returned text click-able.
That function looks like this:
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"$1");
}

Everything works fine, except that the person who is sending the tweets is always trying to make parts of it in bold. And it looks like this Bla. It looks like this on his twitter site and also on my page.
I dont know what he does wrong and I dont care, I am just wondering if I could transform those in actual bold at my site by adding another few lines to the function above?

A: Check the source, there's a good chance that it i actually &lt and &gt instead of < and >.  so do a regex that looks for <b>

A: note the 'g' flag that tells the replacement to apply to all of the matches.
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text
       .replace(exp,"$1")
       .replace(new RegExp('<b>','g'),'')
       .replace(new RegExp('</b>','g'),'');
}

A: This is just a guess, but is the Twitter plug-in returning the HTML escaped -
<b>

if it is you could replace the escaped content -
replace(new RegExp('<b>','g'),'').replace(RegExp('</b>','g'),'')

A: the html characters have been encoded
try this
http://www.prodevtips.com/2008/10/21/jquery-plugin-html-decode-and-encode/


text:
Q: virtual key "backspace" not working I'm trying to implement a simulation of pressing a key (backspace) using Virtual-Key Codes.
Running the code while a text file is open works as expected (deletes the text), but running it while Win 8 photo App is open does not do anything (I would expect it to go up one level to the upper photo album for example).
Does anyone have an idea why? What do I need to do in order to simulate a backspace key press in Win8 photo App?
My code:
INPUT input;

input.type = INPUT_KEYBOARD;
input.ki.wScan = 0;
input.ki.dwFlags = 0;
input.ki.time = 0;
input.ki.dwExtraInfo = NULL;
input.ki.wVk = VK_BACK;

SendInput(1, &(input), sizeof(INPUT));

input.type = INPUT_KEYBOARD;
input.ki.wScan = 0;
input.ki.dwFlags = KEYEVENTF_KEYUP;
input.ki.time = 0;
input.ki.dwExtraInfo = NULL;
input.ki.wVk = VK_BACK;

SendInput(1, &(input), sizeof(INPUT));


text:
Q: cusp sparse matrix to be used in struct in C I am using the cusp library with CUDA to use sparse matrix. Can't I use it in a struct in C like:
  #include <cusp/coo_matrix.h>
  #include <cusp/multiply.h>
  #include <cusp/print.h>
  #include <cusp/transpose.h>
  struct Cat{
         int id;
         cusp::coo_matrix<int, double, cusp::host_memory> A(2,100,10);
  };
  int main(){
  }

I am getting the errors:
try.cu(7): error: expected a type specifier
try.cu(7): error: expected a type specifier
try.cu(7): error: expected a type specifier

What is the correct way to use it in a struct so that I can have array of such structures?

A: That piece of code coo_matrix looks suspiciously like a C++ template.
If so, provide your Cat struct with constructor and initialize A there:
struct Cat {
  int id;
  cusp::coo_matrix<int, double, cusp::host_memory> A;
  Cat(): id(0), A(2,100,10) {}
}


text:
Q: Apache: Redirect blog.foobar.com to www.foobar.com I have a site at blog.foobar.com that I have closed down, and I want any
page requested there to be forwarded to www.foobar.com
I want my VirtualHost config to do this for me. I currently have the following lines that does nearly what I want but not exactly:
redirect permanent / http://www.foobar.com
Unfortunately what happens is that if I ask for blog.foobar.com instead of forwarding to www.foobar.com it serves the pages on blog.foobar.com instead.
Is there a way doing this in the VirtualHost config or should I use a .htaccess file instead?
Regards
Steve

A: You can use the Redirect directive in the context of either a VirtualHost or a .htaccess file.  However, what you probably want is a RedirectMatch:
RedirectMatch permanent (.*)$ http://www.foobar.com$1

With that inside your blog.foobar.com VirtualHost, any request to blog.foobar.com would be directed to the same page on www.foobar.com, ie. blog.foobar.com/my/page would go to www.foobar.com/my/page.


text:
Q: Make header available on all components except on login Supposed I am importing a header component on layouts/default.vue
<template>
  <div>
    <b-container class="mt-5">
      <b-row>
        <b-col md="6" class="mb-3">
          <Header />
        </b-col>
        <b-col md="6">
          <nuxt />
        </b-col>
      </b-row>
    </b-container>
    <Header/>
    <nuxt/>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";

export default {
  components: {
    Header
  }
};
</script>

<style>
...
</style>

and that header will be render on all components.
My question is how can I make the header available on all components except on my Login.vue?
Any idea on where can I start to achieve this.

A: Solved by reading the documentation on https://nuxtjs.org/guide/views/ layouts section. I created another layout file on layouts folder login.vue and use it on my main login.vue
export default {
  layout: 'login' // coming from layouts folder
  // page component definitions
}

A: The current route path is '$route.path',so use 'v-show' to judge.


text:
Q: Supremum and infimum of a sequence- lim sup Do we agree that the sequence $x_n$ as defined by $\begin{cases}7^\frac{1}{n} &, \impliedby n \equiv 0 \mod 2\\n^{-7} &, \impliedby n\equiv 1 \mod 2\end{cases}$ has infimum $0$ (as the second sequence goes to zero and they are both strictly decreasing), and supremum $\sqrt{7}$ (because they are both strictly decreasing and the first starts at $\sqrt{7}$ while the second starts at $1$ ? The exercice I'm doing seems to suggest the supremum is $1$. I should note that it is asking for the $\limsup$, and my problem may stem from the fact that I don't understand the difference between those if there is one.
EDIT : Actually I asked the teacher and we didn't see it in class this year, might be why I don't get that exercise. Eh, I learned something new anyway.

A: Ok si as far as I understand (intuitively), the limit inferior and limit superior are the same as supremum and infimum, only it is when $n\to \infty$. Hence why we don't care about the first terms and see easily that $\lim \sup =1$.


text:
Q: How to rename large amounts of spatial data? I have approximately 1500 raster files following this format:
m_3609922_nw_14_1_20100425

I need these subsetted to, for example: 3609922nw.  What are appropriate methods to rename large numbers of spatial data, that may or may not contain ancillary files (e.g. .xml, .ovr)?

A: Something like this ought to get you going...
import os
import arcpy
from arcpy import env

# directory containing rasters to be renamed
RASTER_DIR = 'C:/MyRasters/'

env.workspace = RASTER_DIR
for raster in arcpy.ListRasters():

    # get the raster name and file extension
    fileName,fileExtension = os.path.splitext(raster)

    # do some shenanigans to rename the file
    # based on your sample raster name, fileNameParts would look like
    # fileNameParts[0] = m
    # fileNameParts[1] = 3609922
    # fileNameParts[2] = nw
    # fileNameParts[3] = 14
    # fileNameParts[4] = 1
    # fileNameParts[5] = 20100425

    fileNameParts = fileName.split('_')
    compactFileName = fileNameParts[1] + fileNameParts[2] + fileExtension

    arcpy.Rename_management(raster,compactFileName)


text:
Q: Nativescript Angular2 tutorial results in error I am getting the below error with the Angular2 tutorial.  TNS Doctor is ok then why the below error?
'tns livesync ios --emulator --watch
Executing before-prepare hook from /Users//Documents/frontend/sample-Groceries/hooks/before-prepare/nativescript-dev-typescript.js
Found peer TypeScript 1.8.10
Project successfully prepared (ios)
Executing before-livesync hook from /Users//Documents/frontend/sample-Groceries/hooks/before-livesync/nativescript-angular-sync .js
Transferring project files...
Successfully transferred all files.
Applying changes...
Successfully synced application org.nativescript.groceries on device D28D29C3-07B6-4B60-B4B0-711475C505DE.
Executing before-watch hook from /Users//Documents/frontend/sample-Groceries/hooks/before-watch/nativescript-dev-typescript.js
Found peer TypeScript 1.8.10
Sep 17 07:34:37 Davids-iMac sampleGroceries[2934]: 1   0x105cd08d7 -[TNSRuntime executeModule:]
Sep 17 07:34:37 Davids-iMac sampleGroceries[2934]: 2   0x10587b6d2 main
Sep 17 07:34:37 Davids-iMac sampleGroceries[2934]: 3   0x109be668d start
Sep 17 07:34:37 Davids-iMac sampleGroceries[2934]: 4   0x1
Sep 17 07:34:37 Davids-iMac sampleGroceries[2934]: file:///app/tns_modules/utils/utils.js:130:72: JS ERROR TypeError: UIDevice.currentDevice is not a function. (In 'UIDevice.currentDevice()', 'UIDevice.currentDevice' is an instance of UIDevice)
Sep 17 07:34:37 Davids-iMac com.apple.CoreSimulator.SimDevice.D28D29C3-07B6-4B60-B4B0-711475C505DE.launchd_sim[2849] (UIKitApplication:org.nativescript.groceries[0xe746][2934]): Service exited due to Segmentation fault: 11
7:34:38 AM - Compilation complete. Watching for file changes.

I am using the new 8x Xcode.

A: Dependences version of the sample-Groceries project will be updated to the latest NativeScript version soon, however you could open your package.json file and change the following versions:
tns-ios": {"version": "2.3.0"}
"nativescript-angular": "1.0.0"
"tns-core-modules": "2.3.0".
You  should also be sure that hooks, node_modules, platforms folders has been deleted. In regard to that, With Xcode 8 some of the methods now are  properties and that will cause issues when native code has been used  in the project as it does in the sample-Groceries. As a temporary solution you could replace some code in the status-bar-util.ts and grocery-list.component.ts files.
app/shared/status-bar-util.ts
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent; replace with UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyle.LightContent;
app/groceries/grocery-list/grocery-list.component.ts
cell.backgroundColor = UIColor.clearColor(); replace with cell.backgroundColor = UIColor.clearColor;


text:
Q: Can we just keep particular tags inside a parent tag and delete all other tags in xslt1.0? Let's say i have data like below:

 some data

  bold data
  italic data
  link data
  underline data

ul list data

ol list data

I want output as:

 some data
  bold data
  italic data
  link data
  underline data
  ul list data
  ol list data

I want to delete all tags inside caption tag except bold italic underine and anchor tag. Thanks in advance.

A: Use the identity template where you want to retain the tags:
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

and a variant that drops the tags in other cases:
<xsl:template match="p|ul|ol|li">
  <xsl:apply-templates/>
</xsl:template>


text:
Q: After renaming solution/projects, ASP.NET IIS is looking in the wrong (old) location for the config file I get the error: "The requested page cannot be accessed because the related configuration data for the page is invalid."

A: Delete the .vs folder (should be in the same directory as your .sln file).  Visual Studio will recreate it with the correct paths.


text:
Q: Display block parent class when element inside has class active So, I have some problems with this. I have multiple parent divs with the same class and I want when an element inside every parent div has class "selected_tip" to display block the parent of the parent of that element. How to do this. Keep in mind that the id's are dinamic. My code is this:

Proaspete

Coapte, tocate

Călite

Prăjite

Fierte

A: You can use .closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$('.selected_tip').closest('div.tip').css('display', 'block')

OR, Use .parent() to traverse up to parent.

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

$('.selected_tip').parent().parent().css('display', 'block')


text:
Q: Explicite proof that complex power function are holomorphic Consider the function  $f(z):=z^n$ and prove that $\dfrac{\partial}{\partial \bar{z}}f(z)=0$.
Here is my attempt:
\begin{equation*}
\begin{split}
    \dfrac{\partial}{\partial\bar{z}}f(z)&=\dfrac{1}{2}\left(\dfrac{\partial}{\partial x}+i\dfrac{\partial}{\partial y}\right)(x+iy)^n=\dfrac{1}{2}\left(\dfrac{\partial}{\partial x}+i\dfrac{\partial}{\partial y}\right)\left(\sum_{k=0}^n\binom{n}{k}x^{n-k}(iy)^k\right)\\
    &=\dfrac{1}{2}\sum_{k=0}^n\binom{n}{k}\left[\dfrac{\partial}{\partial x}\left(x^{n-k}(iy)^k\right)+i\dfrac{\partial}{\partial y}\left(x^{n-k}(iy)^k\right)\right]\\
    &=\dfrac{1}{2}\sum_{k=0}^n\binom{n}{k}\left[(n-k)x^{n-k-1}i^ky^k+ki^{k+1}x^{n-k}y^{k-1}\right]\\
    &=\dfrac{1}{2}\sum_{k=0}^n\binom{n}{k}\left(i^kx^{n-k-1}y^{k-1}\right)\left[(n-k)y+kix\right].
    \end{split}
\end{equation*}
Now, how can I show that it actually vanishes? Thank you.

A: We obtain
\begin{align*}
\color{blue}{\frac{\partial}{\partial\overline{z}}z^n}
&=\frac{1}{2}\left(\frac{\partial}{\partial x}+i\,\frac{\partial}{\partial y}\right)(x+iy)^n\\
&=\frac{1}{2}\frac{\partial}{\partial x}(x+iy)^n
+\frac{i}{2}\frac{\partial}{\partial y}(x+iy)^n\\
&=\frac{1}{2}n(x+iy)^{n-1}+\frac{i}{2}in(x+iy)^{n-1}\\
&\,\,\color{blue}{=0}
\end{align*}


text:
Q: Count occurrence of a data in a Multidimensional array need a help. I want to count number of occurrence of a data in a multi dimensional array using PHP but cant solve the problem using for each. So I am asking for help
Sample array
Array ( [0] => Array ( [id] => 100 [keys] => Array ( [0] => Array ( [id] => x181 ) [1] => Array ( [id] => x853 ) [2] => Array ( [id] => x890 ) ) )
[1] => Array ( [id] => 101 [keys] => Array ( [0] => Array ( [id] => x133 ) ) )
[2] => Array ( [id] => 102 [keys] => Array ( [0] => Array ( [id] => x904) [1] => Array ( [id] => x102 ) ) )
[3] => Array ( [id] => 103 [keys] => Array ( [0] => Array ( [id] => x121 ) ) ) )

I want to count number of occurrences of each IDs, for example
x181 1
x121 1 ...


text:
Q: Changing a icon in ActionBar depending on a condition I am updating a record in a SQLite database when the user presses an icon on the ActionBar. The information being updated is a flag that adds a record to a Favourites page.
PROBLEM
When the user adds or removes the record to favourites, I would like the icon in the ActionBar to change. I have a full star icon and a empty star icon.
The setIcon method displays the the full star icon if the record is a favourite, and a empty star icon if the record is not a favourite.
In the code below you will see I am using a boolean isInFavourite, which is true when String fav = "y".
When entering the Activity, the icon displayed is correct.
When the user clicks on the icon to invoke the onMenuItemClick() method, the record is successfully updated but the icon does not change.
I am unable to change the boolean isInFavourite when the record has been updated because Eclipse wants all the variables to be set as final
Can anyone help me change the icon to once the record has been updated.
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    db = new DBHelper(this);
    db.createDataBase();
    db.openDataBase();

    Bundle bundle = getIntent().getExtras();
    final String rowid = bundle.getString("id");
    final String fav = bundle.getString("fav");

    //Boolean to check if record is a favourite
    final boolean isInFavourite = fav.contentEquals("y");

    menu.add("Add to Favourites")
            .setOnMenuItemClickListener(new OnMenuItemClickListener() {

                public boolean onMenuItemClick(MenuItem item) {

                    String toggle;
                    String message;

                    //Logic to add or remove row from recording.
                    if (isInFavourite) {
                        toggle = "n";
                        message = "Recipe removed from Favourites";
                    } else {
                        toggle = "y";
                        message = "Recipe added to Favourites";
                    }

                    //Update favourite record in database
                    db.updateFavourite(rowid, toggle);
                    db.close();

                    Toast.makeText(getApplicationContext(), message,
                            Toast.LENGTH_LONG).show();

                    return true;
                }

            })

            //Set icon depending on whether record is a favourite or not.
            .setIcon(isInFavourite ? R.drawable.fav_true : R.drawable.fav_false)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    return true;

}

Thanks to @dmon for the solution
SOLUTION
private DBHelper db = null;

public String fav = null;
public String rowid = null;
public boolean isFav;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    Bundle bundle = getIntent().getExtras();
    rowid = bundle.getString("id");
    fav = bundle.getString("fav");

    if (fav.contentEquals("y")) {
        isFav = true;
    } else {
        isFav = false;
    }

    try {
        db = new DBHelper(this);
        db.createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getSupportMenuInflater().inflate(R.menu.menu_settings, menu);

    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem fave = menu.findItem(R.id.add);
    MenuItem unfave = menu.findItem(R.id.remove);

    fave.setVisible(isFav);
    unfave.setVisible(!isFav);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        return true;
    case R.id.add:
        fav = "n";
        isFav = false;
        updateFav();
        supportInvalidateOptionsMenu();
        Toast("Removed from Favourites");
        return true;
    case R.id.remove:
        fav = "y";
        isFav = true;
        updateFav();
        supportInvalidateOptionsMenu();
        Toast("Added to Favourites");
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void updateFav (){
        db.openDataBase();
        db.updateFavourite(rowid, fav);
        db.close();
}

XML File: res/menu/menu_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/add"
    android:icon="@drawable/good"
    android:showAsAction="always"
    />
<item
    android:id="@+id/remove"
    android:icon="@drawable/bad"
    android:showAsAction="always"/>

A: The easiest way is to just provide two different buttons and hide/show them accordingly:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inf = new MenuInflater(this);
  inf.inflate(R.menu.menu_xml, menu);
  return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  MenuItem fave = menu.findItem(R.id.favorite);
  MenuItem unfave = menu.findItem(R.id.unfavorite);

  fave.setVisible(!isFave);
  unfave.setVisible(isFave);
  return true;
}

Then you invalidate the options menu when the state has changed. Note that you have to have a global variable that has the current state of the item (where isFave is coming from)
invalidateOptionsMenu();

A: Make the isInFavourite variable a global field (declare it outside of the method, just in the class). Any local variables must be final for a scope below them to use them. However, if you make it global, and declare it above, it doesn't need to be final.


text:
Q: Terminating the mariadb service in between when the engine is running My application is connected to Maria Db on a different server, So once I start my engine It fetches data by querying into the database, What I am trying to do is, my application queries from DB for every 5sec
I just terminated the maria DB service by this
service mariadb stop

After doing this In my application where I am executing the query thrown this error:
panic: runtime error: invalid memory address or nil pointer dereference
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x54c9a6]

goroutine 50 [running]:
database/sql.(*Rows).close(0x0, 0x0, 0x0, 0x0, 0x0)
    /home/go1.14/go/src/database/sql/sql.go:3063 +0x76
database/sql.(*Rows).Close(0x0, 0x0, 0x0)
    /home/go1.14/go/src/database/sql/sql.go:3059 +0x33
panic(0x8d03e0, 0xf3dd00)
    /home/go1.14/go/src/runtime/panic.go:969 +0x166
database/sql.(*Rows).Next(0x0, 0x1)
    /home/go1.14/go/src/database/sql/sql.go:2744 +0x30
path-to-file/loadConfig.LoadFromDB(0x9ff760, 0xc0000240a0, 0xc000192000, 0xf, 0x0, 0x0, 0x0, 0x0)
    path-to-file/loadConfig/loadConfig.go:65 +0x1a2

My code looks like this:
func LoadFromDB(Ctx context.Context, Conn *sql.DB, modId int) (map[string][]string, map[string]string, error) {
    rows, err := Conn.Query(getQueryFromFile("QUERY"),modId)

    if err != nil {
        log.Println("LOAD CONFIG: Error establishing connection to DB")
    }
    defer rows.Close()
    configValues := make(map[string][]string)
    configTimeVal := make(map[string]string)
    for rows.Next() {
        configParam := ""
        configVal := ""
        var configLastUpdated string
        eror := rows.Scan(&configParam, &configVal, &configLastUpdated)
        if eror != nil {
            return nil, nil, eror
        } else {
            configValues[configParam] = append(configValues[configParam], configVal)
            configTimeVal[configParam] = configLastUpdated
        }
    }

        return configValues, configTimeVal, nil
    }

Can you guys help me on how to handle this situation when the maria db service is stopped

A: You're missing a return when the error is non-nil, so the function just keeps running. Try this:
    if err != nil {
        log.Println("LOAD CONFIG: Error establishing connection to DB")
        return nil, nil, err
    }

You also need to handle errors from the Next() function; see the docs:

Next prepares the next result row for reading with the Scan method. It returns true on success, or false if there is no next result row or an error happened while preparing it. Err should be consulted to distinguish between the two cases.


text:
Q: HTTP Error 405.0 - Method Not Allowed with Put when attempting to upload a file My previously working update function now returns a 405 error when it is run. This is after I added the fileReader functionality to facilitate file uploading for a pictures. How could I now have a HTTP verb error (which is what 405 is to my understanding) if my ajaxCall is untouched from it's working form?
function update()
{

//picture specific upload stuff
var reader = new FileReader();
var file = $('#fileUpload')[0].files[0];
reader.readAsBinaryString(file);
//What is readerEvt?
reader.onload = function (readerEvt)
{
    //get binary data then convert to encoded string
    var binaryString = reader.result;
    var encodedString = btoa(binaryString);

    //normal update fields
    emp = new Object();
    emp.Title = $("#TextBoxTitle").val();
    emp.Firstname = $("#TextBoxFirstname").val();
    emp.Lastname = $("#TextBoxLastname").val();
    emp.Phoneno = $("#TextBoxPhone").val();
    emp.Email = $("#TextBoxEmail").val();
    emp.StaffPicture64 = encodedString;
    emp.Id = localStorage.getItem("Id");
    emp.DepartmentId = localStorage.getItem("DepartmentId");
    emp.Version = localStorage.getItem("Version");
}
ajaxCall("Put", "api/employees", emp)
    .done(function (data) {
        $("#myModal").modal("hide");
        getAll(data);
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        errorRoutine(jqXHR);
    });
return false;
}


text:
Q: How to solve a Sturm-Liouville problem with $(e^{4x}y')'$ For an equation $(e^{4x}y')'+3e^{4x}y=0, 0<x<1$
and $(1-3e^2)y(0)+(1-e^2)y'(0)=0, y'(1)=0$ , I get from the general Sturm-Liouville formulation $(P(x)y')'+(-q(x)+\lambda r(x))y=0$.
Then I get $P(x)=e^{4x}$ and $c_1=(1-3e^2), c_2=(1-e^2),c_3=0$ and $((-q(x)+\lambda r(x))=3e^{4x}$ from here I don't know how to proceed?

A: after simplifying we get the following rquation
$$e^{4 x} y''(x)+4 e^{4 x} y'(x)+e^{4 x} y(x)=0$$
solving this we obtain
$$\left\{\left\{y(x)\to c_1 e^{-3 x}+c_2 e^{-x}\right\}\right\}$$


text:
Q: Set selected values to NumberPicker I have implemented a NumberPicker in which we can roll the numbers from 0 to 99. But my requirement is I only want 1,2,3,4,5,99, these number to be rolled in NumberPicker. Is it possible to do this?
I have tried this where mPicker is the object of NumberPicker
String[] nums= {"1","2","3","4","5","99"};
mPicker.setDisplayedValues(nums);

But in this Am not able to roll it, only be able to type through SoftInputKeyboard. Can anybody help to takle this and get it done without any third party libraries.

A: I solved this problem by doing like this
mPicker.setMaxValue(5);
mPicker.setMinValue(0);

String[] nums= {"1","2","3","4","5","99"};
mPicker.setDisplayedValues(nums);

Setting max value to 5 and adding 5 values to to show.


text:
Q: Matplotlib Secondary_y cause plot to shift right I was hoping someone could help me with an issue.
I am trying to plot a line graph over a bar graph. Below is a link to the line graph and the code:
fig, ax = plt.subplots(figsize=(10, 5), sharex = True)
#df_plot.plot(ax = ax, y='D', kind = 'bar', legend = False)
df_plot.plot(ax = ax, secondary_y = True, y = 'E', kind = 'line', c = 'r')
plt.show()

And the bar graph:
fig, ax = plt.subplots(figsize=(10, 5), sharex = True)
df_plot.plot(ax = ax, y='D', kind = 'bar', legend = False)
#df_plot.plot(ax = ax, secondary_y = True, y = 'E', kind = 'line', c = 'r')
plt.show()

But when I try to combine the graphs onto one figure, the line graph shifts over to the right by one.
fig, ax = plt.subplots(figsize=(10, 5), sharex = True)
df_plot.plot(ax = ax, y='D', kind = 'bar', legend = False)
df_plot.plot(ax = ax, secondary_y = True, y = 'E', kind = 'line', c = 'r')
plt.show()

Does anyone know why this is happening?

A: There is no "shift".
The bars are positionned such that the first bar starts at position 0, the second at 1 etc. The line graph starts at position 1; this is the position where the second bar is shown. Only due to the labeling, this appears to be wrong. But mind that the label could also read "banana" in which case one would not wonder too much about the resulting plot.
In order to overcome this, you may shift your line plot manually by 1 unit.


text:
Q: Typescript / Mocha Test Framework: Initialization code to block and wait for a promise I am working on a suite of API tests. Right now, I believe that Typescript and Mocha are the best choice for that. However, I am running into one issue: Before the API tests run, I need some initialization code that will authenticate with some external systems to create some test fixtures and do authentication.
That needs to happen before any test starts.
My plan was to do this via a mocha require mocha -r initializer.ts src/test/**/*.ts.
That works well so far. However, the challenge I am facing is, that I need to do a lot of HTTP API calls in that initializer. I am using an API client, that is async and uses Promises. This is issue, because I need to ensure that tests are not started, before initializer.ts has done it's work.
Is there any way (except for a busy loop) I could make this work?

A: As per MochaJS's documentation on hooks:

*

*You can define any hook as a root level hook.

You should utilize before() as a root level hook for the problem you are facing.
From inside this hook you can call methods which are used for authentication. Mocha will wait for this before() block to complete before jumping to the execution of actual test cases.


text:
Q: Sending the message Ctrl+Alt+Del from my application I want to write a small utility in MFC which sends the Ctrl+Alt+Del message to OS. Can any one help me how do I achieve this? I tried:
::PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG( MOD_CONTROL | MOD_ALT, VK_DELETE));

But this is not working.
I want to send Ctrl+Alt+Del not to invoke TaskMgr.exe. Also, it is for my local OS (Windows XP Service pack 2). Basically I want to use this application to lock my machine and schedule some actions along with locking.

A: This is not a keystroke you can simulate. It's called the "Secure Attention Sequence".
Here's how to invoke it FROM A REMOTE DESKTOP (XP+ solution):
include <shldisp.h>

IShellDispatch4 *pShell;

CoInitialize(NULL);

HRESULT hr = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER,
IID_IShellDispatch, (void**)&pShell);

if(SUCCEEDED(hr))
pShell->WindowsSecurity();

CoUninitialize();

The only solution to invoke it from the local desktop is to use SASLib. It's not public. Write a note to saslib@microsoft.com to request it.
EDIT: Wait! You want to lock the machine? Just call LockWorkStation()! Click the link for more info about header file, lib file et all other details.

A: Since VNC can let you do this to a remote system, it must be possible. If I were you, I'd trawl through the source to UltraVNC. Then I'd post the answer the here :)

A: Do you need to send control+alt+delete or do you just want to bring up the task manager?
If you just need to bring up the task manager you can simply run \Windows\System32\taskmgr.exe

A: I know it's an old questions but I am posting my solutions here in case someone looking for a solution arrives here. The part1 and part2 articles explain how Winlogon registers the CAD sequence and provides code examples on how to use it.

*

*Send CAD and Unlock workstation for Windows XP - Part 1 (free)

*Send CAD and Unlock workstation for Windows XP - Part 2 (free)

*SasLibEx for Vista and higher (sorry, this is not free)

A: Wouldn't it be easier to just ask the machine to shut down or logout? That key combination isn't really a good idea? You can send these messages.

A: Can't you start a screensaver and it will take care of the locking for you? I don't have a Windows machine available right now, but I recall one could lock the workstation like this.

A: Call the SendSAS function to achieve this.