text:
Q: Why does the MsbuildExtension Detokenise class reload the project? This is problematic because any Properties being passed in are lost.
Further Explanation: I pass in a  property to the project file. This property is a path to a .props file. It contains tokens and replacement values for the detokenise class. The task apparently reloads the project and the path is not maintained. This doesn't seem to be the case for other task, for example the guid tasks.
In the example I am using a example proj entitled guids.proj
Invoked Using :
<MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetFiles="@(FileCollectionToBeDetokenized )"/>

Some command line out put follows :
Task "MSBuild.ExtensionPack.FileSystem.Detokenise" (TaskId:11)
  Detokenise Task Execution Started [13:04:35] (TaskId:11)
  Loading Project: C:\Users\bstrausser\Desktop\guids.proj (TaskId:11)
  Detokenising Collection: 1 files (TaskId:11)
C:\Users\*****\Desktop\guids.proj(37,9): error : Property not found: Asset
Directory
Full project file :
Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Import Project="$(ParentMSBuildProjectDirectory)\Bin\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks" Condition="Exists('$(ParentMSBuildProjectDirectory)\Bin\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks')"/>
<Import Project="C:\Program Files (x86)\MSBuild\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks" Condition="!Exists('$(ParentMSBuildProjectDirectory)\Bin\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks') AND Exists('C:\Program Files (x86)\MSBuild\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks')"/>

<PropertyGroup>
    <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
    <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
    <PROPS>$(DACP)</PROPS>
</PropertyGroup>

<Import Project="$(PROPS)" Condition="'$(DACP)' != ''" />

<Target Name="Default">
    <Message text = "$(DACP)" />
    <!-- Create a new Guid and get the formatted and unformatted values -->
    <MSBuild.ExtensionPack.Framework.Guid TaskAction="Create">
        <Output TaskParameter="FormattedGuidString" PropertyName="FormattedGuidString1" />
        <Output TaskParameter="GuidString" PropertyName="GuidStringItem" />
    </MSBuild.ExtensionPack.Framework.Guid>
    <Message Text="GuidStringItem: $(GuidStringItem)"/>
    <Message Text="FormattedGuidString: $(FormattedGuidString1)"/>
    <!-- Create a new cryptographically strong Guid and get the formatted and unformatted values -->
    <MSBuild.ExtensionPack.Framework.Guid TaskAction="CreateCrypto">
        <Output TaskParameter="FormattedGuidString" PropertyName="FormattedGuidString1" />
        <Output TaskParameter="GuidString" PropertyName="GuidStringItem" />
    </MSBuild.ExtensionPack.Framework.Guid>
    <Message Text="GuidStringItem Crypto: $(GuidStringItem)"/>
    <Message Text="FormattedGuidString Crypto: $(FormattedGuidString1)"/>

    <ItemGroup>
        <FileCollectionToBeDetokenized Include="C:\Code\MSBuildGit\Configuration\TaskExecutorConfigTransforms\App.GREEN.SCRATCH.config"/>
    </ItemGroup>

    <Message text = "BaseUrl        : $(BaseUrl)" />
    <Message text = "DetokenizedTransformFile       : @(FileCollectionToBeDetokenized)" />

    <MSBuild.ExtensionPack.FileSystem.Detokenise TaskAction="Detokenise" TargetFiles="@(FileCollectionToBeDetokenized )"/>

</Target>


text:
Q: Mongoose query ignore fields not in schema Here is my schema:
const Post = mongoose.model('Post', {
  title: String,
  authorId: String,
})

I'd like to query it with:
Post.find({ authorId: '123', someField: 1 })

which results in [], how can I make mongoose ignore query fields not in the schema?

A: There is a flag strictQuery for it (https://mongoosejs.com/docs/guide.html#strictQuery)

For backwards compatibility, the strict option does not apply to the filter parameter for queries. Mongoose has a separate strictQuery option to toggle strict mode for the filter parameter to queries.

const mySchema = new Schema({ field: Number }, {
  strict: true,
  strictQuery: true // Turn on strict mode for query filters
});

const MyModel = mongoose.model('Test', mySchema);

// Mongoose will strip out `notInSchema: 1` because `strictQuery` is `true`
MyModel.find({ notInSchema: 1 });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to upgrade to the latest version from my current Ubuntu version 11.10 without data loss How can I upgrade to the latest Ubuntu version from the present version 11.10 on my DELL Inspiron N5050 laptop without data loss.
Also inform how can download the latest version.


text:
Q: Use workbench.colorCustomizations in extension?
*

*Users can customize the UI using workbench.colorCustomizations settings.

*I'd like to ship such customization in my color theme eppz! (C# theme for Unity).

*How?

I tried to contribute these values to my extension, but nor configuration, nor configurationDefaults contribution points worked. As these customizations are actually workbench user settings, I'm actually asking how to contribute value overrides to settings.json in an extension.

A: Workbench color customizations should be contributed by the theme itself, not through the settings.
In your theme's theme.json, just create a section called colors:
{
    "type": "dark",
    "colors": {
        "editor.background": "#1e1e1e",
        "editor.foreground": "#d4d4d4",
        "editorIndentGuide.background": "#404040",
        "editorRuler.foreground": "#333333",
        "activityBarBadge.background": "#007acc",
        "sideBarTitle.foreground": "#bbbbbb",
        ...
    },
    "tokenColors": "./YourTheme.tmTheme"
}

Here are our docs on contributing workbench colors. Take a look at some builtin themes for examples of this.

A: look for the settings.json file press the CTRL + P key and type settings.json inside this file you can put this information and between the quotes put the colors in hexadecimal

"workbench.colorCustomizations": {
    // Contrast Colors - The contrast colors are typically only set for high contrast themes. If set, they add an additional border around items across the UI to increase the contrast.
    "contrastActiveBorder": "",
    "contrastBorder": "",
    // Base Colors
    "focusBorder": "",
    "foreground": "",
    "widget.shadow": "",
    "selection.background": "",
    "descriptionForeground": "",
    "errorForeground": "",
    // Text Colors — Colors inside a text document, such as the welcome page.
    "textBlockQuote.background": "",
    "textBlockQuote.border": "",
    "textCodeBlock.background": "",
    "textLink.activeForeground": "",
    "textLink.foreground": "",
    "textPreformat.foreground": "",
    "textSeparator.foreground": "",
    // Button Control — A set of colors for button widgets such as Open Folder button in the Explorer of a new window.
    "button.background": "",
    "button.foreground": "",
    "button.hoverBackground": "",
    // Dropdown Control — A set of colors for all dropdown widgets such as in the Integrated Terminal or the Output panel. Note that the dropdown control is not used on macOS currently.
    "dropdown.background": "",
    "dropdown.listBackground": "",
    "dropdown.border": "",
    "dropdown.foreground": "",
    // Input Control — Colors for input controls such as in the Search view or the Find/Replace dialog.
    "input.background": "",
    "input.border": "",
    "input.foreground": "",
    "input.placeholderForeground": "",
    "inputOption.activeBorder": "",
    "inputValidation.errorBackground": "",
    "inputValidation.errorBorder": "",
    "inputValidation.infoBackground": "",
    "inputValidation.infoBorder": "",
    "inputValidation.warningBackground": "",
    "inputValidation.warningBorder": "",
    // Scroll Bar Control
    "scrollbar.shadow": "",
    "scrollbarSlider.activeBackground": "",
    "scrollbarSlider.background": "",
    "scrollbarSlider.hoverBackground": "",
    // Badge — Badges are small information labels, for example, search results count.
    "badge.foreground": "",
    "badge.background": "",
    // Progress Bar
    "progressBar.background": "",
    // Lists and Trees — Colors for list and trees like the File Explorer. An active list/tree has keyboard focus, an inactive does not.
    "list.activeSelectionBackground": "",
    "list.activeSelectionForeground": "",
    "list.dropBackground": "",
    "list.focusBackground": "",
    "list.focusForeground": "",
    "list.highlightForeground": "",
    "list.hoverBackground": "",
    "list.hoverForeground": "",
    "list.inactiveSelectionBackground": "",
    "list.inactiveSelectionForeground": "",
    "list.inactiveFocusBackground": "",
    "list.invalidItemForeground": "",
    // Activity Bar — The Activity Bar is displayed either on the far left or right of the workbench and allows fast switching between views of the Side Bar.
    "activityBar.background": "",
    "activityBar.dropBackground": "",
    "activityBar.foreground": "",
    "activityBar.border": "",
    "activityBarBadge.background": "",
    "activityBarBadge.foreground": "",
    // Side Bar — The Side Bar contains views like the Explorer and Search.
    "sideBar.background": "",
    "sideBar.foreground": "",
    "sideBar.border": "",
    "sideBar.dropBackground": "",
    "sideBarTitle.foreground": "",
    "sideBarSectionHeader.background": "",
    "sideBarSectionHeader.foreground": "",
    // Editor Groups & Tabs — Editor Groups are the containers of editors. There can be up to three editor groups. A Tab is the container of an editor. Multiple Tabs can be opened in one editor group.
    "editorGroup.background": "",
    "editorGroup.border": "",
    "editorGroup.dropBackground": "",
    "editorGroupHeader.noTabsBackground": "",
    "editorGroupHeader.tabsBackground": "",
    "editorGroupHeader.tabsBorder": "",
    "tab.activeBackground": "",
    "tab.activeForeground": "",
    "tab.border": "",
    "tab.activeBorder": "",
    "tab.unfocusedActiveBorder": "",
    "tab.inactiveBackground": "",
    "tab.inactiveForeground": "",
    "tab.unfocusedActiveForeground": "",
    "tab.unfocusedInactiveForeground": "",
    "tab.hoverBackground": "",
    "tab.unfocusedHoverBackground": "",
    "tab.hoverBorder": "",
    "tab.unfocusedHoverBorder": "",
    // Editor Colors — for syntax highlighting, use the editor.tokenColorCustomizations setting. All other editor colors are listed here
    "editor.background": "",
    "editor.foreground": "",
    "editorLineNumber.foreground": "",
    "editorLineNumber.activeForeground": "",
    "editorCursor.background": "",
    "editorCursor.foreground": "",
    "editor.selectionBackground": "",
    "editor.selectionForeground": "",
    "editor.inactiveSelectionBackground": "",
    "editor.selectionHighlightBackground": "",
    "editor.selectionHighlightBorder": "",
    "editor.wordHighlightBackground": "",
    "editor.wordHighlightBorder": "",
    "editor.worldHighlightStrongBackground": "",
    "editor.wordHighlightStrongBorder": "",
    "editor.findMatchBackground": "",
    "editor.findMatchHighlightBackground": "",
    "editor.findRangeHighlightBackground": "",
    "editor.findMatchBorder": "",
    "editor.findMatchHighlightBorder": "",
    "editor.hoverHighlightBackground": "",
    "editor.lineHighlightBackground": "",
    "editor.lineHighlightBorder": "",
    "editorLink.activeForeground": "",
    "editor.rangeHighlightBackground": "",
    "editor.rangeHighlightBorder": "",
    "editorWhitespace.foreground": "",
    "editorIndentGuide.background": "",
    "editorRuler.foreground": "",
    "editorCodeLens.foreground": "",
    "editorBracketMatch.background": "",
    "editorBracketMatch.border": "",
    "editorOverviewRuler.border": "",
    "editorOverviewRuler.findMatchForeground": "",
    "editorOverviewRuler.rangeHighlightForeground": "",
    "editorOverviewRuler.selectionHighlightForeground": "",
    "editorOverviewRuler.wordHighlightForeground": "",
    "editorOverviewRuler.wordHighlightStrongForeground": "",
    "editorOverviewRuler.modifiedForeground": "",
    "editorOverviewRuler.addedForeground": "",
    "editorOverviewRuler.deletedForeground": "",
    "editorOverviewRuler.errorForeground": "",
    "editorOverviewRuler.warningForeground": "",
    "editorOverviewRuler.infoForeground": "",
    "editorError.foreground": "",
    "editorError.border": "",
    "editorWarning.foreground": "",
    "editorWarning.border": "",
    "editorInfo.foreground": "",
    "editorInfo.border": "",
    "editorHint.foreground": "",
    "editorHint.border": "",
    "editorGutter.background": "",
    "editorGutter.modifiedBackground": "",
    "editorGutter.addedBackground": "",
    "editorGutter.deletedBackground": "",
    // Diff Editor Colors — For coloring inserted and removed text, use either a background or a border color but not both.
    "diffEditor.insertedTextBackground": "",
    "diffEditor.insertedTextBorder": "",
    "diffEditor.removedTextBackground": "",
    "diffEditor.removedTextBorder": "",
    // Editor Widget Colors - The Editor widget is shown in front of the editor content. Examples are the Find/Replace dialog, the suggestion widget, and the editor hover
    "editorWidget.background": "",
    "editorWidget.border": "",
    "editorSuggestWidget.background": "",
    "editorSuggestWidget.border": "",
    "editorSuggestWidget.foreground": "",
    "editorSuggestWidget.highlightForeground": "",
    "editorSuggestWidget.selectedBackground": "",
    "editorHoverWidget.background": "",
    "editorHoverWidget.border": "",
    "debugExceptionWidget.background": "",
    "debugExceptionWidget.border": "",
    "editorMarkerNavigation.background": "",
    "editorMarkerNavigationError.background": "",
    "editorMarkerNavigationWarning.background": "",
    "editorMarkerNavigationInfo.background": "",
    // Peek View Colors — Peek views are used to show references and declarations as a view inside the editor.
    "peekView.border": "",
    "peekViewEditor.background": "",
    "peekViewEditorGutter.background": "",
    "peekViewEditor.matchHighlightBackground": "",
    "peekViewResult.background": "",
    "peekViewResult.fileForeground": "",
    "peekViewResult.lineForeground": "",
    "peekViewResult.matchHighlightBackground": "",
    "peekViewResult.selectionBackground": "",
    "peekViewResult.selectionForeground": "",
    "peekViewTitle.background": "",
    "peekViewTitleDescription.foreground": "",
    "peekViewTitleLabel.foreground": "",
    // Merge Conflicts — Merge conflict decorations are shown when the editor contains special diff ranges.
    "merge.currentHeaderBackground": "",
    "merge.currentContentBackground": "",
    "merge.incomingHeaderBackground": "",
    "merge.incomingContentBackground": "",
    "merge.border": "",
    "merge.commonContentBackground": "",
    "merge.commonHeaderBackground": "",
    "editorOverviewRuler.currentContentForeground": "",
    "editorOverviewRuler.currentContentForeground": "",
    "editorOverviewRuler.commonContentForeground": "",
    // Panel Colors — Panels are shown below the editor area and contain views like Output and Integrated Terminal.
    "panel.background": "",
    "panel.border": "",
    "panel.dropBackground": "",
    "panelTitle.activeBorder": "",
    "panelTitle.activeForeground": "",
    "panelTitle.inactiveForeground": "",
    // Status Bar Colors — The Status Bar is shown in the bottom of the workbench.
    "statusBar.background": "",
    "statusBar.foreground": "",
    "statusBar.border": "",
    "statusBar.debuggingBackground": "",
    "statusBar.debuggingForeground": "",
    "statusBar.debuggingBorder": "",
    "statusBar.noFolderForeground": "",
    "statusBar.noFolderBackground": "",
    "statusBar.noFolderBorder": "",
    "statusBarItem.activeBackground": "",
    "statusBarItem.hoverBackground": "",
    "statusBarItem.prominentBackground": "",
    "statusBarItem.prominentHoverBackground": "",
    // Title Bar Colors (macOS)
    "titleBar.activeBackground": "",
    "titleBar.activeForeground": "",
    "titleBar.inactiveBackground": "",
    "titleBar.inactiveForeground": "",
    "titleBar.border": "",
    // Notification Colors — Notification toasts slide up from the bottom-right of the workbench.
    "notificationCenter.border": "",
    "notificationCenterHeader.foreground": "",
    "notificationCenterHeader.background": "",
    "notificationToast.border": "",
    "notifications.foreground": "",
    "notifications.background": "",
    "notifications.border": "",
    "notificationLink.foreground": "",
    // Extensions
    "extensionButton.prominentForeground": "",
    "extensionButton.prominentBackground": "",
    "extensionButton.prominentHoverBackground": "",
    "pickerGroup.border": "",
    "pickerGroup.foreground": "",
    // Integrated Terminal Colors
    "terminal.background": "",
    "terminal.foreground": "",
    "terminal.ansiBlack": "",
    "terminal.ansiBlue": "",
    "terminal.ansiBrightBlack": "",
    "terminal.ansiBrightBlue": "",
    "terminal.ansiBrightCyan": "",
    "terminal.ansiBrightGreen": "",
    "terminal.ansiBrightMagenta": "",
    "terminal.ansiBrightRed": "",
    "terminal.ansiBrightWhite": "",
    "terminal.ansiBrightYellow": "",
    "terminal.ansiCyan": "",
    "terminal.ansiGreen": "",
    "terminal.ansiMagenta": "",
    "terminal.ansiRed": "",
    "terminal.ansiWhite": "",
    "terminal.ansiYellow": "",
    "terminal.selectionBackground": "",
    "terminalCursor.background": "",
    "terminalCursor.foreground": "",
    // Debug
    "debugToolBar.background": "",
    // Welcome Page
    "welcomePage.buttonBackground": "",
    "welcomePage.buttonHoverBackground": "",
    "walkThrough.embeddedEditorBackground": "",
    // Git Colors
    "gitDecoration.modifiedResourceForeground": "",
    "gitDecoration.deletedResourceForeground": "",
    "gitDecoration.untrackedResourceForeground": "",
    "gitDecoration.ignoredResourceForeground": "",
    "gitDecoration.conflictingResourceForeground": ""
}


text:
Q: xfreerdp redirect usb webcam I'm trying to use xfreerdp to connect to a windows VM, and I need to forward the local webcam on my Ubuntu box.
My Ubuntu distro has xfreerdp "2.2.0 (n/a)"
I've found some conflicting documentation, but I believe I'm using the most recent (dated 2020 at least).
I have tried a redirection like this:
xfreerdp /usb:id,dev:1edb:be56 <other options...>

which is not rejected (as many malformed variants are) however, the windows vm does not recognize any camera being available.
Can anyone tell me what's wrong?
Or can anyone suggest how I might start to debug this? I admit I know very little about the windows side of this equation.
TIA

A: I just found a solution elsewhere to just this question that worked for myself. As ist happened, xfreerdp indeed tried to share the USB device, but the Windows 10 Host was not configured to accept it.
There are a couple of policy entries that configure this behaviour.
After setting the entries as described below I now have an audio device and a imaging device for my shared webcam.
The camera does NOT show up amongs cameras, but it is usable in "Teams" on the remote host. Performance is not that great, but even the Logitech settings app does recognize it and I can configure the behaviour. Probably the double transport of video data from the client to the host and back through the RDP session to make it available in the session is not the greatest idea.

*

*Run gpedit.msc on the target VM (the target windows 10 Virtual
Machine) to start the Group Policy Editor. gpedit.msc can be typed
in from a run dialog (use WinKey+R) if you have administrator
access, or start an elevated CMD.EXE and type gpedit.msc from the
command line.

*Locate the item *Computer Configuration \ Administrative Templates
Windows Components \ Remote Desktop Services \ Remote Desktop
Session Host \  Device and Resource Redirection* Do not allow
supported Plug and Play device redirection from the treeview of the
Group Policy Editor.

*set this item to Disabled.

*Run gpupdate /force from an elevated command prompt.

*At least disconnect RDP session and connect again, if this does not
work reboot target VM.
https://stackoverflow.com/questions/33719489/how-to-enable-usb-redirection-in-windows-10/46628854


text:
Q: Is "recyclist" a word? If you are a person who avidly recycles, are you a recyclist?

A: Apart from deliberately quirky usage, I think not. You'd be a recycler.
Things can always change, but I don't think there's really a case for accepting recyclist as a valid English word just yet.

A:
It doesn't even show in the NGram Viewer but there's at least 77 books that mention "recyclist"

A: The OED (Oxford English Dictionary) classifies it as rare (and maybe it means something else too, but I'm not sure from the definition given), while the OALD and the NOAD don't even mention it.
The word you're looking for is recycler, which doesn't appear in the OALD, but on the NOAD it's given as a derivative word from Recycle and on the OED "One who or that which recycles (waste products, etc.)."

A: The third edition of the Oxford English Dictionary ("fully updated"online, March 2016) has the following definition for
recyclist

An advocate of the recycling of waste products; a recycler.

and includes two usage examples not included in previous versions of the entry for this word,  namely

1986   Peace News 23 May 17/1,   I recommend all people who are tree lovers, recyclists and on low incomes to read friends' copies, buy copies collectively or go to the library.
1998   N.Y. Times 20 Sept. 26   Tap-water enthusiasts and recyclists worried that plastic containers will clog landfills.

The OED has also dropped the description rare for this word.
So, yes, it's a word, and it's a synonym for recycler. Not that we needed the OED to verify this.


text:
Q: Linux: device tree to acpi driver I need help on this, my driver already work on device tree mode, and I want support acpi mode for it, I'm stuck on create partitions:
Device Tree:
&spi0 {
status = "ok";

flash: n25q256a@0 {
status = "ok";
cell-index = <0>;
#address-cells = <1>;
#size-cells = <1>;
    compatible = "n25q256a";
    reg = <0>;
    spi-max-frequency = <15000000>;
    spi-cpha;
    spi-cpol;

    partition@0x00000000 {
        label = "Boot loader";
        reg = <0x00000000 0x01000000>;
    };
    partition@0x01000000 {
            label = "n25q256a-test";
            reg = <0x01000000 0x01000000>;
    };
    partition@0x01100000 {
            label = "n25q256a-data";
            reg = <0x01100000 0x00f00000>;
    };
  };
};

Below is acpi table:
        Device (N25P){
            Name (_ADR, 1)
            Name (_CID, "N25Q256A")
            Name (_CRS, ResourceTemplate (){
                SPISerialBus(
                    0,          //Slave select CS0 (_ADR)
                    PolarityLow,        //Polarity of CS0 output(_DPL)
                    FourWireMode,       //(_MOD)
                    8,          //8-bit frame(_LEN)
                    ControllerInitiated,    //(_SLV)
                    15000000,       //Speed Hz (_SPE)
                    ClockPolarityHigh,  //(_POL)
                    ClockPhaseSecond,   //(_PHA)
                    "\\_SB.AHBC.SPI0",          //Controller
                )

            })
        //============ Partitons =========
        }

A: X86 supports ACPI Model, where as ARM, POWERPC supports dts, if you are trying to use your driver for x86, then where exactly you are trying to load this ACPI table ??. From driver perspective similar to "of_match_table" for dts, there will be "acpi_match_table" for ACPI Model


text:
Q: finding process id using program name My program receives a string (a shell script's path) as input. Now I have to launch that shell script and find out the process id for it.
I'm using the system() function to launch a shell script and after that using popen() with ps -aef | grep "ShellScript" to get its PID.
It's being suggested to me that there's a better way to do it. The way I did it will give a wrong PID if multiple scripts are running at same time.
What is the correct way to get a PID for a given script name after launching it?

A: Firstly you should not use system().
A better approach would be using fork(), which returns a PID > 0 if you are in the parent process and return 0 if you are in the child.
Any other return satus is an error and errno is set accordingly.
When you are in the child process you should exec your command, while you should either wait for it in the parent one if you want to avoid to have a zombie process or handle SIGCHLD  signal.
Always read man for better insight.
Here is a brief example
int pid = -1;

If((pid = fork()) > 0)
{
     /* Parent process*/
     wait(NULL);
}
else if(pid == 0)
{
    /*Child process*/
    execv(....);

    exit (0);
}
else
{
    /*Error*/
    perror("fork()");
}


text:
Q: Good way to delete all data according to criteria/child's value in Firebase database admin?
I want to clean up this userPublic by deleting all of its child node which has isTesting == true. I am using Firebase's cloud function. My approach would be :
const userPublic = admin.database().ref("/userPublic")
const testsInUserPublic = userPublic.orderByChild("isTesting").equalTo(true)
testsInUserPublic.once("value", dataSnapshot => {
    // ???
})

*

*Since I can only call .remove() on reference and not snapshot but to filter the child I want it returns snapshot, how can I get the reference from snapshot? (I would like to know the key XXX-XXX-XXX of each filtered child, so I can concatenate with userPublic and .remove() them one by one)

*Also, even if I can get all the references that I want to remove I think deleting them one by one by calling .remove() then wait for promise, then call the next one does not sounds like an optimal way. Are there any way to remove all of them in one go?

*If it involves calling .update() on the top userPublic node, I would have to fetch everything, remove the one with isTesting and then put the remaining back for update. This sounds like it is not efficient compared to the filtering way. As eventually the one with .isTesting is only about 5% of all data. Or is this actually the approach everyone is using?

A: You're almost there. All that's left is to create a single multi-location update from the results of your query:
const userPublic = admin.database().ref("/userPublic")
const testsInUserPublic = userPublic.orderByChild("isTesting").equalTo(true)
testsInUserPublic.once("value", snapshot => {
    var updates = {};
    snapshot.forEach(function(child) {
      updates["/userPublic/"+child.key] = null;
    });
    userPublic.update(updates);
})

Doing this with promises would not be too different:
testsInUserPublic.once("value", snapshot => {
    var promises = [];
    snapshot.forEach(function(child) {
      promises.push(child.ref.remove());
    });
    Promise.all(promises); // this returns a promise that resolves once all deletes are done, or that rejects once one of them fails
})

Performance of this will be very similar, since Firebase pipelines the requests over a single connection. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786


text:
Q: Display Google Map in extension popup I'd like to display (and work with) a Google Maps API map in an extension popup.  I added https://maps.googleapis.com and https://maps.gstatic.com/ to the content_security_policy, but apparently Maps uses inline evals (!) so this just throws errors.
I also tried to create a map page in my extension and pull it in as an iframe but it appears the Maps API detects that and just shows an image.
Any hints how to get a Google Maps API map to show in a popup?

A: We are facing the same issue. Here's what we found out.
If you are using manifest version 2, this issue cannot be fixed. See Bug raised at google maps api issues: Bug 4201
To solve this in our app, we are still using manifest version 1, and adding 'unsafe-eval' in  script-src in the Content security policy string.

A: Google has released a sandboxing mechanism for dealing with "unsafe" JS.  See it here: http://code.google.com/chrome/extensions/trunk/sandboxingEval.html
It works in Chrome Beta and at least in earlier coding seems to cover what I need.
Kinda sad you need to sandbox Google's own code, but there it is.

A: Even i'm facing the same issue. My chrome extension was mainly based on google maps.
I had functionality to show different kind of location with custom markers and it was going to be released in next few weeks. Now this has been a major blocker....


text:
Q: Applying Squeeze Principle I'm doing a university real-analysis course and just had a question about a limit and the squeeze principle.
Take...
$x_n = \frac{Sin(n)}{n}$
We know...
$\frac{1}{n} \rightarrow 0 $
Squeeze principle says...
$x_n \leq y_n \leq z_n$. Then $\forall n \geq N $
and that $x_n \rightarrow x$ and $z_n \rightarrow x$ then Then $y_n \rightarrow x $ as $n\rightarrow \infty$.
Therefore...
$\frac{-1}{n} \leq \frac{sin(n)}{n} \leq \frac{1}{n}$
Therefore by squeeze princible...
$\frac{sin(n)}{n} \rightarrow 0$
Is this correct?
Thanks!


text:
Q: Trap double-click from WebBrowser in VB6 In VB6, I am using a WebBrowser form to display all files and subfolders as medium-size icons in the style of Windows Explorer. On the form, I display a count of all files in the main folder and all subfolders.
When you double-click one of the subfolders, WebBrowser displays the contents of the subfolder in small-size icons.  I want to trap the double-click so I can trigger several actions - a form refresh, display as medium-size icons and count the number of files in the selected subfolder.
Any suggestions?


text:
Q: Change the source of Excel - Powerpoint linked charts: I created an excel template with 50+ sheets and a powerpoint file with 50+ slides, containing linked excel charts from mentioned template.
Every month, I need to build a new report by pasting the monthly data in the excel template's first sheet, which automatically populates all 50+ sheets and charts. However, when I save the file under a new name (say, February sales) the powerpoint remains linked to the empty excel template.
Is there a way how I can make Powerpoint recognise that I have saved the excel template under a new name (in a new map as well) and change the link to the February sales excel file?
Thanks a lot,
Pierre


text:
Q: SQL server views in GeoServer - problem with SQL I try to extract non-spatial data from mssql as spatial data to my GeoServer 2.1.0 installation from a SQL statement looking like this:
SELECT  database.table1.id,
    geometry::STPointFromText('POINT(' + CAST(database.table1.YCOORD AS VARCHAR(6)) + ' ' + CAST(database.table1.XCOORD AS VARCHAR(7)) + ')', 3008) AS geometry
FROM database.table1

The above given statement returns good spatial info in mssql management studio but I'm not sure how to get it working in GeoServer (I have to CAST the data as it is stored as integer). Setting up mssql as a store works fine and I know I can access its tables. I then try to execute the statement as a SQL view. That does not work :(
The geometry attribute shows up as byte[] and I can't change that.
I can't write anything in native SRS and filling in epsg:3008 in declared SRS doesn't seem to do anything when calculating the bounding box, giving the values MIN X & Y as -1 and the MAX X & Y as 0 in native bounds.

@jdeolive - not an option to try trunk at this stage, I have to convince my boss who is a die-hard ESRI-fan and stability is a must.
@unicoletti - I guess I have to read my statements better not to mix geometry and geography objects :-) thank you. It makes sense when calculating bonds, will try it tonight. Creating a view of it is what I have in mind later on. The only thing is that I'm taking my information from another view but as it is only about 6500 points I don't think it will give any larger performance issues.

A: The function STPointFromText  returns a geography type.
Try to use:
geometry::STGeomFromText('POINT(' + CAST(database.table1.YCOORD AS VARCHAR(6)) + ' ' + CAST(database.table1.XCOORD AS VARCHAR(7)) + ')', 3008)

instead.
I also suggest you create a view in the database and then have geoserver query the view. This will add a layer of indirection that increases manageability while not sacrificing performance.
If you worry about view vs query performance have a look at his technical article on MSDN, you'll find it very instructive.

A: There have been a few bugs fixed since geoserver 2.1.0, you might want to try upgrading to the latest 2.1.x nightly [1]. I actually think this may have been fixed but not 100% sure.
[1] http://gridlock.opengeo.org/geoserver/2.1.x/


text:
Q: child process created using execl is not accepting any input I wrote a program which is first replicating the current process (using fork()) and then I m creating a child process using execl().
Now the problem is that the child process is unable to accept any input.
The child.c program :
#include<stdio.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
    int p, pp;
    int a;
    char dummy;
    printf("\n enter value of a \n");
    //fflush(0); // was using to clean STDIN, STDOUT
    //fflush(1);
    scanf("%c",&dummy); // simply using to accept any new line character if present any.
    scanf("%c",&dummy); // simply using to accept any new line character if present any.
    scanf("%d",&a);
    p = getpid();
    pp = getppid();
    printf("\nI m child with pid %d and ppid %d \n", p, pp);
    char *msg = argv[1];
    printf("\n Message from parent is %s \n",msg);
    printf("\n The value of a is %d ",a);
    return 0;
}

I m compiling my child.c with the command: gcc child.c -o child to generate the object file with name child which I m using in my parent.c file
My parent.c program :
#include<stdio.h>
#include<unistd.h>

int main()
{
    int p, pp;
    p = getpid();
    pp = getppid();
    printf("\nI m parent with pid %d and ppid %d \n", p, pp);
    int b = fork();
    if (b == 0)
    {
        sleep(1);// for orphan state
        execl("./child", "child", "hello", 0);
    }
    else
    {
        printf("\nBye\n");
    }
    return 0;
}

I have tried running the program in both the orphan state and zombie state but in both the cases, the input is not getting accepted in the child process.
When I run this ./a.out of parent program the I get the following output:

I m parent with pid 6801 and ppid 4136
Bye [aupadhyay@localhost practice]$   enter value of a
I m child with pid 6802 and ppid 1
Message from parent is hello
The value of a is 0

The console is not accepting any input rather it is printing the default value of a.
Any information/help on how to get input in child process will be appreciated.

A: Note: answer significantly overhauled in light of edits and comments by @Gilles.
Although I can duplicate the behavior you describe, I can also feed input to the child via I/O redirection:
./parent <<EOF

12345
EOF

... resulting in:

I m parent with pid 4430 and ppid 2515
Bye
$
enter value of a
I m child with pid 4431 and ppid 1
Message from parent is hello
The value of a is 12345

Note that the data redirected into the parent's standard input are successfully read and echoed by the child, so the problem is not that the child cannot accept input.  That under some conditions it does not either wait for or successfully read input, but instead continues past the read attempts, can only be explained by the scanf() calls failing under those conditions.
The most plausible explanation for such failures is that the process group has been moved to the background by the time the reads are attempted.  Ordinarily, a background process that attempts to read from its controlling terminal will cause its whole process group to stop (not terminate).  In your case, however, the process group is orphaned: no process in the group has a parent inside the session but outside the group.  In this and a few other special cases, a background process's read()s from its controlling terminal, such as those underlying your scanf() calls, are required to fail, setting errno to EIO.
In that event, scanf in turn returns EOF to indicate an error, leaving errno set to EIO.  Test the return value of scanf and call perror to observe this.  The read failures are a sensible behavior, as they facilitate the processes in the orphaned group running to completion and terminating, instead of hanging, or the OS summarily killing them.  POSIX's objective here seems to be to provide graceful handling for process groups that are orphaned by termination of a parent that is a job-control shell, leaving no process with the expectation of or responsibility to restart the process group.
Yours is not the case that POSIX seems intent to cater to, but the specifications also support the observed behavior: the shell shifting the foreground process group into the background when its leader dies, yet (it seems) not putting it under job control as a background job.  As far as I can determine, POSIX does not mandate that the shell exhibit such behavior, but neither does it require otherwise.  The result is an orphaned process group in similar circumstances to those conceived by POSIX, and equally well served by the special provisions for orphaned process groups.
If you want the child to retain full access to the parent's controlling terminal then you should ensure that the parent does not terminate before the child does.  If the parent has nothing else to do in the meantime, the appropriate way to ensure that the child terminates first is for the parent to wait() or waitpid() for it:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int p, pp;
    p = getpid();
    pp = getppid();
    printf("\nI m parent with pid %d and ppid %d \n", p, pp);
    int b = fork();
    if (b == 0)
    {
        execl("./child", "child", "hello", 0);
    }
    else
    {
        printf("\nBye\n");
        wait(NULL);
    }
    return 0;
}


text:
Q: MySql Update statement (DDT-mygroupname) Database not updating, its just redirecting and not crashing
here is the code:
    protected void cmdUpdate_Click(object sender, EventArgs e)
    {

        MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;" + "pwd=password;database=ddt_data");
        conn.Open();

        string command = String.Format("update `fixture` set `referee`='" + this.txtRef.Text + "',`ScoreA`='" + this.txtScoreA.Text + "',`ScoreB`='" + this.txtScoreB.Text + "',`Winner`='" + this.txtWinner.Text + "' where `idfixture`='" + this.txtFixtureID.Text + "';", conn);
        //MySqlDataReader Reader;
        MySqlCommand Update = new MySqlCommand(command, conn);
        Update.Connection = conn;

        //Update.Parameters.AddWithValue("@Date", txtDate.Text);
        //Update.Parameters.AddWithValue("@Time", txtTime.Text);
        //Update.Parameters.AddWithValue("@Team A", txtTeamA.Text);
        //Update.Parameters.AddWithValue("@Team B", txtTeamB.Text);
        //Update.Parameters.AddWithValue("@Referee", txtRef.Text);
        //Update.Parameters.AddWithValue("@ScoreA", txtScoreA.Text);
        //Update.Parameters.AddWithValue("@ScoreB", txtScoreB.Text);
        //Update.Parameters.AddWithValue("@Winner", txtWinner.Text);
        //Reader = Update.ExecuteReader();
        //while (Reader.Read())

        //{
        //}

        Update.ExecuteNonQuery();

        conn.Close();
        Response.Redirect("FixtureEdit.aspx");

    }

A: I fixed your CommandText values and used a parameterized SQL statement. Make sure that the parameter names match the list from below.
protected void cmdUpdate_Click(object sender, EventArgs e)
{
    MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;" +
        "pwd=password;database=ddt_data");
    conn.Open();
    string command = "UPDATE fixture SET referee=@referee, scorea=@scorea, " +
        "scoreb=@scoreb, winner=@winner WHERE idfixture=@idfixture";
    MySqlCommmand update = new MySqlCommand(command, conn);
    update.Parameters.AddWithValue("@referee", this.txtRef.Text);
    update.Parameters.AddWithValue("@scorea", this.txtScoreA.Text);
    update.Parameters.AddWithValue("@scoreb", this.txtScoreB.Text);
    update.Parameters.AddWithValue("@winner", this.txtWinner.Text);
    update.Parameters.AddWithValue("idfixture", this.txtFixtureID.Text);

    // not sure what you want to achieve from this
    // MySqlDataReader reader = update.ExecuteReader();
    // while (reader.Read())
    // {
         // do something here?
    // }

    update.ExecuteNonQuery(); // use this if you don't need the DataReader
    conn.Close();
    conn.Dispose();
    Response.Redirect("FixtureEdit.aspx");

}


text:
Q: installing pyopenssl on ios when i type: easy_install pyopensll
the results are:
davie:~ root# easy_install pyopenssl
Searching for pyopenssl
Reading http://pypi.python.org/simple/pyopenssl/
Reading http://pyopenssl.sourceforge.net/
Reading http://launchpad.net/pyopenssl
Best match: pyOpenSSL 0.13
Downloading http://pypi.python.org/packages/source/p/pyOpenSSL/pyOpenSSL- 0.13.tar.gz#md5=767bca18a71178ca353dff9e10941929
Processing pyOpenSSL-0.13.tar.gz
Running pyOpenSSL-0.13/setup.py -q bdist_egg --dist-dir /tmp/easy_install-faDtsb/pyOpenSSL-0.13/egg-dist-tmp-bvjmgV
warning: no previously-included files matching '*.pyc' found anywhere in distribution
In file included from OpenSSL/crypto/crypto.c:14:
/usr/include/python2.5/Python.h:18:20: error: limits.h: No such file or directory
/usr/include/python2.5/Python.h:21:2: error: #error "Something's broken.  UCHAR_MAX should be defined in limits.h."
/usr/include/python2.5/Python.h:25:2: error: #error "Python's source code assumes C's unsigned char is an 8-bit type."
/usr/include/python2.5/Python.h:32:19: error: stdio.h: No such file or directory
/usr/include/python2.5/Python.h:34:5: error: #error "Python.h requires that stdio.h define NULL."
/usr/include/python2.5/Python.h:37:20: error: string.h: No such file or directory
/usr/include/python2.5/Python.h:39:19: error: errno.h: No such file or directory
/usr/include/python2.5/Python.h:41:20: error: stdlib.h: No such file or directory
/usr/include/python2.5/Python.h:43:20: error: unistd.h: No such file or directory
/usr/include/python2.5/Python.h:55:20: error: assert.h: No such file or directory
In file included from /usr/include/python2.5/Python.h:57,
             from OpenSSL/crypto/crypto.c:14:
/usr/include/python2.5/pyport.h:7:20: error: stdint.h: No such file or directory
In file included from /usr/include/python2.5/Python.h:57,
             from OpenSSL/crypto/crypto.c:14:
/usr/include/python2.5/pyport.h:73: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Py_uintptr_t'
/usr/include/python2.5/pyport.h:74: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Py_intptr_t'
/usr/include/python2.5/pyport.h:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Py_ssize_t'

thats just one third of the results, does anybody know what I'm doing wrong??

A: If all you want is pyOpenSSL, you can add the iNinjas Cydia repo and install it from there.
It appears that you don't have a working C compiler installed on your device. This has always been problematic for me until I found the package called "Compile C Apps iOS4". It is in the iBeta section of this repo
After installing that, try to easy_install it again if you want to install it manually.


text:
Q: Pipe multiple files from curl to other program I would like to download several images (from a server with a self-signed certificate) and view them all with feh. Is this possible with a single command? Something like curl -sk -b path_to_session_token url1 url2 | feh - - except this only feeds feh one of the files. Preferably without saving to a file and deleting it afterwards.

A: feh will not be able to distinguish between several images sent on its standard input, unless some kind of "protocol" is implemented.
If you don't want to use temporary files, you could maybe use a loop:
for url in 'url1' 'url2'; do
    curl -skb token "$url" | feh -
done

This will download and display each image one after the other. If you'd rather have several viewers opened at the "same time", add a little ampersand to it:
for url in 'url1' 'url2'; do
    (curl -skb token "$url" | feh - &)
done

Note that you can put everything on a single line, or maybe define a function:
$ for url in 'url1' 'url2'; do curl -skb token "$url" | feh -; done
$ for url in 'url1' 'url2'; do (curl -skb token "$url" | feh - &); done

function feh_urls
{
    for url; do
        curl -skb token "$url" | feh -
    done
}

$ feh_urls 'url1' 'url2'

Be careful with your quotes, as there may be some annoying spaces in your URLs or paths (... and I hope I didn't make such a mistake in the above examples...). If you go for a function, maybe add it to your .bashrc so you can use it in your shell without redefining it manually everytime.
For the sake of completeness, here is a little script (which could be made a function of course) involving some temporary files, saving a few curl and feh processes on the way. I am using wget instead of curl because depending on your version, you might not be able to grab remote filenames properly (you could give your images different names of course).
#!/bin/bash

img_dir=$(mktemp -d)
cd $img_dir
wget -q --no-check-certificate --load-cookie token "$@"
feh $img_dir/*
rm -r $img_dir

Usage:
$ ./feh_urls.sh 'url1' 'url2'

Note that the advantage here is that feh doesn't get spawned several times, and can load all the images at once (use the arrow keys to browse them).
You might also be interested in this page if you want more information about cookie management with wget, or this page for details about the SSL/TLS options.


text:
Q: Why Form not get submitted after validation error message? I have a form to update user's information, if validation fails, it displays error message and after correcting the error input, the form doesn't get submit why?. Without error message, it submits well.
<h:form id="update" prependId="false">
    <h:outputText value="Name: " styleClass="titleBlue"/>
    <h:inputText id="contactName" value="#{serviceBean.contactName}" maxlength="50" size="15" style="width:200px" >
        <f:validateLength minimum="3" maximum="50"/>
    </h:inputText>
    <h:message for="contactName" style="color:red;font-size: 0.70em;"/>
    <h:outputText value="Title: " styleClass="titleBlue"/>
    <h:inputText id="contactTitle" value="#{serviceBean.contactTitle}" maxlength="50" size="15" style="width:200px">
        <f:validateLength minimum="3" maximum="50"/>
    </h:inputText>
    <h:message for="contactTitle" style="color:red;font-size: 0.70em;"/>
    <h:panelGroup style="display:block; text-align:center">
        <a4j:commandButton action="#{serviceBean.update}" styleClass="titleBold" value="Update"/>
    </h:panelGroup>
</h:form>

A: Why does form does not get submit after showing the alert message :
What I need id if the value is null set the default value and submit the form.


text:
Q: Iris Dataset - Machine learning classification model I have training data set in data frame format. Below is just for understanding purpose.
Training Data Set:-
 column Names = [SepalL,SepalW,PetalL,PetalW,Species]
 Training Data Set 1 = [5.1,3.5,1.4,0.2,Iris-setosa]
 Training Data Set 2 = [4.9,3.0,1.4,0.2,Iris-setosa]
 Training Data Set 3 = [4.7,3.2,1.3,0.2,Iris-veriscolor]
 Training Data Set 4 = [4.6,3.1,1.5,0.2,Iris-versicolor]
 Training Data Set 5 = [5.0,3.6,1.4,0.2,Iris-verginica]

Is there any way to consider the column values of training data according to test data , when test data with lesser no.of column values compared to training data?
Test Data Set1 Cols = [PetalL,PetalW]
Test Data Set1 = [1.1,0.1]

Test Data Set2 Cols = [SepalL,SepalW,PetalL]
Test Data Set2 = [5.1,3.9,1.4]

A: This will decrease the accuracy of your model I believe. The best way would be to train a few models, each one with 1 or 2 missing columns. Or you could try to impute some missing values with one of the methods here, but note that this will not give you the accuracy that your model would originally get with the same format of the data that it was trained on.

A: kNN models don't handle missing values by default.
If you are using the sklearn model, you should see a failure when using less features, indicating that there is a mismatch in the number of features. The reason is that the k centroids for the models are made based on all the features. For the few features you have, maybe all centroids are the same.
If you have missing values in your training set as well, you may want to chose another algorithm that handles missing values by construction.


text:
Q: Free XSD to DTD conversion utility? I have a XSD (XML Schema) that I need to convert to a DTD. Is there a free utility or simple way to accomplish this? A XSLT for example? Python scripts are welcome too.
Note: this is the opposite direction of the question Free DTD to XSD conversion utility?
I am aware that the conversion may lose information…
I tried XMLSpy or oXygenXML, but it is not free and I don't have the possibility to customize the conversion.

A: XMLPad (https://xmlpad.soft32.com/) claims

Converting XSD to DTD and DTD to XSD.

I've never used it; your mileage may vary.
The Official website is: wmhelp.com

A: I think there are limited number of people needed DTD if they have XSD.
For me, XSD is more usable then DTD, and I know some migrations from DTD to XSD, usually done manually, but I surprised you need opposite conversion done by script.
May be, you have to write or order the custom tool for your needs.

A: Technically, a complete conversion form XSD to DTD is not feasible. Even if you found a tool, you can not be sure that the results are same because there is some features in schema not exist in DTD . For example, the problem of id scoping with IDREF in DTD.


text:
Q: which file to specify during the git pull I have very less experience with 'git'. There is a sub-directory in a git repository,
and I want to pull that sub directory, but in the command
git pull <file-name>, which file name should I specify. I do not see any .git file in the directory.

A: You cannot retrieve just a subfolder of a git repository - you always need to git clone the whole repository.
Whoever told you that you can git pull <filename> told you something wrong. The syntax of git pull is:
git pull [options] [<repository> [<refspec>...]]

A: You can't do this. Git is not like svn.
One possible way to achieve something similar would be to have that directory as a different git repository and use it as a git submodule on both repositories.
Take a look on this part of the git book for more info:
http://git-scm.com/book/en/Git-Tools-Submodules


text:
Q: Formula field giving a value 25 I am trying to set up a field [FormulaVideo] that will give a value 25 only if [Has_Video_Type__c] != None. Has video is a picklist field.
This is where i am at.
 IF( ISPICKVAL( Has_Video_Type__c , "No") , 25, 0)

A: Solution to my question.
CASE( Has_Video_Type__c, "Live", "25", "VoD","25", "No","0","null")

A: If you look at the CASE function properly, you're not following the order of the parameters correctly in your comment:
CASE(expression, value1, result1, value2, result2,...,else_result)
Try this:
CASE(Has_Video_Type__c, "Live", "25", "VoD", "25", "0")
Means if the value is "Live", evaluate 25. If it's "VoD" again "25" and everything else, "0". Or if you want to specifically include "No" and associate it with "0" value, but have different default value, this will be your solution:
CASE(Has_Video_Type__c, "Live", "25", "VoD", "25", "No", "0", "DEFAULTHERE")


text:
Q: uploading files to the uploads folder via ftp What is the reason/s that the WordPress
Media Folder, doesn't display  images that were uploaded via FTP, directly to the uploads folder? Why doesn't WordPress "see" them? why do we always have to upload via the WordPress media uploader? What does it do?

A: Because WordPress is not scanning all the folders all the time. When you upload images Wordpress also makes an entry in the database, records the caption, the sizes that are available and so on.

A: There is a plugin Add From Server that allows you to select files from the "uploads" folder and import them in the Media Library.

A: When you upload a file using the default WordPress media uploader, it saves the file information inside the database. So, when you see them in Media, it means they exist and are registered in the database.
When you use other method to upload the image, like FTP, the database isn't automatically populated and, therefore, WordPress won't recognize their existence.

A: Media from Ftp
and Add from server
Also works. But if the images are more than 25k-1lakh then these plugins wont help you. If anybody knows update here thanks.


text:
Q: Largest closed subset of an half-open interval I have problems understanding the following:
Consider the set $A = ]0,1] \cup  \{2 \}$. What is the largest closed subset of $A$ ? I know that $X_n \subset A$ with $X_n = [1/n , 1] \cup \{2 \} $ and that $X_n \subset X_{n+1}$ for all $n \in \mathbb{N}$. I also know that $X_n$ is closed. So to get the largest closed set I have to take the limit but I also know that $\bigcup_{n \in \mathbb{N}} \ X_n = ]0,1] \cup \{2 \} $ which is not closed anymore. My question is: how can I possibly construct the largest closed set with my definition of the set $X_n$ ? Or is this not possible ?

A: This is not possible. Indeed, assume that $F$ is a closed subset of $A$. Then $0 \notin F$ so there exists $\varepsilon > 0$ such that $F \cap \langle -\varepsilon, \varepsilon\rangle = \emptyset$.
Then $F \cup \left\{\frac\varepsilon2\right\}$ is a closed subset of $A$ which strictly contains $F$.


text:
Q: How to get Context in an Intent Service Here's the scenario: I have a WakefulBroadcastReceiver that does a
backup to a network computer or the cloud. It's set to go off in the
middle of the night, when I know the tablet will have access to the
LAN. The backup will store the data to a location and a file that was "picked" by the fragment that instantiated the WakefulBroadcastReceiver,
using the Storage Access Framework. So I need to be able to access the
ContentResolver and to do that I need the context.
From all my reading of the documents, this is what the
BroadcastReceiver is meant to be used for - a potentially long running
task that should be done in the background when not much else is
happening. - Like a backup. I just haven't seen any examples that puts
everything together.
How do I get the context in an IntentService? Here
is a snippet of the receiver and the scheduling service.
  public class BackupAlarmReceiver extends WakefulBroadcastReceiver {

    @Override
        public void onReceive(Context context, Intent intent) {

            Intent service = new Intent(context, BackupSchedulingService.class);

        startWakefulService(context, service);

        }
}

public class BackupSchedulingService extends IntentService {
    public BackupSchedulingService() {
        super("BackupSchedulingService");
    }

 @Override
    protected void onHandleIntent(Intent intent) {

        Bundle extras = intent.getExtras();
        // How to get the context - it was a parameter when
        // creating the new IntentService class above?
         }
}

The example code pretty much follows exactly the Android reference
manual code here:
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

A: You can get the context in onStartCommand() function.
    public class ExampleService extends IntentService {
    private Context mContext;

    public ExampleService(String name) {
    super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    mContext = getApplicationContext();
    return super.onStartCommand(intent, flags, startId);
    }
    }

A:
So my question is how do I get the context in an IntentService?

The IntentService is the Context, as IntentService inherits from Context.

A: Just call getApplicationContext()

A: Use BackupSchedulingService.this (ServiceName.this) to get Context
Reason:
       Service extends ContextWrapper
       ContextWrapper extends Context

A: You can use Intent service class as Context. because this is the hierarchy of IntentService class.

*

*android.content.Context

*

*android.content.ContextWrapper

*

*android.app.Service

*

*android.app.IntentService

So In java
BackupSchedulingService.this
And in Kotlin
this@BackupSchedulingService

Hope this will help future devs...


text:
Q: Google Analytics Real-Time API batching calls - order of returned data I am trying to batch calls to GA Real-time api but I came across a strange issue. Let's say I want to get 10 dimensions. Since there is max dimension limit of 7 per call, I have to divide it to two calls (I am using Google App Script). For example:
const res = Analytics.Data.Realtime.get(
      "ga:xxxxxxx",
      "rt:activeUsers",
      {
        dimensions: [dimensions] // 7 dimensions here
      }
    )

and
const res = Analytics.Data.Realtime.get(
      "ga:xxxxxxx",
      "rt:activeUsers", // at least one metric is required so calling for active users again
      {
        dimensions: [dimensions] // 3 remaining dimensions here
      }
    )

It would seem like evertyhing is working fine but the order in which i receive data is either reversed or random. For the first call it would be something like this:
rows:
    [ [ 'Chrome',
        '(not set)',
        'MOBILE',
        '(not set)',
        '(not provided)',
        '(not set)',
        'Redmi Note 7',
        '1' ],
      [ 'Firefox',
        '(not set)',
        'DESKTOP',
        '(not set)',
        '(not set)',
        '(not set)',
        '(not set)',
        '1' ] ],

For the second:
rows: [ [ '(not set)', '(direct)', 'NEW', '1' ],
      [ '(not set)', 'google', 'NEW', '1' ] ],

So the chunks of data are corresponding to each other like on this screen

I did a couple of tests and it seems like the order is reversed. But is it really? Maybe it's just random? I couldn't find any guidelines in docs so I don't want to rely on my experiments alone. Have you had any experience with that?


text:
Q: php fopen appending data but it is not showing Hi I have two pdf files
$file1 = 'signed01.pdf';
$file2 = 'signed02.pdf';

Now, Signed01 is 1.8 MB and Signed02 is 426 KB the second file contains the signature in digital format that I want to append inside file1.
I have used
$file1 = 'signed196165991.pdf';
$file2 = 'signed1931217081.pdf';

$GlobalFileHandle = fopen($file1,'a');

$data = file_get_contents($file2);

fwrite($GlobalFileHandle, $data);

//file_put_contents($file1, $data, FILE_APPEND);

fclose($GlobalFileHandle);

Now this append the data to the file as I can see the file01 size is 2.3 MB now that is it is increased by 426 KB but when I open the file I can only see the data from file02 not the combined data for both files so it did append the data but I can not see it each time I run this file file01 size gets increased by 426KB but I can only see the data of file02.


text:
Q: SystemTap support for user space application I want to know how to add support in the systemtap for user space applications. When I am trying to trace any user space program, it is showing that CONFIG_UTRACE not set.

A: Perhaps utrace facility is not set up in your kernel.  Refer here for setting it up and trying again.

A: Note that linux >3.5 includes a subset of old utrace-related capabilities, so e.g. on x86, process.function probes work directly.


text:
Q: Use class name from .css file in
A: Use this:
td{
 //Put content  of myclass here
}

JSFiddle Demo
You can see in demo that TDs don't have any class name.

A: jsfiddle http://jsfiddle.net/harshdand/76gx6akr/

a

b

c

d

css
.myclass{
    background-color:yellow;
}

js
$( "td" ).addClass( "myclass" );

A: If your goal is to add styles to all td element, you can modify the td element directly:
td{
}

You could also add myclass on the tr in your table then use subclasses. In this case an id to only modify thing with .myclass & td.
.myclass td{
    /* stuff */
}

        Text
        More Text

A: There are a few ways in which you can do some interesting styles at a high level. For example, you can declare a global style using
td {
    background: red;
}

This will apply style to all td elements within your document. But what if you want to be more precise? Perhaps you want styles for a td which is a direct child of a certain element. If so, you can try the following
.example tr > td {
    background: blue;
}

Here's a fiddle with some more examples. Fiddle.


text:
Q: Unable to consume android.test.purchased sku, Getting response code 6 from BillingResult I'm unable to consume the android.test.purchased product id.
Below is my code where I'm handling the purchase.
public void handlePurchase(Purchase purchase) {
    try {
        if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
            consumeSKU(purchase.getPurchaseToken(), purchase.getDeveloperPayload());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And below is my consumeSKU method:
public void consumeSKU(String purchase_token, String developer_payload) {
    ConsumeParams consumeParams =
            ConsumeParams.newBuilder()
                    .setPurchaseToken(purchase_token)
                    .setDeveloperPayload(developer_payload)
                    .build();

    billingClient.consumeAsync(consumeParams, this);
}

and my consume response listener:
@Override
public void onConsumeResponse(BillingResult billingResult, String purchaseToken) {
    Toast.makeText(context, "onConsumeResponse: " + billingResult.getResponseCode() + ", purchase token: " + purchaseToken, Toast.LENGTH_LONG).show();
}

I'm getting Response Code: 6 from billingResult everytime the consumeSKU method is called.
Where am I going wrong?


text:
Q: Angular6 | Disable form validation for hidden fields Background
I have a form where I give the user the option to specify either a quick time-frame or a detailed one (with a specific start/end time) - i.e. the user has the option to fill only one out of the two
The type of option that they wish to choose can be toggled with the click of a button. These buttons just toggle the hidden parameter on the specified divs
Issue
My problem here is that both of these fields (all 3 technically as start/end time are 2 separate form group divs under one generalized div) are required only if they are not hidden - I am not sure how this can be achieved with Angular 4/5/6 (using 6 here)
My invalid form trigger always goes off as the hidden field is also required
My Form

  <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>

       Request Type
      <select
      class="form-control"
      [(ngModel)]=data.transactionType
      name ="transactionType"
      #transactionType="ngModel"
      required>
        <option value="something1Count">Something1</option>
        <option value="something2Count">Something2</option>
      </select>

        Please select a transaction type

     Timeframe Type

        <button type="button" class="btn btn-light" (click)="quickTimeframe = false; detailedTimeframe = true;" ng-selected="!quickTimeFrame"> Quick </button>
        <button type="button" class="btn btn-light" (click)="detailedTimeframe = false; quickTimeframe = true;" ng-selected="!detailedTimeframe"> Detailed </button>

      Timeframe
      <select
      class="form-control"
      [(ngModel)]=data.timeframe
      name ="timeframe"
      #timeframe="ngModel"
      required>
        <option value="15">15 Minutes</option>
        <option value="30">30 Minutes</option>
        <option value="45">45 Minutes</option>
        <option value="60">60 Minutes</option>
      </select>

        Please select a timeframe

              Start of Time Range
                  <input
                  type="datetime-local"
                  class="form-control"
                  [(ngModel)]="data.startTime"
                  #startTime="ngModel"
                  name="startTime"
                  required
                  >

                Please select a start-time

                End of Time Range
                <input
                type="datetime-local"
                class="form-control"
                [(ngModel)]="data.endTime"
                #endTime="ngModel"
                name="endTime"
                required
                >

                Please select an end-time

    <input type="submit" class="btn btn-primary btn-block" value="Submit">
  </form>

TS File
import { Component, OnInit } from '@angular/core';
import { Inputs } from '../../models/Inputs';
import { Router } from '@angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';

@Component({
  selector: 'app-main-form',
  templateUrl: './main-form.component.html',
  styleUrls: ['./main-form.component.css']
})
export class MainFormComponent implements OnInit {

  data:Inputs = {
    transactionType:'',
    timeframe:null,
    startTime:'',
    endTime:''
  };

  quickTimeframe:boolean=true;
  detailedTimeframe:boolean=true;
  buttonResult:any;

  constructor(public router:Router, public flashMessagesService:FlashMessagesService) {

  }

  ngOnInit() {

  }

  onSubmit({value, valid}:{value:Inputs, valid:boolean}){

    console.log("Quick Time Flag: " +this.quickTimeframe);
    console.log("Detailed Time Flag: " +this.detailedTimeframe);

    if (valid && !this.quickTimeframe){
      console.log("Form is valid");
      //Stuff should happen
      console.log(value);
    } else if (valid && !this.detailedTimeframe) {
      console.log(this.data.startTime);
      //Other stuff should happen
    }

    else {
      console.log("Form is not valid");
      this.flashMessagesService.show('Choose Valid Parameters', {cssClass:'alert-danger', timeout: 4000});
    }

  }

  radioClick() {
    console.log(this.buttonResult);
  }

}

Report Inputs Interface (for completion's sake)
 export interface Inputs {

    transactionType?:string;
    timeframe?:number;
    startTime?:string;
    endTime?:string;

}

A: *ngIf did the trick
Using ngIf instead of hidden ensure that the elements do not exist within the form in my scenario


text:
Q: Link php interpreter from Docker to bash somehow I'm trying to use my docker php as an interpreter in my terminal. What I need:

*

*I don't keep my dev envs on my host os. That's important to keep it isolated

*It should be available as $php or $/usr/bin/env php

*I'd like to be able to run something like phpcs in my vim. It requires that thingy above.

I've tried this:
alias php='docker-compose exec php php'

But it's not available through /usr/bin/env

A: /usr/bin/env tries to locate the executable via the $PATH variable, see https://unix.stackexchange.com/a/12749
So if you put your command in to a script called PHP and add it to your $PATH before other PHP executables, it might work.


text:
Q: noun countability Are there any recourses on determining the countability of nouns? Either some way to work it out or a dictionary that records whether a noun is likely to countable or not countable?
I'm not interested in whether the noun can be countable but more is it likely to be countable. for instance rice can go to rices which means it can be countable but in most cases it wont be.

A: This is a tough one. Many English words can be both (beer, time, glass, language, etc etc) depending on the context/meaning.
Figuring out (un)countability from the word alone or from a regular dictionary is impossible or impractical.
You can try to figure it out from a large text corpus by seeing how the word is used:

*

*if there's a plural form or not

*if there's an indefinite article before it or none

*if it's used with many/few, much/little, a piece of(?), etc

But many words can function as both nouns and adjectives and that complicates matters. For example in an air pump, air functions as an adjective and an refers to pump, not to air.
Likewise, many words can function as both nouns and verbs and have identical forms. For example, in she pressures him, pressures isn't a plural of pressure.
Also, some uncountable nouns can have an indefinite article before them when they are made more specific, e.g. knowledge vs a good practical knowledge.
You can gather statistics from an analyzed corpus and based on it judge whether or not a word is more likely to be countable or uncountable.

A: There are several existing English lexica that contain information about count/mass/etc. distinctions, none of which quite agree with each other because they focus on slightly different distinctions and it's a complicated task.  Two are ComLex and CUVPlus (which I can't find a download link for at the moment, although you can find it mentioned in many places).
Check out the work by Timothy Baldwin and Francis Bond in 2003 on learning noun countability from corpora.  If you have many occurrences of an unfamiliar noun in a corpus, you can do fairly well at the task of figuring out whether this noun can possibly be a count noun, can possibly be a mass noun, etc. however individual instances are still be quite difficult to classify.  If you have the sentence "the wug was white" and according to your lexicon "wug" can be either count or mass, there's not enough information in the immediate context to help you classify it.

A: I'm not sure if there is an 'official' dictionary saying if a noun is likely to be countable or not, but I can come up with two ways you could go about this:

*

*Either assuming that a noun is likely to be uncountable if somebody put it in a 'list of mass nouns' or 'list of uncountable nouns' (you find quite a lot if you google for those phrases, for example this).

*Or make a little corpus study and see how often the word is used in which way: searching "rice" in the Corpus of contemporary american English gives us 22265 hits, while the word "rices" is only found 69 times.

A: It depends on the context and whether the noun may have plural on its own. Different senses of the same word may differ, e.g.:

*

*expectation: the feeling vs. what is being expected

*salt: table salt vs. a type of a chemical element

Our API, GlobalNLP, returns the countability of nouns (among other things) in a particular context in this method: https://nlp.linguasys.com/docs/services/53fccbb15cfea30d9c48f8d6/operations/542a6da01c78d80a3cd6692a


text:
Q: The past of "must" PUMPKIN HEAD (JOYCE CAROL OATES)

He asked Hadley how long she'd lived in the house, and when she told him that she and her husband had moved there in 1988 he maintained his pained, fixed smile but did not ask about her husband. He must know, then, she thought. Someone at the co-op has told him.

I know that the past of must is had to. The Oxford online dictionary says that must can be used as past tense in reported speech ("she said she must be going"). But the sentence in the text is not reported speech. The modal might would be grammatically correct in the sentence, for might is the past of may. But can I use must as the past of must?
And I'm confused by the last sentence when the author suddenly uses the present tense ("has told him"). Is there a connection with the previously used must?

A:
He must know, then, she thought. Someone at the co-op has told him.

The two marked sentences are both direct "speech", although Oates does not mark them with quotation marks—probably because they are not spoken but only thought. The must here therefore represents present tense.
But the past tense of must is not had to, though had to may substitute for it. The past tense of must is must†.
In any case, there is no justification for using either may or might here; either would completely change the meaning.

† Historically, in fact, must was the past tense of the verb mote, which long since disappeared from use. Must appears to be following in its footsteps, being more and more replaced by the more flexible quasi-modal HAVE to.


text:
Q: Display row by selected ID I started using PDO recently, earlier I used Mysql functions.. Now I am trying to get and display record by selected ID from the previous web page.
    firtly i use Connexion Class
Class Connexion {

private $host = "localhost";
private $user = "root";
private $pass = "";
private $dbname = "cvtheque";
private $dbh;
private $stmt;

public function __construct() {
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT => true,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );
    // Create a new PDO instanace
    try {
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch (PDOException $e) {
        echo "Connexion Error: " . $e->getMessage();
    }
}

public function query($query) {
    $this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null) {
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
    $this->stmt->bindValue($param, $value, $type);
}

public function execute() {
    return $this->stmt->execute();
}

public function resultset() {
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function single() {
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

public function rowCount() {
    return $this->stmt->rowCount();
}

public function lastInsertId() {
    return $this->dbh->lastInsertId();
}

public function beginTransaction() {
    return $this->dbh->beginTransaction();
}

public function endTransaction() {
    return $this->dbh->commit();
}

public function cancelTransaction() {
    return $this->dbh->rollBack();
}

public function debugDumpParams() {
    return $this->stmt->debugDumpParams();
 }
}

i use these script to display items from database
<?php
$c = new Connexion();
$c->query("select * from annonce order by 'client' DESC Limit 20");
$rows = $c->resultset();  ?>

                <?php foreach($rows as $r) { ?>

          <a href="details.php?id=<?php echo($r['id_annonce']) ?>">
                <?php echo($r['poste']); ?>

<?php echo($r['type_contrat']); ?>
        <?php echo($r['client']); ?>

<?php echo tronque($r['desc_annonce'], 230);?>

<a href="details.php?id=<?php echo($r['id_annonce']) ?>">Voir plus

              <?php }?>

then i use these method for select row by ID taken from the URL
 <?php
   require_once '../Model/Connexion.php';
   $c = new Connexion();
   if (isset($_GET['code'])) {
            $results = $c->query("select * from annonce where id=".$_GET['code']);
            $row = $c->single();
                             }
?>

     back

    <?php while($row) { ?>

<?php echo($r['poste']); ?>

 |
            <?php echo($r['client']); ?> |
            <?php echo($r['type_contrat']); ?>

            <?php echo($r['desc_annonce']); ?>
            <?php }?>

it shows  "Undefined variable: $row" on this line  , how can resolve this problem ?

A: This single() function is incorrect
public function single() {
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

Should be
public function single() {
    $this->stmt->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

same applies for resultset():
public function resultset() {
    $this->stmt->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

Most of these functions are one liner which is pointless except for getter and setter but it is not the case, you can create a function with the constructor logic if you need reusability
public function get_connexion() {
    return $this->dbh;
}

php
<?php
if (isset($_GET['code'])) {
    //require only when code is set
    require_once '../Model/Connexion.php';
    //create conn
    $db = new Connexion();
    $conn = $db->get_connexion();
    $stmt = $conn->prepare('select * from annonce where id = ?');
    $stmt->execute(array($_GET['code']));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

HTML (no loop since its single)

     back

<?php echo($row['poste']); ?>

 |
            <?php echo($row['client']); ?> |
            <?php echo($row['type_contrat']); ?>

            <?php echo($row['desc_annonce']); ?>

Avoid Sql injection:
<?php
require_once '../Model/Connexion.php';
$c = new Connexion();
$c->query('select * from annonce where id_annonce= :id');
$c->bind(':id', $_GET['id']);
$r = $c->single();
?>


text:
Q: Sencha touch in webmatrix I'm trying sencha touch in WebMatrix but not having much success.  Everything from the sencha library has been downloaded and IISExpress is running correctly but when I browse to index.html I get the following displayed in the browser?
Ext.application({
    name: 'Sencha',

    controllers: ['Main'],
    views:  ['Main'],
    stores: ['MoreCards'],

    launch: function() {
        Ext.Viewport.add({
            xclass: 'Sencha.view.Main'
        });
    }
});

Any ideas what is going on?  WebMatrix isn't showing any errors and neither is Chrome?

A: I worked out what the problem was in the end.  Basically IISExpress sees app.js and assumes you are working on a NodeJS project which adds handler info into web.config.  Either choose cancel to NodeJS set-up when creating a new project with an existing app.js file or remove the NodeJS config sections in the web.config file.


text:
Q: How does the .NET application version works? I set up a setup (installer) project in my solution and there is the version there 1.0.0.
My question is, how does the version-ing work?
What does each number mean and how does it increase? Can anyone give me an insight on how this numbering system work?
Lastly, how would I go about displaying the version number on my form?
I tried:
Assembly.GetExecutingAssembly().GetName().Version;

But this is showing 1.0.0.0 and not the version I put into the installer (1.2).
What's the correct way to deal with version numbers?

A: The version you are trying to retrieve with Assembly.GetExecutingAssembly().GetName().Version needs to be set in Project Properties, Assembly Information.
Information about Version Numbers can be found here.


text:
Q: Save existing Docx as XML using c# i have an existing word document (office 2010) and want to programatically saveAs it as XML. i was tried
   Microsoft.Office.Interop.Word.Application.Documents.Open(@"C:\Test\NewDocument.docx");

but its not correct.
how can i do this?

A: var myfile= @"C:\Test\NewDocument.docx";
var fileInfo = new FileInfo(myfile);
fileInfo.MoveTo(Path.ChangeExtension(myfile, ".xml"));


text:
Q: .Net - tool to send html emails I am looking for a tool to send html emails from WCF Service.
Currently using Chilkat to do same but in some version of outlook it is showing html emails as multiple attachments (of html file and Images).
Can anyone guide for solution to above or any better tool to send html emails.
Thank you!

A: Have you tried SmtpClient along with MailMessage?

A: Currently using aspNetEmail component to send HTML emails,
issue of multiple attachemnts in outlook is resolved.
Thanks to aspNetEmail commendable support!


text:
Q: Extract info from file I have a file that contains emails.
The format is
< email: sender1@hotmail.com >
1111 2222 3333 aaaa
</email>
< email: sender2@gov.gr>
aaabbbbb cccccc
</email>

and I want to save in variables some info (senders , message and number of emails)
my code is like that
   FILE *fp;
   char line[150];

   fp= fopen("a.txt", "r");

   if (fp==NULL)
          error ("opening file");
   else{
          while (!feof(fp))
          {
             fscanf(fp, "%s", line);
             printf("%s\n", line);

            // does C support regular expressions ???
          }
   }

A: Regular Expression Matching in C.


text:
Q: Get relation for multiple objects with laravel A User has many Phones. I want to get all the phones from active users. I can do:
$phones = [];
$users = User::with('phones')->where('active', 1)->get();
foreach($users as $user) {
    $phones = array_merge($phones, $user->phones->toArray());
}
dd($phones); // <- Here are all the phones.

But I'm not sure it's the more elegant or laravel-ish way. Is there a built in magic function for such a case? Can I get all the phones from active users without writing a loop and insert in an Array?

A: You should use whereHas() method:
$phones = Phone::whereHas('user', function($q) {
    $q->where('active', 1);
})->get();

A: You can also use whereExists, which can be more efficient if you're not using data from the users table:
Phone::whereExists(function($query) {
    $query->select(\DB::raw('NULL'))
          ->from('users')
          ->whereRaw('users.id = phones.user_id AND users.active = 1')
})->get();


text:
Q: How to write full api test case in camel blueprint How do we write a test case using CamelBlueprintTestSupport for a soap service?
My requirement is to hit individual routes so that I can create test cases for each operations.


text:
Q: Why is $e^{-f(z)} = 1-z$, when $f(z)=\sum_{n=1}^\infty \frac{z^n}{n}$? Why does the following hold?
    $$e^{-f(z)} = 1-z$$
where $f(z)$ is defined as:
    $$f(z)=\sum_{n=1}^\infty \frac{z^n}{n}$$
Clearly, $f'(z)=\sum_{n=2}^\infty z^n =\frac{1}{1-z}$ by the known sum of geometric series, so the question is similar to:
    $$e^{f(z)} = f'(z)$$
Thanks in advance.

A: Write $g(z)=(1-z)e^{f(z)}$, then,
  $$g'(z)=0$$
So it follows that $g(z)=c$ (constant).
The constant $c$ is found to be one by evaluating $g(0)$.


text:
Q: Default template argument for function ignored template < class A, class B, class R = A >
void addMultiplyOperation( std::function< R ( const A&, const B& ) > func )
{
    ...
}

addMultiplyOperation< float, int >( []( float a, int b ) { return a * b; } );

This gives the compiler error:
In function 'int main(int, char**)':
error: no matching function for call to 'addMultiplyOperation(main(int, char**)::__lambda1)'
addMultiplyOperation< float, int >( []( float a, int b ) { return a * b; } );
                                                                           ^
note:   candidate is:
note:   template<class A, class B, class R> void addMultiplyOperation(std::function<R(const A&, const B&)>)
void addMultiplyOperation( std::function< R ( const A&, const B& ) > func )
     ^
note:   template argument deduction/substitution failed:
note:   'main(int, char**)::__lambda1' is not derived from 'std::function<R(const float&, const int&)>'
 addMultiplyOperation< float, int >( []( float a, int b ) { return a * b; } );
                                                                            ^

Despite having the R template argument default initialised to A, I have to provide the third argument in order for this to compile.  Is there something else I have to do in order to use default template arguments?
I'm using g++ v4.8.1.

A:
Despite having the R template argument default initialised to A, I have to provide the third argument in order for this to compile.

Actually, this has nothing to do with the fact that it's a default argument. The compiler can't deduce A and B either. Take a look at this simple example:
template<class A>
void f(function<void(A)> f) { }
int main() {
    auto lambda = [](){};
    f(lambda);
}

You'd think this would be super easy, and A should be deduced as void. But nope, it can't be done. When deducing template parameters, the compiler doesn't consider what constructors the parameter type would have for each possible combination of template parameters. It would be intractable to perform this sort of deduction in general.
For now, you'll just have to make addMultiplyOperation accept any type, and hope it's callable...
template<class Function>
void addMultiplyOperation(Function func) {
    // ....
}

If necessary, there are ways to deduce the types of the arguments that the function object can accept, for example as described in this answer: Is it possible to figure out the parameter type and return type of a lambda?
This will lead to some nasty compilation errors if the object passed in is not actually callable, or takes the wrong number of arguments. For now I'm not sure whether there's a nice way to solve this. Concepts, coming in C++14, should alleviate some of these issues.


text:
Q: How to test history.pushState and window.addEventListener using jasmine I am trying to test my piece of code using jasmine. But the jasmine code is giving error.
Code :
self.monitorRoutes = function () {

  var pageRef = window.location.href.split('#').pop();

  history.pushState(null,pageRef, pageRef);

}

Jasmine Code :
it('monitor routes', function () {

   spyOn(history, 'pushState')

   viewmodel.monitorRoutes();
});

Error :
TypeError: 'undefined' is not an object (evaluating 'history.pushState')
how could I mock pushState using jasmine?
I am facing same issue for window.addEventListener


text:
Q: php mysql parallel array checkboxes I have an array of checkboxes that I edit at once to set up a 'tinyint' field. the problem comes in when i uncheck the checkbox and post the vales to mysql. since it posts an array of checkboxes and another parallel array of values to edit, unchecking a checkbox results in the 0 value been ignored by PHP_POST and hence the checkbox array will be less by the number of unchecked values in the form while the array to be edited will have all the records in the form.
here is the submit code
while($row=mysql_fetch_array($result))
{

$checked = ($row[active]==1) ? 'checked="checked"' : '';
...

echo "<input type='hidden' name='TrID[]' value='$TrID'>";
echo "<input type='checkbox' name='active1[]' value='$row[active]''$checked' >";
...

and the processing php script
$userid = ($_POST['TrID']);
$checked= ($_POST['active']);

$i=0;

foreach ($userid as $usid)
{

if ($checked[$i]==1){
$check = 1;
}
else{
$check = 0;
}

$qry1 ="UPDATE  `epapers`.`clientelle` SET  `active` =  '$check' WHERE  `clientelle`.`user_id` =  '$usid' ";
$result = mysql_query($qry1);
$i++;

}

A: You can use the key of the first array to fetch the correct element of the second...
$userid = ($_POST['TrID']);
$checked= ($_POST['active']);

foreach ($userid as $key => $usid)
{

if ($checked[$key]==1){
$check = 1;
}
else{
$check = 0;
}

$qry1 ="UPDATE  `epapers`.`clientelle` SET  `active` =  '$check' WHERE  `clientelle`.`user_id` =  '$usid' ";
$result = mysql_query($qry1);

}

EDIT
If this doesn't work, try to add numeric indexes to the element names in the HTML code. Like this:
echo "<input type='hidden' name='TrID[".$i."]' value='$TrID'>";
echo "<input type='checkbox' name='active1[".$i++."]' value='$row[active]''$checked' >";

You'd obviously have to set $i to zero before the loop.

A: You could try something like:
$i = 0;
while($row=mysql_fetch_array($result))
{

$i++;
$checked = ($row[active]==1) ? 'checked="checked"' : '';
...

echo "<input type='hidden' name='TrID[{$i}]' value='$TrID'>";
echo "<input type='checkbox' name='active1[{$i}]' value='$row[active]''$checked' >";
...

The checkboxes should then at least be in the proper place in the array...

A: Checkboxes shouldn't have the same name, but each one should be named differently. You could solve your problem by modifying the first page like this:
$i = 0;
while($row=mysql_fetch_array($result))
{

$checked = ($row[active]==1) ? 'checked="checked"' : '';
...

echo "<input type='hidden' name='TrID[$i]' value='$TrID'>";
echo "<input type='checkbox' name='active1[$i]' value='$row[active]''$checked' >";
$i++;
...

And accordingly adjust the second script...

A: I have my own script I use to accomplish this... see if you can adapt it or if I'm anywhere on track with what you're trying to do.
Schema: Rows of products each with a checkbox that User can check in order to signify that that product needs to be added to the cart in order to see the price.
Code:
<input type="checkbox" name="addforprice[<?php echo $record['id']; ?>]" />
Then when the form is submitted:

if($_POST['addforprice']){
      foreach(array_keys($_POST['addforprice']) as $var){
          $data['add_for_price'] = 1;
          $update = $db->query_update(TABLE_PRODUCTS, $data, "id=".$var);
          echo "addforprice:".$var.' '.$data['add_for_price'].'';
          unset($data['addforprice']);
      }
  }

$record['id'] is the database id generated when printing out the rows.


text:
Q: Sort By Price: Low to High & High to Low using Magento 2 I want to add filter option: Sort By Price, Low to High & High to Low in sort by box.

A: Override phtml file of Magento_Catalog module in design:
../app/design/frontend/<vendor>/<theme>/Magento_Catalog/templates/product/list/toolbar/sorter.phtml
<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Product list toolbar
 *
 * @var $block \Magento\Catalog\Block\Product\ProductList\Toolbar
 */
use Magento\Catalog\Model\Product\ProductList\Toolbar;
?>

    <?php /* @escapeNotVerified */ echo __('Sort By') ?>
    <select id="sorter" data-role="sorter" class="sorter-options">
        <option value="<?php /* @escapeNotVerified */ echo 'short_by'; ?>"
            <?php if ($block->isOrderCurrent('short_by')): ?>
                selected="selected"
            <?php endif; ?>
            >
            <?php echo $block->escapeHtml(__("Sorting")) ?>
        </option>
        <?php foreach ($block->getAvailableOrders() as $_key => $_order): ?>
                    <?phpif($_key == "price"):?>
                            <option value="<?php /* @escapeNotVerified */ echo $_key.'&product_list_dir=asc'; ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>
                            <?php echo $block->escapeHtml(__("Preis - Low to High")) ?>
                            </option>

                            <option value="<?php /* @escapeNotVerified */ echo $_key.'&product_list_dir=desc'; ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>
                            <?php echo $block->escapeHtml(__("Price - High to Low")) ?>
                            </option>
                    <?php elseif($_key == "position"):?>
                    <?php elseif($_key == "short_by"):?>
                    <?php else:?>
                        <option value="<?php /* @escapeNotVerified */ echo $_key; ?>"
                            <?php if ($block->isOrderCurrent($_key)): ?>
                                selected="selected"
                            <?php endif; ?>
                            >
                            <?php echo $block->escapeHtml(__($_order)) ?>
                        </option>
                    <?php endif; ?>
        <?php endforeach; ?>
    </select>

For %3D added issue with Amasty_Shopby add below code into am_ShopByAjax.js file(line no 48):
/* added custome code */
   link = decodeURIComponent(link);
   var urlPaths = link.split('?');
   var urlParams = urlPaths[1] ? urlPaths[1].split('&') : [];
   var paramcheck = urlParams[0].split("=");

   if (paramcheck[0] == "product_list_dir") {
       var urlPathsParams = urlPaths[1].split('&');
       urlPathsParams.splice(0, 1);;
       var urlParams = urlPathsParams.join('&');
       urlPaths[1] = urlParams;
       link = urlPaths.join('?');
   }
/*end*/

Inform me if have any issue!

A: I did something similar using following code.
app/code/Anshu/Sortby/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Anshu_Sortby',
    __DIR__
);

app/code/Anshu/Sortby/etc/module.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Anshu_Sortby" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

app/code/Anshu/Sortby/etc/di.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">   <preference for="Magento\Catalog\Block\Product\ProductList\Toolbar" type="Anshu\Sortby\Block\Catalog\Product\ProductList\Toolbar" />
    <preference for="Magento\Catalog\Model\Config" type="Anshu\Sortby\Model\Config" />
</config>

app/code/Anshu/Sortby/Model/Config.php
<?php

namespace Anshu\Sortby\Model;

class Config extends \Magento\Catalog\Model\Config
{

    /**
     * Retrieve Attributes Used for Sort by as array
     * key = code, value = name
     *
     * @return array
     */
    public function getAttributeUsedForSortByArray()
    {
        $options = ['position' => __('Most Popular')];
        foreach ($this->getAttributesUsedForSortBy() as $attribute) {
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute\AbstractAttribute */
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
        }

        $options['position'] = __('Most Popular');
        $options['price'] =  __('Price: Low to High');
        $options['price_desc'] = __('Price: High to Low');
        return $options;
    }

}

app/code/Anshu/Sortby/Block/Catalog/Product/ProductList/Toolbar.php
<?php

namespace Anshu\Sortby\Block\Catalog\Product\ProductList;

use Magento\Catalog\Helper\Product\ProductList;
use Magento\Catalog\Model\Product\ProductList\Toolbar as ToolbarModel;

class Toolbar extends \Magento\Catalog\Block\Product\ProductList\Toolbar
{
    /**
     * Set collection to pager
     *
     * @param \Magento\Framework\Data\Collection $collection
     * @return $this
     */
    public function setCollection($collection)
    {
        $this->_collection = $collection;

        $this->_collection->setCurPage($this->getCurrentPage());

        // we need to set pagination only if passed value integer and more that 0
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }
        if ($this->getCurrentOrder()) {
            switch ($this->getCurrentOrder()) {
                case 'price':
                    $this->_collection->setOrder($this->getCurrentOrder(), 'ASC');
                    break;

                case 'price_desc':
                    $this->_collection
                            ->getSelect()
                            ->order('price_index.price DESC');

                default:
                    //$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
                    $this->_collection->setOrder($this->getCurrentOrder(), 'DESC');
                break;
            }
        }

        return $this;
    }

}

I hope this will be helpful.


text:
Q: Yup validate child of an object against a child of another object I have two objects: sending country and receiving country. Each of these two objects have other fields but I'd like to validate only one of them. I'd like to check whether the receiving country is the same as the receiving country, and if it is, return an error. I tried the following schema but it doesn't work. Do I miss something?
const validationSchema = object({
    sending_country: object({
        name: string().ensure().required().max(100, "Name too long")
    }),
    receiving_country: object({
        name: string().ensure().required().max(100, "Name too long").when(
            "$sending_country.name", (sending_country, schema) => {
                return schema.test({
                    test: receiving_country => receiving_country.name !== sending_country.name,
                    message: "Both countries cannot be identical"
                })
            })
    })
})

A: I ended up mixing solutions a bit
const validationSchema = object({
    sending_country: object({
        name: string().ensure().required().max(100, "Name too long")
    }),
    receiving_country: object().shape({
        name: string().ensure().required().max(100, "Name too long")
    }).when(
        "sending_country", (sending_country, schema) => {
            return schema.test({
                test: receiving_country => receiving_country.name !== sending_country.name,
                message: "Both countries cannot be identical"
            })
        })

})