Q: SAME70 read external interrupt polarity in ISR I'm currently working on a SAME70 board made by Atmel. I plugged on it an extention OLED1 board  (Atmel too) on EXT1 port. My goal is to recover the information about interrupt type (falling or raising) when I'm pressing the button 3 on OLED1 board. I have a function which allows me to set the different registers related to an interrupts. But unfortunately the register which indicates the polarity (FLHSR) stay always at 0 whatever the state of the button.
Below my code.
#include <asf.h>

void set_Interupt_Pin()
{
    uint32_t mask = 1 << 19;  /*bitmasking*/
    PIOA->PIO_IER = mask;    /*enable interruptions*/
    PIOA->PIO_AIMER = mask;  /*add new interruption*/
    PIOA->PIO_ESR = mask;     /*set interrupt source on edge*/
    PIOA->PIO_REHLSR = mask; /* set interrupt to rising edge*/
    PIOA->PIO_FELLSR= mask; /* set interrupt to falling edge*/
    NVIC_DisableIRQ(ID_PIOA);
    NVIC_ClearPendingIRQ(ID_PIOA);
    NVIC_EnableIRQ(ID_PIOA);   /*set NVIC to get interruptions from PIOA*/
    NVIC_SetPriority(ID_PIOA, 4); /*priority 4*/

}

void PIOA_Handler(void)
{
    printf("FRLHSR: %x\n",PIOA->PIO_FRLHSR); /*state of polarity event */
    printf("ISR: %x\n",PIOA->PIO_ISR);
    printf("ELSR: %x\n",PIOA->PIO_ELSR);
    printf("AIMMR: %x\n",PIOA->PIO_AIMMR);
}

int main(void)
{
    const usart_serial_options_t usart_serial_options = {
        .baudrate     = CONF_UART_BAUDRATE,
        .charlength   = CONF_UART_CHAR_LENGTH,
        .paritytype   = CONF_UART_PARITY,
        .stopbits     = CONF_UART_STOP_BITS
    };
    sysclk_init();
    board_init();
    stdio_serial_init(CONF_UART, &usart_serial_options);
    set_Interupt_Pin();
    while(1){}
}

You can see here the result of print when I press button (first part) and I release button (second part).

Best regards


Q: Write MDS business rules directly in SQL I'm using Master Data Services to check business rules in SQL. The use of MDS makes it easy for any (non-coder) to add business rules. However, I initially need to add a large amount of business rules and this is a very tedious procedure in MDS.
Is there a way to write the MDS business rules directly in code and add them to the MDS database?

A: There are quite a couple of stored procedures used for updating the MDS, but is is quite difficult to figure out how to use them. (And you can mess up the model if used incorrectly)
Easier would be to try the Business Rules Create method.
This is where you can get started with webservices:
http://sqlblog.com/blogs/mds_team/archive/2010/01/12/getting-started-with-the-web-services-api-in-sql-server-2008-r2-master-data-services.aspx
This is where the method is defined:
https://msdn.microsoft.com/en-us/library/microsoft.masterdataservices.services.servicecontracts.iservice.businessrulescreate(v=sql.120).aspx
You will need to weigh your options whether it would be faster to figure out how to do one of the above, or just knuckle down and create the business rules. MDS 2016 is much more user friendly than the previous versions when creating business rules(fyi)


Q: The ~ prefix in Objective C I've been learning core audio on the iPhone, and when looking through Apple's sample code I found this:
#include <AudioToolbox/AudioToolbox.h>

#include "CAStreamBasicDescription.h"
#include "CAXException.h"

#define kNumberBuffers 3

class AQPlayer
    {
    public:
        AQPlayer();
        ~AQPlayer();

        OSStatus                        StartQueue(BOOL inResume);
        OSStatus                        StopQueue();
        OSStatus                        PauseQueue();

        AudioQueueRef                   Queue()                 { return mQueue;}
        CAStreamBasicDescription        DataFormat() const      { return mDataFormat; }
        Boolean                         IsRunning() const       { return (mIsRunning) ? true : false; }
        Boolean                         IsInitialized() const   { return mIsInitialized; }
        CFStringRef                     GetFilePath() const     { return (mFilePath) ? mFilePath : CFSTR(""); }
        Boolean                         IsLooping() const       { return mIsLooping; }

        void SetLooping(Boolean inIsLooping)    { mIsLooping = inIsLooping; }
        void CreateQueueForFile(CFStringRef inFilePath);
        void DisposeQueue(Boolean inDisposeFile);

    private:
        UInt32                          GetNumPacketsToRead()               { return mNumPacketsToRead; }
        SInt64                          GetCurrentPacket()                  { return mCurrentPacket; }
        AudioFileID                     GetAudioFileID()                    { return mAudioFile; }
        void                            SetCurrentPacket(SInt64 inPacket)   { mCurrentPacket = inPacket; }

        void                            SetupNewQueue();

        AudioQueueRef                   mQueue;
        AudioQueueBufferRef             mBuffers[kNumberBuffers];
        AudioFileID                     mAudioFile;
        CFStringRef                     mFilePath;
        CAStreamBasicDescription        mDataFormat;
        Boolean                         mIsInitialized;
        UInt32                          mNumPacketsToRead;
        SInt64                          mCurrentPacket;
        UInt32                          mIsRunning;
        Boolean                         mIsDone;
        Boolean                         mIsLooping;

        static void isRunningProc(      void *              inUserData,
                                        AudioQueueRef           inAQ,
                                        AudioQueuePropertyID    inID);

        static void AQBufferCallback(   void *                  inUserData,
                                        AudioQueueRef           inAQ,
                                        AudioQueueBufferRef     inCompleteAQBuffer);

        void CalculateBytesForTime(     CAStreamBasicDescription & inDesc,
                                        UInt32 inMaxPacketSize,
                                        Float64 inSeconds,
                                        UInt32 *outBufferSize,
                                        UInt32 *outNumPackets);
    };

Does anyone know what this line does: ~AQPlayer();
I haven't seen the symbol ~ used before.

A: This is not a c related. It looks like c++ in which case the ~ is the desctructor for the class. You might want to read about destructors in the C++ FAQ

A: This is a C++ class, not an Objective-C class. The ~ symbol is used to declare or define a destructor method, a method that is automatically called when an instance's lifetime ends. The destructor method of a C++ class is used in the same way that a dealloc method is used in Objective-C classes (to clean up resources, and so on). The difference is that in Objective-C, dealloc is not invoked until it has no owners (i.e. all owners have relinquished their ownership by sending release).
If you wish to know what this code does, perhaps ask a C++ crowd, although, from a quick glance, it looks like an audio player utilising Apple's AudioToolbox framework.

A: That looks like C++ to me. It is supported on iOS, so that's why you’re seeing it.

A: That is c++ code, to develop with these from Objective-C you'd use Objective-C++.  Files with .mm are Obj-c++ and .m are just standard obj-c.

A: thats the destructor. in C++ the destructors are as this, while this code looks more like C++, in objective C you can write the destructor with "~"


Q: dragonruby-game-toolkit Excerpt from their website:
DragonRuby Game Toolkit is a professional grade (yet beginner-friendly) 2D game engine. It's tiny (~3MB), fast as hell, and cross-platform (including consoles).
So what's so great about DragonRuby Game Toolkit?

*

*Dirt simple APIs capable of creating complex 2D games.

*Fast as hell. Powered by highly-optimized C code written by Ryan C. Gordon, one of the core contributors of SDL (a library that powers every commercial game engine in the world).

*Battle-tested by Amir Rajan, a critically acclaimed indie game dev.
Tiny. Like really tiny. The entire engine is a few megabytes.
Hot loaded, realtime coding, optimized to provide constant feedback to the dev. Productive and an absolute joy to use.

*Turnkey builds for Windows, MacOS, and Linux with seamless publishing to Itch.io.

*Cross platform: PC, Mac, Linux, iOS, Android, Nintendo Switch, XBOX One, and PS4 (mobile and console compilation requires a business entity, NDA verification, and a Professional GTK License, contact us).


Q: How can I use a multiline footer in TCPDF? // Page footer
public function Footer() {
    // Position at 15 mm from bottom
    $this->SetY(-15);
    // Set font
    $this->SetFont('helvetica', 'I', 8);
    // Page number
    $this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}

Right now my footer looks like this:
]
But I need a more komplex footer with multiple lines:
]
How can I achieve this?
I tried to solve it with this stack overflow suggestion:
TCPDF Multiple Footers
But I had no success.

A: Try using MultiCell with some cell width combination, like this:
public function Footer() {
    // Make more space in footer for additional text
    $this->SetY(-25);

    $this->SetFont('helvetica', 'I', 8);

    // Page number
    $this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');

    // New line in footer
    $this->Ln(8);

    // First line of 3x "sometext"
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');

    // New line for next 3 elements
    $this->Ln(4);

    // Second line of 3x "sometext"
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
    $this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');

    // and so on...
}

You can see more examples of how to use MultiCell function in TCPDF official examples: https://tcpdf.org/examples/example_005/


Q: Overriding parameterized methods in Scala Note: I apologise for altering this question, previously I wan't able to express the exact issue I am facing.
Let's say we have an abstract parameterized class abs,
abstract class abs[T] {
    def getA(): T
}

class ABS[Int] extends abs[T] {
    override def getA(): Int = 4
}

gives the following incomprehensible error:
<console>:28: error: type mismatch;
 found   : scala.Int(4)
 required: Int
       override def getA(): Int = 4
                              ^

I want to override the method getA.
Also an explanation or some helpful link would be really appreciated.

A: With the current base method signature this is impossible since generics are erased.
Take a type tag (I also renamed the method's T to U to prevent confusion because of shadowing):
abstract class abs[T] {
    def getA[U: TypeTag](): U
}

class ABS[T] extends abs[T] {
    override def getA[U]()(implicit tag: TypeTag[U]): U = {
        if (tag == typeTag[Int]) new Integer(1)
        else if (tag == typeTag[Char]) new Character('1')
        else throw new Exception("bad type")
    }.asInstanceOf[U]
}

A: Maybe you want something like this

 abstract class Abs[T] {
    def getA: T
    def getA(i: T): T
  }

class Absz extends Abs[Int]{
    override def getA = 4
    override def getA(i: Int) = i
  }

(new Absz()).getA                               //> res0: Int = 4
  (new Absz()).getA(3)                            //> res1: Int = 3

A: You can do it with Shapeless polymorphic functions: https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0
import shapeless._

object Abs extends Poly0{
  implicit def caseInt = at[Int](4)
  implicit def caseChar = at[Char]('4')
}

println(Abs.apply[Int])
println(Abs.apply[Char])


Q: In Javascript While loop repeats last number when counting from 1 to 5 when run on console When running following code on console:
var counter=0; while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
4
whereas for following code works fine, without repeating last value:
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
Now, if I place above for loop after above mentioned while loop , output is perfectly fine:
var counter=0; while(counter<5){ console.log(counter); counter++; }
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
0
1
2
3
4
whereas, if I place while loop after for loop , repetition of last number found.
for(var i=0; i<5; i++){ console.log(i); }
var counter=0;while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
0
1
2
3
4
4
Request all to provide a reason on this unexpected behavior of while loop.
Thanks.

A: When performing operations in the console, the return value of the last executed line is always output.
That means that simply writing
var counter = 0; ++counter;

will log 1 to the console.
The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression.

A: The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself.
Try: var counter=0; while(counter<5){ console.log(counter++); }


Q: R convert nested values to new columns and rows With a dataframe like the following:
currencyDetails = c("Dollar:40, Euro:80, valid",
               "Yen:400, Pound:50",
               "Dollar:40, Pound:50, currency",
               NA)

Can someone recommend a method to append to that dataframe new columns and rows that correspond to the pairs and values in the each row please?  The number of pairs or values in each string is not fixed, and not ordered.
For sample output:
Dollar = c(40,NA,NA,NA)
Pound = c(NA,50,50,NA)
Euro = c(80,NA,NA,NA)
Yen = c(NA,400,NA,NA)
valid = c(1,0,0,0)
currency = c(0,0,1,0)
df = data.frame(Dollar, Pound, Euro,Yen,valid, currency)
cbind(currencyDetails, df)

                currencyDetails Dollar Pound Euro Yen valid currency
1     Dollar:40, Euro:80, valid     40    NA   80  NA     1        0
2             Yen:400, Pound:50     NA    50   NA 400     0        0
3 Dollar:40, Pound:50, currency     NA    50   NA  NA     0        1
4                          <NA>     NA    NA   NA  NA     0        0

I think it's different to the supplied previous answers as there's the extra complexity of splitting out the key:value pair, it's not that each element is turned into a column name as is.  For example, Pound:50 is not the column, Pound is, with 50 as it's value.

A: Try this solution:
splitted<-trimws(unlist(strsplit(aDataFrame,",")))

t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":")))
          [,1]     [,2]
Dollar:40 "Dollar" "40"
Euro:80   "Euro"   "80"
Yen:400   "Yen"    "400"
Pound:50  "Pound"  "50"

Update
df<-data.frame(t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":"))))
> library(reshape2)
> acast(df, X2 ~ X1)
Using X2 as value column: use value.var to override.
    Dollar Euro Pound Yen
40  40     <NA> <NA>  <NA>
400 <NA>   <NA> <NA>  400
50  <NA>   <NA> 50    <NA>
80  <NA>   80   <NA>  <NA>
Levels: 40 400 50 80


Q: Finding objects between two dates Okay so I have a parse database with two keys (startedAt) and (endedAt) basically I would like to return all the objects between these two given times. However, I store the times as strings, not dates. I would really like to not have to change them to dates as that would force me to rework code in a lot of other parts of my program. So is it possible to do the following
    NSDate *leftDate = leftClassRoomAfterDatePicker.date;
    NSDate *arrivedDate = arrivedBeforeDatePicker.date;

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM-dd hh:mm"];

    NSString *leftDateString = [dateFormat stringFromDate:leftDate];
    NSString *arrivedDateString = [dateFormat stringFromDate:arrivedDate];

    NSLog(leftDateString);
    NSLog(arrivedDateString);

    PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
    [query whereKey:@"startTime" greaterThan:leftDate];
    [query whereKey:@"timeArrived" lessThan:arrivedDate];

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       NSLog(@"Successfully retrieved %d objects.", objects.count);
    }];

When I run this code I get the following error
The problem is that the strings are not returning the correct value. In my parse database I have a value of startTime:    Dec 08, 18:28
and             endTime:      Dec 08, 18:28
But it still does not work (no objects are returned). I think this is because the greaterthan/lessthan functions will not work on strings like this.

A:
Error: startTime contains string values but got a date (Code: 102,
  Version: 1.2.21)

The error clearly indicates that you are comparing two different objects one is string and second one is date. So there are two things you can either convert any one into date or string. So to implement the same in a easy way, you can write one category with function which will convert either into date or string and use that method to perform the comparison.

A: You've converted leftDate and arrivedDate to leftDateString and arrivedDateString, but you're still using leftDate and arrivedDate in your query. I think you meant to write:
PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
[query whereKey:@"startTime" greaterThan:leftDateString];
[query whereKey:@"timeArrived" lessThan:arrivedDateString];

in which case you'd no longer get the error since you'd be comparing string to string.
Although I generally recommend that you store and sort your dates with NSDate objects, in this case where your format is in the same descending order of importance as a typical NSDate sort of month, day, hour, then minute, i.e. "MM-dd hh:mm", as long as year or seconds don't matter to you and as long as the queried time format matches the database time format, this query should work since greaterThan and lessThan will compare the string objects alphabetically/numerically.

A: I guess for that to work you have to have Date fields in database, then you pass NSDate to whereKey: on iOS.


Q: Set max time a user can be logged in, regardless of their activity I'm working on a blue green pattern for a system with continuous delivery. I would like to force the users to switch server after 30 min. I'm developing my application in JSF 2. Is there an easy way to make the sessions end after a certain time no matter if the user is active or not?

A: Implement a filter which does basically the following job:
HttpSession session = request.getSession();

if (session.isNew()) {
    session.setAttribute("start", System.currentTimeMillis());
}
else {
    long start = (Long) session.getAttribute("start");

    if (System.currentTimeMillis() - start > (30 * 60 * 1000)) {
        session.invalidate();
        response.sendRedirect("expired.xhtml");
        return;
    }
}

chain.doFilter(request, response);

Map this on the servlet name or URL pattern of interest.
This is only sensitive to changes in system clock, make sure that your server runs UTC all the time. Otherwise better grab System#nanoTime() instead.


Q: Optimizing a set 20 webrequests with threads This is for ASP.NET. I want to improve the time it takes run my function, today it takes around 20-30 seconds, more towards 30secs than 20secs though. That's running on one thread making 20 webrequests.
I'm thinking threads that do all the 20 webreqeusts, in order to quickly find the result or just go through the data (IE do all the 20 requests not finding anything).

Here's how it works.
1. I'm using html agility pack to fetch htmldocuments. 2. Then I parse them for information 3. Lastly I add that information to a dictionary OR I move on to the next webrequest until I reach 20 requests made.
I make at most 20 webRequests, at minimum 1. I have set the function to end when the info I'm searching for is found. Sometimes the info isn't there hence the 20 webrequests(it goes through all the data).
Every webrequest adds between 5-20 entries to the dictionary. This is then compared with the information I sent to it, if it's in the list I get the Key back, otherwise it returns 201. If found it gets added to the database.
QUESTIONS
*A:*If I want to do this with threads, how many should I create? 20 One for each request and let them all loose to do the job? Or should i create like 4 of them making at most 5 requests each?B: What if two threads are finished at the same time and wants to add info to the directory, can it lock the whole site(I'm using ASP.NET), or will it try to add one from thread A and then one result from Thread B? I have a check already today that checks if the key exists before adding it.
C:What would be the fastest way to this?
This is my code, depicting the loop which just shows that 20 requests are being made?
public void FetchAndParseAllPages()
    {

        int _maxSearchDepth = 200;
        int _searchIncrement = 10;

        PageFetcher fetcher = new PageFetcher();
        for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
        {
            string keywordNsearch = _keyword + i;
            ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));

            if (GetPostion() != 201)
            {   //ADD DATA TO DATABASE
                InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
                return;
            }
        }
    }

A: *

*.NET allows only 2 requests open at the same time. If you want more than that, you need to configure it in web.config. Look here: http://msdn.microsoft.com/en-us/library/aa480507.aspx

*You can the Parallel.For method which is very straightforward and handles the "how much threads" for you. Of course you can tweak it to set how much threads (or tasks) you want with ParallelOptions. Look here: http://msdn.microsoft.com/en-us/library/dd781401.aspx

*For making a thread-safe dictionary you can use the ConcurrentDictionary. Look here: http://msdn.microsoft.com/en-us/library/dd287191.aspx


Q: Extract a complex String from between two Strings I have a String which contains the following sub string:
[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]
I'd like to extract the part between [Text: and ] i.e. PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1.
How do I do this?

A: Pattern p = Pattern.compile("\\[Text:(.*?)\\]");
Matcher m = p.matcher("[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]");
m.find();
System.out.println(m.group(1));

Gives:
PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1

The \\[ and \\] are to escape the brackets, which are special characters in regexes. The .*? is a non-greedy quantifier, so it stops gobbling up characters when it reaches the closing bracket. This part of the regex is given inside a capturing group (), which you can access with m.group(1).

A: Use the following string as the regex:
"\\[Text:(.*?)\\]"

The first capture group will give you exactly the substring you want.
The non-greedy match (.*?) is required to make it stop at the first ] rather than also including [Elem:123].

A: String.substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.
You could use this to remove the start and end of the string,
or....
You could use
String.indexOf(String str)

To get the index of the start and end of the match and copy the contents to a new result string.
You could use
String.matches(String regex)

However writing regular expressions can get difficult,
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
I hope this helps.

A: Instead of using "\\[Text:(.*?)\\]", as others have suggested, I'd go one step further and use lookarounds to filter out the text you don't want:
(?<=\\[Text:).*?(?=\\])
This will match exactly the text you want without having to select a capturing group.


Q: How to design an installer so it can be used in automated acceptance tests Background:
We have a windows installer which simply installs and starts our custom WinForms installation program. This custom installer does the real installation: creating an IIS Web Application, copying dlls, installing database, etc...
We now want to write some automated acceptance tests, which will include installing the software using the same installation procedure as we use in production. We want to start by running the acceptance tests every night on a dedicated machine, and later as part of a continuous integration pipeline.
Problem:
It is proving difficult to automate the WinForms installation program. And we do not want special installation code for the acceptance tests.
Question:
What advice do you clever people have for integrating the deployment process into an automated test?
I suspect that the decision to use WinForms for the installer was a bad choice - particularly because the resulting application does not clearly separate the UI code from the real installation code.

A: My recommendation would be to use an MSI based installer instead of trying to roll your own using Windows Forms.  Look into using the Windows Installer XML (WiX) toolset which is a popular free open source toolset for creating installers.
Using MSI has many advantages, in particular it makes it fairly difficult to mix installer logic and UI (kind of like falling into the pit of success) and so making an unattended installer suitable for running on a remote machine is a piece of cake.
If you are already committed to your current installation method then you need to work on separating your UI and logic to the point where you can run an installation without showing any UI - its difficult to give any specific advice on how to do this without a more concrete example.


Q: How to stop collection triggering code when scrolling back in to view swift I'm pretty new so apologies if my title doesn't phrase things correctly. I've been hacking away and haven't been able to find an answer to this problem.
I have a horizontally scrolling collection. I'm trying to visually show poll results programatically adding CGRect to the relevant item in the collection based on voting data held in a Firestore array.
This is working, but the problem is when you scroll away (so the item in the collection is off screen) and then back, the code to draw the CGRects gets triggered again and more graphics get added to the view. Is there a way to delete these CGRects when the user scrolls an item collection off screen so when the user scrolls the item back into view, code is triggered again it doesn't create duplicates?
Here are a couple of screenshots showing first and second load

Here is my code (cell b is where the CGrect gets triggered)
//COLLECTION VIEW CODE
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.sentCollectionView {
            let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "sCell", for: indexPath) as! SentCollectionViewCell

            cellA.sentQuestionLabel.text = sentMessages[indexPath.row].shoutText
            // Set up cell
            return cellA
        }
        else {
            let cellB = receivedCollectionView.dequeueReusableCell(withReuseIdentifier: "pCell", for: indexPath) as! ReceivedCollectionViewCell

            receivedMessages[indexPath.row].pollTotal = receivedMessages[indexPath.row].pollResults.reduce(0, +)
            print("Sum of Array is : ", receivedMessages[indexPath.row].pollTotal!)
            cellB.receivedShoutLabel.text = receivedMessages[indexPath.row].shoutText

            print(receivedMessages[indexPath.row].pollResults.count)

            if receivedMessages[indexPath.row].pollResults != [] {
                for i in 0...receivedMessages[indexPath.row].pollResults.count - 1 {
                    cellB.resultsView.addSubview(sq(pollSum: receivedMessages[indexPath.row].pollTotal!, pollResult: receivedMessages[indexPath.row].pollResults[i]))
                }
            }

            return cellB
        }
    }

//THIS DRAWS THE CGRECT
    func sq(pollSum: Int, pollResult: Int) -> UIView {
        // divide the width by total responses
        let screenDivisions = Int(view.frame.size.width) / pollSum

        // the rectangle top left point x axis position.
        let xPos = 0

        // the rectangle width.
        let rectWidth = pollResult * screenDivisions

        // the rectangle height.
        let rectHeight = 10

        // Create a CGRect object which is used to render a rectangle.
        let rectFrame: CGRect = CGRect(x:CGFloat(xPos), y:CGFloat(yPos), width:CGFloat(rectWidth), height:CGFloat(rectHeight))

        // Create a UIView object which use above CGRect object.
        let greenView = UIView(frame: rectFrame)

        // Set UIView background color.
        greenView.backgroundColor = UIColor.green

        //increment y position
        yPos = yPos + 25

        return greenView

    }

A: Cells of collection are dequeued dequeueReusableCell , you need to override prepareForReuse
Or set a tag
greenView.tag = 333

And inside cellForItemAt do this
cellB.resultsView.subviews.forEach {
   if $0.tag == 333 {
      $0.removeFromSuperview()
    }
}
if receivedMessages[indexPath.row].pollResults != [] {
    for i in 0...receivedMessages[indexPath.row].pollResults.count - 1 {
        cellB.resultsView.addSubview(sq(pollSum: receivedMessages[indexPath.row].pollTotal!, pollResult: receivedMessages[indexPath.row].pollResults[i]))
    }
}


Q: How to access parent form properties from a child form in vb.net I have pretty much the same problem as described in this, but using VB.NET. There is a Form1 which is opened automatically as start window, so I cannot find the instance to use for accessing it. There is a Form2 opened from within Form1. I try to pass the instance of Form1 using keyword "Me":
Private Sub Button1_click(...) Handles Button1.Click
 Dim childform as new Form2(Me)
 childform.show()
End Sub

In Form2 I have:
Public Sub New(parentform As System.Windows.Forms.Form)
 InitializeComponents()
 MessageBox.Show(parentform.Button1.Text)
End Sub

Upon compiling I get the error: "Button1 is not a member of Form".
So how to pass the Form1 instance correctly to Form2?
Also I want to change some properties of the Button1 of Form1 from Form2. Button1 is declared in a Private Sub, will I nevertheless be able to access it from Form2 if I pass the instance correctly? If not, can I declaring a sub in Form1, e.g.
Public Shared Sub ChangeText(newtext As Sting)
 Me.Button1.Text=newtext
End Sub

that will do the job?

A: I'm not 100% sure about what you are trying to achieve, but, you can pass data between forms. So for example you can do something like:
Public Class Form1
   Private Sub Button1_click(...) Handles Button1.Click
      Dim newForm2 as New Form2()
      newForm2.stringText = ""
      If newForm2.ShowDialog() = DialogResult.OK Then
         Button1.Text = newForm2.stringText
      End If
   End Sub
End Class

And in Form2 you have
Public Class Form2
   Dim stringText as string

   Private Sub changeStringText()
      'your method to change your data
      Me.DialogResult = DialogResult.OK 'this will close form2
   End Sub

End Class

I hope this is what you need, if not let me know

A: Thanks for your answer and comment. So I declared the wrong class for the parentform, means in Form2 it needs to be "parentform as Form1":
Public Sub New(parentform As Form1)
 InitializeComponents()
 MessageBox.Show(parentform.Button1.Text)
End Sub

and yes, I need to skip the "shared" in the ChangeText:
Public Sub ChangeText(newtext As Sting)
 Me.Button1.Text=newtext
End Sub

This way it worked for me.


Q: the auto generated code for an Intent defined in a `intentdefinition` throws `No newline at end of file` I have added an Intents.intentdefinition to my project. In it I have added a new intent called OrderItem with a few parameters and parameter combination.
When I try to import the autogenerated OrderItemIntent.h, the compiler throws a No newline at end of file compilation error.
Not sure what is the correct way to resolve this issue.

A: Let me explain please.
The way to find an OrderItemIntent (XXXIntent) file

*

*Move to Intents(XXX).intentdefinition file.

*Select a intent from any custom intents.

*Move to Inspector panel from Xcode right side and go to third Identity Inspector section

*You can find 'Custom class' blank and there are a right arrow button which connect to Class file.

*Click that button

Thanks

A: It seems like Xcode has a bug in the generated Intent class for Objective-C. However you can go to your project settings, search for Intent Class Generation Language and chose Swift. That should fix the problem so far.


Q: @Valid does not work for nested object in bean class in spring I have a Bean class which has one nested object like below.
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class UserRequestDTO {

        private String transactionId;

        private String email;

        @Valid @NotNull HistoryRequestDTO historyRequestDTO;
    }

This is the nested object bean class.
import javax.validation.constraints.*;
    @Data
    public class HistoryRequestDTO {

        @NotNull(message = Constants.INVALID_FIELD_DATA_EN_US)
        @Range(min = 0, max = 100, message = Constants.INVALID_FIELD_DATA_EN_US)
        @NumberFormat(style = NumberFormat.Style.NUMBER)
        Integer pageNumber;

        @NotNull(message = Constants.INVALID_FIELD_DATA_EN_US)
        @Range(min = 50, max = 500, message = Constants.INVALID_FIELD_DATA_EN_US)
        @NumberFormat(style = NumberFormat.Style.NUMBER)
        Integer pageSize;
    }

I already have implemented validator for HistoryRequestDTO and working fine seperately. But when I use UserRequestDTO, HistoryRequestDTO validator does not work.
I tried to implement seperate validator for UserRequestDTO, but still  it is not calling  HistoryRequestDTO validator.

A:
try this
@Valid usage show here  for nested object in bean class just check
  once..

hibernate validator


Q: Finding the first day of specific months in R I currently have a column "Month" & a column "DayWeek" with the Month and Day of the week written out. Using the code below I can get a column with a 1 for each Wednesday in Feb, May, Aug & Nov. Im struggling to find a way to get a column with 1s just for the first Wednesday of each of the 4 months I just mentioned. Any ideas or do I have to create a loop for it?
testPrices$Rebalance <- ifelse((testPrices$Month=="February" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="May" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="August" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="November" & testPrices$DayWeek == "Wednesday"),1,0))))

A: Well, without a reproducible example, I couldn't come up with a complete solution, but here is a way to generate the first Wednesday date of each month.  In this example, I start at 1 JAN 2013 and go out 36 months, but you can figure out what's appropriate for you.  Then, you can check against the first Wednesday vector produced here to see if your dates are members of the first Wednesday of the month group and assign a 1, if so.
# I chose this as an origin
orig <- "2013-01-01"

# generate vector of 1st date of the month for 36 months
d <- seq(as.Date(orig), length=36, by="1 month")

# Use that to make a list of the first 7 dates of each month
d <- lapply(d, function(x) as.Date(seq(1:7),origin=x)-1)

# Look through the list for Wednesdays only,
# and concatenate them into a vector
do.call('c', lapply(d, function(x) x[strftime(x,"%A")=="Wednesday"]))

Output:
 [1] "2013-01-02" "2013-02-06" "2013-03-06" "2013-04-03" "2013-05-01" "2013-06-05" "2013-07-03"
 [8] "2013-08-07" "2013-09-04" "2013-10-02" "2013-11-06" "2013-12-04" "2014-01-01" "2014-02-05"
[15] "2014-03-05" "2014-04-02" "2014-05-07" "2014-06-04" "2014-07-02" "2014-08-06" "2014-09-03"
[22] "2014-10-01" "2014-11-05" "2014-12-03" "2015-01-07" "2015-02-04" "2015-03-04" "2015-04-01"
[29] "2015-05-06" "2015-06-03" "2015-07-01" "2015-08-05" "2015-09-02" "2015-10-07" "2015-11-04"
[36] "2015-12-02"

Note:  I adapted this code from answers found here and here.

A: I created a sample dataset to work with like this (Thanks @Frank!):
orig <- "2013-01-01"
d <- data.frame(date=seq(as.Date(orig), length=1000, by='1 day'))
d$Month <- months(d$date)
d$DayWeek <- weekdays(d$date)
d$DayMonth <- as.numeric(format(d$date, '%d'))

From a data frame like this, you can extract the first Wednesday of specific months using subset, like this:
subset(d, Month %in% c('January', 'February') & DayWeek == 'Wednesday' & DayMonth < 8)

This takes advantage of the fact that the day number (1..31) will always be between 1 to 7, and obviously there will be precisely one such day. You could do similarly for 2nd, 3rd, 4th Wednesday, changing the condition to accordingly, for example DayMonth > 7 & DayMonth < 15.


Q: SimpleXML & PHP: Extract part of XML document & convert as Array Consider the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<OS>
    <data>
        <OSes>
            <centos>
                <v_5>
                    <i386>
                        <id>centos5-32</id>
                        <name>CentOS 5 - 32 bit</name>
                        <version>5</version>
                        <architecture>32</architecture>
                        <os>centos</os>
                    </i386>
                    <x86_64>
                        <id>centos5-64</id>
                        <name>CentOS 5 - 64 bit</name>
                        <version>5</version>
                        <architecture>64</architecture>
                        <os>centos</os>
                    </x86_64>
                </v_5>
                <v_6>
                    <i386>
                        <id>centos6-32</id>
                        <name>CentOS 6 - 32 bit</name>
                        <version>6</version>
                        <architecture>32</architecture>
                        <os>centos</os>
                    </i386>
                    <x86_64>
                        <id>centos6-64</id>
                        <name>CentOS 6 - 64 bit</name>
                        <version>6</version>
                        <architecture>64</architecture>
                        <os>centos</os>
                    </x86_64>
                </v_6>
            </centos>
            <ubuntu>
                <v_10>
                    <i386>
                        <id>ubuntu10-32</id>
                        <name>Ubuntu 10 - 32 bit</name>
                        <version>10</version>
                        <architecture>32</architecture>
                        <os>ubuntu</os>
                    </i386>
                    <amd64>
                        <id>ubuntu10-64</id>
                        <name>Ubuntu 10 - 64 bit</name>
                        <version>10</version>
                        <architecture>64</architecture>
                        <os>ubuntu</os>
                    </amd64>
                </v_10>
            </ubuntu>
        </OSes>
    </data>
</OS>

From the XML document above, I want to extract following 5 element node

*

*<id>

*<name>

*<version>

*<architecture>

*<os>
And have them as a array. I tried doing the following:
<?php
require_once "xml.php";

    try {
        $xml = new SimpleXMLElement($xmlstr);
        foreach($xml->xpath(' //id | //name | //version// | //architecture | //os ') as $record) {
        echo $record;
    }
    } catch(Exception $e){
        echo $e->getMessage();
    }

the above code works but each record is an separate object. I want someone to consolidate all 5 elements nodes as one array element. something like this:
$osList = Array( [0] => Array(
                               ["id"] => "<id>",
                               ["name"] => "<name>",
                               ["version"] => "<version>",
                               ....
)
 .....
);

syntax isn't correct but you get the idea. any idea how to do this?

A: this might help
$obj = new SimpleXMLElement($xml);
$rtn = array();
$cnt = 0;
foreach($obj->xpath('///OSes/*/*') as $rec)
{
  foreach ($rec as $rec_obj)
  {
    if (!isset($rtn[$cnt]))
    {
      $rtn[$cnt] = array();
    }

    foreach ($rec_obj as $name=>$val)
    {
      $rtn[$cnt][(string)$name] = (string)$val;
    }
    ++$cnt;
  }
}

A: By modifying the xpath as others suggested as well, I came to this conclusion. It works with one helper function to re-format each xpath result node and uses array_reduce to iterate over the result. It then returns the converted result (Demo):
$xml = new SimpleXMLElement($xmlstr);
$elements = array_reduce(
    $xml->xpath('//OSes/*/*'),
    function($v, $w) {
        $w = array_values((array) $w); // convert result to array
        foreach($w as &$d) $d = (array) $d; // convert inner elements to array
        return array_merge($v, $w); // merge with existing
    },
    array() // empty elements at start
);

Output:
Array
(
    [0] => Array
        (
            [id] => centos5-32
            [name] => CentOS 5 - 32 bit
            [version] => 5
            [architecture] => 32
            [os] => centos
        )

    [1] => Array
        (
            [id] => centos5-64
            [name] => CentOS 5 - 64 bit
            [version] => 5
            [architecture] => 64
            [os] => centos
        )

    [2] => Array
        (
            [id] => centos6-32
            [name] => CentOS 6 - 32 bit
            [version] => 6
            [architecture] => 32
            [os] => centos
        )

    [3] => Array
        (
            [id] => centos6-64
            [name] => CentOS 6 - 64 bit
            [version] => 6
            [architecture] => 64
            [os] => centos
        )

    [4] => Array
        (
            [id] => ubuntu10-32
            [name] => Ubuntu 10 - 32 bit
            [version] => 10
            [architecture] => 32
            [os] => ubuntu
        )

    [5] => Array
        (
            [id] => ubuntu10-64
            [name] => Ubuntu 10 - 64 bit
            [version] => 10
            [architecture] => 64
            [os] => ubuntu
        )

)

I also opted for converting the original xpath result into an array of two levels, each time within the current level a key already exists, move the current entry to a new entry (Demo):
try
{
    $xml = new SimpleXMLElement($xmlstr);
    $elements = array();
    $curr = NULL;
    foreach($xml->xpath('//id | //name | //version | //architecture | //os') as $record)
    {
        $key = $record->getName();
        $value = (string) $record;
        if (!$curr || array_key_exists($key, $curr)) {
            unset($curr);
            $curr = array();
            $elements[] = &$curr;
        }
        $curr[$key] = $value;
    }
    unset($curr);
}
catch(Exception $e)
{
    echo $e->getMessage();
}

Result is like this then:
Array
(
    [0] => Array
        (
            [id] => centos5-32
            [name] => CentOS 5 - 32 bit
            [version] => 5
            [architecture] => 32
            [os] => centos
        )

    [1] => Array
        (
            [id] => centos5-64
            [name] => CentOS 5 - 64 bit
            [version] => 5
            [architecture] => 64
            [os] => centos
        )

    [2] => Array
        (
            [id] => centos6-32
            [name] => CentOS 6 - 32 bit
            [version] => 6
            [architecture] => 32
            [os] => centos
        )

    [3] => Array
        (
            [id] => centos6-64
            [name] => CentOS 6 - 64 bit
            [version] => 6
            [architecture] => 64
            [os] => centos
        )

    [4] => Array
        (
            [id] => ubuntu10-32
            [name] => Ubuntu 10 - 32 bit
            [version] => 10
            [architecture] => 32
            [os] => ubuntu
        )

    [5] => Array
        (
            [id] => ubuntu10-64
            [name] => Ubuntu 10 - 64 bit
            [version] => 10
            [architecture] => 64
            [os] => ubuntu
        )

)

A: Try this:
// flatten:
function arrayval1($any) {
  return array_values((array)$any);
}
function arrayval2($any) {
  return (array)$any;
}

// xml objects with xml objects:
$oses = $xml->xpath('//OSes/*/*');
// an array of xml objects:
$oses = array_map('arrayval1', $oses);
// merge to a flat array:
$oses = call_user_func_array('array_merge', $oses);
// xml objects -> arrays
$oses = array_map('arrayval2', $oses);
print_r($oses);

My result:
Array
(
    [0] => Array
        (
            [id] => centos5-32
            [name] => CentOS 5 - 32 bit
            [version] => 5
            [architecture] => 32
            [os] => centos
        )

    [1] => Array
        (
            [id] => centos5-64
            [name] => CentOS 5 - 64 bit
            [version] => 5
            [architecture] => 64
            [os] => centos
        )

    [2] => Array
        (
            [id] => centos6-32
            [name] => CentOS 6 - 32 bit
            [version] => 6
            [architecture] => 32
            [os] => centos
        )

    [3] => Array
        (
            [id] => centos6-64
            [name] => CentOS 6 - 64 bit
            [version] => 6
            [architecture] => 64
            [os] => centos
        )

    [4] => Array
        (
            [id] => ubuntu10-32
            [name] => Ubuntu 10 - 32 bit
            [version] => 10
            [architecture] => 32
            [os] => ubuntu
        )

    [5] => Array
        (
            [id] => ubuntu10-64
            [name] => Ubuntu 10 - 64 bit
            [version] => 10
            [architecture] => 64
            [os] => ubuntu
        )

)

If you're using PHP >= 5.3 (ofcourse you are, why whouldn't you) you can omit the nasty tmp function definitions and use cool anonymous functions for the mapping:
// an array of xml objects:
$oses = array_map(function($os) {
  return array_values((array)$os);
}, $oses);


Q: Difference between I am new to php and would like to know if there are any differences between these server tags :
<?php
?>

and
<?
?>

A: The first is a safe open and close tag variation, the second is the so called short-open tag. The second one is not always available, use the first option if it's possible.
You could check the availability of short open tags in php.ini, at the short_open_tag.

A: The problem with short open tags is that the following:
<?xml version="1.0" ?>

will cause problems if you're allowed to use short tags (i.e. <? and ?>). <?php is less open to misinterpretation.
Whether or not you're allowed to use short tags is defined by the ini directive short_open_tag.

A: Also I think shorttags are being removed in one of the upcomming releases.
Edit: I was wrong.

Farewell <% They will remove support
  for the ASP style tags, but the PHP
  short-code tag will remain - so
  to those on php general who reckon the
  short-tag is 'depreceated' - hah! ;)

http://phpmysqldev.blogspot.com/2007/05/php-6.html

A: There is no difference.
The ability to use <? ?> is defined in your php.ini file - usually accessed only by the server host.
You can find more information here

A: Nothing AFAIK, however I have had servers (shared) where the settings do not support shorthand tags <? ?>, so I usually stick with the <?php ?> for good measure.

A: Note short_open_tag = Off did not effect the <?= shorthand tag, which is equivalent to <?php echo

A: As @erenon explained here: https://stackoverflow.com/a/1808372/1961535
The difference is that short_open_tag in some cases isnt available. You can check the status by accessing the php.ini file but in case of shared hosting server, the host does not always allow edits to php.ini file.
You can easily print the phpinfo as explained here:
https://www.php.net/manual/en/function.phpinfo.php
phpinfo();

search for short_open_tag as shown below

It is always better to use full tag because that will always be supported in every version of PHP weather old file or new.


Q: Is this a form of a method's parameter accessing other method's parameter? I am an IT student and I'm completely new with Python. In a workshop I worked on there were a few lines in between that I don't really understand how they work and their purpose in the code. Those lines come from a fellow student who successfully ran it and I would like to fully understand. Thank you!
Overall, this is my code:
class AcademicPublication():
    def __init__(self, title, year):
        self.__year = year
        self.__title = title
        self.__authors = []

    def addAuthor(self, author_name):
        self.author_name = author_name
        self.__authors.append(author_name)

    def getReference(self):
        return f"{self.__authors}, {self.__authors}({self.__year}): {self.__title}."
class Conference():
    def __init__(self, acronym, name):
        self.acronym = acronym
        self.name = name
        self.paper = []

    def addPaper(self, conference_paper):
        self.paper.append(conference_paper)
        conference_paper.Conference = self
        conference_paper.acronym = self.acronym
        conference_paper.name = self.name

class ConferencePaper(AcademicPublication):
    def __init__(self, title, year):
        super().__init__(title, year)

    def getReference(self):
        return super().getReference() + '. In Proceedings of ' + str(self.name) + str(self.acronym)

And I'm struggling with this part:
        self.paper.append(conference_paper)
        conference_paper.Conference = self
        conference_paper.acronym = self.acronym
        conference_paper.name = self.name

At first I thought conference_paper is a class attribute, but there was no definition before in the code, and I did some research but I didn't find anything about a parameter from this method accessing another method's parameter.


Q: How to iterate through a list of objects with a specific variable? So I have a Deck class which holds a deck list which creates 52 Card objects and stores them in an array list. I can iterate through that deck list using the iterator I have shown but now I want to know how I can modify the iterator to  iterate through the deck list for certain variables. For example, I just want to iterate through all the Spades or all the Kings.  Thanks.
fyi: The DeckIterator is within the Deck class I just didn't know how to format the code on stack. Apologies.
    public class Card implements Serializable, Comparable<Card> {
        static final long serialVersionUID = 100;

        Suit suit;
        Rank rank;

        public Card(Rank rank, Suit suit){
            this.rank = rank;
            this.suit = suit;
        }
    }

    public enum Rank {
        TWO(2), THREE(3), FOUR(4), FIVE(5),
        SIX(6), SEVEN(7), EIGHT(8), NINE(9),
        TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);

        int value;

        public static Rank valuesList[] = Rank.values();

        Rank(int value){
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }

        public Rank getNext() {
            if (this.value == 11) {
                return valuesList[0];
            } else {
                return valuesList[ordinal() + 1];
            }
        }

        public int getOrdinal() {
            return ordinal();
        }
    }

    public enum Suit {
        CLUBS, DIAMONDS, HEARTS, SPADES;

        public static Suit suitsList[] = Suit.values();

        public Suit randomSuit() {
            Random random = new Random();
            return suitsList[random.nextInt(4)];
        }
    }

    private class DeckIterator<Card> implements Iterator<Card> {
        private final Deck deck;
        private int pos = 0;

        public DeckIterator(Deck deck) {
            this.deck = deck;
            pos = 0;
        }

        @Override
        public boolean hasNext() {
            return pos < deck.size();
        }

        @Override
        public Card next() {
            return (Card) deck.deck.get(pos++);
        }

        @Override
        public void remove() {
            deck.deck.remove(pos);
        }
    }

A: You can't; not with this data structure. You have a few options:

*

*iterate through everything, but abort this iteration at the top if it doesn't match your required state. For example:
for (Card card : deck) {
    if (card.getRank() != Rank.ACE) continue;
    /* code to deal with aces here */
}

*You use stream API constructs to filter. You did not include your Deck class in your paste, but assuming deck.deck is some sort of java.util.List, you can for example do:
deck.deck.stream().filter(x -> x.getRank() == Rank.ACE).iterator()

which will give you an iterator that iterates through only the aces.

A:
I just want to iterate through all the Spades or all the Kings.

Here we are.
new DeckIterator(deck, card -> Rank.KING.equals(card.getRank()));
new DeckIterator(deck, card -> Suit.SPADES.equals(card.getSuit()));

I fully agree with @rzwitserloot's answer, and will extend his post with my iterator which takes a Predicate to form another iterator that runs over only selected elements.
class DeckIterator implements Iterator<Card> {

    private final Iterator<? extends Card> iterator;

    public DeckIterator(Deck deck, Predicate<Card> predicate) {
        iterator = deck.deck.stream().filter(predicate).iterator();
    }

    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public Card next() {
        return iterator.next();
    }

    @Override
    public void remove() {
        iterator.remove();
    }

}


Q: scala: Specifying method type for currying The following method type describes a function that passes configuration info and data to a method. Each method of this type can perform a different function.
  type FTDataReductionProcess =(PipelineConfiguration,RDDLabeledPoint) => RDDLabeledPoint

The above works fin.
But what I would like to do is different. I want to add the configuration to the method first, and then later add the data. So I need currying.
I thought this would work:
  type FTDataReductionProcess =(PipelineConfiguration)(RDDLabeledPoint) => RDDLabeledPoint

but this causes a compilation error

Cannot resolve symbol RDDLabeledPoint

Any suggestions would be appreciated

A: You want a function that takes a PipelineConfiguration and returns another function that takes an RDDLabeledPoint and returns an RDDLabeledPoint.

*

*What is the domain? PipelineConfiguration.

*What is the return type? A "function that takes RDDLP and returns RDDLP", that is: (RDDLabeledPoint => RDDLabeledPoint).

All together:
type FTDataReductionProcess =
  (PipelineConfiguration => (RDDLabeledPoint => RDDLabeledPoint))

Since => is right-associative, you can also write:
type FTDataReductionProcess =
  PipelineConfiguration => RDDLabeledPoint => RDDLabeledPoint

By the way: the same works for function literals too, which gives a nice concise syntax. Here is a shorter example to demonstrate the point:
scala> type Foo = Int => Int => Double // curried function type
defined type alias Foo

scala> val f: Foo = x => y => x.toDouble / y     // function literal
f: Foo = $$Lambda$1065/1442768482@54089484

scala> f(5)(7)  // applying curried function to two parameters
res0: Double = 0.7142857142857143


Q: how to change column If another column has a special word on python? I have a long dataframe and I want to apply for every rows, I want to do this if 'word' in column 1 I want to change column2, but word will get dictionary.key, and column2 will get dictionary.value
di = {'btw':'By The Way','afk':'Away From Keyboard'}

A: Using apply:
df['temp'] = df['sentences'].apply(lambda x:[j for j in di.keys() if j in x]
df['shortly'] = df['temp'].apply(lambda a:','.join([di[key] for key in a]))

df.drop(['temp'],axis = 1,inplace=True)

Output:
>>> df
          sentences             shortly
0  btw I have to go          By The Way
1      i am afk now  Away From Keyboard

The above would work even if there are multiple short forms in a single sentence, only the output will be separated with , in shortly column (you can change the separator in second apply statement).
eg.
          sentences        temp                        shortly
0  btw I have to go       [btw]                     By The Way
1      i am afk btw  [btw, afk]  By The Way,Away From Keyboard

If the short-forms can be a different case than in the dictionary, then just add .lower() in the first apply statement like so:
df['temp'] = df['sentences'].apply(lambda x:[j for j in di.keys() if j in x.lower()]

keep all the shortforms in dictionary as lower case though


Q: Encoding issue with accented letter passenger RoR I have a bug when I run a RoR application on an Ubuntu server, my config is : ubuntu 14.04 - nginx - passenger 5.0.9 - rbenv - ruby 2.2.2 - rails 4.2.1. Everything works fine with a default config but when I try to change an environment variable and put an accented letter in it, I get an error when I read it from Ruby. My locales are correctly set to en_US.UTF-8. The error occurs in an HAML file. The backtrace is https://gist.github.com/Uelb/207cd29ffd91185529b6 . When I get the env variable from my console and send a to_json, I have no error and I see the accented letter correctly.

A: I managed to solve the issue by explicitly setting the env variable LC_ALL to LC_ALL=en_US.UTF-8 in the rbenv-vars plugin file.


Q: rename regex not working in cygwin I am using cygwin under windows 7.
In my directory there are files like
fort.100
 fort.101
 ...
 fort.1xx
I want to give them all an extension _v1.
When I try to achieve it using rename by
rename 's/$/_v1/' fort.*
the prompt exit with no errors and nothing happens.
I then tried
rename -e 's/$/_v1/' fort.*, an error pops up,
rename: unknown option -- e
I also tried with a different delimiter @ instead of / with no luck.
Now, I thought it was due to the character _ in the expression (I am a newbie to regex), I tried escaping it by \_ with no luck either. Again a try without _, for example,
rename 's/$/v11/' fort.* - nothing happens again.
Although I achieved my goal by
for file in fort.*; do mv $file $file\_v1; done, I wonder why rename doesn't work.
What am I doing wrong here? Is it because I am on cygwin?

A: The manual of rename does not match your expectations.
I see no regex capability.
SYNOPSIS
       rename [options] expression replacement file...

DESCRIPTION
       rename  will  rename  the specified files by replacing the first occur‐
       rence of expression in their name by replacement.

OPTIONS
       -v, --verbose
              Give visual feedback which files where renamed, if any.

       -V, --version
              Display version information and exit.

       -s, --symlink
              Peform rename on symlink target

       -h, --help
              Display help text and exit.

EXAMPLES
       Given the files foo1, ..., foo9, foo10, ..., foo278, the commands

              rename foo foo0 foo?
              rename foo foo0 foo??

       will turn them into foo001, ..., foo009, foo010, ..., foo278.  And

              rename .htm .html *.htm

       will fix the extension of your html files.

for what you want to reach the easy way is:
for i in fort*; do mv ${i} ${i}_v1 ; done

A: I have found a workaround.
I replaced the util-linux rename to perl rename a separate package.
This was provided from @subogero from GitHub.
All the usual rename expressions is working.


Q: Send Azure Service Bus messages to Blob or Azure Data Factory Can someone let me know if its possible to send Azure Service Bus messages, (Service Bus Queues, in particular) to Azure Data Factory or Blob Storage.
According to the following link, there isn’t a connector for Service Bus with ADF. However, it does state that its possible to send messages to Blob Store. But unfortunately, I can’t find any information on how to send messages to blob storage.
Has anyone come across any links?
https://learn.microsoft.com/en-us/answers/questions/424698/suggest-solution-for-reading-data-from-azure-servi.html

A: If you're looking to turn Azure Service Bus into a Storage Blob, that's probably easy to achieve. You need a Service Bus trigger to retrieve the message payload and its ID to use as a blob name, storing the payload (message body) using whatever mechanism you want. Could be using Storage SDK to write the contents into a blob. Or a blob output binding with a random blob name. Or the message ID as the blob name. Below is an example of a function that will be triggered by a new message in Service bus queue called myqueue and will generate a blob named after message's ID in the messages container.
In-process SDK
public static class MessageTriggeredFunction
{
    [FunctionName(nameof(MessageTriggeredFunction))]
    public static async Task Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")]string payload,
        string messageId,
        [Blob("messages/{messageId}.txt", FileAccess.Write, Connection = "StorageAccountConnectionString")] Stream output)
    {
        await output.WriteAsync(Encoding.UTF8.GetBytes(payload));
    }
}

Isolated worker SDK
public class MessageTriggeredFunctionIsolated
{
   [Function(nameof(MessageTriggeredFunctionIsolated))]
   [BlobOutput("messages/{messageId}.txt", Connection = "StorageAccountConnectionString")]
   public string Run(
       [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")] string payload,
       string messageId)
  {
            return payload;
  }
}


Q: I need to implement a function that can be used multiple times I have one swift function and that I want to convert into objective C can any one help me to convert it? Any help will be appreciated
     func getdata(_ send: NSString)
    {

        let url=URL(string:send as String)
        do
        {
            let allContactsData = try Data(contentsOf: url!)
            let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
            print(allContacts)
            if let musicJob = allContacts["Attendance"] as? [Any], !musicJob.isEmpty
            {
                print(musicJob)
                dataArray = allContacts["Attendance"] as! NSArray
                print(dataArray)

            }
}
           { let send: String = String(format:"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017",loadedUserName,studentId,row+1)
            self.getdata(send as NSString)
}

How to convert this into objective C, Any help pls. I need to use this  func getdata(_ send: NSString)
  multiple times

A: NSJSONSerialization in Objective-c
TRY 1:   If Json return Array
 -(void)getdata:(NSString *)send
    {
        NSURL *url = [[NSURL alloc]initWithString:send];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];

        NSError *e = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

        if (!jsonArray) {
            NSLog(@"Error parsing JSON: %@", e);
        } else {
            for(NSDictionary *item in jsonArray) {
                NSLog(@"Item: %@", item);
            }
        }
    }

TRY 2: If Json return Dictinary
-(void)getdata:(NSString *)send
{
    NSURL *url = [[NSURL alloc]initWithString:send];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];

    NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",res);
 }

To call Method:
  NSString *send = [NSString stringWithFormat:@"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017"];
    [self getdata:send];


Q: NHAPI PID 13.1 Segment home phone is not able to get created Please Help me on this :
I have stuct on this line.I'm not getting pid  13.1 Which is a Home Phone-Telephone number.Please tell me how to get this segment created.
I'm using :
NHAPI V231
adtA04.PID.GetPhoneNumberHome(0).PhoneNumber.Value = "(456)120-1478";

Note: Phone number is not the correct segment here.

A: homePhone = a01.PID.GetPhoneNumberHome(0).TelecommunicationUseCode.Value;
businessPhone = a01.PID.GetPhoneNumberBusiness(0).TelecommunicationUseCode.Value;


Q: How can I snap to grid a value between 0 and 1 let's say I have a value that is between 0 and 1. I have a grid size and would like the value to snap to grid. so if grid size is equal to two I would like to switch from 0 to 1 if grid size equal to three this would switch from 0, 0.5 to 1 if it's four 0, 0.33, 0.66, 1 and so on...

A: Assuming the language you use has a round function that rounds to the nearest integer, and calling v the value and n the grid size:
round(v * (n-1)) / (n-1)


Q: Typescript - Access property of class using it's string name I'm having this class:
import { SoapNotePage } from "../pages/forms/soap-note/soap-note";

export class FormMapper {
    public static SOAP_NOTE = SoapNotePage;
}

It is easy to access this property, see the following example:
open(item){
    if(item.id == 1){
       this.navCtrl.push(FormMapper.SOAP_NOTE, { patientId: 509070, formId: 75598 });
    }
}

But what I want is to access the "SOAP_NOTE" property by it's string name, kind of dynamically, for example like this:
this.navCtrl.push(FormMapper['SOAP_NOTE'], { patientId: 509070, formId: 75598 });

The reason  I'm asking this, is that the "item" paramater of the function "open(item)" may contain the property name of the FormMapper class.
Is there any way of doing this?

A: You can do this:
function open(item: keyof typeof FormMapper) {
    console.log(FormMapper[item]);
}

That way you restrict item values to be keys of the FormMapper class, and the compiler won't complain.


Q: multiple url link variables index.php?dc=downloads&dl=all&sort=id shows all downloads, and sorts by id
inside of downloads.php it GETs the variables dl and sort to query MySQL accordingly, to
display the tables on downloads.php
I have the links Show All, tools, etc that set the dl variable to display certain tables
but now, I want to be able to set another variable sort when the user clicks on one of the sort links from the list, without it resetting the dl variable
Sort by id wouldn't work because it would reset dl

A: There are quite a few ways of doing this, but the easiest way, given the code you have supplied, is just to input the current $_GET['dl'] value.  Like so:
<a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>" >id

<?=$_GET['dl']?>: This will take the dl value that is currently in the get parameters and place it into your link.
A better method would probably be to check if there is already a dl value in the GET parameters first:
<? if(isset($_GET['dl']) && $_GET['dl'] != ''): ?>
    <a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>">id
<? else: ?>
    id
<? endif; ?>

This way, you wont end up with a link like index.php?dc=download&sort=id&dl= if dl hasn't yet been set.


Q: Issue on LEMP configuration and how can i redirect to NodeJS request to NGINX I configured a LEMP server on Ubuntu with NodeJS but I'm getting the following error on browser.
"The page you are looking for is temporarily unavailable.
Please try again later." how can i redirect to NodeJS request to NGINX .Can you please help me how can i sort out these issues.

A: If NGINX work through PHP-FPM (FastCGI Process Manager) then you can uncomment the important part for PHP is the  location ~ \.php$ {} stanza in the default vhost which is defined in the file

vi /etc/nginx/sites-available/default

like
[...]

location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
        }

[...]

And for NodeJS you can also modify the same Vhost file

vi /etc/nginx/sites-available/default

and add lines below location ~ \.php$ {} stanza  like
[...]
        location /testapp/ {
        proxy_pass  http://localhost:3000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
[...]

from this you can forwarding port to Node.js app with Nginx
Now you can access the your page by this URL http://localhost/testapp/ instead of http://localhost:3000/

Hope It will work for you


Q: Cant remove commit from Master GIT I can't remove a commit from master. I tried lots of commands from stackOverflow, but nothing works.
Last command git revert 655734672ea28811e0723981853f05cbcdda8ec8 just changed the commit. This how it looks now.
.............................................(master)
$ git log
commit ddd171a390ce613a87e7f4e00135b48a1b03c2ad (HEAD -> master)
Author: pet......... <fffffafafa@yahoo.com>
Date:   Sat Mar 7 15:08:57 2020 +0000

    Revert "adding jacoco-maven-plugin"
    This reverts commit 655734672ea28811e0723981853f05cbcdda8ec8.`
commit 655734672ea28811e0723981853f05cbcdda8ec8 (_D)
Author: pet.... <petttttttt@yahoo.com>
Date:   Sat Mar 7 13:42:48 2020 +0000

   adding jacoco-maven-plugin

A: git revert creates a new commit undoing the changes from a given commit. It seems that the operation you described produces the desired result.
Read also: How to undo (almost) anything with Git .

A: Git is:

*

*distributed, meaning, there is more than one repository; and

*built specifically to make removing commits a little difficult: it "likes" to add commits, not remove them.

Your original question left off the fact that, having added two commits, you published them to GitHub.  (You did eventually note this in a comment.)
If you really do want to remove some commits, you must now convince every Git that has them to give them up.  Even if/when you manage this, they won't go away immediately: in general, you get at least 30 days to change your mind and bring them back again.  But we won't get into that here.  Let's just look at how you convince one Git to discard some commit(s), using git reset.
We'll use git reset --hard here for reasons we won't get into properly.  Be aware that git reset --hard destroys uncommitted work, so before you do that, make sure you do not have anything uncommitted that you do want to save.
As Tarek Dakhran commented, you probably wanted git reset --hard HEAD^^.  You'll need more than that, though—and before you blindly any of these commands, it is crucially important that you understand two things:

*

*what this kind of git reset is going to do;

*what HEAD^^ means.

To get there, and see how to reset your GitHub repository too, let's do a quick recap of some Git basics.
Git stores commits
Git is all about commits.  Git is not really about branches, nor is it about files.  It's about commits.  The commit is your fundamental unit of storage in Git.1  What a commit contains comes in two parts.
First, each commit holds a full snapshot of all of your files.  This isn't a set of changes since a previous commit!  It's just the entire set of files, as a snapshot.  That's the main bulk of a typical commit, and because it is, the files that are stored in a commit like this are stored in a special, read-only, Git-only, frozen form.  Only Git can actually use these files, but the up-side of this is that making hundreds or thousands of snapshots doesn't take lots of space.
Meanwhile, the rest of the commit consists of metadata, or information about the commit: who made it, when, and so on.  This metadata ties each new commit to some existing commit.  Like the snapshot, this metadata is frozen forever once you make the commit.  Nobody and nothing can change it: not you, and not even Git itself.
The unchangeable-ness of every part of a commit is what makes commits great for archival ... and quite useless for getting any new work done.  This is why Git normally extracts one commit for you to work on.  The compressed, dehydrated, and frozen-for-all-time files come out and get defrosted and rehydrated and turned back into ordinary files.  These files aren't in Git at all, but they let you get your work done.  That's part of why a --hard reset is relatively dangerous (but not the whole story).  We'll ignore these usable files here and just concentrate on the commits themselves.
Every commit has a unique hash ID.  The hash ID of a commit is the commit, in a sense.  That hash ID is reserved for that commit, and only that commit can ever use it.  In a way, that hash ID was reserved for that commit before you made the commit, and is still reserved for that commit even after you manage to remove it.  Because the ID has to be unique—and reserved for all time for that commit—it has to be a truly enormous number.  That's why commit hash IDs are so big and ugly, like 51ebf55b9309824346a6589c9f3b130c6f371b8f (and even these aren't big enough any more—they only count to about 1048—and Git is moving to bigger ones).
The uniqueness of these hash IDs means that every Git that has a clone of some repository can talk to any other Git that has a clone of the same repository, and just exchange hash IDs with the other Git.  If your Git has 51ebf55b9309824346a6589c9f3b130c6f371b8f and their Git doesn't, then you have a commit they don't, and they can get it from you.  Now you both have 51ebf55b9309824346a6589c9f3b130c6f371b8f.
That would be all there is to it, except for the part where we said that every commit can store the hash ID(s) of some earlier commit(s).  Commit 51ebf55b9309824346a6589c9f3b130c6f371b8f stores commit hash ID f97741f6e9c46a75b4322760d77322e53c4322d7.  That's its parent: the commit that comes just before it.

1A commit can be broken down into smaller units: commit objects, trees and sub-trees, and blob objects.  But that's not the level on which you normally deal with Git.

This is the key to Git and branches
We now see that:

*

*Every commit has a big ugly hash ID, unique to that commit.

*Every commit contains the hash ID of some earlier commit, which is the parent of that commit.  (A commit can contain two parent hash IDs, making the commit a merge commit, but we won't get into these here.)

When anything contains a commit hash ID, we say that thing points to the commit.  So commits form backwards-pointing chains.
If we use single uppercase letters to stand in for hash IDs, we can draw this kind of chain of commits like this.  Imagine we have a nearly-new repository with just three commits in it.  We'll call them A, B, and C, even though in reality they have some random-looking hash IDs.  Commit C is the last commit, so it points back to B:
    B <-C

But B has a backwards-pointing arrow (really, a stored hash ID) pointing to A:
A <-B <-C

Commit A is special.  Being the very first commit ever made in this repository, it can't point back, so it doesn't.
Adding new commits to a repository just consists of writing out the new commit such that it points back to the previous last commit.  For instance, to add a new commit we'll call D, we just draw it in:
A <-B <-C <-D

No part of any existing commit can change, but none does: C doesn't point to D, D points to C.  So we're good here, except for one thing.  These hash IDs, in a real repository, don't just increment like this.  We have big ugly things like 51ebf55b9309824346a6589c9f3b130c6f371b8f and f97741f6e9c46a75b4322760d77322e53c4322d7.  There's no obvious way to put them in order.  How do we know which one is last?
Given any one hash ID, we can use that commit to find the previous commit.  So one option would be: extract every commit in the repository, and see which one(s) don't have anything pointing back to them.  We might extract C first, then A, then B, then D, or some other order, and then we look at all of them and realize that, hey, D points to C points to B points to A, but nobody points to D, so it must be the last one.
This works, but it's really slow in a big repository.  It can take multiple minutes to check all that stuff.
We could write down the hash ID of the last commit (currently D), perhaps on a scrap of paper or whiteboard.  But we have a computer!  Why not write it down in the computer?  And that's what a branch name does: it's just a file, or a line in a file, or something like that,2 where Git has scribbled down the hash ID of the last commit in the chain.  Since this has the hash ID of a commit, it points to a commit:
A--B--C--D   <-- master

We can get lazy now and stop drawing the arrows between commits, since they can never change, but let's keep drawing the ones from the branch names, because they do change.  To add a new commit to master, we make a new commit.  It gets some random-looking hash ID that we'll call E, and it points back to D.  Then we'll have Git write the hash ID of new commit E into the name master, so that master points to E now:
A--B--C--D--E   <-- master

Let's create a new branch name, feature, now.  It too points to existing commit E:
A--B--C--D--E   <-- feature, master

Now let's create a new commit F.  Which branch name gets updated?  To answer that last question, Git uses the special name HEAD.  It stores the name of the branch into the HEAD file.3  We can draw this by attaching the special name HEAD to one of the two branches:
A--B--C--D--E   <-- feature, master (HEAD)

Here, we're using commit E because we're on branch master, as git status would say.  If we now git checkout feature, we continue using commit E, but we're now on branch feature, like this:
A--B--C--D--E   <-- feature (HEAD), master

Now let's create new commit F.  Git will make F point back to E, the current commit, and will then make the current branch name point to new commit F:
A--B--C--D--E   <-- master
             \
              F   <-- feature (HEAD)

We've just seen how branches grow, within one repository.

2Git currently uses both methods to store branch-to-hash-ID information.  The information may be in its own file, or may be a line in some shared file.
3This HEAD file is currently always a file.  It's a very special file: if your computer crashes, and when it recovers, it removes the file HEAD, Git will stop believing that your repository is a repository.  As the HEAD file tends to be pretty active, this is actually a bit common—not that the computer crashes often, but that when it does, you have to re-create the file to make the repository function.

Git is distributed
When we use Git, we hardly ever have just have one repository.  In your case, for instance, you have at least two repositories:

*

*yours, on your laptop (or whatever computer); and

*your GitHub repository, stored over in GitHub's computers (that part of "the cloud").

Each of these repositories has its own branch names.  This is what is about to cause all our problems.
To make your laptop repository, you probably ran:
git clone <url>

This creates a new, empty repository on your laptop.  In this empty repository, it creates a remote, using the name origin.  The remote stores the URL you put in on the command line (or entered into whatever GUI you used), so that from now on, instead of typing in https://github.com/... you can just type in origin, which is easier and shorter.  Then your Git calls up that other Git, at the URL.
The other Git, at this point, lists out its branch names and the hash IDs that these branch names select.  If they have master and develop, for instance, your Git gets to see that.  Whatever hash IDs those names select, your Git gets to see those, too.
Your Git now checks: do I have this hash ID?  Of course, your Git has nothing yet, so the answer this time is no.  (In a future connection, maybe the answer will be yes.)  Your Git now asks their Git to send that commit.  Their Git is required to offer your Git the parent of that commit, by its hash ID.  Your Git checks: do I have this commit?  This goes on until they've sent the root commit—the commit A that has no parent—or they get to a commit you already have.
In this way, your Git and their Git agree on what you have already and what you need from them.  They then package up everything you need—commits and all their snapshotted files, minus any files you might already have in commits you already have—and send all that over.  Since this is your very first fetch operation, you have nothing at all and they send everything over, but the next time you get stuff from them, they'll only send anything new.
Let's suppose they have:
A--B--C--D--E   <-- master (HEAD)
             \
              F   <-- feature

(your Git does get to see their HEAD).  Your Git will ask for and receive every commit, and know their layout.  But your Git renames their branches: their master becomes your origin/master, and their feature becomes your origin/feature.  These are your remote-tracking names.  We'll see why your Git does this in a moment.
Your Git is now done talking with their Git, so your Git disconnects from them and creates or updates your remote-tracking names.  In your repository, you end up with:
A--B--C--D--E   <-- origin/master
             \
              F   <-- origin/feature

Note that you don't have a master yet!
As the last step of git clone, your Git creates a branch name for you.  You can choose which branch it should create—e.g., git clone -b feature means create feature—but by default, it looks at their HEAD and uses that name.  Since their HEAD selected their master, your Git creates your master branch:
A--B--C--D--E   <-- master (HEAD), origin/master
             \
              F   <-- origin/feature

Note that the only easy way you have of finding commit F is by your remote-tracking name origin/feature.  You have two easy ways to find commit E: master and origin/master.
Now, let's make a new commit on master in the usual way.  This new commit will have, as its parent, commit E, and we'll call the new commit G:
              G   <-- master (HEAD)
             /
A--B--C--D--E   <-- origin/master
             \
              F   <-- origin/feature

Note that your master, in your laptop Git, has now diverged from their master, over on GitHub, that your laptop Git remembers as origin/master.
Your master is your branch.  You get to do whatever you want with it!  Their master is in their repository, which they control.
fetch vs push
Let's make a couple more commits in our master now:
              G--H--I   <-- master (HEAD)
             /
A--B--C--D--E   <-- origin/master
             \
              F   <-- origin/feature

Note that, so far, we have not sent any of these commits to the other Git.  We have commits G-H-I on our master, on the laptop, or wherever our Git is, but they don't have these at all.
We can now run git push origin master.  Our Git will call up their Git, like we did before, but this time, instead of getting stuff from them we will give stuff to them, starting with commit I—the commit to which our master points.  We ask them: Do you have commit I?  They don't, so we ask them if they have H, and G, and then E.  They do have E so we'll give them the G-H-I chain of commits.
Once we've given them these three commits (and the files that they need and don't have—obviously they have E so they have its snapshot, so our Git can figure out a minimal set of files to send), our Git asks them: Please, if it's OK, set your master to point to I.
That is, we ask them to move their master branch, from the master name we used in our git push origin master.  They don't have a mat1/master to keep track of your repository.  They just have their branches.
When we ask them to move their master like this, if they do, they'll end up with:
A--B--C--D--E--G--H--I   <-- master (HEAD)
             \
              F   <-- feature

They won't lose any commits at all, so they'll accept our polite request.  Their name master now points to commit I, just like our name master, so our Git adjusts our remote-tracking name:
              G--H--I   <-- master (HEAD), origin/master
             /
A--B--C--D--E
             \
              F   <-- origin/feature

(Exercise: why is our G on a line above the line with E?  Why didn't we draw it like this for their repository?)
git reset makes removing commits locally easy
Now, let's suppose commits H and I are bad and you'd like to get rid of them.  What we can do is:
git checkout master             # if needed
git reset --hard <hash-of-G>

What this will do, in our repository, we can draw like this:
                 H--I   <-- origin/master
                /
A--B--C--D--E--G   <-- master (HEAD)
             \
              F   <-- origin/feature

Note that commits H and I are not gone.  They are still there, in our repository, findable by starting with the name origin/master, which points to commit I.  From there, commit I points back to commit H, which points back to commit G.
Our master, however, points to commit G.  If we start from here, we'll see commit G, then commit E, then D, and so on.  We won't see commits H-I at all.
What git reset does is let us point the current branch name, the one to which HEAD is attached, to any commit anywhere in our entire repository.  We can just select that commit by its hash ID, which we can see by running git log.  Cut and paste the hash ID from git log output into a git reset --hard command and you can move the current branch name to any commit.
If we do this, and then decide that, gosh, we want commits H-I after all, we can just git reset --hard again, with the hash ID of commit I this time, and make master point to I again.  So aside from wrecking any uncommitted work, git reset --hard is sort of safe.  (Of course, wrecking uncommitted work is a pretty big aside!)
We still have to get their Git to change: we need more force
Moving our master back to G only gets us updated.  The other Git, over on GitHub ... they still have their master pointing to commit I.
If we run git push origin master now, we'll offer then commit G.  They already have it, so they'll say so.  Then we'll ask them, politely:  Please, if it's OK, make your master point to commit G.
They will say no!  The reason they'll say no is simple: if they did that, they'd have:
                 H--I   [abandoned]
                /
A--B--C--D--E--G   <-- master (HEAD)
             \
              F   <-- feature

Their master can no longer find commit I.  In fact, they have no way to find commit I.  Commit I becomes lost, and so does commit H because commit I was how they found commit H.
To convince them to do this anyway, we need a more forceful command, not just a polite request.  To get that forceful command, we can use git push --force or git push --force-with-lease.  This changes the last step of our git push.  Instead of asking please, if it's OK, we send a command: Set your master!  Or, with --force-with-lease, we send the most complicated one: I think your master points to commit I.  If so, make it point to G instead!  Then tell me whether I was right.
The --force-with-lease acts as a sort of safety check.  If the Git over on GitHub lists not just to you, but to other Gits as well, maybe some other Git had them set their master to a commit J that's based on I.  If you're the only one who sends commits to your GitHub repository, that obviously hasn't happened, and you can just use the plain --force type of push.
Again: --force allows you to tell another Git: move a name in some arbitrary way, that doesn't necessarily just add commits.  A regular git push adds commits to the end of a branch, making the branch name point to a commit "further to the right" if you draw your graph-of-commits the way I have been above.  A git push that removes commits makes the branch name point to an earlier commit, losing some later commit, or—in the most complicated cases—does both, removes some and adds other commits.  (We haven't drawn this case and we'll leave that for other StackOverflow answers ... which already exist, actually, regarding rebasing.)
Recap

*

*Branch names find the last commit in a branch (by definition).

*Making new commits extends a branch, by having the new commit point back to the previous tip, and writing the new commit's big ugly random-looking hash ID into the branch name.

*git reset allows you to move branch names around however you like.  This can "remove" commits from the branch (they still exist in the repository, and maybe there's another way to find them).

*git push asks some other Git to move its branch names.  It defaults to only allowing branch-name-moves that *add8 commits.

Hence, since you have pushed the commits you want to "remove", you'll need to git reset your own Git, but then git push --force or git push --force-with-lease to get the GitHub Git to do the same thing.
What HEAD^ etc are about
When we were looking for ways to "remove" commits with git reset, I suggested:

*

*Run git log (and here I'll suggest using git log --decorate --oneline --graph, which is so useful that you should probably make an alias, git dog, to do it: D.O.G. stands for Decorate Oneline Graph).

*Cut-and-paste commit hash IDs.

This works, and is a perfectly fine way to deal with things.  It's a bit clumsy sometimes, though.  What if there were a way to say: starting from the current commit, count back two commits (or any other number)?
That is, we have some chain of commits:
...--G--H--I--...

We can pick out one commit in the chain, such as H, by its hash ID, or any other way.  Maybe it has a name pointing to it:
...--G--H   <-- branchname
         \
          I--J   <-- master (HEAD)

Using the name branchname will, in general, select commit H.  If Git needs a commit hash ID, as in git reset, the name branchname will get the hash ID of commit H.
Using the name HEAD tells Git: look at the branch to which HEAD is attached, and use that name.  Since HEAD is attached to master, and master points to J, the name HEAD means "commit J*, in places where Git needs a commit hash ID.
This means we could run:
git reset --hard branchname

right now and get:
...--G--H   <-- branchname, master (HEAD)
         \
          I--J   [abandoned]

The name branchname selects commit H, and git reset moves the branch name to which HEAD is attached—master—to the commit we select.
Note, by the way, that:
git reset --hard HEAD

means: look at the name HEAD to figure out which commit we're using now, then do a hard reset that moves the current branch name to that commit.  But since that's the commit we're using now, this "moves" the name to point to the same commit it already points to.  In other words, move to where you're standing already ... ok, don't move after all.  So this git reset --hard lets us throw out uncommitted work, if that's what we need to do.
In any case, adding a single caret ^ character after any branch name or hash ID means select that commit's parent.  So since branchname means commit H, branchname^ means commit G.
If we have:
...--F--G--H--I   <-- master (HEAD)

then master^ and HEAD^ both mean commit H.  Adding another ^ tells Git to do that again: master^^ or HEAD^^ means commit G.  Adding a third ^ selects commit F, and so on.
If you want to count five commits back, you can write master^^^^^ or HEAD^^^^^, but it's easier to use master~5 or HEAD~5.  Once you get past "two steps back", the tilde ~ notation is shorter.  Note that you can always use the tilde notation anyway: master~1 and master^ both count one commit back.  You can omit the 1 here too, and write master~ or HEAD~.
(There is a difference between ^2 and ~2.  For more about this, see the gitrevisions documentation.)


Q: Angularjs dynamic table I have following json string to generate report in angularjs:
{
"result": [{name:"AUS ba",date":"02-01-2014", "result": "pass","time" : "morning","reason":"ok"}],
"result": [{name:"SA ba",date":"02-01-2014", "result": "pass","time" : "afternoon","reason":"ok"}],
"result": [{name: "NZ ba",{"date":"02-01-2014", "result": "fail","time" : "morning","reason":"ok"}],
"result": [{name:"AUS ba","date":"03-01-2014", "result": "pass","time" : "morning","reason":"ok"}],
"result": [{name:"SA ba",date":"03-01-2014", "result": "fail","time" : "morning","reason":"batch         failed"}],
"result": [{name: "NZ ba",date": "03-01-2014", "result": "fail","time" : "morning","reason":"batch error"}]

}
Currently I am generating table in simple format using ng-repeat:
Name        Date       Result  Reason    Time
AU ba      02-01-2014   PASS    Ok        Morning
AU ba      03-01-2014   ...
AU ba      04-01-2014   ...
...........
...........

Now I want to dynamically create table like this
         02-01-2014    02-01-2014    02-01-2014   02-01-2014   03-01-2014  03-01-2014
         Morning        Morning      Afternoon     Afternoon   Morning      Morning
 AU ba    Pass[Result]  ok[Reason]   Fail          Ok          Pass         ok
 SA ba    Fail          batch failed

Could somebody please help me with this?

A: You could make a table with one row and then ng-repeat the columns in that row. In each column you can then make a table with 4 rows and one column:
http://plnkr.co/edit/3xvdGC?p=preview (I reformatted your JSON data to be able to work with it)
However, this will give problems if the text of some table cells require multiple lines. To solve that you could just use multiple ng-repeat statements:
http://plnkr.co/edit/EUKNn5?p=preview

A: Write your html like this:

              {{r.date}}

              {{r.result}}

              {{r.time}}

              {{r.reason}}

You will find a plunker here
Note that i reformated your json, dropped some data and left all the fancy formating to you.

A: You can just use ng-repeat multiple times for each label: http://jsfiddle.net/4HHc2/2/
After reformatting your json string as an array of results, you can just call each item as follows:
    {{d.date}}


Q: Is it possible to keep css style in a code/pre tag in markdown? I'm facing an issue while writing a markdown document.
I'd like to insert a diff code output from the console, containing colors, transformed to HTML via a script, something like this:
# Some title

The following code as been updated:

+    if ($url !== $newUrl) {
+        $newDomain = parse_url($newUrl, PHP_URL_HOST);

**Thank you**

I've added some Markdown just to show some context.
The problem is, using pre/code, the code structure is correct (correctly formated lines).
If I change it (switching to code/pre), or changing code or pre to div, I loose either the line breaks, or the coloration.
Here's the output of the above markdown: https://fiddle.md/tmvmwvztfd5d92xk65dwfx

A: I know that Github have a diff expression who let you do something like this : https://gist.github.com/salmedina/ad8bea4f46de97ea132f71b0bca73663#file-markdowndiffexample-md
But I thinks that there is no such way to do what your want in Markdown.
Regards.