Is there a way to display html 5 web pages into android/ios app?

Question: I have a website which needs authentication. Each user can have some personalized graphics. I am looking for a way to create an app which displays the graphics for a particular user when he logs in using the app. Is there an existing solution for this which I can OEM to create my app.
Comment: Welcome to StackOverflow! Your question is not very clear, please consider editing it to include a specific problem (This line of code should do that but instead, I get that, why?). [This help article](https://stackoverflow.com/help/how-to-ask) might help you with that.
Answer: As I said in my comment, your question is very broad. Generally speaking, an app can display any web page using a WebView.
Comment: Thanks for you reply! I am looking more into an existing solution, like an app which can be customized. Or any other easy way rather than creating a new app.
Comment: It strongly depends on your needs. As I said, displaying a web page itself is a very simple task but I guess that this won't be the only thing that you need, right? If the webpage is the only thing, then why not leave it a webpage and just have the users open Chrome/Safari and use the web page?
Comment: However, I strongly encourage you to ask this question in the [java chat](https://chat.stackoverflow.com/rooms/139/java) once you have enough reputation as such broad questions are likely to be closed.
Comment: The web pages have some graphic data which is useful for our customers. It's just the ease of opening an app over a web page. Thanks for your reply!


Why are my functions executing in the wrong order?

Question: I want to know why my program outputs I4 output then I3 output?

var a = 4;
var i = 0;
var i3 = function() {
  console.log("I3 output")
  return i = i + 3
}
var i4 = function() {
  console.log("I4 output")
  return i = 4
}

(a > 3) && i3() || (a < 5) && i4();
console.log(i)

I want I3 output then I4 output. Why doesn't this work?
Comment: @JeremyThille someone (me!) shouldn't do code **before** coffee
Comment: There are many related questions like [TypeError: console.log(...) is not a function](/q/31013221/4642212) or [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](/q/2846283/4642212).
Comment: `(a > 3) && i3()` the first part, `a > 3` is false, so the second one isn't evaluated
Comment: @Cid but `a===4` so `a > 3` though
Answer: It's because you are missing a semicolon.
This :
var i4 = function() {
  console.log("I4 output")
  return i = 4
}

(a > 3)

is executed like this :
var i4 = function() {
  console.log("I4 output")
  return i = 4
}(a > 3) // <--- You are executing i4, passing it "a > 3" as argument

Sidenote : Javascript allows you to do this, leading to a bug; but Typescript complains. It says that you are calling a function with 1 argument, when it expects 0. Typescript really is some improvement over JS and taught me a lot about it.
If you add a semicolon, the function is defined, but not executed :

var a = 4;
var i = 0;
var i3 = function() {
  console.log("I3 output")
  return i = i + 3
};

var i4 = function() {
  console.log("I4 output")
  return i = 4
}; // <-- Add semicolon

(a > 3) && i3() || (a < 5) && i4();
console.log(i)
Answer: First I'd urge you start using semi-colons. ASI (Automatic Semi-colon Insertion) is an error correction process, and you'll find these kinds of errors creeping in if you don't.
Second, further to that, maybe consider function declarations rather than function expressions. Again, you're missing semi-colon at the end of i4 is the issue causing the problem which can be avoided with a declaration instead which don't need to terminate with them.
Third, if you're looking to call both functions you need to call them separately. If you use a logical OR the second expression won't be evaluated because the first will always evaluate as truthy.

var a = 4;
var i = 0;

function i3() {
  console.log('I3 output');
  return i = i + 3;
}

function i4() {
  console.log('I4 output');
  return i = 4;
}

(a > 3) && i3();
(a < 5) && i4();

console.log(i);


Prove that the solution of $2^x = 5$ is irrational

Question: Given the equation
$$2^x = 5.$$
I want to show that the solution of the equation above is an irrational.
My Idea:
First, if we use $\ln$ then we can write
$$x = \frac{\ln 5}{\ln 2}.$$
Finally, we are going to proof that $\frac{\ln 5}{\ln 2}$ is irrational. I stuck at this step.
Second, by assuming $x$ is rational solution of the equation above. So that we can write $x = \frac{p}{q}, p,q \in \mathbb{Q} (p,q) = 1.$ We are going to show the contradiction, but I stuck at this step.
Comment: You don't need to bring logs into this. If $x=m/n$ then multiplying $2^x=5$ on both sides by $2^n$ gives $2^m=5^n$ Now use unique factorization of positive integers. [first note $m,n$ here can be assumed to be positive integers (explain why)].
Comment: I think on the second step you just raise both sides with the power of $n$ (?)

But I understand your idea. It is very clear for me.
Comment: yes each side to n power not 2^n (I erred).
Answer: Suppose there is a solution $x=\frac pq$ where $p,q\in\mathbb Z,q\neq0$.
Then if $2^x=2^{\frac pq}=5$ we can get $2^p=5^q$.
If $p$ and $q$ have different signs then one side is strictly greater than $1$ and one side is strictly less so they can't be equal, so they must have the same sign. So suppose they're positive (or take reciprocals to make them so). Now use the unique factorisation of the naturals to show that these can't be equal, a contradiction so the assumption that there is a rational solution must be false.
Answer: If $2^{p}=5^q$ and if $p,q$ are integers then we get a contradiction because (positive) powers of $2$ are even but powers of $5$ are odd.(Alternatively you can use unique factorisation.)
Comment: @cofeemath I think that's pretty clear. But I have edited. Funny how much people like to nitpick.
Comment: negative powers of 2 are not "even".
Comment: @Shinrin-Yoku It might be clear to you and me but who are we to say it's clear to everyone. No one's perspective is without bias and perhaps giving help in excess is better than in deficit.
Comment: @Shinrin-Yoku: Keep in mind, our goals on this site are not exactly the same as the goals in an individual teacher/student interaction. So although spoonfeeding your individual student may be unhealthy, sometimes on this site the positive effects of maximal clarity outweigh the negative effects of spoonfeeding. The point is that many people besides the OP can benefit from your answer.


Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'Socket')

Question: i have a problem on heroku:
Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'Socket')
i know the solution is change STREAM for Socket in the file Injected.js of whatsapp-web.js. but i dont know how to modify this node_modules file in heroku or how to upload this change in heroku because if i try to upload all node modules i cant
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: This has been fixed in the patch update 1.16.5, so simply update your package.json file
Answer: What I did to solve it was uninstall the whatsapp-web.js library and installed it again. I noticed that it does some additional config modification with puppeteer.js
Comment: updated "whatsapp-web.js": "^1.16.4"
Answer: for multi device use this code for Injected.js
'use strict';

// Exposes the internal Store to the WhatsApp Web client
exports.ExposeStore = (moduleRaidStr) => {
    eval('var moduleRaid = ' + moduleRaidStr);
    // eslint-disable-next-line no-undef
    window.mR = moduleRaid();
    window.Store = Object.assign({}, window.mR.findModule(m => m.default && m.default.Chat)[0].default);
    window.Store.AppState = window.mR.findModule('Socket')[0].Socket;
    window.Store.Conn = window.mR.findModule('Conn')[0].Conn;
    window.Store.BlockContact = window.mR.findModule('blockContact')[0];
    window.Store.Call = window.mR.findModule('CallCollection')[0].CallCollection;
    window.Store.Cmd = window.mR.findModule('Cmd')[0].Cmd;
    window.Store.CryptoLib = window.mR.findModule('decryptE2EMedia')[0];
    window.Store.DownloadManager = window.mR.findModule('downloadManager')[0].downloadManager;
    window.Store.Features = window.mR.findModule('FEATURE_CHANGE_EVENT')[0].GK;
   //window.Store.genId = window.mR.findModule('newTag')[0].newTag;
    window.Store.genId = window.mR.findModule('newTag')?.[0]?.newTag || null;
    //
    window.Store.GroupMetadata = window.mR.findModule((module) => module.default && module.default.handlePendingInvite)[0].default;
    window.Store.Invite = window.mR.findModule('sendJoinGroupViaInvite')[0];
    window.Store.InviteInfo = window.mR.findModule('sendQueryGroupInvite')[0];
    window.Store.Label = window.mR.findModule('LabelCollection')[0].LabelCollection;
    window.Store.MediaPrep = window.mR.findModule('MediaPrep')[0];
    window.Store.MediaObject = window.mR.findModule('getOrCreateMediaObject')[0];
    window.Store.NumberInfo = window.mR.findModule('formattedPhoneNumber')[0];
    window.Store.MediaTypes = window.mR.findModule('msgToMediaType')[0];
    window.Store.MediaUpload = window.mR.findModule('uploadMedia')[0];
    window.Store.MsgKey = window.mR.findModule((module) => module.default && module.default.fromString)[0].default;
    window.Store.MessageInfo = window.mR.findModule('sendQueryMsgInfo')[0];
    window.Store.OpaqueData = window.mR.findModule(module => module.default && module.default.createFromData)[0].default;
   // window.Store.QueryExist = window.mR.findModule(module => typeof module.default === 'function' && module.default.toString().includes('Should not reach queryExists MD'))[0].default;
    window.Store.QueryExist = window.mR.findModule(module => typeof module.default === 'function' && module.default.toString().includes('Should not reach'))[0].default;
    //
    window.Store.QueryProduct = window.mR.findModule('queryProduct')[0];
    window.Store.QueryOrder = window.mR.findModule('queryOrder')[0];
    window.Store.SendClear = window.mR.findModule('sendClear')[0];
    window.Store.SendDelete = window.mR.findModule('sendDelete')[0];
    window.Store.SendMessage = window.mR.findModule('addAndSendMsgToChat')[0];
    window.Store.SendSeen = window.mR.findModule('sendSeen')[0];
    window.Store.Sticker = window.mR.findModule('Sticker')[0].Sticker;
    window.Store.User = window.mR.findModule('getMaybeMeUser')[0];
    window.Store.UploadUtils = window.mR.findModule((module) => (module.default && module.default.encryptAndUpload) ? module.default : null)[0].default;
    window.Store.UserConstructor = window.mR.findModule((module) => (module.default && module.default.prototype && module.default.prototype.isServer && module.default.prototype.isUser) ? module.default : null)[0].default;
    window.Store.Validators = window.mR.findModule('findLinks')[0];
    window.Store.VCard = window.mR.findModule('vcardFromContactModel')[0];
    window.Store.Wap = window.mR.findModule('queryLinkPreview')[0].default;
    window.Store.WidFactory = window.mR.findModule('createWid')[0];
    window.Store.getProfilePicFull = window.mR.findModule('getProfilePicFull')[0].getProfilePicFull;
    window.Store.PresenceUtils = window.mR.findModule('sendPresenceAvailable')[0];
    window.Store.ChatState = window.mR.findModule('sendChatStateComposing')[0];
    window.Store.GroupParticipants = window.mR.findModule('sendPromoteParticipants')[0];
    window.Store.JoinInviteV4 = window.mR.findModule('sendJoinGroupViaInviteV4')[0];
    window.Store.findCommonGroups = window.mR.findModule('findCommonGroups')[0].findCommonGroups;
    window.Store.StatusUtils = window.mR.findModule('setMyStatus')[0];
    window.Store.StickerTools = {
        ...window.mR.findModule('toWebpSticker')[0],
        ...window.mR.findModule('addWebpMetadata')[0]
    };

    window.Store.GroupUtils = {
        ...window.mR.findModule('sendCreateGroup')[0],
        ...window.mR.findModule('sendSetGroupSubject')[0],
        ...window.mR.findModule('markExited')[0]
    };

    if (!window.Store.Chat._find) {
        window.Store.Chat._find = e => {
            const target = window.Store.Chat.get(e);
            return target ? Promise.resolve(target) : Promise.resolve({
                id: e
            });
        };
    }
};

exports.LoadUtils = () => {
    if(!window.Store.genId) {
        window.Store.genId = window.Store.MsgKey.newId;
    }
    window.WWebJS = {};

    window.WWebJS.sendSeen = async (chatId) => {
        let chat = window.Store.Chat.get(chatId);
        if (chat !== undefined) {
            await window.Store.SendSeen.sendSeen(chat, false);
            return true;
        }
        return false;

    };

    window.WWebJS.sendMessage = async (chat, content, options = {}) => {
        let attOptions = {};
        if (options.attachment) {
            attOptions = options.sendMediaAsSticker
                ? await window.WWebJS.processStickerData(options.attachment)
                : await window.WWebJS.processMediaData(options.attachment, {
                    forceVoice: options.sendAudioAsVoice,
                    forceDocument: options.sendMediaAsDocument,
                    forceGif: options.sendVideoAsGif
                });

            content = options.sendMediaAsSticker ? undefined : attOptions.preview;

            delete options.attachment;
            delete options.sendMediaAsSticker;
        }

        let quotedMsgOptions = {};
        if (options.quotedMessageId) {
            let quotedMessage = window.Store.Msg.get(options.quotedMessageId);
            if (quotedMessage.canReply()) {
                quotedMsgOptions = quotedMessage.msgContextInfo(chat);
            }
            delete options.quotedMessageId;
        }

        if (options.mentionedJidList) {
            options.mentionedJidList = options.mentionedJidList.map(cId => window.Store.Contact.get(cId).id);
        }

        let locationOptions = {};
        if (options.location) {
            locationOptions = {
                type: 'location',
                loc: options.location.description,
                lat: options.location.latitude,
                lng: options.location.longitude
            };
            delete options.location;
        }

        let vcardOptions = {};
        if (options.contactCard) {
            let contact = window.Store.Contact.get(options.contactCard);
            vcardOptions = {
                body: window.Store.VCard.vcardFromContactModel(contact).vcard,
                type: 'vcard',
                vcardFormattedName: contact.formattedName
            };
            delete options.contactCard;
        } else if (options.contactCardList) {
            let contacts = options.contactCardList.map(c => window.Store.Contact.get(c));
            let vcards = contacts.map(c => window.Store.VCard.vcardFromContactModel(c));
            vcardOptions = {
                type: 'multi_vcard',
                vcardList: vcards,
                body: undefined
            };
            delete options.contactCardList;
        } else if (options.parseVCards && typeof (content) === 'string' && content.startsWith('BEGIN:VCARD')) {
            delete options.parseVCards;
            try {
                const parsed = window.Store.VCard.parseVcard(content);
                if (parsed) {
                    vcardOptions = {
                        type: 'vcard',
                        vcardFormattedName: window.Store.VCard.vcardGetNameFromParsed(parsed)
                    };
                }
            } catch (_) {
                // not a vcard
            }
        }

        if (options.linkPreview) {
            delete options.linkPreview;

            // Not supported yet by WhatsApp Web on MD
            if(!window.Store.Features.features.MD_BACKEND) {
                const link = window.Store.Validators.findLink(content);
                if (link) {
                    const preview = await window.Store.Wap.queryLinkPreview(link.url);
                    preview.preview = true;
                    preview.subtype = 'url';
                    options = { ...options, ...preview };
                }
            }
        }

        let buttonOptions = {};
        if(options.buttons){
            let caption;
            if (options.buttons.type === 'chat') {
                content = options.buttons.body;
                caption = content;
            } else {
                caption = options.caption ? options.caption : ' '; //Caption can't be empty
            }
            buttonOptions = {
                productHeaderImageRejected: false,
                isFromTemplate: false,
                isDynamicReplyButtonsMsg: true,
                title: options.buttons.title ? options.buttons.title : undefined,
                footer: options.buttons.footer ? options.buttons.footer : undefined,
                dynamicReplyButtons: options.buttons.buttons,
                replyButtons: options.buttons.buttons,
                caption: caption
            };
            delete options.buttons;
        }

        let listOptions = {};
        if(options.list){
            if(window.Store.Conn.platform === 'smba' || window.Store.Conn.platform === 'smbi'){
                throw '[LT01] Whatsapp business can\'t send this yet';
            }
            listOptions = {
                type: 'list',
                footer: options.list.footer,
                list: {
                    ...options.list,
                    listType: 1
                },
                body: options.list.description
            };
            delete options.list;
            delete listOptions.list.footer;
        }

        const meUser = window.Store.User.getMaybeMeUser();
        const isMD = window.Store.Features.features.MD_BACKEND;

        const newMsgId = new window.Store.MsgKey({
            from: meUser,
            to: chat.id,
            id: window.Store.genId(),
            participant: isMD && chat.id.isGroup() ? meUser : undefined,
            selfDir: 'out',
        });

        const extraOptions = options.extraOptions || {};
        delete options.extraOptions;

        const ephemeralSettings = {
            ephemeralDuration: chat.isEphemeralSettingOn() ? chat.getEphemeralSetting() : undefined,
            ephemeralSettingTimestamp: chat.getEphemeralSettingTimestamp() || undefined,
            disappearingModeInitiator: chat.getDisappearingModeInitiator() || undefined,
        };

        const message = {
            ...options,
            id: newMsgId,
            ack: 0,
            body: content,
            from: meUser,
            to: chat.id,
            local: true,
            self: 'out',
            t: parseInt(new Date().getTime() / 1000),
            isNewMsg: true,
            type: 'chat',
            ...ephemeralSettings,
            ...locationOptions,
            ...attOptions,
            ...quotedMsgOptions,
            ...vcardOptions,
            ...buttonOptions,
            ...listOptions,
            ...extraOptions
        };

        await window.Store.SendMessage.addAndSendMsgToChat(chat, message);
        return window.Store.Msg.get(newMsgId._serialized);
    };

    window.WWebJS.toStickerData = async (mediaInfo) => {
        if (mediaInfo.mimetype == 'image/webp') return mediaInfo;

        const file = window.WWebJS.mediaInfoToFile(mediaInfo);
        const webpSticker = await window.Store.StickerTools.toWebpSticker(file);
        const webpBuffer = await webpSticker.arrayBuffer();
        const data = window.WWebJS.arrayBufferToBase64(webpBuffer);

        return {
            mimetype: 'image/webp',
            data
        };
    };

    window.WWebJS.processStickerData = async (mediaInfo) => {
        if (mediaInfo.mimetype !== 'image/webp') throw new Error('Invalid media type');

        const file = window.WWebJS.mediaInfoToFile(mediaInfo);
        let filehash = await window.WWebJS.getFileHash(file);
        let mediaKey = await window.WWebJS.generateHash(32);

        const controller = new AbortController();
        const uploadedInfo = await window.Store.UploadUtils.encryptAndUpload({
            blob: file,
            type: 'sticker',
            signal: controller.signal,
            mediaKey
        });

        const stickerInfo = {
            ...uploadedInfo,
            clientUrl: uploadedInfo.url,
            deprecatedMms3Url: uploadedInfo.url,
            uploadhash: uploadedInfo.encFilehash,
            size: file.size,
            type: 'sticker',
            filehash
        };

        return stickerInfo;
    };

    window.WWebJS.processMediaData = async (mediaInfo, { forceVoice, forceDocument, forceGif }) => {
        const file = window.WWebJS.mediaInfoToFile(mediaInfo);
        const mData = await window.Store.OpaqueData.createFromData(file, file.type);
        const mediaPrep = window.Store.MediaPrep.prepRawMedia(mData, { asDocument: forceDocument });
        const mediaData = await mediaPrep.waitForPrep();
        const mediaObject = window.Store.MediaObject.getOrCreateMediaObject(mediaData.filehash);

        const mediaType = window.Store.MediaTypes.msgToMediaType({
            type: mediaData.type,
            isGif: mediaData.isGif
        });

        if (forceVoice && mediaData.type === 'audio') {
            mediaData.type = 'ptt';
        }

        if (forceGif && mediaData.type === 'video') {
            mediaData.isGif = true;
        }

        if (forceDocument) {
            mediaData.type = 'document';
        }

        if (!(mediaData.mediaBlob instanceof window.Store.OpaqueData)) {
            mediaData.mediaBlob = await window.Store.OpaqueData.createFromData(mediaData.mediaBlob, mediaData.mediaBlob.type);
        }

        mediaData.renderableUrl = mediaData.mediaBlob.url();
        mediaObject.consolidate(mediaData.toJSON());
        mediaData.mediaBlob.autorelease();

        const uploadedMedia = await window.Store.MediaUpload.uploadMedia({
            mimetype: mediaData.mimetype,
            mediaObject,
            mediaType
        });

        const mediaEntry = uploadedMedia.mediaEntry;
        if (!mediaEntry) {
            throw new Error('upload failed: media entry was not created');
        }

        mediaData.set({
            clientUrl: mediaEntry.mmsUrl,
            deprecatedMms3Url: mediaEntry.deprecatedMms3Url,
            directPath: mediaEntry.directPath,
            mediaKey: mediaEntry.mediaKey,
            mediaKeyTimestamp: mediaEntry.mediaKeyTimestamp,
            filehash: mediaObject.filehash,
            encFilehash: mediaEntry.encFilehash,
            uploadhash: mediaEntry.uploadHash,
            size: mediaObject.size,
            streamingSidecar: mediaEntry.sidecar,
            firstFrameSidecar: mediaEntry.firstFrameSidecar
        });

        return mediaData;
    };

    window.WWebJS.getMessageModel = message => {
        const msg = message.serialize();

        msg.isEphemeral = message.isEphemeral;
        msg.isStatusV3 = message.isStatusV3;
        msg.links = (message.getLinks()).map(link => ({
            link: link.href,
            isSuspicious: Boolean(link.suspiciousCharacters && link.suspiciousCharacters.size)
        }));

        if (msg.buttons) {
            msg.buttons = msg.buttons.serialize();
        }
        if (msg.dynamicReplyButtons) {
            msg.dynamicReplyButtons = JSON.parse(JSON.stringify(msg.dynamicReplyButtons));
        }
        if (msg.replyButtons) {
            msg.replyButtons = JSON.parse(JSON.stringify(msg.replyButtons));
        }

        if (typeof msg.id.remote === 'object') {
            msg.id = Object.assign({}, msg.id, { remote: msg.id.remote._serialized });
        }

        delete msg.pendingAckUpdate;

        return msg;
    };

    window.WWebJS.getChatModel = async chat => {

        let res = chat.serialize();
        res.isGroup = chat.isGroup;
        res.formattedTitle = chat.formattedTitle;
        res.isMuted = chat.mute && chat.mute.isMuted;

        if (chat.groupMetadata) {
            const chatWid = window.Store.WidFactory.createWid((chat.id._serialized));
            await window.Store.GroupMetadata.update(chatWid);
            res.groupMetadata = chat.groupMetadata.serialize();
        }

        delete res.msgs;
        delete res.msgUnsyncedButtonReplyMsgs;
        delete res.unsyncedButtonReplies;

        return res;
    };

    window.WWebJS.getChat = async chatId => {
        const chatWid = window.Store.WidFactory.createWid(chatId);
        const chat = await window.Store.Chat.find(chatWid);
        return await window.WWebJS.getChatModel(chat);
    };

    window.WWebJS.getChats = async () => {
        const chats = window.Store.Chat.models;

        const chatPromises = chats.map(chat => window.WWebJS.getChatModel(chat));
        return await Promise.all(chatPromises);
    };

    window.WWebJS.getContactModel = contact => {
        let res = contact.serialize();
        res.isBusiness = contact.isBusiness;

        if (contact.businessProfile) {
            res.businessProfile = contact.businessProfile.serialize();
        }

        res.isMe = contact.isMe;
        res.isUser = contact.isUser;
        res.isGroup = contact.isGroup;
        res.isWAContact = contact.isWAContact;
        res.isMyContact = contact.isMyContact;
        res.isBlocked = contact.isContactBlocked;
        res.userid = contact.userid;

        return res;
    };

    window.WWebJS.getContact = async contactId => {
        const wid = window.Store.WidFactory.createWid(contactId);
        const contact = await window.Store.Contact.find(wid);
        return window.WWebJS.getContactModel(contact);
    };

    window.WWebJS.getContacts = () => {
        const contacts = window.Store.Contact.models;
        return contacts.map(contact => window.WWebJS.getContactModel(contact));
    };

    window.WWebJS.mediaInfoToFile = ({ data, mimetype, filename }) => {
        const binaryData = window.atob(data);

        const buffer = new ArrayBuffer(binaryData.length);
        const view = new Uint8Array(buffer);
        for (let i = 0; i < binaryData.length; i++) {
            view[i] = binaryData.charCodeAt(i);
        }

        const blob = new Blob([buffer], { type: mimetype });
        return new File([blob], filename, {
            type: mimetype,
            lastModified: Date.now()
        });
    };

    window.WWebJS.arrayBufferToBase64 = (arrayBuffer) => {
        let binary = '';
        const bytes = new Uint8Array(arrayBuffer);
        const len = bytes.byteLength;
        for (let i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    };

    window.WWebJS.getFileHash = async (data) => {
        let buffer = await data.arrayBuffer();
        const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
        return btoa(String.fromCharCode(...new Uint8Array(hashBuffer)));
    };

    window.WWebJS.generateHash = async (length) => {
        var result = '';
        var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    };

    window.WWebJS.sendClearChat = async (chatId) => {
        let chat = window.Store.Chat.get(chatId);
        if (chat !== undefined) {
            await window.Store.SendClear.sendClear(chat, false);
            return true;
        }
        return false;
    };

    window.WWebJS.sendDeleteChat = async (chatId) => {
        let chat = window.Store.Chat.get(chatId);
        if (chat !== undefined) {
            await window.Store.SendDelete.sendDelete(chat);
            return true;
        }
        return false;
    };

    window.WWebJS.sendChatstate = async (state, chatId) => {
        if (window.Store.Features.features.MD_BACKEND) {
            chatId = window.Store.WidFactory.createWid(chatId);
        }
        switch (state) {
        case 'typing':
            await window.Store.ChatState.sendChatStateComposing(chatId);
            break;
        case 'recording':
            await window.Store.ChatState.sendChatStateRecording(chatId);
            break;
        case 'stop':
            await window.Store.ChatState.sendChatStatePaused(chatId);
            break;
        default:
            throw 'Invalid chatstate';
        }

        return true;
    };

    window.WWebJS.getLabelModel = label => {
        let res = label.serialize();
        res.hexColor = label.hexColor;

        return res;
    };

    window.WWebJS.getLabels = () => {
        const labels = window.Store.Label.models;
        return labels.map(label => window.WWebJS.getLabelModel(label));
    };

    window.WWebJS.getLabel = (labelId) => {
        const label = window.Store.Label.get(labelId);
        return window.WWebJS.getLabelModel(label);
    };

    window.WWebJS.getChatLabels = async (chatId) => {
        const chat = await window.WWebJS.getChat(chatId);
        return (chat.labels || []).map(id => window.WWebJS.getLabel(id));
    };

    window.WWebJS.getOrderDetail = async (orderId, token) => {
        return window.Store.QueryOrder.queryOrder(orderId, 80, 80, token);
    };

    window.WWebJS.getProductMetadata = async (productId) => {
        let sellerId = window.Store.Conn.wid;
        let product = await window.Store.QueryProduct.queryProduct(sellerId, productId);
        if (product && product.data) {
            return product.data;
        }

        return undefined;
    };
};

Answer: check is whatsapp-web.js is ready status with the code below, if whatsapp-web.js is ready status you will not find error in anymore
client.on("ready", () => {
    console.log("Client is ready!");
});


Extracting words based on a $ and unnesting the data

Question: I am trying to do two things to my data. The data looks like:
# A tibble: 10 x 2
     grp newCol
   <int> <chr>
 1  6303 "The company sees earnings of $3.40 to $3.60 a share for all of 2008, agai…
 2  7686 "   -- reaffirmed its fiscal 2015 guidance of per share diluted earnings b…
 3  9577 "Analysts polled by FactSet anticipate earnings of 96 cents a share, down …
 4  6475 ""
 5  5229 "The company also expects income to be \"significantly impacted\" by costs…
 6  2648 "Hoku also expects losses for the foreseeable future on significant cost i…
 7  3691 "St. Louis-based Emerson now sees full-year earnings of $2.40 to $2.60 a s…
 8  9297 ""
 9  2080 "The restaurant group also raised its earnings guidance for fiscal 2007 to…
10  3513 "Guidance, For the full fiscal year 2008, the Company is moderating its pr…

I can run the following:
x <- d %>%
  mutate(
    extractedWords = str_extract_all(newCol, "([^\\s]+\\s){2}earnings(\\s[^\\s]+){12}")
  )

Where I get:
# A tibble: 10 x 1
   extractedWords
   <list>
 1 <chr [1]>
 2 <chr [3]>
 3 <chr [1]>
 4 <chr [0]>
 5 <chr [0]>
 6 <chr [0]>
 7 <chr [1]>
 8 <chr [0]>
 9 <chr [2]>
10 <chr [4]>

I firstly want to modify the str_extract_all(newCol, "([^\\s]+\\s){2}earnings(\\s[^\\s]+){12}") - which currently extracts the 2 words before the Word earnings and 12 words after the Word earnings. I want to change it such that it extracts the words before the dollar $ symbol.
Secondly I want to unnest the columns. When I run:
x %>%
  unnest(extractedWords)

The number of rows from the data goes from 10 to 12. I want to unnest it but paste the c("text", more text") into something like text, more text or separated by | (or some variation).
Data:
d <- structure(list(grp = c(6303L, 7686L, 9577L, 6475L, 5229L, 2648L,
3691L, 9297L, 2080L, 3513L), newCol = c("The company sees earnings of $3.40 to $3.60 a share for all of 2008, against $2.74 a share from continuing operations in 2007, an increase of 24% to 31%.   ",
"   -- reaffirmed its fiscal 2015 guidance of per share diluted earnings between , We believe the guidance outlook for fiscal 2015 remains realistic and takes into consideration the heightened competitive market trends for the Diagnostics segment offset by strategic investments that target the growing outpatient segment and further growth of our Life Science segment through our focus on global expansion, increasing industrial market efforts, and emerging success in the AgriBio and genomics research areas., FISCAL 2015 GUIDANCE REAFFIRMED, For the fiscal year ending September 30, 2015, management expects net revenues to be in the range of $193 million to $200 million and per share diluted earnings to be between $0.85 and $0.91. The per share estimates assume an increase in average diluted shares outstanding from approximately 41.9 million at fiscal 2014 year end to approximately 42.4 million at fiscal 2015 year end. The revenue and earnings guidance provided in this press release is from expected internal growth and does not include the impact of any additional acquisitions the Company might complete during fiscal 2015.",
"Analysts polled by FactSet anticipate earnings of 96 cents a share, down 10 cents from a year earlier. Revenue is expected to have decreased 5.5% to $30.4 billion, which would mark the fourth consecutive quarterly decline after six years of growth. Verizon has said it expects earnings and sales will be roughly flat this year.",
"", "The company also expects income to be \"significantly impacted\" by costs related to its pending acquisition of SRS Labs Inc. (SRSL)., The company also expects income to be \"significantly impacted\" by costs related to its pending acquisition of SRS Labs Inc. (SRSL).",
"Hoku also expects losses for the foreseeable future on significant cost increases.   ",
"St. Louis-based Emerson now sees full-year earnings of $2.40 to $2.60 a share, down from its February forecast of $2.70 to $2.95 a share. The company also expects net sales for the fiscal year to fall 13% to 15% to $21 billion to $21.7 billion. Sales are expected to be hurt by about 5% because of currency translations, but boosted by 1% because of acquisitions.",
"", "The restaurant group also raised its earnings guidance for fiscal 2007 to a range of $3.45 a share to $3.50 a share, and said its expects earnings for the third quarter ending in July of 85 cents to 89 cents a share and same-store sales growth of 5% to 6%.   ",
"Guidance, For the full fiscal year 2008, the Company is moderating its previously issued guidance and expects net sales to be approximately $950 million and earnings per diluted share to be approximately $1.00, which includes approximately $0.45 per diluted share of restructuring charges and other unusual items. For the twelve months ended February 2, 2008, net sales were $1.09 billion and earnings per diluted share were $2.59., Set forth below is our reconciliation of net earnings per share, calculated in accordance with generally accepted accounting principles, or GAAP, to net earnings per share, as adjusted, for certain historical periods and certain future periods. For reference, we also include our previous guidance for third quarter fiscal 2008. Net earnings per share, as adjusted, excludes (i) the net impact of certain restructuring costs and other unusual items as well as the write off of unamortized financing costs during the first three quarters of fiscal 2008 and (ii) the anticipated impact of certain restructuring costs in the fourth quarter of fiscal 2008. We believe that investors often look at ongoing operations as a measure of assessing performance and as a basis for comparing past results against future results. Therefore, we believe that presenting our results and expected results excluding these items provides useful information to investors because this allows investors to make decisions based on our ongoing operations. We use the results excluding these items to discuss our business with investment institutions, our board of directors and others. Further, we believe that presenting our results and expected results excluding these items provides useful information to investors because this allows investors to compare our results and our expected results for the periods presented to other periods.,                           Guidance   Results      for      Guidance   Guidance"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-10L))

Comment: "I want to change it such that it extracts the words before the dollar $ symbol"--which, and/or how many, words?
Answer: I'm not 100% sure what you mean with the first part of your question. Assuming you want to extract all words after the word earnings and before $, this should do what you want. It uses a 'positive lookahead' and allows for any number of words until it finds the first dollar sign (hence the *?).
Rather than unnesting, I loop over the extractedWords column using purrr::map_chr, which returns a character vector, which makes further unnesting unneccessary.
library(tidyverse)

d %>%
  mutate(
    extractedWords = str_extract_all(newCol, "([^\\s]+\\s){2}\\$(\\s?[^\\s]+){12}")
  ) %>%
  mutate(result = map_chr(extractedWords, str_c, "", collapse="|"))

EDIT: edited the regular expression to extract 2 words before the dollar sign and 12 words after it. Note I had to escape the dollar sign (\\$) for it to work, since a dollar sign has a special meaning in a regular expression.
Comment: Thanks! actually what I want is to replace `earnings` with the `$` sign. That is, extract the two words before the `$` and the `12` words after the `$`.
Comment: I get this error `Error: Result 4 must be a single string, not a character vector of length 0`
Comment: See new edit: this should work. It replaces the empty character vectors with an empty string.


Converting numpy array to rpy2 matrix (forecast package, xreg parameter)

Question: I don't seem to be able to get the line fit = forecast.Arima(series, order=order, xreg=r_exog_train) to work. It does work without the xreg parameter so I'm pretty sure it's the numpy array to rpy2 matrix conversion that makes a problem.
Does anyone observe a mistake here? Thanks!
This is the error I get (parts in German unfortunately):
Fehler in `colnames<-`(`*tmp*`, value = if (ncol(xreg) == 1) nmxreg else paste(n
mxreg,  :
  Länge von 'dimnames' [2] ungleich der Arrayausdehnung
Traceback (most recent call last):
  File "r.py", line 58, in <module>
    res = do_forecast(series, horizon=horizon, exog=(exog_train, exog_test))
  File "r.py", line 39, in do_forecast
    fit = forecast.Arima(series, order=order, xreg=exog_train)
  File "C:\Python27\lib\site-packages\rpy2\robjects\functions.py", line 86, in _
_call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "C:\Python27\lib\site-packages\rpy2\robjects\functions.py", line 35, in _
_call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Fehler in `colnames<-`(`*tmp*`, value = if (ncol(
xreg) == 1) nmxreg else paste(nmxreg,  :
  Lõnge von 'dimnames' [2] ungleich der Arrayausdehnung

Here is the code example:
# Python wrapper for R forecast stuff
import numpy as np

print 'Start importing R.'
from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects.numpy2ri import numpy2ri
robjects.conversion.py2ri = numpy2ri

base = importr('base')
forecast = importr('forecast')
stats = importr('stats')
ts = robjects.r['ts']
print 'Finished importing R.'

def nparray2rmatrix(x):
  nr, nc = x.shape
  xvec = robjects.FloatVector(x.transpose().reshape((x.size)))
  xr = robjects.r.matrix(xvec, nrow=nr, ncol=nc)
  return xr

def nparray2rmatrix_alternative(x):
  nr, nc = x.shape
  xvec = robjects.FloatVector(x.reshape((x.size)))
  xr = robjects.r.matrix(xvec, nrow=nr, ncol=nc, byrow=True)
  return xr

def do_forecast(series, frequency=None, horizon=30, summary=False, exog=None):
  if frequency:
    series = ts(series, frequency=frequency)
  else:
    series = ts(series)
  if exog:
    exog_train, exog_test = exog
    r_exog_train = nparray2rmatrix(exog_train)
    r_exog_test = nparray2rmatrix(exog_test)
    order = robjects.IntVector([1, 0, 2]) # c(1,0,2) # TODO find right model
    fit = forecast.Arima(series, order=order, xreg=r_exog_train)
    forecast_result = forecast.forecast(fit, h=horizon, xreg=r_exog_test)
  else:
    # fit = forecast.auto_arima(series)
    #robjects.r.plot(series)
    fit = stats.HoltWinters(series)
    forecast_result = forecast.forecast(fit, h=horizon)
  if summary:
    modsummary = base.summary(fit)
    print modsummary
  forecast_values = np.array(list(forecast_result.rx2('mean')))
  return forecast_values

# Example
series = np.arange(100)
exog_train = np.ones((100,2))
exog_test = np.ones((100,2))
horizon = 100
res = do_forecast(series, horizon=horizon, exog=(exog_train, exog_test))
print res

Comment: As a general comment, I would limit the mixing of R into Python as much as possible. Just create the `doforecast` function in R, source the function into the current workspace, and call it. This way you limit the interface of R and Python to just a few lines of R code in Python. This makes it less likely you'll run into rpy specific problems, and makes debugging the R code easier.
Comment: Thanks Paul, that makes sense. Still, I would have the same problem of getting the xreg matrix to work.
Comment: True, but still as a general way of avoiding issues I would make the code as independent of each other as you can.
Comment: I got it working by explicitely stating "dimnames" as in: `xr = robjects.r.matrix(xvec, nrow=nr, ncol=nc, dimnames=dimnames)`.
Comment: You can post this as answer, and accept it. This will inform others that your question has been answered.
Answer: I got it working by explicitely stating "dimnames" as in: xr = robjects.r.matrix(xvec, nrow=nr, ncol=nc, dimnames=dimnames). Apparently the forecast package requires this.


Diminished progression

Question: How can you use a progression (like the one below) and have it fit in C major well and support the melody?
Do these diminished chords fit in a diatonic scale well, even though they're chromatic?

Cmaj7 > Dbm7 > Ebdim7 > Em7 > Dbdim7 > Dm7 > Bdim7 > CMaj7 > G7 > Abdim7 > Am7
Answer: You wrote:
<code>Do these diminished chords fit in a diatonic scale well, even though they're chromatic?
</code>
This is not a yes/no question, but rather, the answer is "It depends".  If you want your melody to remain purely diatonic, you would probably want to focus on notes that are in the key of C, and that also are members of the chord at hand.
For instance, in CM7, you have all four notes that would work: C E G B.  Then in Dbm7, only Cb would fit (it is the same frequency as B; Db Fb Ab do not reside in the C scale).
You could continue to use this method to build a melody that is strictly in C, and in fact, all your chords have at least one note that is in C.  Although you could try some notes outside of C as well, if you're interested in experimenting.
Now, whether they fit "well" is a more complicated question.  You'll need to go one chord-melody combination at a time, and possibly need to go back and rewrite until you have a satisfying melody.  There is a lot of study necessary to work out such a complicated chord progression.
Comment: i just gave you one ill give you as many as you want, please help. https://www.youtube.com/watch?v=2xwny96CSLs how can you use this progression he gave in a song? what scale would this be in ? C ? what melody would you use over this
Comment: For a progressive rock direction, you really want to decide what kind of sound you want.  You can go in so many directions, and use many different tones on your instruments.
Comment: Regarding the melody in the video, it is not all in C.  Keep in mind that as chords change, so do the scales.  This is a very big question, and I think it is best for you to continue with theory tutorials and gather more and more knowledge about music theory.  The video you are watching has some good advice, but if it is too complicated at first, take a step back and read up on chord theory.
Comment: in the last 3 minutes of the video what keys did he modulate to and what keys did he start and end with ? and how did he do it and what keys where used and where they all diantonic keys? like C or chromatic?
Comment: He did not modulate, but rather, just used diminished chords to lead to chords that fit in C.  Those chords are the Em7, Dm7, G7, and Am7, all which are in C.  Those chords are like "landing spots".  They are more stable than the diminished ones.

Diminished progression


A different version is showing in different command in a Debian container

Question: I am running a docker Debian 9.6 container. But when I run "uname" it is showing Ubuntu. But, "cat /etc/debian_version" is showing Debian version 9.6.
root@a2bb8bf8e79c:/# uname -a
Linux a2bb8bf8e79c 4.15.0-39-generic #42~16.04.1-Ubuntu SMP Wed Oct 24 17:09:54 UTC 2018 x86_64 GNU/Linux
root@a2bb8bf8e79c:/# cat /etc/debian_version
9.6
root@a2bb8bf8e79c:/#

Answer: Docker containers run on the host's kernel, #42~16.04.1-Ubuntu SMP Wed Oct 24 17:09:54 UTC 2018 is the kernel section of the output. If you run uname -a on the host it should give you the same value for the kernel.


How can I to learn sight-singing, transcribe, and sight-reading?

Question: I'm curious what the best route would be to become proficient in sight singing & ear training, along with polishing my technique on my preferred instruments (guitar & piano). I have a broad understanding of theory (rhythm, harmony, voice leading, etc.) but I have never taken the time to develop my reading and writing skills.
My goal is to be able to transcribe whatever I'm hearing in my head even when I'm away from my instrument. I would love to be able to look at a brand new piece of music and read/sing through it just as effortlessly as when I read a page out of book.
Comment: Regarding the sight-reading: do you already practices this when playing piano and guitar? Or do you for example play by ear or use TAB notation for guitar?
Comment: The part of your question looking for "suggestions on reading material, online instructors or courses" is [off-topic](https://music.stackexchange.com/help/on-topic), since requests for external resources are off-topic.
Comment: I normally play by ear, but I have played in a jazz quartet where we'd communicate using chord charts and fragments of the notated melody.
Comment: But no, I have neglected any serious practice routine when it comes to sight-reading with my instrument. I'm basically at the point where I can look at a lead sheet and understand what's going on harmonically from the accompanying chords, rhythmically from the time signature and common melodic phrases - but when it comes to reading notation on the spot, I am a complete beginner. I purchased the Berklee Method 1,2,3 for guitar.
Answer: I like your analogy

read/sing through it just as effortlessly as when I read a page out of book.

because you basically hit the spot already.
Remember how you learned to read books?
You had (very) short and simple texts and put together the letters / syllables and words. This was slow and sometimes frustrating in the beginning, but with enough practice you became more and more proficient and could read longer and more sophisticated texts.
So, for sight-reading, pick very short and simple songs, and try to play them note-by-note with your instruments. Start slowly first. If you play piano, start playing each hand separately. Focus on correct pitch and rhythm first, if you are confident, increase speed.  If this becomes easy, pick more complex pieces.
For sight-singing, I would recommend as a first step to look at melody sheets of (simple!) songs you know  while slowly singing them and try to follow the notes while singing. Furthermore, practice intervals: first, listen to them and learn to distinguish them by ear. Then practice singing them (control yourself using the instruments). Next, pick a simple, but unknown (to you) song and try to sing the melody by putting together the intervals.
Intervals are also handy for your wish to transcribe melodies. If you have practised distinguishing intervals by ear, you can put together the intervals you hear and write the melody. Again, start simple.
And to come back to your analogy: expect it to be tiring, frustrating at some times, but whenever this happens, don't give up. Take a break, try another piece and consider taking lessons from a teacher.
Answer: Sight reading can be split into two separate entities - timing and pitch.
They are unrelated until put together to make tunes. Start with tapping rhythms from the dots, counting all the time. Eventually, you'll get to recognise some common patterns - just like you do with groups of letters that make words.
When, on a tune, you have established its rhythmic shape, then play the notes written, in that rhythm. Start with simple tunes that don't stretch too much, particularly on piano, so your hand doesn't have to float all over, but is stable. One hand at a time initially.
Look ahead, just like you have to when reading text out loud. Sometimes a metronome can help.
Get some sight reading material - ABRSM produces books for this purpose - the grades keep you on track.
Guitar is somewhat different, with so many different places to play the exact same notes. Learn some scale patterns, and adhere to them while sight reading.
Learn intervals, especially using the key root as a start point, rather than plodding through thinking 'C-E, M3, E-G, m3, G-A, M2. Instead, M3, P5, M6.
Sight singing, best done at the piano. Sing a couple of notes, after giving yourself the start note (obviously!) then play them, to check.
It's a long process, and needs doing very regularly, but it obviously worked when you began to read words, didn't it?! Playing with others is another opportunity to get better, once you're happy reading at more than the beginner stage. Good luck!


How to properly create CA certificate and sign the SSL/TLS cert to use in Apache for localhost?

Question: I've found this article and this what I used to generate CA cert:
openssl genrsa -des3 -out myCA.key 2048
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem

I name it "MyCert"
And I used it to sign the cert I generated for localhost (it was the output of ChatGPT)
$ openssl req -newkey rsa:2048 -nodes -keyout localhost.key -out localhost.csr
$ openssl x509 -req -in localhost.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial -out localhost.crt -days 365 -sha256

I've added the CA cert to the system (I use Fedora):
sudo cp myCA.pem /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust extract

I restarted the server and when access https://localhost
Got this error:
NET::ERR_CERT_COMMON_NAME_INVALID
Subject: localhost
Issuer: MyCert

What did I wrong? I use default fields for the CA cert:
CN = MyCert
O = Default Company Ltd
L = Default City
C = pl

and the localhost cert have those fields:
CN = localhost
C = pl

How to properly create CA cert and sign the cert for Apache on Fedora?
Comment: Did you add localhost to the SAN?
Comment: Install `xca`, I've not seen any other frontend to ssl certs that comes close.
Comment: See [this answer](https://stackoverflow.com/a/41366949/3527940) (not a dup because you want a CA + cert and not a self-signed cert, but the details on the cert are very similar, especially the need for the SAN).
Answer: This worked for me:

Generate CA certificate.

openssl req -x509 -new -nodes -newkey rsa:2048 -keyout myCA.key \
  -sha256 -days 1825 -out myCA.crt -subj /CN='localhost ca'

Generate the server certificate request. Note that in addition to setting CN=localhost we're also setting a subjectAlternativeName  for localhost, because:

RFC 2818, published in May 2000, deprecates the use of the Common Name (CN) field in HTTPS certificates for subject name verification. Instead, it recommends using the "Subject Alternative Name" extension (SAN) of the "dns name" type. ref

(Note that the deprecation of commonName for identifying hosts was 24 years ago.)
openssl req -newkey rsa:2048 -nodes -keyout localhost.key -out localhost.csr \
  -subj /CN=localhost -addext subjectAltName=DNS:localhost

Sign the certificate request to create a certificate. Note the use of -copy_extensions copy so that we copy the subjectAlternativeName from the request to the certificate.

openssl x509 -req -in localhost.csr -copy_extensions copy \
  -CA myCA.crt -CAkey myCA.key -CAcreateserial -out localhost.crt -days 365 -sha256

Add the CA certificate to the trust store.

sudo cp myCA.crt /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust

I'm testing the certificate by setting up a simple TLS-enabled server using caddy. I start with this Caddyfile:
{
    http_port 8080
}
:8443 {
    respond "this is a test"
    tls localhost.crt localhost.key
}

And then:
caddy run

And now we can see that curl trusts the certificate:
$ curl https://localhost:8443
this is a test

If I remove the CA certificate from the trust store:
sudo rm  /etc/pki/ca-trust/source/anchors/myCA.crt
sudo update-ca-trust

Then we will see that curl fails:
$ curl https://localhost:8443
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.


How to use Git pull requests when testing on feature branch

Question: We have just upgraded to the latest version of BitBucket, which allows us to disable direct pushes to the master branch. Now we are using a version of the Github Flow process (i.e. cloning feature branches from the master branch), and can only use pull requests to merge from feature/bugfix branches to the master.
We would like to perform our tests (some automated, some manual) while still working on the feature branch, and before merging onto the master branch. I was thinking of using the pull request cycle as follows:

issue pull request for feature
pull request approved by team
test the feature
after tests completed, merge to master

If we wait until after pushing to the master before testing, this might lead to bugs and regressions also being introduced onto the master.
My question is this: Since there is always the possibility that other users can merge to the master using other pull requests, this would mean that my pull request might have to be rebased to the updated state of the master if some time had elapsed after the pull request was initially opened. This means either performing the tests again, or locking the repository while at least one outstanding pull request is active. But locking the repository also has its problems, since no one else would be able to work.
Has anyone else come across this problem?
Thanks,
Paul
Comment: I think your assumption is wrong. Testing on pullRequest "merge commit" actually tests "feature branch merged to base branch (master in this case)", so it actually does the integration test. It does not test feature in isolation
Answer: Yes, contention on merging to master is an issue for any team using feature branches.
Teams work fastest if they can work independently and don't have to coordinate, so locking is usually not a good solution.
The usual solution is something like this:

Develop the feature on its feature branch
Test the feature
Rebase the feature branch against master (or merge master into the feature branch)
If there were significant merge conflicts, go back to 2.
Merge the feature branch to master
Regression-test master

This workflow works best when features are small and tests are fast, so

automate your tests as much as you possibly can. The effort will pay off. Thorough automated acceptance tests will serve both for pre-merge testing of the feature and regression testing of master.
Plan your features so that they can be developed and merged to master in small pieces. To some extent this can be done by finding parts of a larger feature that are independently useful so can be deployed and exposed to users independently. Otherwise, develop and deploy pieces of the feature without exposing them to users until the feature is complete, using a feature toggle to hide parts of the feature that would otherwise be user-visible until the feature is complete.

It will still sometimes be necessary to lock the repository for very large changes which can't be merged in pieces, such as framework upgrades.


Why can't I find the certificate by store name and hash?

Question: In my code I enumerate all local IIS sites and for each site I try to validate the certificate for port 443.
using( var sm = new ServerManager() ) {
  foreach( var site in sm.Sites ) {
    foreach( var binding in site.Bindings ) {
       if( binding.EndPoint.Port == 443 ) {
          var thumbprint = binding.CertificateHash;
          var storeName = binding.CertificateStoreName;
          //validation here...
       }
    }
  }
}

This code yeilds the storeName being "MY" and thumbprint being some byte array that I convert into a hex representation.
Now the "validation" part works like this:
var store = new X509Store("MY");
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates;
//find and validate my cert
store.Close();

and this code yields an empty collection. Yet if I change
var store = new X509Store("MY");

to
var store = new X509Store(StoreLocation.LocalMachine);

then the code yields a collection with two certificates and one of them has the right thumbprint and I can validate it.
Why does it happen that Binding returns a certificate store name but I can't find any certificates in the store with that name?
Answer: There's a difference between a store name and a store location.
All of the certificates for IIS are stored in the Local Machine location, rather than one for a specific user account.
This is what the constructor for X509Store looks like, that just takes a StoreLocation, that your second example is calling:
public X509Store(StoreLocation storeLocation) : this("MY", storeLocation)
{
}

Which is calling the constructor that takes both a store name and a location.
Your first example:
var store = new X509Store("MY");

Is opening the MY store for the CurrentUser, not the local machine. So you're looking in the wrong store. Switch to using the constructor that takes both a name and a location.
Answer: This method will get certificate for you:
private X509Certificate2 GetServiceCertificate(String certificateSubjectName, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.CurrentUser)
{
    X509Store certificateStore = new X509Store(storeName, storeLocation);
    foreach (X509Certificate2 certificate in certificateStore.Certificates)
    {
        if (certificate.SubjectName.Name == certificateSubjectName)
        {
            return certificate;
        }
    }
    return null;
}

Comment: Great, except I don't know the certificate subject.


Certificate and provisional profile issues

Question: Not sure if it is Certificate but #Invalid Provisional Profile#
Here is the error:

ERROR ITMS-9000: "Invalid Provisioning Profile. The provisioning
  profile included in the bundle com.DOMAIN.APPNAME
  [Payload/APPNAME.app] is invalid. [Missing code-signing certificate.]
  For more information, visit the iOS Developer Portal."

This error comes up in Application Loader for uploading/sending apps to the app store.
Need more info? Just ask! :)
Thanks for taking your time to help me about the is issue! :)
EDIT:
When I try to archive and distribute or validate in Xcode, the certificate/profile is invalid.
Comment: check this answer u may have same issue http://stackoverflow.com/questions/19697237/invalid-provisioning-profile-missing-code-signing-certificate
Comment: This is not helping me @user3614966
Comment: did u check in developer credential that ur certificate is valid on inactive status or try it by recreating the distribute certificate
Comment: I have done this zoo many times.. Can\t download Identity in Xcode ...
Know this problem? @user3614966
Comment: sorry im not getting wt ur saying
Comment: did u change ur appname after creating the app id
Comment: Yes, I think I did.
Whats the issue then? @user3614966
Comment: in my answer i have given reason for ur issues please check it
Comment: @user3614966 please let me know whether its working or not
Answer: The AppID/BundleIdentifier identifies a unique App. BundleIdentifier means is ur App once u created an Appid with the Bundleidentifier it cannot be changed u have changed the App name after creating the Appid so the problem is the distribute certificate which u have created with appid is not same with bundleidentifier which u have changed recently. Once u create the Appid with one Bundlename it can't changed so u need to created new appid with ur new BundleIdentifier name.
Using the new Appid create the distribute certificate then it will work.
Comment: If the apps name is ex: Stig Ping.
The identifier sets to Stig-Ping.
What do I use as APPID?
Comment: its very simple while creating appid it wont take white space so thats y we using the - symbol Stig-Ping like this nothing will happen
Comment: I will check on it later, and thanks for your help :) If it works, I will :)
Answer: I had a similar issue after I changed app name, fixed it by changing back.
Answer: Follow the steps carefully before submitting -

Your bundle id should be unique. Generate app identifier on iOS provisional portal using the bundle id. (Registering an App ID)
Then in the same portal, generate the provisional profile for your app.(development or distribution)
Download the provisional profile file and install it on xCode by double clicking.
Finally, generate the build (archive) and upload to iTunes connect.


Trouble writing binary numbers in a file using Pandas

Question: My code consists of removing the redundancy from the code as a form of backup. But when writing again in the file it removes the zeroes to the left of the 1. Like in the image below
https://imgur.com/a/OU07DzX
mydataset2 = pd.read_csv('fieldstatebackup.binetflow')

mydataset2.drop_duplicates(['State2','State'], keep='first', inplace=True)
mydataset2.to_csv('fieldstatebackup.binetflow', columns=['State2', 'State'], index=False)

Answer: The easiest solution is probably to read the data as string. Otherwise, the data is read as numerical where leading zeros are dropped. Plus the data is interpreted using decimal numeral system by default, which is not what you'd want anyway.
pd.read(csv('fieldstatebackup.binetflow', dtype=str)


Inject a service from a class library to another class library

Question: I have two class libraries and a console application,
in my console application I have:
class Program
{
    static void Main(string[] args)
    {
        IConfiguration config = new ConfigurationBuilder()
        .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
        .AddJsonFile("appsettings.json", false, true)
        .Build();

        var services = new ServiceCollection()
            .AddSingleton(provider => (IConfigurationRoot)config)
            .AddDbContext<Context>(options => options.UseNpgsql(config.GetConnectionString("DefaultConnection")))
            .AddScoped<IQueryService, QueryService>()
            .BuildServiceProvider();

        var a = new MockReader.MockDataServer();
        a.ReadData();
    }
}

One of the class libraries is a classic database project, reading/writing to the database, and that library defines and implements a service, IDataService. It defines fx the method
public List<int> getAll()

The second class library is supposed to be created by the console app and should have access to the IDataService methods
public class MockDataServer
{

    private IQueryService _queryService;
    public MockDataServer (IQueryService queryService)
    {
        _queryService = queryService;
    }

But I dont know how to give it access/resolve properly?
Answer: Add the server to the service collection as well so that the built provider is aware of how to resolve its dependencies.
//...

var services = new ServiceCollection()
    .AddSingleton(provider => (IConfigurationRoot)config)
    .AddDbContext<Context>(options =>
        options.UseNpgsql(config.GetConnectionString("DefaultConnection"))
    )
    .AddScoped<IQueryService, QueryService>()
    .AddScoped<MockDataServer>() //<-- Add server
    .BuildServiceProvider();

MockDataServer server = services.GetService<MockDataServer>();
server.ReadData();

The console in this case acts as the composition root and needs to be are of all types involved in order to perform its designed function.
Comment: Thank you! I did almost that, I made an interface for the MockDataServer as well and added that similarily to the services


Assign NTFS permission using Powershell via CSV

Question: I have a CSV file as below
Foldername----------    Securitygroup
Folder1----------             SG_Folder1-Access
Folder2----------     SG_Folder2-Access
I need to assign permissions like below,
so Security Group " SG_Folder1-Access " will have modify access on "Folder 1"
Security Group " SG_Folder2-Access " will have modify access on "Folder 2"
I have 500 folders and their own security group and need to create a power shell  script to assign permissions.
Any help would be much appreciated.
Thanks
Comment: That doesn't look by any means like a csv [comma separated file](https://en.wikipedia.org/wiki/Comma-separated_values) If you have a real csv file you can use Import-csv, if necessary with a `-Delimiter ';'` and/or `-Header FolderName,SecurityGroup` parameter .
Answer: You can try the following script:
<code>$acl = Get-Acl "\\$servername\folderpath"

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("domain\user or usergroup","Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users","Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)

Set-Acl "\\$servername\folderpath" $acl
</code>
Here are informative links for help.
http://tomandersonpro.net/ntfs-permissions-with-powershell/
https://blogs.technet.microsoft.com/josebda/2010/11/12/how-to-handle-ntfs-folder-permissions-security-descriptors-and-acls-in-powershell/
Answer: <code>$CSV= Get-Content $CSVFileName
foreach ($line in $CSV) {
    $folder= $line.split(";")[0]
    $group= $line.split(";")[1]

    $acl= Get-Acl $folder
    $ar = New-Object system.security.accesscontrol.filesystemaccessrule($group,"Modify","Allow")
    $acl.SetAccessRule($ar)

    $Set-Acl $folder $acl
}
</code>
I haven't tested it but this is a basic idea. Try to improve it by yourself.
Also follow this links:
Set-Acl
Get-Acl
MS Technet
Answer: I've written a support methods that can help you achieve it in easy way.
<code>function Remove-Permission($StartingDir, $UserOrGroup = "", $All = $false) {
    $acl = get-acl -Path $StartingDir
    if ($UserOrGroup -ne "") {
        foreach ($access in $acl.Access) {
            if ($access.IdentityReference.Value -eq $UserOrGroup) {
                $acl.RemoveAccessRule($access) | Out-Null
            }
        }
    }
    if ($All -eq $true) {
        foreach ($access in $acl.Access) {
            $acl.RemoveAccessRule($access) | Out-Null
        }

    }
    Set-Acl -Path $folder.FullName -AclObject $acl
}
function Set-Inheritance($StartingDir, $DisableInheritance = $false, $KeepInheritedAcl = $false) {
    $acl = get-acl -Path $StartingDir
    $acl.SetAccessRuleProtection($DisableInheritance, $KeepInheritedAcl)
    $acl | Set-Acl -Path $StartingDir
}
function Set-Permission($StartingDir, $UserOrGroup = "", $InheritedFolderPermissions = "ContainerInherit, ObjectInherit", $AccessControlType = "Allow", $PropagationFlags = "None", $AclRightsToAssign) {
    ### The possible values for Rights are:
    # ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, Synchronize, FullControl
    # ReadExtendedAttributes, WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, ReadAttributes
    # WriteAttributes, Write, Delete, ReadPermissions, Read, ReadAndExecute, Modify, ChangePermissions, TakeOwnership

    ### Principal expected
    # domain\username

    ### Inherited folder permissions:
    # Object inherit    - This folder and files. (no inheritance to subfolders)
    # Container inherit - This folder and subfolders.
    # Inherit only      - The ACE does not apply to the current file/directory

    #define a new access rule.
    $acl = Get-Acl -Path $StartingDir
    $perm = $UserOrGroup, $AclRightsToAssign, $InheritedFolderPermissions, $PropagationFlags, $AccessControlType
    $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $perm
    $acl.SetAccessRule($rule)
    set-acl -Path $StartingDir $acl
}
</code>
Now if you were to use it... just loop thru csv entries and provide it to functions.
Full story is available on my website: https://evotec.xyz/manage-ntfs-permissions-powershell/


Ring of even integers

Question: So I am given a ring of even integers.  It is an isomorphism of Z to R that is defined by f(x)=2x+4.  I am trying to find the O(R) and the 1(R).  I just set the function equal to 0 or 1 but apparently that is not the right thing to do in this case. Any rational as to what I am doing wrong or the correct way to think about it to set it up right?  Should you plug in 0 for 2 instead?
Comment: "Let $R$ be the set of even integers made into a ring with some addition and multiplication operations. Suppose $f:\Bbb Z\to R$ given by $x\mapsto 2x+4$ is a ring isomorphism. What are $0_R$ and $1_R$?" I'd have understood the problem instantly if you'd said this, for instance. The fact that multiple people have addressed a different form of question and you're spending time to explain yourself indicates that you were not clear to begin with in the original post.
Comment: It seems like $f$ is not an isomorphism since $f(0)\neq 0$
Comment: the question says it is an isomorphism
Comment: @DaenerysNaharis it must not be a ring under usual addition and multiplication.
Comment: Oh yeah sorry, we suppose there are special rules for both in this problem
Comment: Your question is very hard to read. Is English your first language? If so, it might help to cite the problem word-for-word.
Comment: I find it pretty easy to read, and yes it is.
Comment: R is a ring of even integers with special rules for multiplication and addition.  Suppose that f : Z to R is an isomorphism that is defined by f(x) = 2x+4. Which integer in the ring is the identity and which is the zero (0(R)).
Comment: alright ill make sure to do better next time
Answer: The addition on $R$ has not been specified. If $f$ is to be an additive group isomorphism, then the addition $\oplus$ on $R$ has to be defined by $2s\oplus 2t=2s+2t-4$.
This is because $2s=f(s-2)$ and $2t=f(t-2)$. Since $f$ is an additive group isomorphism, we have $f((s-2)+(t-2)=2s\oplus 2t$. But
$$f((s-2)+(t-2))=2s+2t-8+4=2s+2t-4.$$
Now the zero-element is not hard to identify. Call it $2z$. Then we want $2s\oplus 2z=2x$. That gives $2z=4$.
Do something similar to identify the  multiplication $\otimes$ on $R$.
Answer: Since $f$ is an isomorphism, it sends $0$ to $0(R)$ and $1$ to $1(R)$.  So you're correct in setting the function equal to $0$ and $1$, respectively (that is, taking $f(0) = 4$ and $f(1) = 6$).
Let's find the units of $R$.  The units of $\mathbb Z$ are $-1$ and $1$, and since this is an isomorphism, $f$ maps units to units, so the units of $R$ are $f(-1) = 2$ and $f(1) = 6$
Comment: So just for the sake of my final exam I kind of want to look at the regular stuff for a ring of integers (units are 1,-1, identity is 1, zero is 0) and just know that because it is defined by a function that these will be different based off that function pretty much.
Comment: refer to my comment above with the whole question written out
Comment: @D-Man The answer still stands; just ignore the second paragraph.
Comment: this was a question on my test and I got this wrong.  I am pretty sure that my teacher said to just plug in 1 and 0 for x.
Comment: @D-Man then we are all in agreement.
Comment: so if i were to find the units I would set 2x+4=6 because we need xc=1(R)=6 where c is an integer in the ring? but that would give 2 and 1 are units but since it is only even integers it is just 2?
Comment: The fact that it is even integers is irrelevant.  The $1$ of $R$ is $f(1)$, since $f$ is an isomorphism.  $f(1) = 6$.  We don't solve any equations, (we only solve the equation $2x+4 = 6$ if we know $6$ is the $1(R)$ and we're trying to get the unity of $\mathbb Z$.
Comment: so 1 would be the unit... now just basing it off of my books definition of unit like i used above there needs to be ac=1(R), im just trying to relate this to the ring and its polynomial.  what would be the a and what would be the c based off the ring? or is that just looking at it in the wrong way?
Comment: @D-Man You're confusing unit with unity.  $1$ is a unity, whereas you're giving the definition of a unit.  $-1$ is a unit in the ring $\mathbb Z$ since $-1 \cdot -1 = 1$, but it is not *the* unity $1$.
Comment: yeah the question was what are the units in R?
Comment: @D-Man OK, the answer has been updated in light of this.
Comment: and also would you know how to find the special rules of addition and multiplication? i am given a hint that i should let a =f(x) and b=f(y).
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14347/discussion-between-andrew-salmon-and-d-man)
Comment: i do not have the reputation unfortunately
Comment: I wouldn't have said 'set the function equal to 0' even with the clarification; to me, that implies solving the equation $f(x)=0$ for $x$.  Rather, a better phrase might be 'seeing where the function takes 0 to'.
Comment: Here's what I wrote up in chat:OK, so let's just go through this.
Let's use +' for addition in our new ring R and *' for multiplication.
f(a+b) = f(a) +' f(b)
2(a+b) + 4 = 2a+4 +' 2b+4
This doesn't give us any information yet--we want an expression for 2x +' 2y, so we have to make a change of variables first.
2x = 2a + 4, so 2x - 4 = 2a. Similarly, 2y - 4 = 2b.
So 2x-4 + 2y-4 + 4 = 2x +' 2y
And 2x +' 2y = 2x + 2y - 4
Do the same for *'

Ring of even integers


Unrealistic coefficients when comparing two count samples with glm poisson

Question: I would like to test the significance of the difference in mean between two independent count samples. I'm doing this with a GLM poisson in R, as shown in the code below:
a=c(0,0,0,0,0,0,0,0,0,0)
b=c(1,2,0,1,1,2,0,1,0,2)

c=data.frame(sp=c(a,b),grp=c(rep('A',10),rep('B',10)))

summary(glm(sp~grp,data=c,family=poisson))

Call:
glm(formula = sp ~ grp, family = poisson, data = c)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.41421  -0.00006  -0.00006   0.00000   0.87897

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)    -20.3     4914.8  -0.004    0.997
grpB            20.3     4914.8   0.004    0.997

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 22.1807  on 19  degrees of freedom
Residual deviance:  8.3178  on 18  degrees of freedom
AIC: 28.159

Number of Fisher Scoring iterations: 18

As you can see, the coefficient values are not reflecting reality. I noticed that this happened because group "A" has mean=0.
In this way, I would like to know if there is any way to fix this problem in glm, or if there is any other better method to test my hypothesis.
Answer: The expected value predicted by Poisson regression is
$$
E[y|X,\beta] = e^{\beta_0 + \beta_1 X}
$$
assuming we're using the standard log link function. So your model predicts:
> beta <- c(-20.3, 20.3)
> exp(beta[1] + beta[2] * 0)
[1] 1.52694e-09
> exp(beta[1] + beta[2] * 1)
[1] 1
> mean(a)
[1] 0
> mean(b)
[1] 1

I would say that there's nothing wrong with the predictions. The only issue is that you are assuming Poisson distribution for a group that has zero mean, while the distribution is parametrized by $\lambda \ge 0$.
Answer: If willing to do an alternative test, here is code to do an E-test for the difference in Poisson means:
# Forgive me, will make putting this in a package on my ToDo list
source('https://dl.dropboxusercontent.com/s/r4zmlxmi41tqsts/ETest.R?dl=0')
poisson.etest(0,10,10,10)

Which returns a p-value of 0.0005782135.
If you want/need to stick with GLM's, it is common for logistic regression to use penalized regression for perfectly separated data. It may also make sense here for Poisson, although there isn't an obvious default for the penalties, nor am I sure about how the standard errors/coverage for coefficients will behave.


What Is Bigger $100^{100}$or $\sqrt{99^{99} \cdot 101^{101}}$

Question: Hello every what is bigger $100^{100}$or $\sqrt{99^{99} \cdot 101^{101}}$?
I tried to square up and I got $100^{200}$ or $99^{99} \cdot 101^{101}$ and I don't have an idea how to continue.
Comment: I think I would divide them, and check if the result is larger or smaller than 1. Hint: The result may have some repeating structure, and substitute, and think about the graph
Answer: Taking logarithms, we see that we want to compare $f(100)$ and $\frac12(f(99)+f(101))$, where $f(x) = x\log x$. But $f(x)$ is a convex function (its second derivative $\frac1x$ is always positive), which means that the the secant line through $(99,f(99))$ and $(101,f(101))$ lies above the graph of the function. In particular, the fact that the midpoint of this secant line lies above the point $(100,f(100))$ on the graph is exactly the statement that $\frac12(f(99)+f(101)) > f(100)$, and so $\sqrt{99^{99}101^{101}} > 100^{100}$.
Comment: Thank you very much!!!
Answer: Let $f(x)=x\ln{x}$.
Thus, $f$ is a convex function.
Thus, $$x\ln{x}+y\ln{y}\geq2\cdot\frac{x+y}{2}\ln\frac{x+y}{2}$$ or
$$x^xy^y\geq\left(\frac{x+y}{2}\right)^{x+y}.$$
Now, for $x=101$ and $y=99$ we obtain
$$99^{99}101^{101}>100^{200}$$ or
$$\sqrt{99^{99}101^{101}}>100^{100}.$$
Answer: It is "well-known" that $\log(u) \le u-1$ for all $u>0$, with strict inequality for $u \ne 1$ (see for example for each $x>1 , \frac{x-1}{x}\ < \ln x < x-1$).
It follows that for all real $x > 1$
$$
 \log \left( \frac{x^{2x}}{(x-1)^{x-1} (x+1)^{x+1}}\right)
= (x-1) \log \left( \frac{x}{x-1}\right) + (x+1) \log \left( \frac{x}{x+1}\right) \\
< (x-1) \left( \frac{x}{x-1} - 1 \right) + (x+1) \left( \frac{x}{x+1} - 1\right)
= 1 - 1 = 0
$$
and therefore
$$
x^x < \sqrt{(x-1)^{x-1} (x+1)^{x+1}} \, .
$$


What is the area of the part of the plane $2x + 2y - z = 10$ that lies in the cylinder $x^2 + y^2 = 4$?

Question:
Calculate the area of the part of the plane $2x + 2y - z = 10$ that lies in the cylinder $x^2 + y^2 = 4$.

What can I use to solve this? Can I use the Green's theorem?
Answer: Think about projecting onto the $xy$-plane. What is the relation between the two areas? Hint: The angle between the two planes is relevant.


hook_field_schema not being used

Question: I'm trying to create a field with an additional property (or column) to define an extra relationship to a taxonomy term.
I have this in my module file:
/**
 * Implements hook_field_info().
 */
function emtr_field_info() {
    return array(
        // We name our field as the associative name of the array.
        'field_emtr_denominations' => array(
            'label' => t('Denominations'),
            'description' => t('Field linked to target entity as well as denomination taxonomy term holding denomnation value.'),
            'default_widget' => 'number',
            'default_formatter' => 'number_decimal',
        ),
    );
}

And this in my install file:
/**
 * Implements hook_field_schema().
 */
function emtr_field_schema($field) {
    $columns = array(
        'denomination_value' => array(
            'type' => 'int',
            'not null' => FALSE,
        ),
        'denomination_tid' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
        ),
    );
    $indexes = array(
        'denomination_tid' => array('denomination_tid'),
    );
    return array(
        'columns' => $columns,
        'indexes' => $indexes,
    );
}

/**
 * Implements hook_enable().
 */
function emtr_enable() {

    field_cache_clear();
    field_associate_fields('emtr');

    if (field_info_field('emtr_denominations')) return;

    // Create a field for denominations to be used by safe checks and till reads
    $field = array(
        'field_name' => 'emtr_denominations',
        'type' => 'field_emtr_denominations',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
        'translatable' => FALSE,
    );
    field_create_field($field);

    // Attach the emtr_denominations reference field to safe checks instance
    $instance = array(
        'field_name' => 'emtr_denominations',
        'entity_type' => 'emtr_safe_check',
        'bundle' => 'emtr_safe_check',
        'label' => 'Denominations',
        'required' => false,
        'widget' => array(
            'type' => 'number'
        ),
        'settings' => array(
            'target_type' => 'emtr_safe_check',
            'handler_settings' => array('target_bundles' => NULL),
        ),
        'display' => array(
            'default' => array('label' => 'inline', 'type' => 'number_integer'),
        ),
    );
    field_create_instance($instance);
}

But after uninstalling and re-enabling my module (drush devel-reinstall emtr -y
) a table called field_data_emtr_denominations is created but it does not have my 2 custom columns.
At what point in this process should I tell Drupal to use my custom field_schema?
Comment: I'm not sure what I've done but after a couple more hours repeatedly installing and uninstalling my module it started working. I think maybe there was a conflict with another field created though the field UI but I'm not entirely sure. But for future reference the above code is now working fine.
Answer: You should remove function emtr_enable() out of the .install file, and place its code in a more proper hook where the field is meaningful to be created, like for instance hook_node_type_insert() or EntityAPIController-derived class for your entity bundle, etc.  It depends on what one wants to achieve really.
Comment: emtr_enable implements hook_enable. I would put the code in there in hook_install however I understood that that would lead to problems as my hook_field_schema would not have run when the hook_install runs. Hook enable can only live in the modules install file so I can't move that anywhere else.

hook_field_schema not being used


Hide or remove the "Remove" button, "Quantity" box, and Price for specific product/SKU on cart page of Ubercart

Question: I have a zero-dollar product that, once added to the cart, should never be removed until checkout is completed. Currently, that product has the "Remove" button, "Quantity" field, and Price that all products are displayed with in the cart. How can I remove those three items just for this one product/SKU?
Thanks!
Answer: You could achive this with hook_form_alter() and hide the field with $form['field_name']['#access'] = FALSE;
Comment: Thanks! Do you have any ideas/guidance on how I would target the form elements only for the specific product, and leave all the other products' form elements alone?
Comment: I hope, you could get product id in the form, just make the changes only for the product id with in the if condition,


Jasper Print - Java Heap space memory

Question: Am using Jasper Reports to generate the reports. But I have huge data coming from the Database. While executing Jasper print to fill the Report data, it is taking huge memory and giving the Java Heap Space memory issues.
JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, params, dataSource);

This is the line taking so much time and giving error.
Please help me, how to come out of this issue.
Stackrace :
java.lang.OutOfMemoryError: Java heap space
    at net.sf.jasperreports.engine.fill.JRFillTextField.fill(JRFillTextField.java:691)
    at net.sf.jasperreports.engine.fill.JRFillElementContainer.fillElements(JRFillElementContainer.java:570)
    at net.sf.jasperreports.engine.fill.JRFillBand.fill(JRFillBand.java:390)
    at net.sf.jasperreports.engine.fill.JRFillBand.fill(JRFillBand.java:351)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2039)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:771)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportContent(JRVerticalFiller.java:301)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:148)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:909)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:841)
    at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:88)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:653)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:969)
    at com.jci.eprt.web.controller.report.ReportController.previewEngineeringReport(ReportController.java:250)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.jci.eprt.service.utility.helper.JCIUserFilter.doFilter(JCIUserFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

Answer: This is a common issue when you are dealing with reports with huge result set. An obvious solution is not to read the whole result-set at once and try reading it incrementally instead.
A detailed explanation about dealing with this issue is provided in Java DevZone: Generating Huge reports in JasperReports. A few lines written in this reference:

There are certain things to care while implementing the Jasper Reports for huge dataset to handle the memory efficiently, so that the appliacation does not go out of memory.
They are:
1) Pagination of the data and use of JRDataSource,
2) Viruatization of the report.
Answer: Tomcat web server often suffers from java.lang.OutOfMemoryError: PermGen space whenever you deploy-undeploy your web application couple of time. No matter you are using tomcat6, tomcat7 or using bundled tomcat in Netbeans or Eclipse you will face this error now and then while developing web application on tomcat server.
Try to increase PermGen Space of heap. you can refer this Link
Comment: The question is referring to heap space, not permgen space. Heap and permgen are two different things.

Jasper Print - Java Heap space memory


Tensorflow confusing error reading images with labels

Question: I'm trying to read a set of images and labels for batch training, but I keep getting the error:
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

Here is my very reduced code that reproduces the error:
import tensorflow as tf
import numpy as np

image = tf.image.decode_jpeg('C:\\Users\\Alex\\Documents\\Programing\\Python\\cs_dataset\\square.jpeg', channels = 1)
image.set_shape([15, 15, 1])
label = np.array([0, 1])
tf.convert_to_tensor(label)

ibatch, lbatch = tf.train.batch([image, label], batch_size=1)
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    init_op.run()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    sess.run(ibatch, lbatch)
    coord.request_stop()
    coord.join(threads)

I only used one image in this example.
What is the cause of this error in this simple example?
A related question that didn't help:
Tensorflow read images with labels
Comment: At what lines does this error occur? Also it should be `sess.run([ibatch, lbatch])`.
Comment: @bodokaiser Also, can you post that as a full reply?
Comment: @bodokaiser line 16, "sess.run(ibatch, lbatch)". Your fix worked, Thanks!
Answer: If you want evaluate multiple tensors in a session you need to pass them in an array fetches to session.run(fetches).
So change sess.run(ibatch, lbatch) to sess.run([ibatch, lbatch]) see docs for more.


Cauchy's Formula

Question: In the proof for Cauchy's Formula in my notes it states that $$\frac{1}{2\pi i}\int_{∂D}\frac{dw}{w-z}=1,$$ can somebody please explain why this is to me. Is it something to do with Euler's identity?
If anybody could help me it would be much appreciated, sorry if this is not explained very well.
Thanks very much,
Comment: Is $w$ a function of $z$?
Comment: No, I'm pretty sure w is just another member of the domain
Comment: It is linked to the existence of the *complex logarithm*.
Comment: I've just googled that and that makes sense now, there was absolutely zero explanation of that in my note. Thanks very much
Answer: You can suppose that $\partial D$ is the circle of center $z$ and radius $r$, parametrize it $w = z + re^{it}$, $t\in[0,2\pi]$ and calculate directly the integral:
$$\frac{1}{2\pi i}\int_{|w - z| = r}\frac{dw}{w-z} = \cdots$$
Can you continue?
Answer: $$
\int_{\partial D} \frac {dw} w
$$
For the moment let's suppose $\partial D$ is the circle of unit radius centered at $0$ and you're going around in the counterclockwise direction. Think of $dw$ as an infinitely small change in $w.$ The direction in which you move around the circle is alwasy $90^\circ$ counterclockwise from the direction from $0$ out to $w.$ Multiplication by $i$ is a $90^\circ$ counterclockwise rotation. Therefore $\dfrac{dw} w = i \, \left| \dfrac{dw} w\right| = i\,\left|dw\right|.$ Hence
$$
\int_{\partial D} \frac{dw} w = \int_{\partial D} i\,\left|dw\right|.
$$
The value of the integral is then $i$ times the length of the curve.
Now supposing $D$ is not the unit disk centered at $0.$ There's a short intuitive argument, which can be made rigorous, showing that integrals along curves homotopic to each other are equal. The reason the boundary of the disk is not homotopic to zero is that it winds around the origin, which is a point that is not in the domain.

Cauchy's Formula


Combinatorial proof - ladder problem - take 1 or two steps at a time

Question: A ladder consists of 12 steps . A man wants to go up through the ladder. He may take 1 or two steps at a time or any combination of these two . Find the total number of ways he can go up .
This question is taken from here and answer given says, as the number of steps increases, the solution goes as fibonacci numbers,
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
But, can anybody please provide a combinatorics proof for this or this fibonacci numbers algorithm is the only standard way of solving this?
Answer: Let $a_n$ denote the number of ways the fellow can get to step $n$.  Look at the last step; by definition it must be either $1$ or $2$.  If $1$, then he got to step $a_{n-1}$ and stepped $1$.  If $2$ then he got to $a_{n-2}$ and stepped $2$.  Hence we have the recursion $$a_{n}=a_{n-1}+a_{n-2}$$ which is the same recursion satisfied by the Fibonacci numbers.  All that remains is to compute $a_n$ for some small $n$, but that is not difficult.
Comment: so answer is 233 for the given question?
Comment: Yes, it is $233$.
Answer: Let $n$ be the number of rungs on the ladder. For $n=0$ and $n=1$, there is exactly one way to climb the ladder. For $n>1$, the man may climb $n-1$ rungs, and then take one step, or climb $n-2$ rungs, then skip one. This exhausts all possibilities, so if $F(n)$ counts the number of ways to climb $n$ rungs, $F(n) = F(n-1)+F(n-2)$.
Comment: so answer is 233 for the given question?


How can I achieve this functionality?

Question: I am a new vibe drupal developer and I have created content type as an event which displays on home page upcoming event as blogs
i have created a simple blog event using view home page but I don't know how to achieve these using view or other modules. plz correct me if i am wrong thanks in advance
Expected result
when a user clicks these of any event it displays image and title description main square

image
event title

One
event description

title: 1 jan(Date)
description:event description
title: 2 jan(Date)
description:event description
title: 3 jan(Date)
description:event description
Answer: I assume you have already added the image and event description, etc. as fields for the event content type.
For custom content types, normally you control the display using the Manage Display link from Structure -> Content Types -> Edit.
You can rearrange the fields how you want in the UI, and you can also use a Twig theme template to customize the specific HTML.  Core also provides the Layout Builder module to make something more complex.
It's also possible to use Views to overwrite the default content page, but it is usually easier to use Twig templates and/or Layout Builder.  If you do want to use Views, take a look at the core Taxonomy Term display to see how Views can be used to override a path for a custom content type.
Comment: thank you for guide me. help me any other tutorial which i should read ?layout builder and view
Comment: If you don't know about the differences between Views and Layout Builder, it's probably good to read a whole book about Drupal, not just a tutorial: https://www.drupal.org/books
Comment: i am small knowlage about view.layout builder and view combine can i achive this?
Comment: As I wrote in my answer, you don't need Views for this. You can use theme templates combined with fields to do this easily.

How can I achieve this functionality?


How to enter in textarea in WYSIWYG editor in behat

Question: I'm trying to insert text into a textarea with a wysiwyg editor (summernote) from a form, i'm using behat featurecontext file for this. The textarea doesn't have a id tag so i need to select the class using javascript code:
 document.getElementsByClassName('note-editing-area').item(0).innerText="something"
But when i do this, also the innerhtml is overwritten with the text from innerText.
Any suggestions?
Answer: Best way is to set an id or class and select that. If you do not use that it is way more difficult to maintain. You could add this through twig:
{{ form_widget(form.task, {'attr': {'class': 'task_field'}}) }}