text:
Q: Loop through Google Sheet I know enough to be dangerous. But not enough for some things. I have cobbled this script together and it works. Currently this checks if a CSV file is in a specific folder, if so, creates a tab and imports the data into that tab. But, I have like 50 offices and are expanding. So rather than repeat the function 50 times, I want to read the list of offices from the Google Sheet and loop through the results replacing the "DTMadisonData" portion. Can anyone help me?
var fSource = DriveApp.getFolderById('XXXXXXXfK70bknfK1lY4NJNZxxwgvLUu');
  // reports_folder_id = id of folder where csv reports are saved

var fi = fSource.getFilesByName('DTMadisonData.csv');
      // latest report file

    if ( fi.hasNext() ) { // proceed if "DTMadisonData.csv" file exists in the reports folder
    /*
    Check if Sheet exists, if not create it
    */

      var ss = SpreadsheetApp.getActiveSpreadsheet();
       var mysheet = "MadisonDTData";

       if (ss.getSheetByName(mysheet ) == null){
           ss.insertSheet('MadisonDTData');
           var sheet = ss.getActiveSheet();

        }
      var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function

    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getSheetByName('DTMadisonData');

      // loop through csv data array and insert (append) as rows into 'DTMadisonData' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
      }

    };

    // http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
    // This will parse a delimited string into an array of
    // arrays. The default delimiter is the comma, but this
    // can be overriden in the second argument.

    function CSVToArray( strData, strDelimiter ) {
    // Check to see if the delimiter is defined. If not,
    // then default to COMMA.
    strDelimiter = (strDelimiter || ",");

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
    (
      // Delimiters.
        "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

        // Quoted fields.
        "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

        // Standard fields.
        "([^\"\\" + strDelimiter + "\\r\\n]*))"
      ),
      "gi"
    );

    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;

    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
    }

    // Return the parsed data.
    return( arrData );
    };

A: I think I was able to work it out with another script I dug up!
function importCSVFromGoogleDrive() {
var fSource = DriveApp.getFolderById('XXXXXXXXX0bknfK1lY4NJNZxxwgvLUu');
  // reports_folder_id = id of folder where csv reports are saved

  //var sheet = SpreadsheetApp.setActiveSpreadsheet('OfficeList');
  var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.setActiveSheet(ss.getSheetByName("OfficeList"));

   var startRow = 1;  // First row of data to process
  var numRows = 50;   // Number of rows to process
  // Fetch the range of cells A1:A50
  var dataRange = sheet.getRange(startRow, 1, numRows, 1)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var officeName = row[0];  // First column
   var fi = fSource.getFilesByName(officeName + ".csv");
  // latest report file

if ( fi.hasNext() ) { // proceed if "officeName.csv" file exists in the reports folder

/*
Check if Sheet exists, if not create it
*/

  var ss = SpreadsheetApp.getActiveSpreadsheet();
   var mysheet = officeName;

   if (ss.getSheetByName(mysheet ) == null){
       ss.insertSheet(officeName);
       var sheet = ss.getActiveSheet();

    }

var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function

var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(officeName);

  // loop through csv data array and insert (append) as rows into 'SpoonerData' sheet
for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
  sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
  }

  }
};


text:
Q: How to Continue R.raw.audio sound after completing one loop by clicking on button in android my program is working only once but i want to continue play sound every time, i have 98 audios, when i click on button and  1,2,3,.....97, 98 it's playing well but after 98,1,2,3 it's not playing sound in second loop. How to continue it's sound on next loop? your help will be appreciated. Thanks
my Code:
public class MainActivity extends Activity {
private ImageView hImageViewPic;
private Button iButton, gButton;
MediaPlayer ourSong;

private int currentImage = 0;
private int currentAudio = 0;

int[] images = { R.drawable.p1, R.drawable.p2, R.drawable.p3,
        R.drawable.p4, R.drawable.p5, R.drawable.p6, R.drawable.p7,
        R.drawable.p8, R.drawable.p9, R.drawable.p10, R.drawable.p11,
        R.drawable.p12, R.drawable.p13, R.drawable.p14, R.drawable.p15,
        R.drawable.p16, R.drawable.p17, R.drawable.p18, R.drawable.p19,
        R.drawable.p20, R.drawable.p21, R.drawable.p22, R.drawable.p23,
        R.drawable.p24, R.drawable.p25, R.drawable.p26, R.drawable.p27,
        R.drawable.p28, R.drawable.p29, R.drawable.p30, R.drawable.p31,
        R.drawable.p32, R.drawable.p33, R.drawable.p34, R.drawable.p35,
        R.drawable.p36, R.drawable.p37, R.drawable.p38, R.drawable.p39,
        R.drawable.p40, R.drawable.p41, R.drawable.p42, R.drawable.p43,
        R.drawable.p44, R.drawable.p45, R.drawable.p46, R.drawable.p47,
        R.drawable.p48, R.drawable.p49, R.drawable.p50, R.drawable.p51,
        R.drawable.p52, R.drawable.p53, R.drawable.p54, R.drawable.p55,
        R.drawable.p56, R.drawable.p57, R.drawable.p58, R.drawable.p59,
        R.drawable.p60, R.drawable.p61, R.drawable.p62, R.drawable.p63,
        R.drawable.p64, R.drawable.p65, R.drawable.p66, R.drawable.p67,
        R.drawable.p68, R.drawable.p69, R.drawable.p70, R.drawable.p71,
        R.drawable.p72, R.drawable.p73, R.drawable.p74, R.drawable.p75,
        R.drawable.p76, R.drawable.p77, R.drawable.p78, R.drawable.p79,
        R.drawable.p80, R.drawable.p81, R.drawable.p82, R.drawable.p83,
        R.drawable.p84, R.drawable.p85, R.drawable.p86, R.drawable.p87,
        R.drawable.p88, R.drawable.p89, R.drawable.p90, R.drawable.p91,
        R.drawable.p92, R.drawable.p93, R.drawable.p94, R.drawable.p95,
        R.drawable.p96, R.drawable.p97, R.drawable.p98, R.drawable.p99 };

int[] audios = {R.raw.a0 ,R.raw.a1, R.raw.a2, R.raw.a3, R.raw.a4, R.raw.a5,
        R.raw.a6, R.raw.a7, R.raw.a8, R.raw.a9, R.raw.a10, R.raw.a11,
        R.raw.a12, R.raw.a13, R.raw.a14, R.raw.a15, R.raw.a16, R.raw.a17,
        R.raw.a18, R.raw.a19, R.raw.a20, R.raw.a21, R.raw.a22, R.raw.a23,
        R.raw.a24, R.raw.a25, R.raw.a26, R.raw.a27, R.raw.a28, R.raw.a29,
        R.raw.a30, R.raw.a31, R.raw.a32, R.raw.a33, R.raw.a34, R.raw.a35,
        R.raw.a36, R.raw.a37, R.raw.a38, R.raw.a39, R.raw.a40, R.raw.a41,
        R.raw.a42, R.raw.a43, R.raw.a44, R.raw.a45, R.raw.a46, R.raw.a47,
        R.raw.a48, R.raw.a49, R.raw.a50, R.raw.a51, R.raw.a52, R.raw.a53,
        R.raw.a54, R.raw.a55, R.raw.a56, R.raw.a57, R.raw.a58, R.raw.a59,
        R.raw.a60, R.raw.a61, R.raw.a62, R.raw.a63, R.raw.a64, R.raw.a65,
        R.raw.a66, R.raw.a67, R.raw.a68, R.raw.a69, R.raw.a70, R.raw.a71,
        R.raw.a72, R.raw.a73, R.raw.a74, R.raw.a75, R.raw.a76, R.raw.a77,
        R.raw.a78, R.raw.a79, R.raw.a80, R.raw.a81, R.raw.a82, R.raw.a83,
        R.raw.a84, R.raw.a85, R.raw.a86, R.raw.a87, R.raw.a88, R.raw.a89,
        R.raw.a90, R.raw.a91, R.raw.a92, R.raw.a93, R.raw.a94, R.raw.a95,
        R.raw.a96, R.raw.a97, R.raw.a98 };

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    hImageViewPic = (ImageView) findViewById(R.id.idImageViewPic);
    iButton = (Button) findViewById(R.id.bIleri);
    gButton = (Button) findViewById(R.id.bGeri);
    // Just set one Click listener for the image

    iButton.setOnClickListener(iButtonChangeImageListener);
    gButton.setOnClickListener(gButtonChangeImageListener);

}

View.OnClickListener iButtonChangeImageListener = new OnClickListener() {

    public void onClick(View v) {
        try {
            // Increase Counter to move to next Image and Audio
            currentImage++;
            currentAudio++;

            currentImage = (currentImage + images.length) % images.length;

            hImageViewPic.setImageResource(images[currentImage]);

            ourSong = MediaPlayer.create(MainActivity.this,audios[currentAudio]);

            ourSong.start();

        } catch (Exception e) {

        }

    }

};

View.OnClickListener gButtonChangeImageListener = new OnClickListener() {

    public void onClick(View v) {
        try {
            // Decrease Counter to move to previous Image and Audio
            currentImage--;
            currentAudio--;

            currentImage = (currentImage + images.length) % images.length;

            hImageViewPic.setImageResource(images[currentImage]);

            ourSong = MediaPlayer.create(MainActivity.this, audios[currentAudio]);

            ourSong.start();

        } catch (Exception e) {

        }

    }
};

}

A: I think you are missing rollover for currentAudio.
currentAudio = ++currentAudio % audios.length;
 AND
currentAudio = (--currentAudio + audios.length) % audios.length;

redpajama_set_name: RedPajamaStackExchange


text:
Q: receive content from other applications with plugin WebIntent I want to receive information shared from other applications.
For this I am trying to use The plugin WebIntent : https://github.com/phonegap/phonegap-plugins/tree/master/Android/WebIntent
Use Phonegap 2.5.0
In AndroidManifest.xml (To show my application in the section to share)
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>

In index.html
document.addEventListener('deviceready', onDeviceready, true);

function onDeviceready() {
    window.plugins.webintent.getUri(function(url) {
      if(url !== "") {
        // url is the url the intent was launched with
         alert (url);
      }
    });
}

var url, the value returned is null.
Plugin src/com/borismus/webintent/WebIntent.java
in res/xml/config.xml
</plugins>
....
....
    <plugin name="WebIntent" value="com.borismus.webintent.WebIntent" />
</plugins>

Thanks!!!

A: I can get the uri now! I'm using:
window.plugins.webintent.getExtra(window.plugins.webintent.EXTRA_TEXT, function (url) {
              alert(url);
        }, function() { //Fail
              alert ("error");
});


text:
Q: Knockoutjs valueHasMutated not working correctly Hopefully this will be a quick one for a knockout guru....
I'm writing a couple of custom bindings to help me translate a UI using a custom translation engine in the project I'm working on.
One is to translate text, the other is to translate the 'placeholder' attribute on HTML5 input elements.
Both bindings are identical apart from the last statement, where one updates the text in the element and the other updates an attribute value.
The text one works perfectly, but the place holder one does not, and I'm stuck for an answer as to why.
The binding code is as follows:
Translated Text Binding
ko.bindingHandlers.translatedText = {

    init: (element: HTMLElement, valueAccessor: Function, allBindings: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {

        // Get our custom binding values
        var value = valueAccessor();
        var associatedObservable = value.observable;
        var translationToken = value.translationToken;

        // Set up an event handler that will respond to events telling it when our translations have finished loading
        // the custom binding will instantly update when a key matching it's translation ID is loaded into the
        // local session store
        window.addEventListener("TranslationsLoaded", (e) => {
            //associatedObservable(" "); // Force an update on our observable, so that the update routine below is triggered
            associatedObservable.valueHasMutated();
        }, false);

    },

    update: (element: HTMLElement, valueAccessor: Function, allBindings: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {

        // Get our custom binding values
        var value = valueAccessor();
        var associatedObservable = value.observable;
        var translationToken = value.translationToken;

        // Ask local storage if we have a token by that name
        var translatedText = utilityLib.getTranslatedString(translationToken);

        // Check if our translated text is defined, if it's not then substitute it for a fixed string that will
        // be seen in the UI (Whatever you put into the 'associatedObservable' at this point WILL appear in the element
        if (undefined === translatedText || translatedText === "" || translatedText === null) {
            if (sessionStorage["translations"] === undefined) {
                // No translations have loaded yet, so we blank the text
                translatedText = "";
            } else {
                // Translations have loaded, and the token is still not found
                translatedText = "No Translation ID";
            }
        }
        associatedObservable(translatedText);
        ko.utils.setTextContent(element, associatedObservable());
    }

} // End of translatedText binding

Translated Placeholder Binding
ko.bindingHandlers.translatedPlaceholder = {

    // This one works pretty much the same way as the translated text binding, except for the final part where
    // the translated text is inserted into the element.

    init: (element: HTMLElement, valueAccessor: Function, allBindings: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {
        var value = valueAccessor();
        var associatedObservable = value.observable;
        var translationToken = value.translationToken;
        window.addEventListener("TranslationsLoaded", (e) => {
            debugger;
            associatedObservable.valueHasMutated();
        }, false);
    },

    update: (element: HTMLElement, valueAccessor: Function, allBindings: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {
        var value = valueAccessor();
        var associatedObservable = value.observable;
        var translationToken = value.translationToken;
        var translatedText = utilityLib.getTranslatedString(translationToken);
        debugger;
        if (undefined === translatedText || translatedText === "" || translatedText === null) {
            if (sessionStorage["translations"] === undefined) {
                translatedText = "";
            } else {
                translatedText = "No Translation ID";
            }
        }
        associatedObservable(translatedText);
        element.setAttribute("placeholder", translatedText);
    }

} // End of translatedPlaceholder binding

The idea is a simple one, if the binding runs and the translations are already present in sessionStorage, then we pick up the translated string and plug it in to the observable associated with the element.
If the translations have loaded, but the translation is not found "No Translation ID" is plugged into the observable bound to the element.
If the translations have NOT yet loaded, plug an empty string into the observable, then wait for the event 'TranslationsLoaded' to fire.  When this event is raised, the observable bound to the element is mutated, causing an update to happen, which in turn re-checks the translations, which it then finds have loaded and so acts accordingly.
However.....
It doesn't matter how hard I try, the translated placeholder binding just will not fire it's update.
I can clearly see in the debugger that the event is recieved on both bindings, and the mutate function IS called.
On the translated text binding, I get the following sequence...
'init' -> 'update' -> 'event' -> 'mutate' -> 'update'
Which is exactly what I expect, and it occurs on every element+observable bound to that binding.
On the translated placeholder i get
'init' -> 'update' -> 'event' -> 'mutate'
but the final update never occurs.
As a result, the translated string for the placeholder is never looked up correctly, the text one with identical code works perfectly!!
For those who'll ask, i'm using the bindings like this:
<input type="text" class="form-control" data-bind="value: userName, translatedPlaceholder: { observable: namePlaceHolderText, translationToken: 'loginBoxNamePlaceholderText'}">

and inside the view model, the 'observable' parameters are just normal ko.observable variables holding strings.
Cheers
Shawty

A: I believe you have event bubbling issues... try putting a 'return true' after your call to valueHasMutated like this:
init: (element: HTMLElement, valueAccessor: Function, allBindings: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {
    var value = valueAccessor();
    var associatedObservable = value.observable;
    var translationToken = value.translationToken;
    window.addEventListener("TranslationsLoaded", (e) => {
        associatedObservable.valueHasMutated();
        return true; // allow event to bubble
    }, false);
},

That being said, I am thinking all this manual eventing is against-the-grain for what knockout can do for you. You should be observing your data, binding to it, and letting knockout do all the internal eventing for you... that's what it does.
An example building on user3297291's fiddle:
ko.bindingHandlers.translatedPlaceholder = {
  init: function(element, valueAccessor) {
    var va = valueAccessor();
    var obs = ko.utils.unwrapObservable(va.obs);
    var placeholderStr = obs[va.key];
    console.log(placeholderStr);
    element.setAttribute("placeholder", placeholderStr);
  },
  update: function(element, valueAccessor) {
    var va = valueAccessor();
    var obs = ko.utils.unwrapObservable(va.obs);
        var placeholderStr = obs[va.key];
    console.log(placeholderStr);
    element.setAttribute("placeholder", placeholderStr);
  }
};

var vm = function() {
    var self = this;
    self.dictionary = ko.observable({
    "placeholder": "Initial State"
  });

  self.switchTranslations = function() {
    // Set the 'new' dictionary data:
    self.dictionary({
      "placeholder": "My Translated Placeholder"
    });
  };
}
ko.applyBindings(new vm());

Fiddle: https://jsfiddle.net/brettwgreen/5pmmd0va/

A: Trigger the update handler
From the Knockout documentation:

Knockout will call the update callback initially when the binding is applied to an element and track any dependencies (observables/computeds) that you access. When any of these dependencies change, the update callback will be called once again.

The key is that you have to access the observable within the update function to get updates. In your translatedText binding you do so:
ko.utils.setTextContent(element, associatedObservable());

But there is no such access of associatedObservable in the update function of translatedPlaceholder. You'll need to add it like this:
associatedObservable(translatedText);
associatedObservable();  // get notified of updates to associatedObservable
element.setAttribute("placeholder", translatedText);

A better approach
For your case, there really isn't a need for an update handler because you don't need to update the view based on changes to the viewmodel. Instead your updates just come from events, which can be set up in the init handler.
ko.bindingHandlers.translatedPlaceholder = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        function loadTranslation() {
            var translationToken = valueAccessor(),
                translatedText = utilityLib.getTranslatedString(translationToken);
            element.setAttribute("placeholder", translatedText || "No Translation ID");

            window.removeEventListener("TranslationsLoaded", loadTranslation);
        }
        if (sessionStorage["translations"] === undefined)
            window.addEventListener("TranslationsLoaded", loadTranslation, false);
        } else {
            loadTranslation();
        }
    }
}

Usage:
data-bind="value: userName, translatedPlaceholder: 'loginBoxNamePlaceholderText'"


text:
Q: React map array modal window items not working I'm using state everything works fine except for the modal window. Inside the state, I use objects that are normally displayed (you can look at the screenshot https://ibb.co/YBg30NW) please pay attention to the buttons named "Open modal" when you click on this button, a modal window opens and should display the name of the programming language as shown in the screenshot. The problem is that when opening a modal window, only the same name of the programming languages "CSS" is displayed https://ibb.co/J5jrZF0 no matter what button I click to open the modal window, only "CSS" is displayed, how can I solve this problem ?
import React from "react"
import cnStyle from "./ContentCourses.module.css"
import python from "./Icons/pyhton.png"
import cPlusPlus from "./Icons/c++.png"
import JavaScript from "./Icons/JavaScript.png"
import swift from "./Icons/swift.png"
import HTML from "./Icons/HTML.png"
import CSS from "./Icons/CSS.png"
import Modal from 'react-modal';

const customStyles = {
    content: {
        top: '50%',
        left: '50%',
        right: 'auto',
        bottom: 'auto',
        marginRight: '-50%',
        transform: 'translate(-50%, -50%)'
    }
};

Modal.setAppElement('#root');

export class ContentCourses extends React.Component {

    constructor() {
        super();
        this.state = {
            languageInfo: [
                {
                    languageName: "Python 3",
                    about: `
                    Learn Python, one of today's most in-demand programming languages on-the-go!
                    Practice writing Python code, collect points, & show off your skills now!`,
                    Learners: 30045,
                    Lessons: 87,
                    Quizzes: 271,
                    icon: python,
                },

                {
                    languageName: "JavaScript",
                    about: `
                    Learn all the basic features of JavaScript, including making your website more interactive,
                    changing website content, validating forms, and so much more.`,
                    Learners: 42123,
                    Lessons: 42,
                    Quizzes: 321,
                    icon: JavaScript,
                },

                {
                    languageName: "C++",
                    about: `
                    Our C++ tutorial covers basic concepts, data types, arrays, pointers, conditional statements,
                    loops, functions, classes, objects, inheritance, and polymorphism.`,
                    Learners: 53241,
                    Lessons: 23,
                    Quizzes: 451,
                    icon: cPlusPlus,
                },

                {
                    languageName: "Swift",
                    about: `
                    Learn all the main concepts of Swift programming and apply your newly gained knowledge
                    to create your own, fully functioning iOS app!`,
                    Learners: 63211,
                    Lessons: 54,
                    Quizzes: 623,
                    icon: swift,
                },

                {
                    languageName: "HTML",
                    about: `
                    This FREE course will teach you how to design a web page using HTML.
                    Complete a series of hands-on exercises and practice while writing real HTML code.`,
                    Learners: 18024,
                    Lessons: 32,
                    Quizzes: 962,
                    icon: HTML,
                },

                {
                    languageName: "CSS",
                    about: `
                    Our CSS course will teach you how to control the style & layout of websites.
                    Complete a series of exercises and practice while filling out actual CSS templates.`,
                    Learners: 58932,
                    Lessons: 46,
                    Quizzes: 125,
                    icon: CSS,
                },

            ],

            modalIsOpen: false,
            setIsOpen: false,
        }
    }

    openModal() {
        this.setState({setIsOpen: true})
        this.setState({modalIsOpen: true})
    }

    afterOpenModal() {
        // references are now sync'd and can be accessed.
        // subtitle.style.color = '#f00';
    }

    closeModal() {
        this.setState({setIsOpen: false})
        this.setState({modalIsOpen: false})
    }

    render() {
        var subtitle;
        const resultsRender = [];

        for (var i = 0; i < this.state.languageInfo.length; i += 2) {
            resultsRender.push(

                    {
                        this.state.languageInfo.slice(i, i + 2).map((item, index) => {
                                return (

{item.languageName}

                                                            {item.about}

                                                    <button onClick={this.openModal.bind(this)}>Open Modal</button>
                                                    <Modal
                                                        isOpen={this.state.modalIsOpen}
                                                        onAfterOpen={this.afterOpenModal.bind(this)}
                                                        onRequestClose={this.closeModal.bind(this)}
                                                        style={customStyles}
                                                        contentLabel="Example Modal"
                                                    >

 (subtitle = _subtitle)}>{item.languageName}

                                                        <button onClick={this.closeModal.bind(this)}>close</button>

I am a modal

                                                        <form>
                                                            <input />
                                                            <button>tab navigation</button>
                                                            <button>stays</button>
                                                            <button>inside</button>
                                                            <button>the modal</button>
                                                        </form>
                                                    </Modal>

Learners

{item.Learners}

Lessons

{item.Lessons}

Quizzes

{item.Quizzes}

                                );
                            }
                        )
                    }

            );
        }

        return (

                {resultsRender}

        );
    }
}

A: This is the culprit: isOpen={this.state.modalIsOpen}. Once modalIsOpen === true, all modals will show up and you see only CSS modal because it stays on top of the other modals.
To fix this, you can specific which modal should be opened when the button is clicked. It can be done by passing a parameter to the openModal function.
For example, you can pass item.languageName to openModal function. And modify isOpen={this.state.modalIsOpen === item.languageName}. Thus, when modalIsOpen === "CSS", the modal for Javascript will not show up.


text:
Q: How do I patch a class attribute in pytest? I have a service class that connections to AWS S3. The connection uses boto3 within the __init__() method. I would like to mock this to use a moto s3 instance I've defined in a fixture, but I just can't get the mock to do anything.
Let's say I have a service class that looks like this:
import boto3

class S3Storage:
    def __init__(self):
        self._s3 = boto3.resource('s3')

    def do_download(self):
        self._s3 .download_file(
            Key='file.txt',
            Bucket='mybucket',
            Filename='path/to/destination/file.txt',
        )

and then I create a conftest file that has these moto fixtures:
# Fixtures
@pytest.fixture(scope='function')
def mocked_s3r():
    with mock_s3():
        yield boto3.resource('s3')

@pytest.fixture(scope='function')
def mocked_s3client():
    with mock_s3():
        yield boto3.client('s3')

@pytest.fixture(scope='function', autouse=True)
def upload_s3_resources(mocked_s3client, s3files):
    mocked_s3client.create_bucket(Bucket='mybucket')
    mocked_s3client.upload_file(
        Filename='path/to/destination/file.txt',
        Bucket='mybucket',
        Key='file.txt',
    )

The bottom fixture will grab a local file and place it in the moto s3 instance, which can be accessed from the mocked_s3r client mock.
My problem is that I cannot make a successful patch for the S3Storage._s3 attribute that holds the boto resource (I know I'm mixing boto clients and resources here, but I don't think that's causing the issue).
So I tried writing some fixtures to patch (using pytest-mock) or monkeypatch the boto resource and/or client.

# This is what I can't make work...
@pytest.fixture(autouse=True)
def mocked_s3(mocked_s3client, mocker):
    mocker.patch('app.utils.s3_storage.boto3.resource', return_value=mocked_s3r)
    return mocked_s3client

# This other approach also doesn't work...
@pytest.fixture(autouse=True)
def mocked_s3(mocked_s3client, mocker):
    mocker_s3storage = mocker.patch('app.utils.s3_storage.boto3.resource')
    mocker_s3storage()._s3 = mocked_s3client
    return mocked_s3client

# Nor this...
@pytest.fixture(autouse=True)
def mocked_s3(mocked_s3client, monkeypatch):
    monkeypatch.setattr('app.utils.s3_storage.S3Storage._s3', mocked_s3client)
    return mocked_s3client

But nothing works. I think I might be fundamentally misunderstanding how to patch an attribute that belongs to an instance of a class.
I'd rather do all this in a fixture, not in each individual test, such that I can write a test like:
def test_download_file(mocked_s3client):
    s3storage = S3Storage()
    s3storage._s3 # This should be a mock object, but it just connects to the real AWS
    s3storage.do_download()

and I don't have to specify the mock each time.

A: It is not necessary to patch the client, in order for Moto to work. As long as clients/resources are created while the mock is active, they are automatically patched.
Using your example fixtures, the following test works:
def test_file_exists(upload_s3_resources):
    S3Storage().do_download()
    test_file_exists()  # todo: actually verify somethign happened

Note that the download-file call in your logic should be slightly modified, but I'm assuming that was just a example to keep things simple.
I had to change to the following to get the test to succeed:
self._s3.Bucket('mybucket').download_file('file.txt', 'test.txt')


text:
Q: Python linux script (whois error) I'm trying to create a python script on linux that does a 'whois' command on every connected/connecting IP Address that is parsed from the 'netstat' command.
I am get an error saying "sh: 1: Syntax error: Unterminated quoted string"
and the whois usage options posted below that.
Can anyone explain to me what's wrong the script? I believe it's something to do with the for loop and the way it executes the whois command I just cant seem to find a solution. Below is the script in question:
#!/usr/bin/python
from os import system

answer = [system("netstat -alpntu46 |grep 'ESTABLISHED\|SYN_RECV' | awk '{print $5 }' |cut -d: -f1'")]

for i in answer:
    system('whois')

EDIT So my original problem is completely fixed, I'm getting no errors. However, now all the script does is list the IP Addresses and underneath that it lists the whois usage examples:
-h HOST, --host HOST   connect to server HOST
-p PORT, --port PORT   connect to PORT
-H                     hide legal disclaimers
      --verbose        explain what is being done
      --help           display this help and exit
      --version        output version information and exit"

So it seems to be running the  answer variable but not being able to run the whois command on each address.

A: Your command string (inside de system() command) has one ' more than needed (at the end of the string). Here it is corrected:
#!/usr/bin/python
from os import system

answer = [system("netstat -alpntu46 |grep 'ESTABLISHED\|SYN_RECV' | awk '{print $5 }' |cut -d: -f1")]

for i in answer:
    system('whois')

EDIT (your second question):
When you do for i in answer in python you are looping through all items in your answer, that is correct, however for each IP address you are looping on you are executing only a 'whois' command, without passing any parameters. You should add the parameter to the string, as in:
for i in answer:
    system('whois %s' % i)

that is assuming the variable i holds the ip string.

A: Please check the edit on my first answer (posting this just so you get notified.)


text:
Q: Azure. The system memory and CPU change cause slowdown app respond? we had a problem at 24th of February between 12:35 and 12:50 (pm by utc). Our app starts to respond slowly and it led to failures, but our app didn't overload Availability and Performance.
Could the system memory and CPU change cause slowdown our app respond? If yes, then how can avoid this problem next time?
There is a screenshot of our app slowdown chart: Web App Slow
In this time we detect change in physical memory and CPU Memory Analysis, High CPU Analysis

Availability and Performance tools detected top 5 slow request execution. It is requests from our app service to external services. Could these requests the overall performance of the app service or app service plan?

A: Yes. Low compute resource can lead to slow performance (application using high memory/CPU).
Other reasons for performance issue at application level issues, network requests taking a long time, application code or database queries being inefficient, or application crashing due to an exception. To isolate and avoid such issues in future you may try these steps.
Firstly, review the service heath for any reported issues during that time-frame:
You can track the health of the service on the Azure portal
From the screenshots you have shared, it looks like there 2 5xx errors and 48 4xx errors, you may review the logs to fetch more details on the issue.
-Access Kudu - https://.scm.azurewebsites.net/.

*

*To analyze logs and collect diagnostic dumps as required.

Enable diagnostics logging for apps in Azure App Service
Typically, in Azure App Service, for increased performance and throughput, you can adjust the scale at which you are running your application. I'm unsure on what App Service Plan (ASP) you're using.
If you have multiple Apps under a single ASP, the compute resources are shared by all of those running apps. Based on your requirement and usage you may either consider changing your App Service plan to a higher pricing tier or scale-out instances.


text:
Q: Shap Summary Plot not displaying using XGB I am trying to display the summary plot but somehow it does not work. What works though is displaying a force plot. Why is the summary plot not showing?
import shap
shap.initjs()
model = XGBClassifier(use_label_encoder=False)
model.fit(X_train,y_train)

explainer = shap.TreeExplainer(model,data = X_train,model_output='probability')
shap_values = explainer.shap_values(X_train)

shap.summary_plot(shap_values, features=df_enc, feature_names=df_enc.columns,show=True)

It displays nothing when my force plot is showing data. What could be the issue?


text:
Q: How/Why would Ethernet devices switch to a lower speed entirely on their own? As far as I know, usually an Ethernet connection either negotiates the maximum rate advertised by both ends (regardless of actual cable quality), or fails negotiation and falls back to 10 Mbps half-duplex. If two 100 Mbps devices are connected with a really bad cable, I would expect them to still negotiate 100 Mbps and just work poorly.
But I've seen various cases where devices actually switch to a lower rate:

*

*A computer should have a 1 Gbps connection (and does for some time after connecting), but several minutes later switches to 100 Mbps full-duplex on its own. Reconnecting the cable brings 1 Gbps back, but a few hours later it's at 100 Mbps again.
(The cable is 4–5 meters Cat5e. Computer's owner insists it's because the Ethernet cable is running right next to AC mains cable, though posts on SU usually say that shouldn't be a problem.)

*An Ubiquiti device should have a 100 Mbps connection (and does for some time), but several days later I find it using 10 Mbps full-duplex. Merely reconnecting the cable brings 100 Mbps back, but several days later the problem repeats again.
(The cable is Cat5e, somewhere around 20–40 m. Two similar devices exhibit this problem. They're both on the roof, and I'm not sure if the cable is an "outdoors" one, although it is at least FTP from what I remember. It wasn't professionally installed, that's for sure.)
In either case, the speed negotiation seems to succeed (it's not a half-duplex mode, and both the device and the switch agree on the selected mode), I just have no idea what the mechanism is? Port statistics on all devices always show 0 errors received, for what it's worth.
(I guess at least the 1st case could be explained by the "Ethernet@Wirespeed" feature, but do they apply even after all 4 pairs were determined to work? And in the second case, it's only a 10/100 device with a two-pair connection anyway.)

A: There are network cable testers available (e.g. from Fluke) which measure the physical properties of ethernet cables if you're unsure about the cabling.
You also might want to check the power supplies of Ethernet switches in between. It has happened several times to me that dying power supplies (usually seen after 5 years of use) create the strangest connection problems.
About the fact, that some cables are installed outdoors:
I had cheap SFTP cables for indoor use routed on the outside of a house for 10 years in direct sunlight without any visible cracks to the outer PVC layer after that period. YMMV if the cables are exhibited to very hot or cold conditions.


text:
Q: `this` accessing object properties

class Test {
  X = 'X';
  someFunc = () => {
    console.log('someFunc is called');
    //someFunc2(); // undefined
    this.someFunc2(); //works
  }

  someFunc2() {
    console.log('someFunc2 is called');
  }
}

Z = new Test();
console.log(Z.hasOwnProperty('X')); // true
console.log(Z.hasOwnProperty('someFunc')); // true
console.log(Z.hasOwnProperty('someFunc2')); // false

Z.someFunc();

I'm trying to understand when i should use this keyword, as far as i know it's used when trying referring/using some object property, but in the code above i tried to test is someFunc2 is property of the object and it returned false but still can called through this.someFunc2();. So does that mean this keyword not for accessing object property?

A: I think, console.log(Z.hasOwnProperty('someFunc2')); // false is not a problem with this in JavaScript. It relates more to function declaration.
someFunc = ()=>{
    console.log('someFunc is called');
    //someFunc2(); // undefined
    this.someFunc2(); //works
}

is an attribute which is assigned an anonymous function. Whereas
someFunc2(){
    console.log('someFunc2 is called');
}

is a shorthand function definition. For reference:
class Test {
  X = 'X';
  someFunc = ()=>{
    console.log('someFunc is called');
    //someFunc2(); // undefined
    this.someFunc2(); //works
  }

  someFunc2 = function (){
    console.log('someFunc2 is called');
  }
}

Z = new Test();
console.log(Z.hasOwnProperty('X')); // true
console.log(Z.hasOwnProperty('someFunc')); // true
console.log(Z.hasOwnProperty('someFunc2')); // true

console.log(Z.hasOwnProperty('someFunc2'));

resolves to true!
Doc: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Methoden_Definitionen
My first answer, I hope it was helpful.

A: class Test {
  X = 'X';
  someFunc = () => {
    console.log('someFunc is called');
    //someFunc2(); // undefined
    this.someFunc2(); //works
  }

  someFunc2() {
    console.log('someFunc2 is called');
  }
}

and
class Test {
  X = 'X';
  someFunc = () => {
    console.log('someFunc is called');
    //someFunc2(); // undefined
    this.someFunc2(); //works
  }

  someFunc2 = () => {
    console.log('someFunc2 is called');
  }
}

the difference is:
In the first example, we used function definition but never assign the function to any attribute or property.  so when you trying to use hasOwnProperty, it finds that the no attribute or property of name someFunc2 is available.
class Test {
  ....
  someFunc2() {
    console.log('someFunc2 is called');
  }
}

in the second example, we are assigning an anonymous function to an attribute  someFunc2,  so when you trying to use hasOwnProperty, it finds that the attribute or property someFunc2 is available
class Test {
  ...
  someFunc2 = () => {
    console.log('someFunc2 is called');
  }
}

A: The difference is on how arrow functions works,
Arrow functions dont have their own context, meaning their "this" keyword is the same as their parent function "this" keyword (or in this case the Test class) they both refer to the same context.
meaning when you initiate an instance of "Test" using the "new Test()", the "someFunc" will automatically inherit the context of that instance, while "someFunc2" wont, and will be inherited through the prototype chain.
You can confirm by using
console.log(Z.__proto__.hasOwnProperty('someFunc2'))

thats why you still be able to call it.
I hope this clarifies a bit of whats going on exactly.


text:
Q: Can't move mouse/keyboard on startup for a few seconds while Windows loads USB devices? I run Windows 7 in Boot Camp on an iMac. For some reason, sometimes when I start it up, I can't move my mouse (using USB via RF) and my Bluetooth keyboard for about 10–20 seconds while Windows loads USB devices (since I can hear the "device connected" sound effect). The devices that I have are three external HDs.
However, this doesn't happen on EVERY startup, only about half the time. I'm wondering why it happens at all?

A: This happens to me too sometimes as I connect my keyboard and mouse via a KVM switch. Sometimes a chkdsk can't be aborted because it hasn't fully attached my keyboard in time.
This will happen because of the asynchronous approach Windows has had to loading drivers since Windows XP, meaning that all drivers are just told to load at the same time and Windows waits until they're all done without caring which order they finish in. The results are never the same.
In Windows 2000 all drivers were loaded synchronously, as in, each driver was loaded in order and only when the previous driver had finished loading. This is why Windows 2000 was able to have an accurate progress bar during boot time, rather than just one that keeps scrolling across forever until it's done. This behaviour was stopped as the asynchronous approach pretty much always resulted in a quicker boot.


text:
Q: Google chrome account broken I have been experiencing this problem ever since I re installed ubuntu 14.04
I can not force google sync account to work properly
I get this error every time I start chrome

First I thought it was fault of "passwords and keys" (I am talking about the password, you set after you install chrome)
 Well I disabled it and no go it still would give me that error.
Then I've tried to re install chrome multiple times, even tried to install beta version, Still no go.
 While installing and re installing chrome I've signed in and signed out multiple times from google chrome but nothing helps.
I even deleted chrome's folder from ubuntu file
Nothing seems to work, does anyone knows what to do in a situation like this ??
THank you in advance
ls -al .config/ | grep chrom shows this:
drwx------  7 levan levan 4096 სექ 11 03:52 google-chrome

her is (ls -al .config/google-chrome/) output
    ls -al .config/google-chrome/
total 7508
drwx------  7 levan levan    4096 სექ 11 04:00 .
drwx------ 27 levan levan    4096 სექ 11 03:15 ..
-rw-r-----  1 levan levan  213973 სექ 11 03:50 Certificate Revocation Lists
-rw-------  1 levan levan       6 სექ 11 03:15 Channels
drwx------  2 levan levan    4096 სექ 11 03:15 Crash Reports
drwx------ 12 levan levan    4096 სექ 11 03:24 Default
drwx------  2 levan levan    4096 სექ 11 03:16 Dictionaries
-rw-r-----  1 levan levan       0 სექ 11 03:15 First Run
-rw-------  1 levan levan   49236 სექ 11 04:00 Local State
drwx------  3 levan levan    4096 სექ 11 03:35 pnacl
drwx------ 16 levan levan    4096 სექ 11 03:56 Profile 1
-rw-rw-r--  1 levan levan 5163740 სექ 11 03:33 Safe Browsing Bloom
-rw-rw-r--  1 levan levan 1009218 სექ 11 03:33 Safe Browsing Bloom Prefix Set
-rw-r--r--  1 levan levan    6144 სექ 11 03:33 Safe Browsing Cookies
-rw-r--r--  1 levan levan    4640 სექ 11 03:33 Safe Browsing Cookies-journal
-rw-rw-r--  1 levan levan  113284 სექ 11 03:33 Safe Browsing Csd Whitelist
-rw-rw-r--  1 levan levan 1016684 სექ 11 03:33 Safe Browsing Download
-rw-rw-r--  1 levan levan   14532 სექ 11 03:33 Safe Browsing Download Whitelist
-rw-rw-r--  1 levan levan   36664 სექ 11 03:33 Safe Browsing Extension Blacklist
-rw-rw-r--  1 levan levan     696 სექ 11 03:33 Safe Browsing IP Blacklist
lrwxrwxrwx  1 levan levan      20 სექ 11 03:29 SingletonCookie -> 15826594184631451903
lrwxrwxrwx  1 levan levan      12 სექ 11 03:29 SingletonLock -> Genesis-3672
lrwxrwxrwx  1 levan levan      46 სექ 11 03:29 SingletonSocket -> /tmp/.com.google.Chrome.gBPfaM/SingletonSocket

A: *

*Sign out of your Google Chrome account if signed in.  And quit the browser.

*Delete the user data with this command: rm -r ~/.config/google-chrome/Default

*Relaunch Google Chrome.  The error should now be gone, re-signin to your Google Chrome account and let it sync back your personal settings, extensions, and bookmarks.
Edit: Warning.  If you don't have your bookmarks and such synced to your Google account then #2 will delete them with no recovery.

A: Make sure you use latest version of Chrome. If not install it.
sudo apt-get purge google-chrome-stable
sudo apt-get autoremove
sudo apt-get install google-chrome-stable

A: I get this now and then.
Usually there are leftover/crashed chrome processes still open.
Kill them via Terminal/System Monitor, reopen chrome and the account-error is gone.
At least for me this does the trick.


text:
Q: programmatically adding a multilingual product I am writing an import script that is going to loop through some records and add products. I have it adding the products nicely but my store is multilingual so each product needs and english or a spanish name depending on which store is being viewed.
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
try{
$product

    ->setWebsiteIds(array(1))
    ->setStoreId(0)
    ->setAttributeSetId(4)
    ->setTypeId('bundle')
    ->setName($en_title)
    ->setCreatedAt(strtotime('now'))
    ->setSku('resource'.$resource_id)
    ->setStatus(1)
    ->setTaxClassId(0)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
    ->setPrice(number_format($price, 2, '.', ''))
    ->setStockData(array(
                       'use_config_manage_stock' => 0,
                       'manage_stock'=>0,
                   )
    )
    ->setCategoryIds(array(51))
    //->save()
    ->setStoreId(1)
    ->setName($en_title)
    //->save()
    ->setStoreId(2)
    ->setName($es_title)
    ->save();
}catch(Exception $e){
Mage::log($e->getMessage());
}

My English store had an ID of 1, and my Spanish store has an ID of 2. When I use the posted code all names are in Spanish regardless of store, and when I uncomment the save functions then all names are in English. I can't figure out why it wont save my Spanish name under my spanish store and my English name as Default and under the English store.

A: Try this:
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
try{
   $product
      //set all attributes here as you already do
      //....
   ;
   $product->save();
   //now for the spanish store
   //get the id of the product you just created
   $productId = $product->getId();
   //load the product in the ES store
   $esProduct = Mage::getModel('catalog/product')->setStoreId(2)->load($productId);
   //set the values you need
   $esProduct->setName('name in es');
   //....
   $esProduct->save();
}
catch (Exception $e) {
    //do something if there is an error
}

An other faster way of doing it is, after adding the product with the default values, just update certain attributes that are different in ES.
So the first part is the same
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
try{
   $product
      //set all attributes here as you already do
      //....
   ;
   $product->save();
   //now for the spanish store
   //get the id of the product you just created
   $productId = $product->getId();

   //now update the attribute for ES.

   Mage::getSingleton('catalog/product_action')->updateAttributes(
       array($productId), //an array with the id you get from above
       array(  //array with all the attributes to update 'key'=>'value'
           'name' => 'Name in Es',
           'description' => 'Description in Es',
           ....
       ),
       2 //the id of the ES store
   );
catch (Exception $e) {
       //do something when an exception occurs.
}


text:
Q: What does 'of what' mean here? Just look at this sentence:

Numerous studies have been done of what a subject can extract from a brief visual presentation.

I am not sure how I should understand 'of'. I know it's a preposition but, if it is used before 'what', how should I understand it?
Can I use 'about' instead of 'of':

"Numerous studies have been done about what a subject can extract from a brief visual presentation?

A: This is just poor academic style. It means:

*

*There are many studies which investigate the following question: what can subjects extract from brief visual presentations?

But the style is poor, for various reasons. I would write:

*

*Many studies have investigated the question of what subjects can extract from brief visual presentation [of stimuli].

The 'academically correct' preposition with study here would be on, not of. Note the difference:

*

*The study of zoology; the study of language

*A study on the guttural phonemes of Yemenite Hebrew; a study on genetic mutations in seahorse

A: "On" would be more idiomatic here instead of "of." Either way, it does mean "about," but "studies about" is also not as idiomatic as "studies on."


text:
Q: Why will one loop modify a list of lists, but the other won't One of the answers in "python way" to parse and conditionally replace every element in 2D list
has revealed to me that I understand even less than I thought.
Given a list of lists containing strings:
myLists = [['5','cat','23'],
           ['33','parakeet','scalpel'],
           ['correct','horse','battery','staple','99']]

I wish to replace each element with the return of:
def numParser(string):
    try:
        return int(string)
    except ValueError:
        return string

My original code was this, but it does not modify the original array. I assumed because list is a copy, not the actual list (am I wrong?):
for single_list in myLists:
    single_list = map(numParser, rawData)

And one of the answers which modifies the lists in place is:
for single_list in myLists:
    for i, item in enumerate(single_list):
        single_list[i] = numParser(item)

Why does the second solution work but not the first?

A: This statement:
single_list = ...

assigns a value to the local variable named single_list.  It does not have any effect on any other data.
The statement:
single_list[i] = ...

modifies the value of the object referenced by the local variable named single_list, specifically it sets the value of a particular element of the list.

A: for list in myLists:
    list = map(numParser, rawData)

The loop assigns "list" as a variable which references the list in myLists. when you reassign the "list" variable it now points to a new list, but the list in used to reference in "myLists" is unchanged. (Also, you shouldn't use "list" as a variable name as it is a Python keyword).
In the second example you do overwrite the reference to the list in myLists, so it alters myLists.

A: In your first example you are assigning a new list to the name "single_list", in the second example you are modifying the list referenced by single_list.


text:
Q: Reading BLOB image from MySQL database in spring mvc I'm having some trouble reading a blob back from a MySQL database. I've gotten it to successfully insert into the database, but can't seem to get it to read back. I know some of you might be thinking "why is he using a database to store blobs for images, and not just the file paths / file names", but i want to have flexibility and as a lot of these images will be stored on a server and not locally, this optimises efficiency, as well as allowing me to move images to local if needed. I've followed a (short) tutorial and have written this following method for recieving a blob.
the below is my domain class:
    @Entity
      @Table(name="PROFILE")
     public class Profile implements Serializable{

           private static final long serialVersionUID = 3641L;

          @Id
       @Column(name="PROFILE_ID")
            @GeneratedValue(strategy=GenerationType.AUTO)
       private int profileId;

      @OneToOne
      @JoinColumn(name="CUSTOMER_ID")
      private Customer customer;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "ADDRESS")
    private String address;

    @Column(name = "CONTACT_NUMBER")
    private String contactNumber;

    @Column(name = "PROJECT_NAME")
    private String projectName;

        @Column(name="CONTENT")
    @Lob
    private Blob content;

    @Column(name="filename")
      private String filename;

    @Column(name="content_type")
      private String contentType;
   //getters and setter
             }

this is my controller:
        @RequestMapping(value="/myProfile.htm", method=RequestMethod.GET)

    public ModelAndView Profilelist(HttpServletRequest request,ModelMap model,Customer
    customer,Profile profile, HttpServletResponse response) throws SQLException ,
    Exception{
    //Profile profile = new Profile();

    String customerName = request.getUserPrincipal().getName();

    customer = customerService.getCustomerId(customerName);
    profile = profileService.getBycustomerId(customer);
    System.out.println("cust:  "+ customer);
    System.out.println("profile:  "+ profile);
    logger.error("Viewing Profile" +customerName);
    //Customer customer = new Customer();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    byte[] encodeBase64 = Base64.encodeBase64(buf);
    String base64Encoded = new String(encodeBase64, "UTF-8");
    ModelAndView mav = new ModelAndView();
    mav.addObject("profile", base64Encoded);
    //Blob blob = profile.getContent();

    customer.setEmailId(customerName);
    profile.setCustomer(customer);
    //profile.setContent(blob);
    System.out.println();
    profile = profileService.findProfileById(customer);
    model.addAttribute("content",base64Encoded);

    model.addAttribute("profile", profile);
    mav = new ModelAndView("myProfile");
    return mav;

   }

here am unable to set the bytes to my profile.setContent...... please give any solution to get rid of my issue

A: You should not do it in the controller, from the docs

By default drivers implement Blob using an SQL locator(BLOB), which
  means that a Blob object contains a logical pointer to the SQL BLOB
  data rather than the data itself. A Blob object is valid for the
  duration of the transaction in which is was created.

What you should do instead, if you need an access to your byte array, is create a JPA transient property in your Profile class, e.g. something like
  @Transient byte[] image; // do add getters and setters

and set the byte array to that property. Transient properties are ignored by your persistence mechanism.
UPDATE with respect to the comment
Since the intention is to show the picture in jsp, you can go two ways, first one, is to store as file at a web accessible location and simply point to it from a src element, but I understand from your question that this is not what you need.
Second option is to render an image as a sequence of bytes, but in order to do so you first must encode your byte array into a Base64 encoded String. Here's an example
To show the image on JSP without storing to filesystem and linking to it, you'll have to do a Base64 encoding of the byte array. Change your controller method to
@RequestMapping(value="/myProfile.htm", method=RequestMethod.GET)
public String Profilelist(HttpServletRequest request,ModelMap model,Customer
        customer,Profile profile, HttpServletResponse response) throws SQLException ,
        Exception{
    //Profile profile = new Profile();

    String customerName = request.getUserPrincipal().getName();

    customer = customerService.getCustomerId(customerName);
    profile = profileService.getBycustomerId(customer);
    System.out.println("cust:  "+ customer);
    System.out.println("profile:  "+ profile);
    logger.error("Viewing Profile" +customerName);
    //Customer customer = new Customer();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    Blob blob = profile.getContent();
    InputStream in =  blob.getBinaryStream();
    System.out.println("id content" +in);
    int n = 0;
    while ((n=in.read(buf))>=0)
    {
        baos.write(buf, 0, n);

    }

    in.close();
    byte[] bytes = baos.toByteArray();
    System.out.println("bytes" +bytes);
    byte[] encodeBase64 = Base64.encodeBase64(buf);
    String base64Encoded = new String(encodeBase64, "UTF-8");

    customer.setEmailId(customerName);
    profile.setCustomer(customer);
    //profile.setContent(blob);
    System.out.println();
    profile = profileService.findProfileById(customer);
    model.addAttribute("content",base64Encoded);
    model.addAttribute("profile", profile);
    return "myProfile";
}


text:
Q: SAS Proc Freq Not Displaying Values I am doing some simple cross tabulations using Proc Freq, but I'm noticing that the output SAS gives me doesn't contain any frequency counts; I'm only getting percents.
Here is an example code that I ran in SAS (I am using SAS 9.4):
data test;
  input year 1-5 group $6;
cards;
2018 A
2018 A
2018 B
2018 B
2019 A
2019 A
2019 A
2019 B
;
run;

proc freq data = test;
  table year * group / norow nopercent;
run;

I'm expecting a table that has the frequency counts with the column percentage below, but instead, this is what SAS is giving me:

Does anyone know how I can get the frequency values to be shown?

A: I ran your code and got this.  I reckon there is something you are not telling us.

A: Thank you all for your help- I found the issue.  It looks like there was an issue with the cross-tab frequency template that came with SAS.  I was able to restore it by using the following code:
proc template;
    delete base.freq.crosstabfreqs;
run;

Thank you all for your help!

A: @_null_ your image is NOT the output I get when running the questions code.
The Frequency and Col Pct are NOT in row header cells, and instead are shown in a box offset to the left from the table.


text:
Q: Dotfuscator renaming File version and product version as blank Dotfuscator tool renaming "file version" and "product version" as blank after obfuscation.
Can we exclude these attributes from renaming?
The tool being used - https://www.preemptive.com/products/dotfuscator/[dotfuscator][1]

A: I had the same issue, so I reached out to support and they told me to add these lines in the properties section:
<propertylist>
        <property name="ILDASM_v4.0" value="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\ildasm.exe"/>
        <property name="ILASM_v4.0" value="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ilasm.exe"/>
</propertylist>

That was the solution in my particular case - hope it helps you.


text:
Q: Mobile navigation bar Issue with jQuery I'm working on mobile navigation bar with jQuery. I have a slight issue the jQuery works perfectly with the mobile navigation bar, but when I resize my screen to desktop the desktop navigation disappears.
jQuery(document).ready(function() {
  jQuery(".navtoggle").click(function() {
    jQuery(".nav-menu").slideToggle();
  });
});

Mobile Breackpoints SASS
@include breakpoint(xxxs) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        margin: 20px 0px;
        display: block;
      }
    }
  }

 @include breakpoint(xxs) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        height: auto;
        margin: 20px 0px;
        display: block;
      }
    }
  }

@include breakpoint(xs) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        height: auto;
        margin: 20px 0px;
        display: block;
      }
    }
  }

@include breakpoint(sm) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        height: auto;
        margin: 20px 0px;
        display: block;
      }
    }
  }

@include breakpoint(table) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        height: auto;
        margin: 20px 0px;
        display: block;
      }
    }
  }

 @include breakpoint(md) {

  header {
    nav {

      ul {
        background: #6c49b8;
        li {
          display: block;
          border-bottom: 1px solid rgba(0,0,0,.1);
          border-left: none;
          border-right: none;
          padding: 15px;
          &:last-child {
            border-left: none;
            border-right: none;
          }
        }

      }

      .sub-menu  {
        position: relative;
        top: 0;
        padding: 0px;
        background-color: #563a92;
        z-index: 1;
      }
    }
  }

    .second-navbar {
      #open {
        height: auto;
        margin: 20px 0px;
        display: block;
      }
    }
  }

A: I'll try to answer this without seeing your HTML, but if your navigation is the same .nav-menu element on mobile as it is on desktop, then I'd guess that this is happening because you're toggling your navigation from hidden to visible with your jQuery function. So if you resize once the navigation is hidden, it'll be hidden on desktop as well.
You can make sure that your desktop navigation is always visible by using a media query such as @media (min-width: 768px) where your .nav-menu display is explicitly set to block. (Potentially set to display:block !important;
That way, no matter what a user did with your mobile toggle button, the browser knows that any time your screen width is over 768px, show the navigation.


text:
Q: Javascript code to show and destroy bootstrap popover not performing as intended I've created a function createPopover() that is being used to create a popover over an element as follows:
function createPopover(destination, content){
    var popoverTemplate = ['
',
            '

',
            '
',
            '
',
            '
'].join('');
    destination.popover({
        template: popoverTemplate,
        content: content,
        html: true,
        placement:'top',
        trigger: 'manual'
    });
    destination.popover('show');
}

It is called as follows:
createPopover($('.drop-time-text'), 'Please select a drop off time');

I've also written a destroy popover function that destroys all popovers on the page present or not
function destroyPopover(destination){
    $('.styled-select-car').popover('destroy');
    $('.pick-date-text').popover('destroy');
    $('.pick-time-text').popover('destroy');
    $('.drop-date-text').popover('destroy');
    $('.drop-time-text').popover('destroy');
}

These are being used in a basic validation process as follows:
if(pickUpDate == ''){
    destroyPopover(); //All popovers removed before creating a new one
    createPopover($('.pick-date-text'), 'Please select a pick up date');
    return false;
}

where pickUpDate = $('.pick-date-text').val().
While debugging the code proceeds in the expected manner but in the UI, the popover appears on first click but flickers and dies on the second click of the validation button. I'm not quite sure as to why this is happening.


text: Q: Saving data on Android for data visualization I'm creating an app where I'm going to be storing data that the user enters. Let's say for instance it's someone weight. I have created an SQLite database that is able to store this information. However, I want the user to be able to update the value if the weight changes, but I don't want to lose the previous data. Would I have to create a separate database to store this past information? Or is there a more effective approach? Thanks for your time.


text:
Q: Trouble finding hidden email from a webpage Although the webpage doesn't display any email addresses, running my scraper I can fetch that on the console but it comes up cluster documents. Is there any way to keep only email and phone number out of the set of documents? Here is what i am up to:
import requests
from lxml import html

def Mainpage():
    url = "https://www.houzz.de/professionals/c/Deutschland"
    response = requests.get(url)
    tree = html.fromstring(response.text)
    titles = tree.xpath('//div[@class="name-info"]')
    for title in titles:
        Name=title.xpath('.//a/@href')[0]
        FindindEmail(Name)

def FindindEmail(pagelink):
    response = requests.get(pagelink)
    tree = html.fromstring(response.text)
    titles = tree.xpath('//div[@class="professional-info-content"]/text()')
    for title in titles:
        print(title.strip())

Mainpage()

Here is what is being scraped:

A: Found the solution finally:
import requests
from lxml import html

def Mainpage():
    url = "https://www.houzz.de/professionals/c/Deutschland"
    response = requests.get(url)
    tree = html.fromstring(response.text)
    titles = tree.xpath('//div[@class="name-info"]')
    for title in titles:
        Name=title.xpath('.//a/@href')[0]
        FindingEmail(Name)

def FindingEmail(pagelink):
    response = requests.get(pagelink)
    tree = html.fromstring(response.text)
    titles = tree.xpath('//div[@class="professional-info-content"]/text()')
    for title in titles:
        if "E-Mail:" in title or "Fax:" in title:
            print(title)

Mainpage()


text:
Q: Getting see through ribbons on time-series in R So I have been trying to get semi-sheer ribbons onto a time-series plot. I have done the same for bar-plots using ggplot which was pretty effective BUT due to the size of the data I am working with for the time-series I can't type it out into a dataframe (working from a microsoft excel comma separated values file loaded into R).
So looking to either be able to convert this to a dataframe OR plot semi-sheer blocks onto it.
Code and associated error messages below.
plot(Nitrate_Interp~RiverWensum$Rdates, type="l", xlab="Time", ylab="Nitrate (mg N L)", las=1,
col="black")
rect((RiverWensum$Rdates)-1,lower_yNr,(RiverWensum$Rdates)+1,upper_yNr, density=30, col="#FF000080",
border="red")
#defining the colour
mycol <- rgb(225,0,0,max=225,alpha=125,names="red.5")
mycol
red.5 = "#FF000080"
#error given when script run:
Error in rgb(255, 0, 0, max = 220, alpha = 125, names = "red50") :
colour intensity 1.15909, not in [0,1]

Thanks inn advance

A: The rgb() function has a setting of maxColorValue, not max, which you should set to your chosen max value (though it seems to work and doesn't seem to be your problem). Looking at the error:
Error in rgb(255, 0, 0, max = 220...

...your max is less than your red value too so it will not work. 255/220>1


text:
Q: Incomplete JSON response data I am trying to download instagram stories using HttpUrlConnection ans even tried Jsoup and volley.
But it returns incomplete json response data.
Api call code
        URL url = new URL("https://i.instagram.com/api/v1/feed/reels_tray/");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("GET");
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);
        con.setRequestProperty("User-Agent", "Instagram 219.0.0.12.117 Android");
        con.setRequestProperty("Cookie", MainActivity.cookies);

Reading from InputStream
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String temp = "";

        while((temp=br.readLine()) != null)  sb.append(temp +"\n");

        Log.i("-------data--------", sb.toString());

Response
2022-04-28 21:36:58.716 6283-6396/com.example.storyviewer I/reel_tray_data: {"tray":[{"id":44236909635,"latest_ ... scans_profile":"e15"},{"width":150,"height":

I used ellipses in between, but the end is abrupt with incomplete datavalues and incomplete brackets.


text:
Q: First DNS Lookup always fails I'm having a very weird problem with a new Windows 10 Pro build using an intel I219-v adapter (integrated into the mobo). Every time a DNS lookup occurs, either in a browser or triggered manually via command prompt, the first request times out and then the next resolves properly. I only have the two google servers (8.8.8.8 and 8.8.4.4) configured as dns servers in the adapter settings and configured on the router (Tried both manual and automatic discovery). From what I can see the wireshark capture looks normal. I've been tearing my hair out all day as it completely ruins the browsing experience on the computer.
Below are some screenshots illustrating the problem:
Chrome
nslookup
wireshark: http:// i.stack.imgur.com/ETpTa.png

A: You can try all possible fixes:

*

*Try disabling malwarebytes/firewall

*Try resetting DNS client

*Try flushing DNS cache

*Remove IPv6 option under particular connection

Sometimes i faced few strange issue,

*

*Skype was working fine, but, i was not able to browse in browsers due to dns issue.  so it worked when cleared all temp files.

*When i connect with different internet connections, for example, 3G, broadband, that time i faced issues.  For that, i installed one utility to flush DNS in all connections quickly.

Try one by one and see if you can solve the issue.

A: I'm thinking about the OSI model.

Working from the bottom up, it sounds like you have the physical, data link, and network layers in check as demonstrated with the wireshark image. Application appears fine. My guess is that something might be happening between Transport-Presentation. As someone said, disabling anti-virus might solve between the presentation and application layers. If connected to a VPN, do you still have the same problem? Do you have more than 1 network adapter? Windows 10 will send DNS requests to all available adapters and it might be incorrectly choosing one.

A: I would try to flush the dnscache:
Open a cmd:
ipconfig/flushdns


text:
Q: How to get all the values in a Select2 dropdown? How can we get all the elements that are in the jQuery Select2 dropdown plugin.
I have applied Select2 to a input type = hidden, and then populated it using Ajax.
Now at one instance I need to get all the values that are appearing in the dropdown.
Here is a input field.
<input type="hidden" id="individualsfront" name="individualsfront" style="width:240px" value="" data-spy="scroll" required />

and to this input field I have applied this
$("#individualsfront").select2({
    multiple: true,
    query: function (query){
        var data = {results: []};
        $.each(yuyu, function(){
            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                data.results.push({id: this.id, text: this.text });
            }
        });
        query.callback(data);
    }
});

The yuyu is a json coming from some AJAX call and populating the Select2.
Now I want in some other code a way to get all the values inside the Select2.

A: I was trying to figure this out myself and found that you can get at least the options in a select2.
var options = $("#dropdown").find("option")
var optionsText = $("#dropdown").find("option[value='1']").text()

A: option 1: you can use directly the data object
var results = [];
$("#individualsfront").select2({
    multiple: true,
    query: function (query){
        var data = {results: []};
        $.each(yuyu, function(){
            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                data.results.push({id: this.id, text: this.text });
            }
        });

        results = data.results; //<=====
        query.callback(data);
    }
});

and use it like this for example:
$('#individualsfront').on('open',function(){
    $.each(results, function(key,value){
        console.log("text:"+value.text);
    });
});

option 2: request the feature and use (temporary) something like:
$('#individualsfront').on('open',function(){
    $(".select2-result-label").each(function()
        {
            console.log($(this).text());
        })
    });
});

http://jsfiddle.net/ouadie/qfchH/1/

option 3: you can use .select2("data"); but it returns all elements only if there is no selected element.
var arrObj = $("#individualsfront").select2("data");
for each(yuyu in arrObj)
{
   console.log("id: "+yuyu.id+ ", value: "+yuyu.text);
}

A: function select2Options($elementSelect2) {
    var data = [],
        adapter = $elementSelect2.data().select2.dataAdapter;
    $elementSelect2.children().each(function () {
        if (!$(this).is('option') && !$(this).is('optgroup')) {
            return true;
        }
        data.push(adapter.item($(this)));
    });
    return data;
}


text:
Q: How to turn a string of numbers being stored in SQL back into integers in Python? So I've got "1,5,12" stored as a string in a SQL database, I've managed to get the string into python using cursor.fetchone etc.
How do I separate this "1,5,12" string into say an array of integers? If possible I want to be able to call the individual integers as indexes in an array.

A: Use a list comprehension and str.split:
data = "1,5,12"
example_list = [int(x) for x in data.split(',')]

A: Suppose you string was stored in a variable, you could do something like this;
data_result="1,5,12"
int_result=list(map(int,data_result.split(",")))

A: You can split() your string on the commas, to get a list of strings. These can then be turned to integer numbers using the int() function inside a list comprehension.
To catch conversion errors, this can be wrapped in a try ... except block, especially if the original string comes from external/user input.
Example:
string_of_ints= "1,5,12"
try:
    list_of_ints = [int(x) for x in string_of_ints.split(",")]
except ValueError:
    print("Value Error")

This yields:
[1, 5, 12]

A: First split the string into a list using the , delimiter mylist.split(','). Then convert each member of that list into an integer. You now have a list of integers.
Use a list comprehension:
results = [int(i) for i in results]

e.g.

mylist = ['1, 2, 3']
      results = mylist.split(',')
      results = [int(i) for i in results]
      results
          [1, 2, 3]

A: Use ast.literal_eval:
>>> from ast import literal_eval
>>> s = '1,5,12'
>>> literal_eval(s)
(1, 5, 12)

>>> list(literal_eval(s))
[1, 5, 12]


text:
Q: Rails geocoder near I want to return a list of job postings that are near a location (based on [latitude, longitude]). I am using geocoder and it seems to be working. I can import a CSV file with a list of addresses and geocoder populates the latitude and the longitude columns.
But I can't seem to get the near or nearby functions to work. It returns a undefined method error. I've tried following this: Rails Geocoder - Still learning which explains that nearby is a model function. But the example there did not work for me either.
This is what I have in my show.html.erb:
<%= @jobposting.latitude %>, <%= @jobposting.longitude %>

40.7494011, -73.9389437
<% @location = Jobposting.near([@jobposting.latitude, @jobposting.longitude], 150) %>
<%= @location.inspect %>

It does not error but returns a empty array: #<ActiveRecord::Relation []> when there are points within 10 miles of the latitude and longitude.
I'm unsure if I am calling it incorrectly, based on the documentation it looks like near is used with the model but not limited to calling it in the model.

A: As a partial answer, I believe the method is nearbys, not nearby. That might explain the undefined method error you mentioned. I don't know why you aren't getting results for the near function. The code you posted for the near method looks okay to me.


text:
Q: How to pass and access a slice of struct and a struct in template I have a struct type Topic:
type Topic struct {
Forum_id  int
Topic_id  int
Author    string
Title     string
Sub_Title string
Body      string
}

And a Slice of type Replay:
type Replay struct {
Replay_ID int
Topic_ID  int
Author    string
Body      string
}

And I need to pass that data into a template, how should I do to pass it with only one variable? And then how should i access it in my template?

A: Create a wrapper struct or use a map. For example
type templateData struct {
  Topic Topic
  Replays []Replay
}

err := t.Execute(os.Stdout, templateData{topic, replays})

In your template, you can access both with their field name.
{{ .Topic.Title }}
{{ range .Replays }}
{{ .Body }}
{{ end }}


text:
Q: how to change react native android picker background

All of them work except the background, but I couldn't get the background color to work. All I want is #000 for the background, but no matter what I tried, colorBackround popupBackround etc. I tried all of them but it didn't work. Everyone on the internet gave the same link. I've been trying for about 5 6 hours, but I couldn't change the background color.
 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:forceDarkAllowed">false</item>
    <item name="android:navigationBarColor">#151617</item>
    <item name="android:windowBackground">#151617</item>
    <item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
    <item name="android:spinnerItemStyle">@style/SpinnerItem</item>
    <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
</style>

<style name="SpinnerItem" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textSize">18dp</item>
</style>

<style name="SpinnerDropDownItem" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:textColor">#ffffff</item>
    <item name="android:textSize">18dp</item>
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:gravity">center</item>
    <item name="android:background">#000</item>
</style>

<item name="android:background">@drawable/mydivider</item> // I tried that too, it didn't work

When I run it like this, all items are centered, a white page comes up background white texts white what I want is black background white text

A: Your background custom code seems to be in the wrong place.

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:forceDarkAllowed">false</item>
    <item name="android:navigationBarColor">#151617</item>
    <item name="android:windowBackground">#151617</item>
    <item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
    <item name="android:spinnerItemStyle">@style/SpinnerItem</item>
    <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
</style>

<style name="SpinnerItem" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textSize">18dp</item>
</style>

<style name="SpinnerDropDownItem" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:textColor">#ffffff</item>
    <item name="android:textSize">18dp</item>
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:gravity">center</item>
    <item name="android:background">#000</item>
    <item name="android:background">@drawable/mydivider</item> // here
</style>


text:
Q: Is every closed simply connected manifold a non-trivial covering space? We know that every universal covering space is simply connected. The converse is trivially true, every simply connected space is a covering space of itself. But I'm wondering what simply connected spaces, specifically manifolds, are covering spaces of another (connected) space other than itself.
I found this paper that shows that there exist certain contractible open simply connected manifolds that aren't non-trivial covering spaces of manifolds. If we restrict to closed simply connected manifolds, can we also find such examples, or can there always be a different manifold that it covers?

A: The manifold $\mathbb{CP}^2$ is not the universal covering space of any manifold other than itself.
One way to see this is to note that if $M \to N$ is a $d$-sheeted covering of closed manifolds, then $\chi(M) = d\chi(N)$. As $\chi(\mathbb{CP}^2) = 3$, we see that $d = 1$, in which case $N = \mathbb{CP}^2$, or $d = 3$. If a three-sheeted covering were to exist, the manifold $N$ would satisfy $\pi_1(N) \cong \mathbb{Z}_3$ (as this is the only group of order $3$). As $\mathbb{Z}_3$ has no index two subgroups, the manifold $N$ is orientable. But then the signature of $N$ satisfies $1 = \sigma(\mathbb{CP}^2) = 3\sigma(N)$ which is impossible, so the only manifold which is covered by $\mathbb{CP}^2$ is itself.
More generally, the connected sum of $k$ copies of $\mathbb{CP}^2$ does not cover any manifold other than itself. The argument above for orientability of the quotient doesn't apply when $k$ is even, instead you can use the argument in this answer (which works for any $k$).

A: A closed simply connected $n$-manifold for $n = 2, 3$ is a sphere, so the smallest example occurs in dimension at least $4$. In dimension $4$ we can show that $\mathbb{CP}^2$ doesn't cover another manifold. There are two nice arguments given in the answers to this math.SE question, which I'll briefly sketch:

*

*Using the Lefschetz fixed point theorem, we can show that every diffeomorphism $f : \mathbb{CP}^2 \to \mathbb{CP}^2$ has a fixed point. It follows that $\mathbb{CP}^2$ does not admit a free action by any nontrivial group. This argument generalizes to all $\mathbb{CP}^{2k}$.

*$\chi(\mathbb{CP}^2) = 3$, so a nontrivial space that $\mathbb{CP}^2$ covers can only have $\chi(X) = 1$. This space must be a quotient by some action of $\mathbb{Z}/3$ and so has $\pi_1(X) \cong \mathbb{Z}/3$, which implies that $H^1(X, \mathbb{F}_2) = 0$ and hence that $X$ is orientable. But this implies $b_4 = 1$ so $\chi(X) \ge 2$; contradiction. This argument generalizes to $\mathbb{CP}^{2k}$ whenever $2k+1$ is prime.
It's worth noting the way in which both of these arguments fail for the spheres $S^n$ (which cover the real projective spaces $\mathbb{RP}^n$): 1) Lefschetz shows that a diffeomorphism can be fixed-point-free if it acts by $(-1)^{n+1}$ on $H_n$, which the antipode map does, and 2) $\chi(S^n) = 1 + (-1)^n$ so when $n$ is odd we only learn that a covered space also has $\chi = 0$ (true of e.g. the lens spaces) and when $n$ is even we learn that a nontrivial covered space has $\chi = 1$, $\pi_1 = \mathbb{Z}_2$ and can't be orientable, which is consistent, and true of $\mathbb{RP}^n$.
I also want to note that unlike the classification of covering spaces, which is purely homotopy-theoretic in that it only depends on $\pi_1$, the classification of covered spaces depends delicately on homeomorphism type. For example a point doesn't cover anything nontrivially but $\mathbb{R}$ does. In fact for every group $G$ and every simply connected space $X$ we can find a homotopy equivalent space $X'$ which covers a space with $\pi_1 \cong G$. So studying covered spaces is genuinely a point-set topological question.

A: Below, I'll give an example which, as a topological manifold can non-trivially cover, but as a smooth manifold it cannot.
Recall that in each dimension, the set of diffeomorphism types of $S^n$ forms an abelian group under the connect sum operation, where the inverse to an element is given by switching the orientation.
Elements of order $2$ in this group are precisely the exotic spheres which admit an orientation reversing diffeomorphism.
In dimension $10$, the group of exotic spheres has order $6$.  By Cauchy's theorem, there is an element $\Sigma$ of order $3$.  In particular, such a $\Sigma$ does not admit an orientation reversing diffeomorphism.
It follows from an easy application of the Lefschetz fixed point formula that any orientation preserving diffeomorphism $f:\Sigma\rightarrow \Sigma$ must have a fixed point.  Thus, $\Sigma$ cannot smoothly cover anything.
On the other hand, $\Sigma$, being homeomorphic to $S^{10}$ can topologically cover $\mathbb{R}P^{10}$.


text:
Q: Reference Request: Differential Graded Hopf Algebras To prepare an upcoming seminar talk I'm trying to find introductory texts on differential graded Hopf algebras (over a field $k$).
My knowledge of Hopf algebras encompasses roughly the first 5 chapters of Sweedler's book.
I also have a rough idea of how to define dg-Hopf algebras, namely by the same diagrams as an ordinary Hopf algebra but with dg-vector spaces instead of just vector spaces (i.e. as "Hopf objects" in the monoidal category of dg-vector spaces).
I'm thus looking for references that do the following:

*

*Providing an explicit definition of dg-Hopf algebras and showing their fundamental properties.

*Giving (basic) examples for dg-Hopf algebras.

*Explaining the differences and similarities between ordinary Hopf-algebras and dg-Hopf algebras.

*(Giving me a way to check my thoughts and suspicions.)

I was originally given [1] and [2] as references (the last of which is also given on the nlab) but [1] only really deals with ordinary Hopf algebras and [2] doesn't seem to provide introductory material.
I already found [3], which provides some background on dg-algebras, -coalgebras and -Lie algebras, but only little on dg-bialgebras and nothing on dg-Hopf algebras.
[1]: Loday, Cyclic Homology, Appendix A
[2]: Quillen, Rational Homotopy Theory, Appendix B
[3]: Félix, Halperin, Thomas, Rational Homotopy Theory, Chapters 3,21

A: I cannot give you a reference better than "wikipedia definition of Hopf algebra in a braided category" and it specialization to the braiding $v\otimes w\mapsto (-1)^{|v||w|}w\otimes v$. But I can give you the first elementary and nontrivial example of d.g. Hopf algebra that is not a Hopf algebra in the usual sense:
Fix a field of characteristic not 2 and $H=k[x]/x^2$. Then $H$ is not a Hopf algebra, because it is commutative and has nontrivial nilpotent elements. On the other hand, it is a d.g. Hopf algebra with $|1|=0$, $|x|=1$ and $d(x)=1$, simply defining
$$\Delta(x)=x\otimes 1 +1\otimes x$$
The reason is that, if you define $\Delta$ as above, the way you extend it to $k[x]$ in the d.g. setting is considering the algebra structure in $k[x]\otimes k[x]$ given by
$$(x^n\otimes x^m)\cdot (x^i\otimes x^j)=(-1)^{im}x^{n+1}\otimes x^{n+j}$$
With this structure, the element $x^2$ mapsto
$$(x\otimes 1+1\otimes x) ^2 =x^2\otimes 1+x\otimes x -x\otimes x+1\otimes x^2=x^2\otimes 1+1\otimes x^2$$
(and not to $x^2\otimes 1+2x\otimes x+1\otimes x^2$)
So, the "super sign" makes the job so that the ideal $(x^2)$ is also a coideal, and hence $\Delta:k[x]/x^2\to k[x]/x^2\otimes k[x]/x^2$ is a well-defined algebra map, when considering $k[x]/x^2\otimes k[x]/x^2$ as algebra using the Koszul signs.

A: I would suggest to start from Peter Schauenburg's Differential-Graded Hopf Algebras and Quantum Group Differential Calculi. He is used to be pretty clear, at least for those who like category theory. The references therein may be a further source.


text:
Q: In ANTLR 3, how do I generate a lexer (and parser) at runtime instead of ahead of time? I want to generate an antlr lexer at runtime -- that is, generate the grammar and from the grammar generate the lexer class, and its supporting bits at runtime. I am happy to feed it into the the java compiler, which is accessible at runtime.

A: Here's a quick and dirty way to:

*

*generate a combined (!) ANTLR grammar .g file given a String as grammar-source,

*and create a Parser & Lexer from this .g file,

*compile the these Parser & Lexer .java files,

*create instances of the Parser & Lexer classes and invoke the entry point of the parser.

Main.java
import java.io.*;
import javax.tools.*;
import java.lang.reflect.*;
import org.antlr.runtime.*;
import org.antlr.Tool;

public class Main {

    public static void main(String[] args) throws Exception {

        // The grammar which echos the parsed characters to theconsole,
        // skipping any white space chars.
        final String grammar =
                "grammar T;                                                  \n" +
                "                                                            \n" +
                "parse                                                       \n" +
                "  :  (ANY {System.out.println(\"ANY=\" + $ANY.text);})* EOF \n" +
                "  ;                                                         \n" +
                "                                                            \n" +
                "SPACE                                                       \n" +
                "  :  (' ' | '\\t' | '\\r' | '\\n') {skip();}                \n" +
                "  ;                                                         \n" +
                "                                                            \n" +
                "ANY                                                         \n" +
                "  :  .                                                      \n" +
                "  ;                                                           ";
        final String grammarName = "T";
        final String entryPoint = "parse";

        // 1 - Write the `.g` grammar file to disk.
        Writer out = new BufferedWriter(new FileWriter(new File(grammarName + ".g")));
        out.write(grammar);
        out.close();

        // 2 - Generate the lexer and parser.
        Tool tool = new Tool(new String[]{grammarName + ".g"});
        tool.process();

        // 3 - Compile the lexer and parser.
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, System.out, System.err, "-sourcepath", "", grammarName + "Lexer.java");
        compiler.run(null, System.out, System.err, "-sourcepath", "", grammarName + "Parser.java");

        // 4 - Parse the command line parameter using the dynamically created lexer and
        //     parser with a bit of reflection Voodoo :)
        Lexer lexer = (Lexer)Class.forName(grammarName + "Lexer").newInstance();
        lexer.setCharStream(new ANTLRStringStream(args[0]));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        Class<?> parserClass = Class.forName(grammarName + "Parser");
        Constructor parserCTor = parserClass.getConstructor(TokenStream.class);
        Parser parser = (Parser)parserCTor.newInstance(tokens);
        Method entryPointMethod = parserClass.getMethod(entryPoint);
        entryPointMethod.invoke(parser);
    }
}

Which, after compiling and running it like this (on *nix):
java -cp .:antlr-3.2.jar Main "a b    c"

or on Windows
java -cp .;antlr-3.2.jar Main "a b    c"

, produces the following output:

ANY=a
ANY=b
ANY=c

A: You'll have to use org.antlr.Tool() class to get it working.
You can check ANTLRWorks source code on github to have an idea how to use it, specifically the generate() method here:
ErrorListener el = ErrorListener.getThreadInstance();
ErrorManager.setErrorListener(el);

String[] params;
if(debug)
    params = new String[] { "-debug", "-o", getOutputPath(), "-lib", window.getFileFolder(), window.getFilePath() };
else
    params = new String[] { "-o", getOutputPath(), "-lib", window.getFileFolder(), window.getFilePath() };

new File(getOutputPath()).mkdirs();

Tool antlr = new Tool(Utils.concat(params, AWPrefs.getANTLR3Options()));
antlr.process();

boolean success = !el.hasErrors();
if(success) {
    dateOfModificationOnDisk = window.getDocument().getDateOfModificationOnDisk();
}
lastError = el.getFirstErrorMessage();
el.clear();
ErrorManager.removeErrorListener();
return success;

A: Have you tried calling org.antlr.Tool.main(String[]) with an appropriate String[] argument?
If that's too cumbersome, you could reverse engineer the Tool class (source code) to figure out how it works, and how to do the specific tasks you need to do.


text:
Q: SVG infinite animation lead to memory increase and high CPU utilization I made a simple demo, it only has three same svg tags with css3 animation, when run it on chrome ( version: 52.0.2743.116 (64-bit)) in windows, it turns out memory leaks when running for a while, here is the snapshot, the task manager shows memory increases!!!

I also test on the Mac, the result shows: not only memory increase, but also high cpu occupancy.

the demo is so simple, I can't find some where wrong, does someone has meet such problem? Thanks?
the svg code is here:
<svg class="line-1" xmlns="http://www.w3.org/2000/svg" width="224" height="73.969" viewBox="0 0 224 73.969">
  <path class="cls-1" d="M635,413H779c9.5,0,18.685,1.462,26,10s51,59,51,59" transform="translate(-633.5 -411.5)"/>
</svg>