Q: How to instantiate a scikit-learn model from a string variable? I have a list of models as parameters in a YAML file.
When I read them into my Python script, they appear there as strings:
my_model = "LinearRegression()"
print(type(my_model)) #output: <class 'str'>

I want to initialize my sklearn model as:
model = LinearRegression()

but with LinearRegression() being a string variable.
At the moment, naturally, model = my_model is a string, and can't be fitted, etc.
How to instantiate the sklearn model from a string variable?
My use case: I want to put different models in a YAML file as params in order to sweep over them in the model fine-tuning procedure (a simple AutoML).

A: You have few options:

*

*Use eval as a quick&dirty solution:

from sklearn.linear_model import LinearRegression
model_str = 'LinearRegression()'
model = eval(model_str)
print(model)

Note: using eval is not a safe because it will execute any string so if you have no control about a string variable being executed a malicious code may be executed.
Also you need to import exact the same class before using eval. Without the first line the code will not work.

*use pickle.dumps
from sklearn.linear_model import LinearRegression

model_class_serialized = pickle.dumps(LinearRegression)
print(model_class_serialized)
model_class = pickle.loads(model_class_serialized)
print(model_class)

In that case you do not need explicitly import classes from sklearn.
An example of saving models to YAML:
import pickle
import yaml

from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC

models = [LinearRegression, RandomForestClassifier, LinearSVC]

with open('models.yml', 'w') as out_file:
    yaml.dump({m.__name__: pickle.dumps(m) for m in models}, out_file)

After that you can read YAML file like that:
import pickle
import yaml

with open('models.yml', 'r') as in_file:
    models = yaml.load(in_file, Loader=yaml.FullLoader)
    models = {name: pickle.loads(serialized_cls) for name, serialized_cls in models.items()}

print(models)

Which produces:
{'LinearRegression': <class 'sklearn.linear_model._base.LinearRegression'>, 'LinearSVC': <class 'sklearn.svm._classes.LinearSVC'>, 'RandomForestClassifier': <class 'sklearn.ensemble._forest.RandomForestClassifier'>}

so you can easily instantiate these models:
model = models['RandomForestClassifier']()
print(model)
# model.fit(...)


Q: Grails form token not available for ajax forms? In grails it is easy to add tokens to prevent form double submission and also the click hijacking.
Just add useToken="true" to the form tag:
<g:form ... useToken="true" >

But, this is not available for formRemote tag. I know that I can do normal form and write js code to transform them into ajax froms with token, but because of that is odd that is not supported by default in the formRemote tag.
Any reason for this, or is just (another) bug in Grails?


Q: material-ui component style customization – change color of select component to white I want to use a dropdown menu of the material-ui components (see https://material-ui.com/components/selects/). Therefore, I copied the specific component out of the example:
Component
return

<FormControl variant="outlined" className={classes.root}>
  <InputLabel ref={inputLabel} id="demo-simple-select-outlined-label">
    Plan
  </InputLabel>
  <Select
    labelId="demo-simple-select-outlined-label"
    id="demo-simple-select-outlined"
    value={age}
    onChange={handleChange}
    labelWidth={labelWidth}

  >
    <MenuItem value="">
      None
    </MenuItem>
    <MenuItem value={10}>dsnfsdjfnsduifn</MenuItem>
    <MenuItem value={20}>Twenty</MenuItem>
    <MenuItem value={30}>Thirty</MenuItem>
  </Select>
</FormControl>

Style
const useStyles = makeStyles(theme => ({
root: {
  margin: theme.spacing(1),
  minWidth: 120,
  color: 'white',
  borderColor: 'white'
},}));

Because of my app design, I want to change the color of this dropdown menu to white. At the moment the component looks like this:

As you can see in the component, the variant is outlined. As I understand the documentation (https://material-ui.com/api/select/)  I have to overwrite the .MuiSelect-outlined class but I am not sure how I can do this. Unfortunately, the manual only describes the style of simple buttons and not how I can change the style of more complex components like these.
I hope someone can give me an example how I can change the color of the outline, the text and the arrow to white.

A: There you go
.MuiOutlinedInput-notchedOutline {
    border-color: #fff;//for border color
}
 .MuiSelect-icon {
    color: #fff;// for icon drop down icon color
}
.MuiInputLabel-root {
    color: #fff;// for lable color
}

For focus just add the parent .Mui-focused selector on these

A: const useStyles = makeStyles(theme => ({
select: {
  borderColor: 'white'
},
fomrControl{
  margin: theme.spacing(1),
  minWidth: 120,
  color: 'white',
}
}));


Q: Using a DocumentTermMatrix with a neural net classifier to make predictions in R I have been trying to learn how to use a DocumentTermMatrix to make predictions in R.
I have been using the following link as a reference to try and make predictions for a different dataset.
https://rpubs.com/cen0te/naivebayes-sentimentpolarity
Here, the author uses an IMDB movie review dataset where the review text is analysed. Predictions are then made based on the review text as to whether the review is positive or negative using the Naive Bayes classifier (from e1071). The dataset contains a separate column with yes/no values where if a review was positive, the value is 'yes' else it is 'no'.
I have successfully implemented this for the naive bayes classifier on a different dataset however I now want to use different classifiers to do this so I can compare their performance.
I have been trying to use the neural net classifier (from the neuralnet package) however I do not know where to begin.
For the naive bayes classifier the following code was used to make predictions:
classifier <- naiveBayes(train_DocumentTermMatrix, input_training_data$class, laplace = 1)
pred <- predict(classifier, test_DocumentTermMatrix)

For the neural net package, I require a formula to run the classifier however I want to make predictions based on the document term matrix so I am confused as to what the formula is.
Could somebody please point me to the right direction and tell me how to proceed with this?


Q: How to run 2 functions simultaneously in vuejs I wanted to run 2 functions simultaneously in VUE. One function will be called when component is mounted and it will be running every 10 seconds. The other function will start executing when we click on the button.
Now my problem is when I click the button the function start executing and the first function will not be called till this function completed its execution.
<template>
  <div>
    <select v-model="file_id" class="form-control" id="">
      <option v-for="(file, index) in files" :value="file.value" :key="index">
        {{ file.label }}
      </option>
    </select>
    <button class="btn btn-success" @click="handleFileUpload">Import</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      files: [],
    };
  },
  mounted() {
    this.upload_status = setInterval(() => {
      this.getUploadedStatus();
    }, 5000);
  },
  methods: {
    handleFileUpload() {
       //it will start executing when we click the button (need to call API)
       axios.post();
    },
    getUploadedStatus() {
        //it has to run every 10 seconds (Need to call API)
        axios.get();
    },
    beforeDestroy() {
      clearInterval(this.upload_status);
    },
  },
};
</script>


Q: Can I play an audio (or audio/video) file from a DLL written in C++? We want to play audio (and video) files from a DLL.  RenderSharedEvent/TimerDriven works, but for a number of reasons we prefer to do playback at a higher level- Media Foundation, or even the deprecated MediaPlay or waveOut functions would work.  However, so far I'm not seeing the callbacks, and they seem to be a critical part of the process.
Is that because they don't work from a DLL, or is there something I'm missing?  I remember it used to be impossible to use waveOut from a DLL, but I assumed the new frameworks would support a DLL.


Q: Problem extracting Youtube search results I am new to Python and have learned basis of Web Scraping with bs4. here i tried to extract all the links of Youtube search results , it doesn't work like on other sites. i analyzed the search result html data and the links of search results were in anchor tag with id "video title" , but the tag doesn't appear in my bs4 parsed html document
from bs4 import BeautifulSoup as bs
import requests
name=input("Enter video name ")
url='https://www.youtube.com/results?search_query='+name
searched=requests.get(url)
soup=bs(searched.text,'html.parser')
aid=soup.find_all('a',{'id':'video-title'})
print(aid)

i expect the output contain all the search result.
i have not learned other packages , i want to do this in bs4 if possible.

A: All this trouble to get YouTube search result data is just a waste of time and effort.
Why not try out these options

*

*YouTube Data API

*Selenium + Headless chrome
That being said, for the first 20 results, you can get the data from the JavaScript content in the source. The answer to that is given below.
After about 1 hr of making sense of the resulting json, it still fails for some queries.YouTube is a very complicated site. The response may vary based on location, browser, search query etc.
We are extracting the data from this script tag in the source.

Code:
from bs4 import BeautifulSoup as bs
import requests
import re
import json
headers={
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
name=input("Enter video name: ")
url='https://www.youtube.com/results?search_query=hello'+name
searched=requests.get(url,headers=headers)
soup=bs(searched.text,'html.parser')
aid=soup.find('script',string=re.compile('ytInitialData'))
extracted_josn_text=aid.text.split(';')[0].replace('window["ytInitialData"] =','').strip()
video_results=json.loads(extracted_josn_text)
#print(item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1])
item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]

for item in item_section:
    try:
        video_info=item["videoRenderer"]
        title=video_info["title"]["simpleText"]
        url=video_info["navigationEndpoint"]["commandMetadata"]["webCommandMetadata"]["url"]
        print('Title:',title)
        print('Url:',url, end="\n----------\n")
    except KeyError:
            pass

Output:
Enter video name: hello
Title: New Punjabi Songs 2017-Hello Hello(Ful Song)-Prince Narula-Yuvika Chaudhary-Latest Punjabi Song 2017
Url: /watch?v=mv326-zVpAQ
----------
Title: Alan Walker - The Spectre
Url: /watch?v=wJnBTPUQS5A
----------
Title: Hello Hello (Full HD) - Rajvir Jawanda | MixSingh | Josan Bros | New Punjabi Songs 2018
Url: /watch?v=xydupjQSj44
----------
Title: Bachchan - Hello Hello - Kannada Movie Full Song Video | Sudeep | Bhavana | V Harikrishna
Url: /watch?v=oLMMgoug4Uk
----------
Title: Hello Hello latest 2017 16 june punjabi song
Url: /watch?v=MqCSsPXw8QU
----------
Title:   Hello Hello   | + More Kids Songs | Super Simple Songs
Url: /watch?v=saDkICxEdgY
----------
Title: 'Gallan Goodiyaan' Full VIDEO Song | Dil Dhadakne Do | T-Series
Url: /watch?v=jCEdTq3j-0U
----------
Title: Hello Hello Gippy Grewal Feat. Dr. Zeus Full Song HD | Latest Punjabi Song 2013
Url: /watch?v=IRW2O4QZhgs
----------
Title: Hello Hello | Pataakha | Malaika Arora | Vishal Bhardwaj & Rekha Bhardwaj | Gulzar | Ganesh Acharya
Url: /watch?v=RxBAitQLSLA
----------
Title: Hello Hello (Lyrical Audio) Prince Narula ft. Yuvika Chaudhary | Punjabi Lyrical Audio 2017 | WHM
Url: /watch?v=v8VIsIvhDoQ
----------
Title: Hello Hello Full Video Song || Bhale Bhale Magadivoi || Nani, Lavanya Tripathi
Url: /watch?v=y3FI02OO_kU
----------
Title: Hello hello gaad bahe dhufee na egaa  (new comedy hhhhhh)
Url: /watch?v=DuRrcTo4rgg
----------
Title: Proper Patola - Official Video | Namaste England | Arjun | Parineeti | Badshah | Diljit | Aastha
Url: /watch?v=YmXJp4RtBCM
----------
Title: Official Video: Nikle Currant Song | Jassi Gill | Neha Kakkar | Sukh-E Muzical Doctorz | Jaani
Url: /watch?v=uBaqgt5V0mU
----------
Title: Insane (Full Song)  Sukhe - Jaani - Arvindr Khaira - White Hill Music - Latest Punjabi Song 2018
Url: /watch?v=mKpPhVVF8So
----------
Title: Radha bole HELLO HELLO-cartoon song mix with step up 2
Url: /watch?v=TFCTgNCzrck
----------
Title: Hello Song | CoCoMelon Nursery Rhymes & Kids Songs
Url: /watch?v=fxVMqaViVaA
----------
Title: Bachchan - Hello Hello Unplugged Version | Sudeep | Bhavana | V Harikrishna
Url: /watch?v=lvH3kTGJeEQ
----------
Title: Hello Hello! Can You Clap Your Hands? | Original  Kids Song | Super Simple Songs
Url: /watch?v=fN1Cyr0ZK9M
----------

One last thing that you can try out is to emulate the API used by youtube itself
ie. POST request to
https://www.youtube.com/results?search_query=yoursearchtext
It has a lot of cookie and session values being sent as parameters.  You may need to emulate all of them. You may need to use Requests session objects to do that.


Q: How to create pdf programmatically in specific format?
I have all the data in NSData object but I dont know how to create a pdf that will display in this format. The main problem is that product does not have a fixed content size, there will be more and more depending upon the customer, how much he/she purchases.
I don't want to make uiview like below format because if do so then how do captured entire uitableview in .png format.
Please give the logic how to create pdf for below format. Thanks a ton!

A: There are two ways to create PDFs in iOS:
If you want text in your PDF, you need to use Quartz 2D
There is no API that helps you to draw in tabular format. You need to draw lines, text by calculating x and y positions, all done manually. If you have fixed set of fields then only you can follow this approach.
Else, you can create a html page for your required format, and then set this page in PDF as an image, a very simple approach.
Both will be done using Quartz 2D
Hope this helps :)

A: Best place to start here and then here
need to draw a table with lines and add text and image to it also :)
For info refer
and docs

A: There are two ways to draw PDF.

*

*Using UIKit API:
For this your can draw pdf line by line & image by imagem i.e. Object by Object.
  Link to this is : http://www.raywenderlich.com/6581/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-1

*Using Quartz 2D Api:
Using this You can draw pdf using the UIViews. Link for the same is:
http://mobile.tutsplus.com/tutorials/iphone/generating-pdf-documents/
http://www.ioslearner.com/generate-pdf-programmatically-iphoneipad/
The UIKit Api creates a nice clean & smooth PDF. While Quartz2D framework creates a little blur pdf. So you need to be sure before using it.
Let me know if it works or any issues.


Q: No matching constructor for initialization of "Type" I am writing a board game using C++ (with SFML2.2 library, Xcode 6.1.1). I created two classes: block and board. The idea is to create a 4x4 vector of blocks inside board. The codes are below:
In block.h
#ifndef __Game1024__block__
#define __Game1024__block__
#include <stdio.h>
#include <iostream>
#endif /* defined(__Game1024__block__) */

using namespace std;

class block{
public:
    sf::RectangleShape rect;
    sf::Text text;
    block();
    block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor);
};

In block.cpp
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <sstream>
#include "block.h"

using namespace std;

block::block(){}

block::block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor){

    double centerX = (X+0.5)*size;
    double centerY = (Y+0.5)*size;
    stringstream ss;
    ss << value;
    string sval = ss.str();

    rect.setSize(sf::Vector2f(blockSize,blockSize));
    rect.setOrigin(blockSize/2.0, blockSize/2.0);
    rect.setPosition(centerX, centerY);
    rect.setFillColor(fillColor);

    text.setStyle(sf::Text::Bold);
    text.setCharacterSize(charSize);
    text.setString(sval);
    text.setColor(textColor);
    text.setOrigin(text.getLocalBounds().width/2.0, text.getLocalBounds().height);
    text.setPosition(centerX, centerY);
 }

In board.h
#ifndef __Game1024__board__
#define __Game1024__board__
#include <stdio.h>
#endif /* defined(__Game1024__board__) */
#include <vector>
#include "block.h"
using namespace std;

class board{
private:
    int winSizeX;
    int winSizeY;
    int margin;
    double charSize;
public:
    vector<vector<block>> matrix;
    board();
    board(int winSizeX_,int winSizeY_,int margin_, double charSize_);
    void draw();
};

And in board.cpp
#include "board.h"
//#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "block.h"
using namespace std;

board::board(){}

board::board(int winSizeX_,int winSizeY_,int margin_, double charSize_){
    winSizeX = winSizeX_;
    winSizeY = winSizeY_;
    margin = margin_;
    charSize = charSize_;
    matrix = vector<vector<block>>(4,vector<block>(4));

    double size = winSizeX/4.0; // = 256
    double blockSize = size - 2*margin;
    const sf::Color fillColor = sf::Color::Red;
    const sf::Color textColor = sf::Color::White;

    sf::Font font;
    if(!font.loadFromFile("./sansation.ttf")){
        exit(EXIT_FAILURE);
    };
    for (int i = 0; i < 4; ++i){
        for (int j = 0; j < 4; ++j){
            int value = 4*j + i + 1;
            matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor);
            matrix[i][j].text.setFont(font);
            matrix[i][j].text.setOrigin(matrix[i][j].text.getLocalBounds().width/2.0,b[i][j].text.getLocalBounds().height);
        }
    }
}

The error comes from board.cpp
matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor);

One weird thing is when I typed matrix[i][j] = block, the autofill of my IDE (Xcode) will generate
matrix[i][j] = block(<#const int X#>, <#const int Y#>, <#const double size#>, <#const double blockSize#>, <#const double charSize#>, <#const int value#>, <#const int fillColor#>, <#const int textColor#>)

The last two arguments of constructor block are changed from type sf::Color into int.
If I create a 4x4 vector of blocks in the main.cpp file and call the constructor of block, there is no error...
Any help?
Thanks in advance!
[Update] I attached the scrrenshot of the error message

A: Thanks @molbdnilo
I made a stupid mistake that I forgot to include the SFML header in "block.h"
#include <SFML/Graphics.hpp>

Now problem solved! Thanks for all advices. I am new to C++ projects, please feel free to speak out all my bad practices in the code. Very helpful!


Q: Access to object in module Im doing some logic which parse json data to object and I want to expose in some module specific object outside that other module can use,
I try with the following which doesnt work,any other idea?
var jsonObject;

module.exports = {

    parse: function () {
    //here I do the parsing
    ....

    jsonObject = JSON.parse(res)

    ,
    //here I want to expose it outside
    jsonObj:jsonObject
    }

A: If you are trying to expose the entire object, you build it like you would any other JavaScript object and then use module.exports at the end :
MyObj = function(){
   this.somevar = 1234;
   this.subfunction1 = function(){};
}
module.exports = MyObj;

If you just want to expose certain functions, you don't NEED to build it like an object, and then you can export the individual functions :
var somevar = 1234;
subfunction1 = function(){};
nonExposedFunction = function(){};
module.exports = {
   subfunction1:subfunction1,
   somevar:somevar
};

A: you simply assign the result of JSON.parse to this.jsonObj:
module.exports = {
    parse: function (res) {
        this.jsonObj = JSON.parse(res);
    }
};

Using this.jsonObj you are exposing the JSON object to the outside and you can use your module in this way:
var parser = require('./parser.js'),
    jsonString = // You JSON string to parse...

parser.parse(jsonString);
console.log(parser.jsonObj);


Q: Setting CSS classes with current_user I'm having trouble arriving at an approach to this problem. tl;dr I want to be able to set the css class of an li to the name of the current_user that posted the chat. Then based on that class, I'll apply different styling.
This is for a chat window and I want all the current users messages to display on one side and I want all other messages to display on the other side with a different color, etc.
I have a file.js.coffee that basically reads in some user input and apends it to an ordered list and adds some elements and classes along the way
      projectRef.on "child_added", (snapshot) ->
        message = snapshot.val()
        $("
").append($("
").append($("
").text(message.text))).prepend($("").text(message.name + ": ")).appendTo $("#messagesDiv")
        $("#messagesDiv")[0].scrollTop = $("#messagesDiv")[0].scrollHeight

      $("#messageInput").keypress (e) ->
        if e.keyCode is 13
          text = $("#messageInput").val()
          projectRef.push
            name: userName
            text: text
          $("#messageInput").val ""

The above would yield something like this in the browser

 User :

My chatt message from file.js.coffee!!

That 'self' class in the li is what I have been trying to dynamically set based on the current_user. So I have 2 issues - 1. I'm trying to figure out who posted the li and 2. I'm trying to dynamically set the class of that li based on the user that chatted/posted it.
My thinking was something along the lines of in the file.js.coffee use JQuery to grab that li and add the <%= current_user.name %> as a class then I could have a file.js.erb where I would do something like
<% unless $('li').hasClass('<%= current_user.name %>'); %>
    <%= $('li').toggleClass('others') %>
<% end %>

This way it checks if the class of the target li is from the current user and if it is keep the css class as self if not toggle it to others. Then I could style the classes appropriately (left, right, background-color:blue;, etc).
Is there a more correct way to approach this problem given what I am trying to accomplish? I think so..

A: It seems like you are saying you're trying to assign a class as the current user's name.
I'm wondering if going that far is necessary.
Assigning the list element with a class named "current_user" might be enough, then have separate CSS to control anything with class named "current_user".
Here's an example fiddle.
CSS
li {
    list-style:none;
    clear:both;

    float:right;
    text-align:right;
    background-color:#A7A2A0;
    border:1px solid #EEE;
    width:200px;
    margin:10px;
    padding:5px;
}
li.current_user {
    float:left;
    text-align:left;
    background-color:#24887F;
}

HTML

    Current User:

My message!

    All Other Users:

Other person's smessage.

UPDATE:
Looking at the firebase example I altered it to add a class "current_user" if the username matched the the name of the user that wrote the message. Below is the part of the code that I altered in the "displayChatMessage" function, I also added CSS to the head section for the "current_user" class.
Here's a link to the working example, view it in to different web browsers using different usernames at the same time to see.
function displayChatMessage(name, text) {
  if(name == $('#nameInput').val()){
    $('
').text(text).prepend($('').text(name+': ')).appendTo($('#messagesDiv')).addClass('current_user');
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  }
  else{
    $('
').text(text).prepend($('').text(name+': ')).appendTo($('#messagesDiv'));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  }
};

This is the CSS I added to the head.

A: There are many users using the app concurrently. But for every user, there is only one current_user in session. Don't mix it up.
Since the message is to be processed by server, you can easily add a new attribute of message.klass in server side by judging the message comes from current_user. If it is, the class may be current, else blank or others.
Then, in JS
$('li').addClass('<%= message.klass %>')


Q: Meteor: change a user password WITHOUT logout? Accounts.setPassword(userId, password);
Before Meteor v1.0.2, the user was not logout when calling this function.
Since v1.0.2, I quote from https://github.com/meteor/meteor/blob/devel/History.md, "Expire a user's password reset and login tokens in all circumstances when their password is changed".
I don't know the reason of this change,but the fact is that function above logout the user.
Is there a way, with v1.0.2, to change a user password without logout the user?
If not, how do I downgrade the package account-base so the behaviour is like before?
Thanks.

A: The above answer is correct and here's the exact copy-paste code in case you're struggling:
Accounts.setPassword(userId, password, {logout: false});

Note: make sure you are doing this call server side.

A: Accounts.setPassword(userId, password, options)

This method now supports options parameter that includes options.logout option which could be used to prevent the current user's logout.

A: You could use Accounts.changePassword (docs) to change the password instead, this will not affect the user's existing tokens (as from) https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L299-L302
If you want to do this from the server without knowing the existing password you would have to fork the accounts-password package and remove this line: https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L338 and add this package into the /packages directory of your app
If you want to downgrade your package (so long as the version you're using of meteor supports it):
meteor remove accounts-password
meteor add accounts-password@1.0.3


Q: Why am I getting error: initializing argument 1 of 'Item::Item(int)' [-fpermissive] in Eclipse when I try to compile my C++ code? I'm new to C++, and have finally given up on trying to get this to compile after staring at it for too long. The compiler seems to be rejecting the constructor prototype in the header file for some reason... I can't figure out what's wrong with it.
Item.h:
#ifndef ITEM_H_
#define ITEM_H_

class Item {
public:
    Item(int); //This line is what Eclipse keeps flagging up with the error in the title
    virtual ~Item();
    Item* getNextPtr();
    int getValue();
    void setNextPtr(Item *);
};

#endif /* ITEM_H_ */

In my Item.cpp file I have:
int val;
Item* nextPtr = 0;
Item::Item(int value) {
    val = value;
}

Item* Item::getNextPtr() {
    return nextPtr;
}

void Item::setNextPtr(Item *nextItem) {
    nextPtr = nextItem;
}

int Item::getValue() {
    return val;
}

Item::~Item() {
    // TODO Auto-generated destructor stub
}

Oops, I'm using GCC. And yeah, they should have been member variables! How do I go about doing that using this format? The code where I use instantiate Item is below. I am aware that there should be no global variables in that either...
#include "LinkList.h"
#include "Item.h"

Item* first = 0;
int length = 0;

LinkList::LinkList(int values[], int size) {
    length = size;
    if (length > 0) {
        Item firstItem = new Item(values[0]);
        Item *prev = &firstItem;
        first = &firstItem;
        for (int i = 0; i < size; i++) {
            Item it = new Item(values[i]);
            prev->setNextPtr(&it);          //set 'next' pointer of previous item to current item
            prev =                      // set the current item as the new previous item
        }

    }
}

LinkList::~LinkList() {
    for (int i = 0; i < length; i++) {
        Item firstItem = *first;
        Item *newFirst = firstItem.getNextPtr();
        delete(first);
        first = newFirst;
    }
}

int LinkList::pop() {
    Item firstItem = *first;
    first = firstItem.getNextPtr();
    return firstItem.getValue();
}

I've just noticed a bug with the functionality of the pop() and destructor functions... please ignore those, I just want to figure out what's wrong with the instantiation of Item.
GCC error:
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\LinkList.o" "..\\src\\LinkList.cpp"
..\src\LinkList.cpp: In constructor 'LinkList::LinkList(int*, int)':
..\src\LinkList.cpp:16:38: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]
..\src\LinkList.cpp:20:32: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]

21:24:26 Build Finished (took 256ms)

A: Here:
Item firstItem = new Item(values[0]);

You are creating a new Item with an item pointer as its argument. This is the same as:
Item firstItem(new Item(values[0]));

And it should be:
Item *firstItem = new Item(values[0]);


Q: why my custom tld not accessible from /WEB-INF/lib/ In my web application I'd placed my custom.tld file in /WEB-INF/lib/custom.tld and referenced in my web.xml as
<jsp-config>
    <taglib>
        <taglib-uri>customTldUri</taglib-uri>
        <taglib-location>/WEB-INF/lib/custom.tld</taglib-location>
    </taglib>
</jsp-config>

and if I do add taglib in jsp then I'm getting JasperException for not able to find/add referenced tld.
But if I do move the custom.tld to /WEB-INF/custom.tld and update the web.xml to <taglib-location>/WEB-INF/custom.tld</taglib-location> then it works.
But in the same project I do have struts tld files added in /WEB-INF/lib/struts-*.tld and there is not exception for them.
My question is why my custom.tld is not accessible if I do place it in /WEB-INF/lib/ while the strtus tlds are working fine?


Q: Copy from HTML div without copying the formatting style I have a div which has a bunch of styling (font-family, font-size, background-color, etc.) and I'd like to be able to copy text from it, and paste it into a rich text editor (Google Docs or Gmail for eg.) without it pasting the styles.
I know I can use the "paste without formatting" or equivalent option, but I'd like to know if there's a clean way to disable copying the formatting at all on the webpage itself, because I only care about the text.
To test: run this snippet, copy the styled text, and paste it into a google doc.

<div style="background-color: orange">
Copy me!
</div>


Q: Scala / Spray: Return all rejections as JSON I'm writing a JSON API using Spray 1.2.1 and I would like to return all HTTP Responses in the following format by default.
{
"type":"error",
"status":404,
"message":"Not Found"
}
My own custom rejections / exceptions will have less generic content in the 'message' field, but I'm looking for a way of globally formatting (and possibly otherwise decorating, for debug/testing) all non-2xx responses.
Is this possible without handling every possible rejection and status code?
Thanks!
Sam

A: I don't know if this is generic enough for you but here's how I do something similar:
import spray.json.DefaultJsonProtocol

case class Rejection(type:String, status: Int, message: String)

object RejectionJsonProtocol extends DefaultJsonProtocol{
   implicit val rejectionFormat = jsonFormat3(Rejection)
}

Then you can complete your routes with a Rejection, possibly in your RouteExceptionHandler like this:
trait RouteExceptionHandlers extends HttpService {

  import RejectionJsonProtocol._

  implicit def routeExceptionHandler(implicit log: LoggingContext) = ExceptionHandler {
    case e: UnsuccessfulResponseException =>
      requestUri { uri =>
        complete(e.response.status, Rejection("error",e.response.status,"Not found"))
      }
  }
    //other exceptions go here
}


Q: CLion doesn't sort include statements on commit I'm using clang-format to define rules for sorting my include statements. This works perfectly when using the "Code > Reformat Code" button or pressing CTRL + ALT + L within a file.
However, even when setting the "Reformat code" checkbox in the CLion commit dialog, the include statements don't get sorted when commiting. For some reason other formatting tasks (such as fixing indentation) take place when commiting. It's just the include sorting that's missing.
Does anybody know why that is the case? Many thanks!
From the .clang-format file:
IncludeCategories:
  - Regex: '^<.*\.h>'
    Priority: 1
  - Regex: '^<[^.]*>'
    Priority: 2
  - Regex: '<.*>'
    Priority: 3
  - Regex: '.*'
    Priority: 3
IncludeBlocks: Regroup
SortIncludes: true

A: JetBrains Support confirmed to be that this is a bug within CLion that they managed to reproduce on their system.
Hoping for it to be fixed in a future version :)


Q: Is possible to make screen shot in ipad programmatically?
Possible Duplicate:
screenshots programmatically in IPad with the image name

Is possible to make screenshot programmatically like this?

I want to be able to take screenshots of the current screen, which is not necessarily my app, i.e., my app may be in the background when activated. You might think of it as programatically pressing the home and sleep button at the same time.
I am aware that this will be limited to jailbroken devices.


Q: Assigning id to validation message I am trying to assign id to span where validation message is dynamically shown. Am I doing some thing wrong?
 <div>@Html.ValidationMessageFor(model => model.Title,new{id="prjTitle"})</div>

It throws Argument type is not assignable to parameter string

A: just use the correct overload:
 @Html.ValidationMessageFor(model => model.YourProperty, "", new { @class = "a-class-if-you-want-one", id = "yourId" })

A: There is no overload that takes only the linq expression and an html attributes object.
According to MSDN there is an overload that takes a linq expression, an errormessage (string) AND an html attributes object, like this:
@Html.ValidationMessageFor(model => model.Title,"entry invalid",new{id="prjTitle"})

A: public static MvcHtmlString IDValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string id)
    {
        var validationString = Regex.Replace(htmlHelper.ValidationMessageFor(expression).ToString(), @"^data-valmsg-for=""*\""$", String.Format("data-valmsg-for=\"{0}\"", id));

        return MvcHtmlString.Create(validationString);
    }


Q: Jenkins and local PyCharm running tests using different path I am checking out a project from git repo. The project was run on Jenkins. One of the unit tests file is reading the file with filename:
filename = os.path.join(self.config_dir, name, 'my_parameters.json')

This works fine on Jenkins, but failed to work on my local machine using pyCharm. On the local machine, I have to change the filename to:
filename = '../' + os.path.join(self.config_dir, name, 'my_parameters.json') to make the test works.
It seems that Jenkins and local pyCharm is running test files in different path. How do I resolve this issue to make the code running in both machines? Thank you!


Q: problem with mapping table in NHibernate I rewrite application from ASP.NET to Silverlight and use NHibernate 2.
Tables in my db looks like this:
alt text http://img268.imageshack.us/img268/4940/tablesqp.jpg
In Dziecko table I have reference to id of Opiekun and Grupy. In ASP it's ok for me but in videos Summer with NHibernate I see that Stephen Bohlen  in exchange use object of this type, for me its Opiekun and Grupy.But in SQL Server I can't define object type, so better is map only this id[will I could problem querying for id] and or something else ?? Using all object of specific type is efficiency? We must query all object in exchange only int type of id's ??

A: (I hope I've understood your question correctly.)
The relations in your database are always defined in database types, probably either an int or a uniqueidentifer in the case of foreign key columns. The database should know nothing of the data transfer objects NHibernate returns to your application code.
When you map the foreign key columns in your data transfer objects using ManyToOne, etc., you specify the type of the object because NHibernate knows that the relation is always going to be between the foreign key column you specify in the attribute, and the Id (primary key) of the object type to be returned. This saves you the trouble of doing extra queries to return parent or child entities -- NHibernate just does a JOIN for you automatically and returns the relational information as an object hierarchy, instead of just a set of id values.


Q: Multiline regular expressions with python requests module I am iterating over a web page line by line using requests, but trying to capture some multi-line regular expressions:
import requests

r = requests.get(url)

for line in r.iter_lines():
    pat = re.search(regex, line)
    if pat:
        print pat.group(1)

I have tried concatenating the whole file into one long string, but that seems wrong.
What is the best way to capture these multiline expressions (preferably using requests)?
Note: I am new to requests. I have looked at the docs but haven't found, or understood, the answer.
Thanks

A: r = requests.get(url)
pat = re.search(regex, r.text)


Q: Classroom.Courses.CourseWork.patch I am trying to update the "state" of an assignment within Google Classroom using Google Apps Script. The current state of the assingment is DRAFT.
I am trying in two different codes and get two different errors:
function publicarBorradores() {
      var courseId = "320315007220"
      var assingid = "320315007244"
      var newState = { "state":'PUBLISHED'}

     var patchDraft = Classroom.Courses.CourseWork.patch(newState,courseId,assingid);
     patchDraft.updateMask = newState;

or
      patchDraft.updateMask = 'state'
         }

I always get the same Error:
"GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required"
I also tried this other way:
function valoresDraft (){
     var courseId = "320315007220"
     var assingId = "320315007244"
     changeState(courseId,assingId);
    }

 function changeState(courseId,assingId) {
      var estado = {'state': "PUBLISHED",}
      const patchDraft = Classroom.Courses.CourseWork
      patchDraft.patch(estado, courseId, assID,{"updateMask":"state"});
  }

And I get a different error: "API call to classroom.courses.courseWork.patch failed with error: @ProjectPermissionDenied The Developer Console project is not permitted to make this request." which is strange as I am the owner of the class AND I have published via the same "Developer Console project" other publications within this same class. (The class was NOT created via API. I created it manually from within classroom.google.com)
Thanks

A: The are a few issues with your code:

*

*In the first example, the GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required" error you are receiving is due to the fact that you are not specifying the updateMask field before making the request.

So even though you added the patchDraft.updateMask = newState;  line, this won't help as it will be execute after the API call.

*The second example ends up executing properly because you supplied the updateMask field at the time of making the request.

However, since the class was created manually from the Classroom UI, this is the expected behavior, as the class is essentially not associated with any Developer Console Project.
According to the documentation:

ProjectPermissionDenied indicates that the request attempted to modify a resource associated with a different Developer Console project.
Possible Action: Indicate that your application cannot make the desired request. It can only be made by the Developer Console project of the OAuth client ID that created the resource.

What you can do in this situation is to create the class from the API and afterwards execute the patch call.
Reference

*

*Classroom API Access Errors.


Q: How can I return an object (ie. List) from an object mocked with NSubstitute? I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List.
But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func.
I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function.
I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq (https://www.youtube.com/watch?v=DwbYxP-etMY). I am considering switching to that if I can't manage to return an object with NSubstitute.

A: Here is an example of how to return a List<string> from an object mocked by NSubstitute:
using System.Collections.Generic;
using NSubstitute;
using Xunit;

public interface ISomeType {
    List<string> MyFunction();
}

public class SampleFixture {
    [Fact]
    public void ReturnList() {
        var _mockedObject = Substitute.For<ISomeType>();
        var myList = new List<string> { "hello", "world" };

        _mockedObject.MyFunction().Returns(myList);

        // Checking MyFunction() now stubbed correctly:
        Assert.Equal(new List<string> { "hello", "world" }, _mockedObject.MyFunction());
    }
}

The error you have described sounds like there are different types involved. Hopefully the above example will help show the source of the problem, but if not please post an example of the _mockedObject interface and the test (as suggested in @jpgrassi's comment).


Q: MS Tests/ Moq - ExpectedException failing I'm trying to create unit test for one of my method using MS test and Moq. Below is my interface, implementation class and method.
public  interface IDocumentManagementHandler
    {
      Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata);
    }

public class DocumentManagementHandler : IDocumentManagementHandler
    {
        private readonly IService _service;
        private readonly IFService _fService;
        public readonly ILogger _logger;
        private static readonly long rootFolderId = 123456;

        public DocumentManagementHandler(IService Service, IFService FService, ILogger Logger)
        {
            _service = Service;
            _fService = FService;
            _logger = Logger;
        }

public Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata)
        {
            if(string.IsNullOrEmpty(metadataCategoryName))
                throw new ArgumentNullException(nameof(metadataCategoryName));

            if (metadata == null)
                throw new ArgumentNullException(nameof(metadata));

            return AddDocumentMetadataAsync(documentId, metadataCategoryName, metadata);
        }

My MSTest method
[TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TestAddData()
        {
            long documentID = 123;
            string metadataCategoryName = null;
            List<KeyValuePair<string, string>> metadata = null;

            var documentHandler = new Mock<IDocumentManagementHandler>();
            documentHandler.Setup(s => s.AddData(documentID, metadataCategoryName, metadata));

            var newresult = documentHandler.Object.AddData(documentID, metadataCategoryName, metadata);

        }

I'm expecting the test method to pass when I pass the variable "metadataCategoryName" as NULL but test is failing with the message "Test method did not throw expected exception System.ArgumentNullException." .
Any idea what's wrong here.

A: Your issue: you are using a mock representing an interface of the object containing the method you want to test, which means your code is never really called (a breakpoint would have revealed this particular issue).
As for how you should have written your test :
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestAddData()
{
    long documentID = 123;
    string metadataCategoryName = null;
    List<KeyValuePair<string, string>> metadata = null;

    // Configure as needed using Mock.Get()
    var service = Mock.Of<IService>();
    var fService = Mock.Of<IFService>();
    var logger = Mock.Of<ILogger>();

    var documentHandler = new DocumentManagementHandler(service, fService, logger);

    documentHandler.AddData(documentID, metadataCategoryName, metadata);
}

Additionally, you might want to assert the data contained in your exception. E.g. To check that your ArgumentNullException is reporting the correct parameter name


Q: Make php date dropdown function 'sticky' Out of coffee and brain's given up...
...can anyone help to make this form date dropdown function retain selected month on $_POST ['submit'] or isset($missing) in the case of there being an error/missing field etc
 function createMonths($id='month_select', $selected=null)
{
    /*** array of months ***/
    $months = array(
            1=>'Jan',
            2=>'Feb',
            3=>'Mar',
            4=>'Apr',
            5=>'May',
            6=>'Jun',
            7=>'Jul',
            8=>'Aug',
            9=>'Sep',
            10=>'Oct',
            11=>'Nov',
            12=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('m') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    foreach($months as $key=>$mon)
    {
        $select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';
        $select .= ($key==$selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";

    }
    $select .= '</select>';
    return $select;
}

A: In the event you have invalid form data, you should check if the $_POST['month_select'] variable is set and not empty and create your dropdown passing in it's value like so:
$selected = (!empty($_POST['month_select'])) ? $_POST['month_select'] : null;
createMonths('month_select', $selected);

function createMonths($id='month_select', $selected = null)
{
    /*** array of months ***/
    $months = array(
            '01'=>'Jan',
            '02'=>'Feb',
            '03'=>'Mar',
            '04'=>'Apr',
            '05'=>'May',
            '06'=>'Jun',
            '07'=>'Jul',
            '08'=>'Aug',
            '09'=>'Sep',
            '10'=>'Oct',
            '11'=>'Nov',
            '12'=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('n') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    $select .= "<option value=""></option>\n";
    foreach($months as $key => $mon)
    {
        $select .= '<option value="'.$key.'"';
        $select .= ($key == $selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";
    }
    $select .= '</select>';
    return $select;
}

I have also taken the liberty of fixing your createMonths() function by the recommendation regarding date('n') and changing your array keys to strings as this will avoid having to pad your months.


Q: ruby on rails - thin - HTTP GET URL > 1024 When I use an URL bigger than 1024 appear this in the console of the rails server.

Invalid request: HTTP element REQUEST_PATH is longer than the 1024 allowed length.
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `execute'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `parse'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/connection.rb:41:in `receive_data'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/backends/base.rb:73:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/server.rb:162:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands/server.rb:84:in `start'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:76:in `block in <top (r
equired)>'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `tap'
        /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `<top (required)>
'
        bin/rails:4:in `require'
        bin/rails:4:in `<main>'

Can I rescue this exception?


Q: QuantLib's HestonModelHelper class is throwing error I have below QuantLib model in python -
import QuantLib as ql
import pandas as pd
day_count = ql.Actual365Fixed()
calendar = ql.UnitedStates()
calculation_date = ql.Date(6, 11, 2015)
spot = ql.SimpleQuote(659.37)
risk_free_rate = ql.SimpleQuote(0.01)
dividend_rate = ql.SimpleQuote(0.0)

riskFreeCurve = ql.FlatForward(
                                calculation_date,
                                ql.QuoteHandle(risk_free_rate),
                                day_count
                            )
dividend_yield = ql.FlatForward(
                                calculation_date,
                                ql.QuoteHandle(dividend_rate),
                                day_count
                            )
yield_ts = ql.YieldTermStructureHandle(riskFreeCurve)
dividend_ts = ql.YieldTermStructureHandle(dividend_yield)
p = ql.Period(ql.Date(6,12,2015) - calculation_date, ql.Days)
s = 527.50
vols = 0.35
helper = ql.HestonModelHelper(
                                            p,
                                            calendar,
                                            ql.QuoteHandle(spot),
                                            ql.QuoteHandle(ql.SimpleQuote(s)),
                                            ql.QuoteHandle(ql.SimpleQuote(vols)),
                                            yield_ts,
                                            dividend_ts
                                        )

With above I got below error -
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
  File "/usr/local/lib/python2.7/dist-packages/QuantLib/QuantLib.py", line 9840, in __init__
    _QuantLib.HestonModelHelper_swiginit(self, _QuantLib.new_HestonModelHelper(*args))
TypeError: Wrong number or type of arguments for overloaded function 'new_HestonModelHelper'.
  Possible C/C++ prototypes are:
    HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &,BlackCalibrationHelper::CalibrationErrorType)
    HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &)

Any clue where my code went wrong will be highly helpful.
Thanks,

A: The problem is that the HestonModelHelper expects the type of the spot and the strike to be a float.
For it to work with minimal change, use:
helper = ql.HestonModelHelper(
                                            p,
                                            calendar,
                                            spot.value(),
                                            s,
                                            ql.QuoteHandle(ql.SimpleQuote(vols)),
                                            yield_ts,
                                            dividend_ts
                                        )


Q: Creating a Docker volume at a specific location Can I tell Docker to create a volume at a specific location on the host machine?
The host machine has some storage restrictions and I'd like the volume to be stored in /data instead of /var/lib/docker/vfs/dir/.
This isn't even mentioned in the documentation so I suspect I misunderstood something.

A: Do you want to use a  different directory than the default /var/lib/docker as Docker runtime? You can do this by starting docker daemon with -g option and path to the  directory of your choice. From the man page:
-g, --graph=""
     Path to use as the root of the Docker runtime. Default is /var/lib/docker.

A: When firing up your container with "docker run":
 docker run -v /data/some_directory:/mount/location/in/your/container your_docker_image

You cannot do this in the same way via Dockerfile because of portability.


Q: Is there a way I can specify a different repository for the CocoaPods master repo? At my work, we have a private cocoapods repository that we use to host whitelisted libraries for developers, and I am trying to validate a library I wrote.
Whenever i do a pod spec lint MYPODNAME --verbose, CocoaPods tries to validate my spec against the master repo instead of my private repo.
Is there any way to get around this behavior?
I have tried completely removing the master repo, but it still attempts to validate my pod's dependencies against master
EDIT: This issue seems to describe what I am experiencing.

A: Answering my own question. You have to manually specify the --sources for what CocoaPods will validate the spec against.
pod spec lint MYPODNAME --verbose --sources=git@<DOMAIN>:<REPO>.git


Q: how to access php variable out side of a foreach loop i have a veriable named (num) which is used for increments changes names of ids by 1 num+1 but in my foreachloop i cant access it .
i tried declaring it before the loop still doesnot work
<?php $num = 0; ?>
<?php foreach($listings as $list):?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num+1;?>" name="treatment<?php echo $num+1;?>">
            <label for="visit<?php echo $num+1;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach;   ?>

<input type="hidden" value="<?php echo $num;?>" name="total"/>

i want the input ids to be incremented by 1 like treatment1,treatment2

A: You should increment the $num variable by doing $num++; once inside the loop, then print it where you need it with <?php echo $num; ?> without using <?php echo $num+1; ?> - as doing so will only increment it as you echo it - not add one to each iteration.
<?php
$num = 0;
foreach($listings as $list):
    $num++; // Increment $num for each iteration
    ?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach; ?>

If your $listings is numeric indexed, you can use the key of each element in the array instead by doing
foreach($listings as $num=>$list):
    ?>

            <input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
            <label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <?php echo $list['price'];?>£

<?php endforeach; ?>

A: The problem is you did not set the value of $num variable you just only print or echo it inside the html tags. You need to add or increment the $num variable  inside the loop like this.
 <?php $num++; ?>

or
 <?php $num = $num+1; ?>


Q: Vagrant broken with Ruby 'Segmentation Fault' Error All of a sudden Vagrant is broken on my machine.
I don't see what might have caused this. It came up with an older version of Virtualbox and Vagrant 1.9.8. I updated both to the current version in hope to get it fixed.
I run

*

*Windows 10 Pro 1709

*Virtualbox 5.2.0-118431

*Vagrant 2.0.1

I was using a current Ruby installation in parallel but removed it for testing.
For any Vagrant command I get this error:
https://gist.github.com/cfoellmann/b8c50dc386d241d44ed0fca60e7680d1
I have read about issues with the ffi gem but I see no way to fix the bundled components of the vagrant install.
Any pointer into debugging this will be much appreciated.


Q: In text classification, how to find the part of sentence that is important for the classification? I have trained a text classification model that works well. I wanted to get deeper and understand what words/phrases from a sentence were most impactful in the classification outcome. I want to understand what words are most important for each classification outcome
I am using Keras for the classification and below is the code I am using to train the model. It's a simple embedding plus max-pooling text classification model that I am using.
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping

# early stopping
callbacks = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', min_delta=0,
patience=5, verbose=2,  mode='auto', restore_best_weights=True)

# select optimizer
opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999,
epsilon=1e-07, amsgrad=False, name="Adam")
embedding_dim = 50

# declare model
model = Sequential()
model.add(layers.Embedding(input_dim=vocab_size,
                           output_dim=embedding_dim,
                           input_length=maxlen))
model.add(layers.GlobalMaxPool1D())
model.add(layers.Dense(10, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer=opt,
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.summary()

# fit model
history = model.fit(X_tr, y_tr,
                    epochs=20,
                    verbose=True,
                    validation_data=(X_te, y_te),
                    batch_size=10, callbacks=[callbacks])
loss, accuracy = model.evaluate(X_tr, y_tr, verbose=False)

How do I extract the phrases/words that have the maximum impact on the classification outcome?

A: It seems that the keyword you need are "neural network interpretability" and "feature attribution". One of the best known methods in this area is called Integrated Gradients; it shows how model prediction depend on each input feature (each word embedding, in your case).
This tutorial shows how to implement IG in pure tensorflow for images, and this one uses the alibi library to highlight the words in the input text with the highest impact on a classification model.


Q: Modal view controller not in the window hierarchy The App I'm trying to do has a tabbar controller.
When the App starts, I'm getting the user location in the AppDelegate and when I've got the accuracy I need the AppDelegate sends an NSNotification to my App's starting page (index 0 of the tab bar controller).
Upon receiving the notification, this view tries to send an email with the user coordinates and other data, but as soon as the MFMailComposeViewController is presented I get the following error:
Warning: Attempt to present <MFMailComposeViewController: 0x98a0270> on <UITabBarController: 0x988c630> whose view is not in the window hierarchy!

What am I missing?
Thanks.
EDIT: adding some code...
This is what I've got in my AppDelegate.m:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults];
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 10.0) {
    [self locationUpdate:newLocation];
    smsLoc = newLocation;
    if ([[phoneNumbers objectForKey:@"sendSMS"] isEqualToString:@"yes"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendSMS" object:nil];
    } else if ([[phoneNumbers objectForKey:@"sendEmail"] isEqualToString:@"yes"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendEmail" object:nil];
    }

}
}

Then, in my first view controller I have:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendSMS:) name:@"sendSMS" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendEmail:) name:@"sendEmail" object:nil];
}

And at the end, the selector for "sendSMS" (the other is pretty similar):
- (void)sendSMS: (NSNotification *)notification {
NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults];
if ([phoneNumbers objectForKey:@"first"] || [phoneNumbers objectForKey:@"second"]) {
        MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
        if ([MFMessageComposeViewController canSendText]) {
            AppDelegate *deleg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            controller.body = [NSString stringWithFormat:@"some message with coordinates %.4f - %.4f", [deleg currentLocation].coordinate.latitude, [deleg currentLocation].coordinate.longitude];
            controller.recipients = [NSArray arrayWithObjects:[phoneNumbers objectForKey:@"first"], [phoneNumbers objectForKey:@"second"], nil];
            controller.messageComposeDelegate = self;
            [self presentModalViewController:controller animated:YES];
        }
    }
}
}

Second edit: adding some more code.
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.delegate = self;
tabBarController.selectedIndex = 0;
[[tabBarController.tabBar.items objectAtIndex:0] setTitle:NSLocalizedString(@"Home", nil)];
[[tabBarController.tabBar.items objectAtIndex:1] setTitle:NSLocalizedString(@"Requests", nil)];
[[tabBarController.tabBar.items objectAtIndex:2] setTitle:NSLocalizedString(@"Account", nil)];
[[tabBarController.tabBar.items objectAtIndex:3] setTitle:NSLocalizedString(@"Settings", nil)];
//some other controls from DB
[[tabBarController.tabBar.items objectAtIndex:1] setBadgeValue:[NSString stringWithFormat:@"%d",number]];

The tabbarController has been made via IB, but I've added the code above in my AppDelegate because I need to localize the tab bar items and to add a badge to one of them.
Am I doing something wrong here?

A: Using this may help someone: [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:NO completion:nil];

A: I'm not sure if you have solve this issue. The error message means the viewcontroller you use to present another modal viewcontroller is not visible on the window. This can happen for e.g:
[VC1 presentModalViewController:VC2];

// Error here, since VC1 is no longer visible on the window
[VC1 presentModalViewController:VC3];

If your issue is like above, you can fix it like:
if (self.modalViewController != nil) {
    [self.modalViewController presentModalViewController:VC3 animated:YES];
} else {
    [self.tabBarController presentModalViewController:VC3 animated:YES];
}

If that doesn't fix your issue, maybe you can try to present using self.tabBarController instead of self. Again just suggestion, not sure if it works though.

A: Since modalViewController and presentModalViewController are deprecated, the following is what works for me:
presentingVC = [[UIApplication sharedApplication] keyWindow].rootViewController;
if (presentingVC.presentedViewController) {
    [presentingVC.presentedViewController presentViewController:VC3 animated:YES completion:nil];
} else {
    [presentingVC presentViewController:VC3 animated:YES completion:nil];
}

A: You can follow this pattern
[VC1 presentModalViewController:VC2];

//
[**VC2** presentModalViewController:VC3];


Q: Detecting a pattern in a list/array This is rather an algorithmic question.
I have a Java List (sorted) or array that consists of chars (X and Y) and I need to detect a certain pattern of the way the values are ordered.
The List size is fixed (for example 5). The patterns I'd like to detect are the following:
XYYYY
XXYYY
XXXYY
XXXXY
XXXXX

So X is always followed by only Y's.
Simple String.equals or contains doesn't work, since it's not scalable and is restricted to a known list size.

A: You can use a simple regular expression for this:
boolean matches = s.matches("^X+Y*$");

This means:

*

*^ matches the start of the string

*X+ means one or more consecutive Xs

*Y* means zero or more consecutive Ys

*$ is the end of the string

Alternatively, you can check the string character-wise:
int i = 0;
while (i < s.length() && s.charAt(i) == 'X') {
  ++i;
}
if (i < s.length()) {
  if (s.charAt(i) != 'Y') {
    return false;
  }
  while (i < s.length() && s.charAt(i) == 'Y') {
    ++i;
  }
}
return i == s.length();

A: You can use the following regular expression to detect the particular pattern.
String pattern = "^(X){1,}Y*$";

Here's the complete java code,
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatch {
    public static void main(String[] args){
        // String to be scanned to find the pattern.
        String line = "XXXXY";
        String pattern = "^(X){1,}Y*$";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find( )) {
             System.out.println("Found value: " + m.group(0) );
        } else {
             System.out.println("NO MATCH");
        }
    }
}


Q: What goes into writing a cache simulator program? Can any one explain or point me to a source that explain what goes into writing a cache simulator program.
It's a school project and I have no intention to use anyone else's code as it does me no good. I will be tested on understanding of the program and concept, but I would like so see some detailed material, a pseudo code or gant chart or something.
I'm asking here because text book and lectures have not given me enough information and I've googled for hours this week and found nothing relevant.

A: Try this. But keep in mind about Academic Integrity, which is posted at the bottom of the page. It may not be the same school you go to, but I'm sure AI is universal regardless of whatever school assignment you're going through. You can also try Googling your problem, I found ~five references for doing so.


Q: How Do I Draw Two Overlapping JPanels such that the Graphics Drawn On Both Of Them Display On The Screen? I have two JPanels. One panel has a 100x100 rectangle drawn at 0,0. And the other has a 100x100 rectangle drawn at 100, 100. My problem is that when both JPanels are drawn on the JFrame's content pane, one JPanel (the last one drawn) covers the other, hiding its graphics. Below is oversimplified code drawing two rectangles and the things I've tried.
package playground;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Playground{

    public Playground(){
        JFrame frame = new JFrame("My Frame");
        frame.setSize(400, 400);

        JPanel backPanel = new JPanel(){;

                @Override
                public void paintComponent(Graphics g){
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    Rectangle2D rect = new Rectangle2D.Double(0, 0, 100, 100);
                    g2.draw(rect);
                }
        };
        JPanel frontPanel = new JPanel(){

            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                Rectangle2D rect = new Rectangle2D.Double(150, 150, 100, 100);
                g2.draw(rect);
            }
        };
        frontPanel.setOpaque(true); //Does nothing
        frontPanel.setBackground(new Color(0, 0, 0, 0)); //Does nothing
        frontPanel.setForeground(new Color(0, 0, 0, 0)); //Erases the rectangle drawn

        frame.getContentPane().add(backPanel);
        frame.getContentPane().add(frontPanel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args){
        System.out.println("Hello World");
        new Playground();
    }

}

If anyone cares why I want to do this,
I'm creating the game breakout. I am a novice programmer and I have no knowledge of gaming theory. So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels. A static JPanel at the very back with an image drawn on it (fun background image). A JPanel with the paddle drawn on it. A JPanel with bricks drawn on it. And a JPanel with a ball drawn on it. My rationale is that I won't have to redraw the paddle if it is not being moved, the background, and bricks that are not being hit. If a brick lets say is hit, I will update an arrayList of bricks and call repaint on the corresponding JPanel.

A:
I am a novice programmer and I have no knowledge of gaming theory.

Ok, we can work with that.

So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels.

You've just unnecessarily complicated your program.
Think of a JPanel as a canvas.  You want to draw the entire Breakout game; bricks, paddle, and ball, on one JPanel canvas.  Don't worry, you'll be able to redraw the entire canvas fast enough to get 60 frames per second if you want.
The way to do this is to create a Brick class, a Paddle class, and a Ball class.  You create a Game Model class that contains one instance of the Paddle class, one instance pf the Ball class, and a List of instances of the Brick class.
The Brick class would have fields to determine its position in the wall, the number of points scored when the ball collides with the brick, the color of the brick, and a draw method that knows how to draw one brick.
The ball class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows how to draw the ball.
The Paddle class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows haw to draw the paddle.
The Game Model class would have methods to determine when the ball collides with a brick, determine when the ball collides with a brick, determine when the ball collides with a wall, and a draw method that calls the other model class draw methods to draw a ball, a paddle, and a wall of bricks.
This should be enough for now to get you started going in the right direction.
Edited to answer questions:

How would I implement a draw method in all these classes?

Here's an example Ball class.  I haven't tested the moveBall method, so it might need some adjustment
import java.awt.Graphics;
import java.awt.geom.Point2D;

public class Ball {

    private Point2D position;

    /** velocity in pixels per second */
    private double  velocity;

    /**
     * direction in radians
     *

     *
0 - Heading east (+x)

     *
PI / 2 - Heading north (-y)

     *
PI - Heading west (-x)

     *
PI * 3 / 2 - Heading south (+y)

     *

     * */
    private double  direction;

    public Point2D getPosition() {
        return position;
    }

    public void setPosition(Point2D position) {
        this.position = position;
    }

    public double getVelocity() {
        return velocity;
    }

    public void setVelocity(double velocity) {
        this.velocity = velocity;
    }

    public double getDirection() {
        return direction;
    }

    public void setDirection(double direction) {
        this.direction = direction;
    }

    public void moveBall(long milliseconds) {
        Point2D oldPosition = position;

        // Calculate distance of ball motion
        double distance = velocity / (1000.0D * milliseconds);

        // Calculate new position
        double newX = distance * Math.cos(direction);
        double newY = distance * Math.sin(direction);

        newX = oldPosition.getX() + newX;
        newY = oldPosition.getY() - newY;

        // Update position
        position.setLocation(newX, newY);
    }

    public void draw(Graphics g) {
        int radius = 3;
        int x = (int) Math.round(position.getX());
        int y = (int) Math.round(position.getY());

        // Draw circle of radius and center point x, y
        g.drawOval(x - radius, y - radius, radius + radius, radius + radius);

    }

}

The draw method draws the ball wherever it actually is located.  That's all the draw method does.
Actually moving the ball is the responsibility of the Game Model class.  The method for moving the ball is included in this class because the information necessary to move the ball is stored in the Ball class.
I gave the ball a radius of 3, or a diameter of 6 pixels.  You may want to make the ball bigger, and use the fillOval method instead of drawOval.

should I just call repaint() at a 30ms interval

Basically, yes.
In psudeocode, you create a game loop
while (running) {
    update game model();
    draw game();
    wait;
}

First, you update the game model.  I gave you a Ball class.  You would have similar classes for the paddle and bricks.  They all have draw methods.
Your Game model class calls all of these draw methods in the proper order.  In Breakout, you would draw the boundaries first, then the bricks, then the paddle, and finally, the ball.
Your JPanel (canvas) calls the one draw method in the Game Model class.
I don't have an example game to show you, but if you read the article Sudoku Solver Swing GUI, you'll see how to put together a Swing GUI and you'll see how model classes implement draw methods.
I suggest that you stop working on Breakout for a while and go through the Oracle Swing Tutorial.  Don't skip any sections in your haste to write a program.  Go through the entire tutorial so you understand how Swing works before you try and use it.


Q: jQuery: I need to show consecutive fields in a form at each new click I have 5 upload fields but I need to hide them except the first. Then at each click to show them one by one.
I created the following script but it seems like item.show() is not displaying the hidden fields.10x
first = $('.webform-client-form').find('div[id$="-ajax-wrapper"]').first();
    first.after('[+] Add more');
    $('.webform-client-form').find('div[id$="-ajax-wrapper"]').each(function(){
            $(this).hide();
            first.show();
    });

    var c = 1;//counter
    $('#addmore').bind('click', function(e) {
        item = $('edit-submitted-file'+c+'-ajax-wrapper');
        item.show();
        ++c;
    if (c == 5) {
      $('#addmore').hide();
      return false;
    }
  });

A: shouldn't this:
var item = $('edit-submitted-file'+c+'-ajax-wrapper');

be
var item = $('#edit-submitted-file'+c+'-ajax-wrapper'); //if using id
or
var item = $('.edit-submitted-file'+c+'-ajax-wrapper'); //if using class

A: You need to prepend '#' to the selector for -ajax-wrapper because you are selecting it by ID.
The counter needs to start at 2 and hide addmore on 6.  The return false (should actually be e.preventDefault() should be outside of that conditional.
addmore should be added after the last of the file input rows, not the first.

A: Just use the next() function and :visible selector
Example:
HTML
File <input type="file" />
File <input type="file" />
File <input type="file" />
...

JQuery
$('label:gt(0)').hide(); // hide all except the first one
$('label:visible').click($(this).next('label').show()); // show the following

:visible is not necessary, as you can't click on hidden elements, but it's just an optimisation.


Q: Find Instance ID for Azure Servers In AWS we have instance IDs to identify machines. What's the equivalent in Azure and how do I find that?
I'd like to list the instance ID in powershell so I can put that into a script.

A: If I have not misunderstood, I suppose you want to get the InstanceId of the VM in the Azure VM Scale set.
You could try to use Get-AzureRmVmssVM to get it.
Get-AzureRmVmssVM -ResourceGroupName <ResourceGroupName> -VMScaleSetName <VMScaleSetName>

Update:
If you want to get the ResourceId of azure resource, you could use Get-AzureRmResource to do it, just specify the properties what you want.
For example:
1.Get ResourceId of the specific resource:
$resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName> -ResourceType <ResourceType> -ResourceName <ResourceName>
$resource.ResourceId

2.Get ResourceIds of all resources in the specific resource group
$resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName>
$resource.ResourceId

3.Get ResourceIds of all resources under your subscription.
$resource = Get-AzureRmResource
$resource.ResourceId

The result will like(actual result will decided by your properties):


Q: What is the best approach to upload a file using Jersey client? I want to upload a file (a zip file to be specific) to a Jersey-backed REST server.
Basically there are two approaches (I mean using Jersey Client, otherwise one can use pure servlet API or various HTTP clients) to do this:
1)
 WebResource webResource = resource();
    final File fileToUpload = new File("D:/temp.zip");

    final FormDataMultiPart multiPart = new FormDataMultiPart();
    if (fileToUpload != null) {
        multiPart.bodyPart(new FileDataBodyPart("file", fileToUpload, MediaType.valueOf("application/zip")));
    }

    final ClientResponse clientResp = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(
        ClientResponse.class, multiPart);
    System.out.println("Response: " + clientResp.getClientResponseStatus());

2)
File fileName = new File("D:/temp.zip");
        InputStream fileInStream = new FileInputStream(fileName);
        String sContentDisposition = "attachment; filename=\"" + fileName.getName() + "\"";
        ClientResponse response = resource().type(MediaType.APPLICATION_OCTET_STREAM)
            .header("Content-Disposition", sContentDisposition).post(ClientResponse.class, fileInStream);
        System.out.println("Response: " + response.getClientResponseStatus());

For sake of completeness here is the server part:
@POST
    @Path("/import")
    @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_OCTET_STREAM})
    public void uploadFile(File theFile) throws PlatformManagerException, IOException {
        ...
    }

So I am wondering what is the difference between those two clients?
Which one to use and why?
Downside (for me) of using 1) approach is that it adds dependency on jersey-multipart.jar (which additionally adds dependency on mimepull.jar) so why would I want those two jars in my classpath if pure Jersey Client approach 2) works just as fine.
And maybe one general question is whether there is a better way to implement ZIP file upload, both client and server side...

A: Approach 1 allows you to use multipart features, for example, uploading multiple files at the same time, or adding extra form to the POST.
In which case you can change the server side signature to:
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException {
}

I also found that I had to register the MultiPartFeature in my test client...
public FileUploadUnitTest extends JerseyTest {
@Before
    public void before() {
        // to support file upload as a test client
        client().register(MultiPartFeature.class);
    }
}

And server
public class Application extends ResourceConfig {
    public Application() {
        register(MultiPartFeature.class);
    }
}

Thanks for your question, it helped me write my jersey file unit test!


Q: Can you have WPF references in an XNA project for xbox 360 I'm writing a XNA project in both Windows and Xbox 360 and the Windows side of it has a console I bring up written as a WPF application.  What I was wondering is if I leave this in my library code with the references to WPF, will the dll still work on the 360?

A: No.  You're limited to using the .NET Compact Framework on the XBOX 360.  This will not include WPF.
In fact, you're limited to the XBOX 360's implementation of the Compact Framework, which is built off the .NET 2.0 Compact Framework.  This means that any .NET 3.0/3.5 specific classes will not work.  MSDN lists the entire collection of the supported namespaces, types, and members for the XBOX 360.


Q: Is there any problem with using HTML5's "data-*" attributes for older browsers? I want to associate some custom data with some HTML nodes. I was going to use the new HTML5 style 'data-*' attributes. e.g.: <tr class="foo" data-typeid="7">…, and then I was going to select this HTML node and show/hide it etc. by reading the value with $(node).attr("data-typeid").
However this web page needs to work with older browsers aswell. I'm not using the data-* attribute as a special attribute, but I'd like to know if older browsers will ignore, wipe, or make inaccessible this attribute since it's not valid HTML4.

A: There isn't really, they're not 100% correct/valid usage in HTML4 of course....but they don't cause problems either, so they're still a great way to solve the "I need an attribute for this" problem.
If it helps, I've used these while supporting IE6 and have had zero issues thus far, and I can't recall a single SO question reporting any either.

A: Internet Explorer and Microsoft has added several custom attributes that are not valid HTML4. Browsers don't check the element attributes against a specification, you can name an attribute roryscoolinfo="hello" if you like (though you shouldn't).
The Dojo Toolkit adds its custom dojo* attributes.
It's fine to use data- today, with a HTML5 doctype.


Q: How to visualize CGAL resutls with VTK library I am new in this forum.
I have a problem in my project in c++.
I used vtk and Itk and Qt, but the mesh was not perfect so I tried to include CGAL with cmake.
I can do everything using CGAL, but I can't visualize the object created with CGAL. I have tried to export the results (coordinates, vertices, triangles...) to a generic file like xml or txt to be able to read it from vtk and render it.
Please can you help me to find a way to visualize the CGAL operations?
Thank you

A: There is a mesh to vtk converter which I used a while ago.


Q: mysql delete and then insert. Does not insert into delete line for AI table! Why? I am not sure I am correct in this.
I have insert 5 rows with values with id as primary key and autoincrement.
Then I delete row number 2-4.
when I insert on a new line with none id, the new id becomes "6". Is this normal?
How is it possible if you want the mysql to insert in the deleted row? what are the settings?

A: Yes, this is normal. If you want to insert with a specific ID number you have to specify that number on your insert statement.
The idea of auto increment is for the value to continually increase.

A: This is normal, though for some database engines you might receive 2, but usually it will be 6.  In MSSQL it is possible to specify a value for an autoinc field with particular setting. Not sure what it is in mysql.

A: That's the expected behavior. Autoincrement primary keys are designed to be unique and continually increasing - so they are not assigned again.
If you TRUNCATE a table the autoincrement value is being reset while it stays as it is if you delete all rows with an DELETE query - that's a subtle but sometimes important difference.
As webdestroya suggested, the only possibility to reuse old and deleted autoincrement values is to set them specifically on the INSERT statement.


Q: Zapier Javascript: Unexpected token ] - working in IDE, Repl.it, & Node v6.3.1 The Solution:
Thanks to @Kunal Mukherjee for the help.
const pattern = /\](,)\s{2,}?/gm
let res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]")
            .split(/\s{2,}/gm)
            .map(x => JSON.parse(x));

res = res[0];   //reassign to scrape an array layer
let resultString = '';

for (let i = 0; i < res[0].length; i += 1) {
  let cv = res[0][i];
  if (cv.length === 0) resultString += `    ${res[1][i]}: ${inputData.rows[2][i]}\n`
  else resultString += `${cv}\n    ${res[1][i]}: ${res[2][i]}\n`;
}

output = {KPI: resultString};

Original Post:
The problem
In a Zapier Zap, I'm extracting data from Google Sheets and using JS to prettify it to later send in an email. I'm bumping into an error with the following message:
SyntaxError: Unexpected token ]
  stringOfArraysToArrayOfArrays (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:22:52)
  theFunction (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:29:18)
  eval (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:51:20)
  Domain.<anonymous> (/var/task/index.js:53:5)
  Domain.run (domain.js:242:14)
  module.exports.handler (/var/task/index.js:51:5)

What I've tried
I've successfully run this code from the most current version of Node back to Node v6.3.1 in different environments - local IDE, Repl.It IDE, and an online IDE set to Node v6.3.1. They all clear. I've also tried clearing the code of all ES6+ syntax (sans the example data)
Example of data
let inputData = {
  rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"],
    ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"],
    ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]`
}

Code producing the error
function stringOfArraysToArrayOfArrays(string) {
  let arrayPointers = [0, 1];
  let arrOfArr = [];

  for (let i = 0; i < string.length; i += 1) {
    let cv = string[i];
    if (cv === "[") arrayPointers[0] = i;
    else if (cv === "]") {
      arrayPointers[1] = i + 1;
      arrOfArr.push(string.slice(arrayPointers[0], arrayPointers[1]));
      arrOfArr[arrOfArr.length - 1] = eval(arrOfArr[arrOfArr.length - 1]);
    }
  }

  return arrOfArr;
}

inputData.rows = stringOfArraysToArrayOfArrays(inputData.rows);

let resultString = '';

for (let i = 0; i < inputData.rows[0].length; i += 1) {
  let cv = inputData.rows[0][i];
  if (cv.length === 0) resultString += '    ' + inputData.rows[1][i] + ':  ' + inputData.rows[2][i] + '\n';
  else resultString += cv + '\n    ' + inputData.rows[1][i] + ':  ' + inputData.rows[2][i] + '\n';
}

output = {KPI: resultString};

Expected results
I'm expecting for the code to run, first off, then I'm expecting output.KPI to be a prettified string.
Thanks for the time & help :)

A: This approach may be a little functional.
You need to first replace the ], in every row to an empty string I have used this Regex to split it.
After that, I split the strings by whitespaces which are more than 2 characters.
Then finally I used .map to project over the splitted items to parse it back and make an array of array.

const inputData = {
  rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"],
    ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"],
    ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]`
};

const pattern = /\](,)\s{2,}?/gm
const res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]")
            .split(/\s{2,}/gm)
            .map(x => JSON.parse(x));

const output = { KPI: res };

console.log(output);


Q: HTML nested numbered list with starting index In my application I have a page which lists some data grouped by categories.
Each item on the list can have subitems.
So I'd it to look like this:

*

*List item
1.1 List item
1.2 List item

*List item
2.1 List item
2.2 List item
I can achieve this easily using this three lines of css code:
OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }

However on this page I have tabs for each category, which contains such nested list of items and I want to make index of first item of next tab to be x+1-th item, where x is number of last item from previous tab ( category ).
#tab 1
 1. List item

   1.1 List item

   1.2 List item
 2. List item

   2.1 List item

   2.2 List item

#tab 2
 3. List item

   3.1 List item

   3.2 List item
 4. List item

   4.1 List item

   4.2 List item

So I need functionality to provide starting index to
 tag. I found out that there is attribute start="x", however it doesn't work with these 3 lines of css code for nested lists.
Any idea how to do something like this?

A: From http://www.w3.org/TR/css3-lists/#html4:
/* The start attribute on ol elements */
ol[start] {
    counter-reset: list-item attr(start, integer, 1);
    counter-increment: list-item -1;
}

Adding this to the CSS allowed the start attribute to be recognized in my tests.
EDIT:
Instead of using the start attribute, you can use CSS classes for each new starting point.  The downside is that this will require more maintenance should you need to change anything.
CSS:
ol.start4
{
    counter-reset: item 4;
    counter-increment: item -1;
}

ol.start6
{
    counter-reset: item 6;
    counter-increment: item -1;
}

HTML:

Item 1

Item 2

Item 1

Item 2

Item 3

Item 1

Item 2

Item 4

Item 1

Item 2

Item 5

Item 6

Item 7

Item 1

Item 2

A: Just remove the css, and correctly close and reopen
 tags.
If you need to split the list in two separate tabs, you have to close the first
 inside the first tab. Then, reopen the new list with the start parameter inside the second tab:
.
Working fiddle - (I set start="5" to show it's working; for your purposes, just set it to 3 or what you need)
UPDATE:
Keep the CSS, and wrap all the tabs in the main
 and
, so the counter doesn't reset.
http://jsfiddle.net/qGCUk/227/


Q: How to get object dictionary representation in Python I have objects message of type azure.servicebus.common.message.Message. I can print it and get representation that looks like dictinorary.
print(message)
{b'Type': b'TEST', b'Subtype': b'subtype'}
print(type(message))
<class 'azure.servicebus.common.message.Message'>
print(dict(message))
TypeError: 'Message' object is not iterable

I would like to add dictionary representation of this object to the list, not the object like below
batch.append(message)

How to convert representation of the object to dictionary ?


Q: ASP.net IdentiyServer 3 AuthorizationCodeReceived not firing when a user authenticates with Identity Server 3, AuthorizationCodeReceived never fires.  RedirectToIdentityProvider  does get fired but thats it.  I am trying to call a function that will get the users email or windows ID, and then add a custom claim.  But without the AuthorizationCodeReceived method being called, I am not sure how to do that.  Anyone have experience with this?  Not sure if it matters, but my code is ASP.net windows form (not MVC)
Here is my code:
    Public Sub ConfigureAuth(app As IAppBuilder)
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = New Dictionary(Of String, String)

        app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
            .AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
        })

        Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
           .Authority = "https://myidentityserver.azurewebsites.net/core/",
           .ClientId = "adfafasfasdfa",
           .RedirectUri = "https://localhost:44321/default.aspx/",
           .ResponseType = ("access_token"),
           .RequireHttpsMetadata = False,
           .SignInAsAuthenticationType = "Cookies",
           .Notifications = New OpenIdConnectAuthenticationNotifications() With {

                .AuthorizationCodeReceived = Function(ctx)
                                                 Dim claimPrincipal As ClaimsPrincipal = ctx.AuthenticationTicket.Identity.Claims
                                                 TransformClaims(claimPrincipal)
                                                 Return Task.FromResult(0)
                                             End Function,
                .RedirectToIdentityProvider = Function(context)
                                                  RedirectLogin(context)
                                                  Return Task.FromResult(0)
                                              End Function
                }
        }
        app.UseOpenIdConnectAuthentication(OpenIdAuthOption)
    End Sub


Q: Why is the Binding Format event called twice? I am playing around with data binding and noticed that the Binding Format is called twice upon loading the form in the code below.  I thought it would only happen once when the test class TextBoxText property is fist bound to textbox1.  Is this normal?  If not, then what can I do to prevent it? Note, when I press button1 and it changes the TextBoxText property of the test class, the format event fires once as expected.
public partial class Form1 : Form
{
    Test _test = new Test();
    public Form1()
    {
        InitializeComponent();
        Binding binding = new Binding("Text", _test, "TextBoxText");
        binding.Format += new ConvertEventHandler(Binding_Format);
        this.textBox1.DataBindings.Add(binding);
    }

    private void Binding_Format(object sender, ConvertEventArgs e)
    {
        Debug.WriteLine("Format");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _test.TextBoxText = "test1";
    }
}

class Test : INotifyPropertyChanged
{
    private string _text;

    public string TextBoxText
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged(new PropertyChangedEventArgs("TextBoxText"));
        }
    }

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged(this, e);
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

A: The simple answer:  "Because that is the way Microsoft implemented it".
The goal is to just respond to the event... whenever it happens... however often it occurs.  We can't make any assumptions.  There are cases where you might get called six times on the same event.
We just have to roll with it and continue to be awesome.


Q: delphi7 converted to delphi tokyo app taskbar icon does not like to move to second screen app my delphi7 apps always show in the primary screen monitor taskbar , Now in delphi 10.2 If I move the app to the second screen the taskbar icon move to that seconds screen .
So now my issue is with the old delphi7 apps which I open and compile with delphi 10.2, they still have the old behavior . So how can I solve that??

A: In Delphi 7, all TForm windows are owned by the hidden TApplication window at runtime, which is the window that actually manages the app's Taskbar button. That window remains on the primary monitor when you move your Forms to other monitors. That is why you don't see the app's Taskbar button move to other monitors.
In Delphi 2007 and later, TForm windows are no longer owned by the hidden TApplication window by default on Vista+. This behavior is controlled by the TApplication.MainFormOnTaskBar property, which did not exist yet in Delphi 7.  Being owned by the hidden TApplication window causes all kinds of problems in Vista+ for the Taskbar, the Task switcher, Aero, etc, so ShowMainFormOnTaskBar should always be set to true.
When you upgrade your Delphi 7 project to Delphi 10.2, be sure to set Application.MainFormOnTaskBar := true; in the app's main startup code so the app interacts with Vista+ properly.  MainFormOnTaskBar is false by default when migrating a pre-D2007 project.


Q: jQuery UI - make div not resizable I have a div that is made resizable using jQuery UI. How can I dynamically make it not resizable anymore?
I tried calling resizable({ disabled: true }) but the handle still showed.

A: Use this code:    .resizable( "destroy" )

A: Try .resizable("option", "disabled", true);
http://jqueryui.com/demos/resizable/#option-disabled
Your solution is not working because, as per the documentation you need use the setter that I mentioned, if you want to disable it after initialization (you code will only work if its an initialization call)

A: Oops...
I was disabling "resizable" before I enabled it...