text:
Q: Custom control with viz frame as aggregation Hello Sapui5 developers,
Today i get into a situation where i have 5 charts to display each of different style and uses different data so I thought instead of using viz frames multiple times in my page i want to write a custom control which  takes grapghtype,FlattenedDataset data,DimensionDefinition value,MeasureDefinition name value ,list of feed items.
SO general code is as below
<viz:VizFrame id="idVizFrame"
              uiConfig="{applicationSet:'fiori'}"
              height='100%'
              width="100%"
              vizType='donut'>
  <viz:dataset>
    <viz.data:FlattenedDataset data="{/milk}">
      <viz.data:dimensions>
        <viz.data:DimensionDefinition name="Store Name"
                                      value="{Store Name}" />
      </viz.data:dimensions>
      <viz.data:measures>
        <viz.data:MeasureDefinition name="Revenue"
                                    value="{Revenue}" />
      </viz.data:measures>
    </viz.data:FlattenedDataset>
  </viz:dataset>

  <viz:feeds>
    <viz.feeds:FeedItem uid="size"
                        type="Measure"
                        values="Revenue" />
    <viz.feeds:FeedItem uid="color"
                        type="Dimension"
                        values="Store Name" />
  </viz:feeds>
</viz:VizFrame>

I want it to be like
<chart frameType="donut"
       flattenedData="{/milk}"
       dimensionDefinationData="{Store Name}"
       measureDefinationData="{Revenue}" />

then in should render a donut graph.
this is what i have tried
shadowChart.js:
sap.ui.define([
  "sap/ui/core/Control",
  "sap/viz/ui5/controls/VizFrame",
  "sap/viz/ui5/data/FlattenedDataset",
  "sap/viz/ui5/controls/common/feeds/FeedItem"
], function(Control, gViz, gData, gFeeds) {

  "use strict";

  return Control.extend("NWS.control.shadowCharts",  {

    "metadata": {
        "properties": {
            "value": {
                "type": "float",
                "defaultValue": 0
            },
            "frameType": {
                "type": "string",
                "defaultValue": "bar"
            },
            "flattenedData": {
                "type": "object",
                "defaultValue": ""
            },
            "dimensionDefinationData": {
                "type": "string",
                "defaultValue": ""
            },
            "measureDefinationData": {
                "type": "string",
                "defaultValue": ""
            },
            "height": {
                "type": "string",
                "defaultValue": "90%"
            },
            "width": {
                "type": "string",
                "defaultValue": "90%"
            }
        },
        "aggregations": {
            "_vizFrames": {
                "type": "sap.viz.ui5.controls.VizFrame",
                "multiple": false,
                "visibility": "hidden"
            }

        }
    },

    init: function() {

        var oDataSet = new sap.viz.ui5.data.FlattenedDataset({
            "data": {
                "path": this.getFlattenedData()
            },
            "dimensions": [{
                "name": "dimensionNameHere",
                "value": this.getDimensionDefinationData()
            }],
            "measures": [{
                "name": "measureNameHere",
                "value": this.getMeasureDefinationData()
            }]
        });
        var feedItem1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
            "uid": "ValueAxis",
            "type": "Measure",
            "values": ["measureNameHere"]
        });
        var feedItem2 = new sap.viz.ui5.controls.common.feeds.FeedItem({
            "uid": "categoryAxis",
            "type": "Dimension",
            "values": ["dimensionNameHere"]
        });
        var vizFrame = new sap.viz.ui5.controls.VizFrame({
            "vizType": this.getFrameType(),
            "dataset": oDataSet,
            "feeds": [feedItem1, feedItem2],
            "iConfig" : "{applicationSet:'fiori'}",
            "selectData": this._dataSelect.bind(this)
        })
        this.setAggregation("_vizFrames", vizFrame);

    },

    _dataSelect: function(oEvent) {

    },

    renderer: function(oRM, oControl) {
        oRM.write("
");
        oRM.renderControl(oControl.getAggregation("_vizFrames"));

        oRM.write("
");
    }
  });
});

in login view.xml
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
    controllerName="view.Login" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form" xmlns:cViz="NWS.control">
  <Page title="{i18n>Title}" >
    <content>
      <VBox class="sapUiSmallMargin">
         <cViz:shadowCharts frameType="donut"
                            flattenedData="{gDataModel>/milk}"
                            dimensionDefinationData="{Store Name}"
                            measureDefinationData="{Revenue}" />
      </VBox>
    </content>
  </Page>
</mvc:View>

The error while debugging (in init function) is with passing binding data.. as i am getting
this.getFrameType() as "bar" but not "donut",this.getFlattenedData() as ""

probably it has something to do with properties type.
Kindly help me out with requirement

A: I figured out the issue with help of my friends.
so problem here is we can't get property values in init function so i shifted the code to renderer function.
chartController.js
sap.ui.define([
"sap/ui/core/Control",
"sap/viz/ui5/controls/VizFrame",
"sap/viz/ui5/data/FlattenedDataset",
"sap/viz/ui5/controls/common/feeds/FeedItem"], function(Control, gViz, gData, gFeeds) {
"use strict";

return Control.extend("NWS.control.shadowCharts", {

    "metadata": {
        "properties": {
            "value": {
                "type": "float"

            },

            "frameType": {
                "type": "string"
            },
            "flattenedData": {
                "type": "string"
            },
            "dimensionDefinationData": {
                "type": "string"

            },
            "measureDefinationData": {
                "type": "string"

            },
            "height": {
                "type": "string"

            },
            "width": {
                "type": "string"

            },
            "press":{
                "type":"string"
            }
        },
        "aggregations": {
            "_vizFrames": {
                "type": "sap.viz.ui5.controls.VizFrame",
                "multiple": false,
                "visibility": "hidden"
            }

        },
        "events":{
            press:{}
        }
    },

    init: function() {
      this.getControlInstance=this;
    },

    _dataSelect: function(oEvent) {

          this.fireEvent("press");

    },

    renderer: function(oRM, oControl) {

        var oDataSet = new sap.viz.ui5.data.FlattenedDataset({
            "data": {
                "path": oControl.getFlattenedData()
            },
            "dimensions": [{
                "name": oControl.getDimensionDefinationData(),
                "value": "{"+oControl.getDimensionDefinationData()+"}"
            }],
            "measures": [{
                "name": oControl.getMeasureDefinationData(),
                "value": "{"+oControl.getMeasureDefinationData()+"}"
            }]
        });
        var gType=oControl.getFrameType();
        var measureUid="";
        var dimesionUid="";
        switch(gType){
            case "donut":measureUid="size";dimesionUid="color";break;
            case "bar":measureUid="valueAxis";dimesionUid="categoryAxis";break;
            default:throw "error beacause of unknown graph type"

        }
        var feedItem1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
            "uid": measureUid,
            "type": "Measure",
            "values": [oControl.getMeasureDefinationData()]
        });
        var feedItem2 = new sap.viz.ui5.controls.common.feeds.FeedItem({
            "uid": dimesionUid,
            "type": "Dimension",
            "values": [oControl.getDimensionDefinationData()]
        });
        var vizFrame = new sap.viz.ui5.controls.VizFrame({
            "vizType": oControl.getFrameType(),
            "dataset": oDataSet,
            "feeds": [feedItem1, feedItem2],
            "iConfig": "{applicationSet:'fiori'}",
            "selectData": oControl._dataSelect.bind(oControl.getControlInstance)
        })
            vizFrame.setVizProperties({

                    title: {
                        visible: false,
                        text: 'Statastics'
                    }
                });
        oControl.setAggregation("_vizFrames", vizFrame);
        oRM.write("
");
        oRM.renderControl(oControl.getAggregation("_vizFrames"));

        oRM.write("
");
    }
});});

so my controller usage in xml is:
 <cViz:shadowCharts frameType="bar" flattenedData="/milk" dimensionDefinationData="Store Name" measureDefinationData="Revenue" press="shadowChartsClick"></cViz:shadowCharts>

there is scope for optimization :-)

A: You could try to implement logging inside the "INIT"-function. Make sure that this.getFrameType refers to the proper instance and
to verify that the "INIT"-function is not being executed twice since it could also be a timing problem.
You might also try to implement a specific setter function (setValue) to make sure that the setter is called before the "INIT"-function.


text:
Q: Custom properties in Spring Boot project using Gradle In my Spring Boot project (1.5.6.RELEASE) that I build using gradle, I want to include some custom properties. The approach laid out in the documentation does not seem to work (on build, I get: Could not set unknown property 'additional' for task ':properties' of type org.gradle.api.tasks.diagnostics.PropertyReportTask.):
springBoot {
    buildInfo {
        properties {
            additional = [
                'a': 'alpha',
                'b': 'bravo'
            ]
        }
    }
}

Luckily this approach, which I found here, does work for me (no compile error and I'm then able to access the property from my code):
springBoot{
    buildInfo {
        additionalProperties = [
            'testpropertykey': 'testpropertyvalue'
        ]
    }
}

But, since the former is the "officially" documented approach, I would prefer to take that approach. How would I get the former approach to work? I assume I'm missing something - unless the documentation is wrong or maybe this changed from Spring Boot 1.5.6.RELEASE.

A: The docs you linked are for the current version of the plugin which aligns with the current GA version of Spring Boot: 2.1.7
Version 1.5.x of the plugin does have a additionalProperties field: https://github.com/spring-projects/spring-boot/blob/1.5.x/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/buildinfo/BuildInfo.java#L66
The 2.1.x version does not and you use properties instead: https://github.com/spring-projects/spring-boot/blob/2.1.x/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java#L45
Suggest you migrate/upgrade to Spring Boot 2.1.x or 2.2.x when that is released soon since 1.5.x has already reached EOL: https://spring.io/blog/2018/07/30/spring-boot-1-x-eol-aug-1st-2019

redpajama_set_name: RedPajamaStackExchange


text:
Q: Edit existing wiki page with libreoffice writer I've read about sending a page to a mediawiki using libre writer.
But is it possible to call up an existing wiki page, edit it and send it back to the wiki?
If so, how is this done?

A: As far as I know there is no such option, the connection is one-way only. In some cases you could be able to convert WikiText e.g. with pandoc. For a local wiki it is a possible workflow to keep the Writer documents, and only use them for export.
Another workaround is using the new visual editor of MediaWiki, which I find quite user friendly in comparison with WikiText.


text: Q: Can I use an extra 'etc' folder inside /usr in linux? I'm experimenting with linux from scratch. I'm using stow to install extra packages into /usr/local/stow/. I'm using the command stow <package dir> -t /usr which symlinks everythin to /usr/bin, /usr/lib, /usr/share, etcetara. But this also creates a folder /usr/etc. To my knowledge 'etc' folder is inside root folder, /. So, my question is, will the package work if the configuration files are inside /usr/etc instead of /etc ?


text:
Q: Locating image in selenium I want to check if a logo (image) is displayed or not but i am unable to find out the xpath for the same.The html code is as below:

 The Logo<\a>

What could be the possible xpath for verifying "The Logo " is displayed.

A: May one of these works:
//a[contains(text(), 'The Logo')]

//a[contains(text(), 'The Logo') and @href='www.com']

//div[@class='page-wrapper']/a[contains(text(), 'The Logo')]

//div[@class='page-wrapper']/a[contains(text(), 'The Logo') and @href='www.com']


text:
Q: GestureDetectorCompact not working? My code
 public class TestActivity extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        GestureDetectorCompat gestureDetectorCompat=new GestureDetectorCompat(this,this);
        gestureDetectorCompat.setOnDoubleTapListener(this);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }
}

I'm debugging every method, but none get's called.
Where i'm wrong?

A: The GestureDetectorCompat is not called automatically. You have to override onTouchEvent(MotionEvent event) in your Activity, and pass the event to the gesture detector. E.g.
public boolean onTouchEvent(MotionEvent event) {
    return gestureDetectorCompat.onTouchEvent(event);
}

You can find the documentation here. Please refer to it, for the meaning of the returning value.

A: Add the following to your code. It's mentioned here.
@Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        // Be sure to call the superclass implementation
        return super.onTouchEvent(event);
    }


text:
Q: Prevent Form from showing outside the working area I created a custom form to show it as a ToolTip but to show data on it, the show will be display when the user hovers on a Button and disappear on mouse leave, everything works perfectly but how can I prevent the Form from display outside the screen area??
Here is the code I used to show the Form:
Info_Form tooltip = new Info_Form();
private void Button131_MouseHover(object sender, EventArgs e)
{
    Button b = (Button)sender;

    tooltip = new Info_Form();
    tooltip.Height = tooltip.Height + 30;
    tooltip.Location = new Point(
    b.Right,
    b.Top);

    tooltip.Show();
}

private void Button131_MouseLeave(object sender, EventArgs e)
{
    tooltip.Close();
}

A: I suggest to:

*

*declare your ToolTip Form in Program.cs

*add static Methods to show and hide it

Of course you can use a dedicated class that exposes static methods to handle your ToolTip Form
You can then reach your ToolTip Form from anywhere in your application, just call ShowToolTip() and HideToolTip() when the Mouse pointer enters or leaves a specific Control: the bounds of this Control, translated to Screen coordinates, are used as reference to position the ToolTip.
Here, I'm using a simplified method to determine whether the ToolTip should be shown to the right or left and to the top or bottom of the reference Control:

*

*if the reference Control is positioned to the left half of the screen, then the left potion of the Form is: ToolTip.Left = [ref Control].Left

*otherwise, ToolTip.Left = [ref Control].Right - ToolTip-Width

*the same logic applies to the top position of the ToolTip

Adjust this simple calculation to position your ToolTip Form using a different logic, if needed.
▶ There's no need to dispose of the ToolTip Form: it's automatically disposed of when the Form instance passed to Application.Run() is closed.
Note: If the Application is not DpiAware and the Screen where the Application's Windows are shown is scaled, any measure relative to either the Screen or the Windows/Forms may be virtualized, so you receive wrong results and any calculation will be off.
See the notes here:
Using SetWindowPos with multiple monitors
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

public static frmToolTip tooltip = null;

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    tooltip = new frmToolTip();
    Application.Run(new SomeForm());
}

public async static Task ShowToolTip(Control control, string title) {
    await Task.Delay(400);
    if (tooltip.Visible) return;

    Rectangle refBounds = control.RectangleToScreen(control.ClientRectangle);
    if (!refBounds.Contains(Cursor.Position)) {
        HideToolTip();
    }
    else {
        var screen = Screen.GetBounds(control);
        var leftPos = refBounds.Left <= screen.Width / 2 ? refBounds.Left : refBounds.Right - tooltip.Width;
        var topPos = refBounds.Top <= screen.Height / 2 ? refBounds.Bottom + 2: refBounds.Top - tooltip.Height - 2;
        tooltip.Location = new Point(leftPos, topPos);
        tooltip.Text = title;
        tooltip.Show(control.FindForm());
    }
}
public static void HideToolTip() => tooltip.Hide();

In any Form, use a Control's MouseEnter and MouseLeave events to show/hide your ToolTip.
Note: I'm using Task.Delay() to delay the presentation of the ToolTip, so it doesn't show up if you briefly move the Mouse Pointer over the Control that shows it.
It also verifies whether the Form ToolTip is already shown (you cannot show a Form twice) or the Mouse Pointer has moved outside the bounds of the reference Control in the meanwhile (the ToolTip is not shown in this case).
Change this behavior as required.

*

*In ShowToolTip(), I'm passing a string, meant to be used as the Title of the ToolTip. It's just an example, to show that you may pass any other parameter to this method (a class object, maybe) to setup the ToolTip Form in a custom way, different based on the caller requirements.

using System.Threading.Tasks;

public partial class SomeForm : Form
{
   // [...]

    private async void SomeControl_MouseEnter(object sender, EventArgs e)
    {
        await Program.ShowToolTip(sender as Control, "Some Title Text");
    }

    private void SomeControl_MouseLeave(object sender, EventArgs e)
    {
        Program.HideToolTip();
    }
}


text:
Q: issue while deploying gcp cloud function deployment I have following issue while deploying the cloud function (I am completely new to gcp and terraform )
I am trying to deploy a cloud function through the terraform; but the issue is that when I am deploying its destroying an existing cloud function which was already deployed in gcp (deployed by other colleague) even though cloud function name , bucket object name and archive file name are different (only bucket name and project id  are same)
looks like its taking the state of existing cloud function which is already deployed
is there any way to keep the existing state unaffected?
code Snippet(as mentioned above there is already one cloud function deployed with same project id and bucket)
main.tf:
provider "google" {
  project = "peoject_id"
  credentials = "cdenetialfile"
  region  = "some-region"
}

locals {
  timestamp = formatdate("YYMMDDhhmmss", timestamp())
    root_dir = abspath("./app/")
}

data "archive_file" "archive" {
  type        = "zip"
  output_path = "/tmp/function-${local.timestamp}.zip"
  source_dir = local.root_dir
}

resource "google_storage_bucket_object" "object_archive" {
  name   = "archive-${local.timestamp}.zip"
  bucket = "dev-bucket-tfstate"
  source = "/tmp/function-${local.timestamp}.zip"
  depends_on = [data.archive_file.archive]

}

resource "google_cloudfunctions_function" "translator_function" {
  name = "Cloud_functionname"
  available_memory_mb = 256
  timeout = 61
  runtime = "java11"
  source_archive_bucket = "dev-bucket-tfstate"
  source_archive_object = google_storage_bucket_object.object_archive.name
  entry_point = "com.test.controller.myController"
  event_trigger {
    event_type = "google.pubsub.topic.publish"
    resource = "topic_name"
  }
}

backend.tf
terraform {
  backend "gcs" {
    bucket = "dev-bucket-tfstate"
    credentials = "cdenetialfile"
  }
}


text:
Q: Resetting Netbeans 8.x GIT versioning (folder ?) I am using Netbeans 8.1 IDE  (Windows) and I am a complete noob at versioning on the first step of the learning curve, and I have accidentally deleted the GIT folder (was apparently empty) created by Netbeans 8.1 upon Versioning Git initialisation.
Now I see all my files in Netbeans tree-view green-coloured as if versioning is active, however the Git folder in the filesystem is still empty. I suspect Netbeans being fooled somehow so I have closed Netbeans and deleted the cache folder however once restarted, GIT seems to be there, enabled and working.
To ensure GIT is working as expected I'd like to completely reset versioning to it's initial state so I can create again the repo folder and verify it is working as expected but I don't know how to achieve this.
EDIT:
I see the .git folder as it was hidden in the filesystem, so I was wrong I did not delete the folder! However to ensure everything is working as expected how can I reinitialise this?

A:
However to ensure everything is working as expected how can I reinitialise this?

Deleting (or at least moving) that .git folder would be a good first step.
Then use Netbeans to re-initialize your repo.


text:
Q: How to handle generate custom composite key from multiple request I would like to generate costume unique invoiceno with help of two column Year and CompanyId in SQL Server (composite key (Year, CompanyId, Invoiceno)).
I can do with custom login to generate this unique key but how can handle if multiple request come at same to insert record.
My expectation records as below :

InvoiceId | Year            | CompanyId | InvoiceNo
1         | 2018            |      1    | IN0001
2         | 2018            |      1    | IN0002
3         | 2018            |      2    | IN0001
3         | 2018            |      3    | IN0001
4         | 2019            |      1    | IN0001
5         | 2019            |      1    | IN0002
6         | 2019            |      2    | IN0001

Thanks in advance !

A: One can use ROW_NUMBER to get a number that can be used to form such InvoiceNo.

SELECT
 InvoiceId, [Year], CompanyId,
 'IN'+ RIGHT(
        CONCAT(
         REPLICATE('0',3),
          ROW_NUMBER() OVER (PARTITION BY [Year], CompanyId ORDER BY InvoiceId)
        ) ,4) AS InvoiceNo
FROM YourInvoiceTable
ORDER BY InvoiceId

Test on db<>fiddle here


text:
Q: awk: filter a file with another file I'm trying to filter a file with another file.
I have a file d3_tmp and m2p_tmp; They are as follows:
$ cat d3_tmp
0x000001     0x4d    2
0x1107ce     0x4e    2
0x111deb     0x6b    2

$ cat m2p_tmp
mfn=0x000001 ==> pfn=0xffffffffffffffff
mfn=0x000002 ==> pfn=0xffffffffffffffff
mfn=0x000003 ==> pfn=0xffffffffffffffff

I want to print out the lines in m2p_tmp whose second column is not equal to the first column of d3_tmp. (The files are split with \t and =)
So the desired result is:
  mfn=0x000002 ==> pfn=0xffffffffffffffff
  mfn=0x000003 ==> pfn=0xffffffffffffffff

However, after I use the following awk command:
awk -F '[\t=]' ' FNR==NR { print $1; a[$1]=1; next } !($2 in a){printf "%s \t 0\n", $2}'     d3_tmp  m2p_tmp

The result is:
0x000001
0x1107ce
0x111deb
0x000001     0
0x000002     0
0x000003     0

I'm not sure why "$2 in a" does not work.
Could anyone help?
Thank you very much!

A: Using awk
awk 'NR==FNR{for (i=1;i<=NF;i++) a[$i];next} !($2 in a)' d3_tmp FS="[ =]" m2p_tmp

a[$i] is used to collect all items in file d3_tmp into array a, NR==FNR used to control the collection is only focus on d3_tmp.
in second part, set the FS to space or "=", and compare if $2 in file m2p_tmp is in this array a or not, if in, print it.
The question has been edited, so I have to change the code as well.
awk 'NR==FNR{a[$1];next} !($2 in a)' d3_tmp FS="[ \t=]" m2p_tmp

A: awk -v FS="[\t= ]"  ' FNR==NR { a[$1]=$1; next } !($2 in a){print $0}'     d3_tmp  m2p_tmp
mfn=0x000002 ==> pfn=0xffffffffffffffff
mfn=0x000003 ==> pfn=0xffffffffffffffff


text:
Q: wp_schedule_event / cron_schedules - custom recurrence time not working in Plugin I am trying to add custom intervals for the WP cron in a plugin.
It run with "hourly", "daily" default recurrence time.
It dont' run when I add my own custom recurrence time for the function wp_schedule_event.
I want to execute a function every X hours (defined by users).
Thanks.
Here is the code:
<?php
/*
Plugin Name: Test Cron
Description: Plugin to Test Cron Jobs.
Version: 1.00
*/
class WP_TestCron {
    function __construct()
    {
        register_activation_hook(__FILE__, array($this, 'TestCron_cron_activate'));
        register_deactivation_hook(__FILE__, array($this, 'TestCron_cron_deactivate'));
        add_filter('cron_schedules', array($this, 'TestCron_cron_update_schedules'));
        add_action('TestCron_cron_eventOne', array($this, 'TestCron_cron_fct'));
        add_action('TestCron_cron_eventTwo', array($this, 'TestCron_cron_fct'));
    }

    function TestCron_cron_activate()
    {
        // Run => In Schedule Cronjobs
        if (!wp_next_scheduled('TestCron_cron_eventOne')) { wp_schedule_event(time(), 'hourly', 'TestCron_cron_eventOne'); }

        // Dont't Run => Not in Schedule Cronjobs
        if (!wp_next_scheduled('TestCron_cron_eventTwo')) { wp_schedule_event(time(), 'in_per_minute', 'TestCron_cron_eventTwo'); }
    }

    function TestCron_cron_deactivate()
    {
        wp_clear_scheduled_hook('TestCron_cron_eventOne');
        wp_clear_scheduled_hook('TestCron_cron_eventTwo');
    }

    function TestCron_cron_update_schedules()
    {
        return array(
            'fively' => array('interval' => 300, 'display' => 'Once in Five minutes'),
            'in_per_minute' => array('interval' => 60, 'display' => 'In every minute'),
            'in_per_ten_minute' => array('interval' => 60 * 10, 'display' => 'Once in Ten minutes'),
            'three_hourly' => array('interval' => 60 * 60 * 3,  'display' => 'Once in three hours')
        );
    }

    function TestCron_cron_fct()
    {
        $testCcron_post = array();
        $testCcron_post['post_title'] = 'Cron Update - '.date('d/m/y \a\t h:i A');
        $testCcron_post['post_content'] = 'WP-Cron job is working!';
        $testCcron_post['post_status'] = 'publish';
        $testCcron_post['post_author'] = 1;
        $testCcron_post['post_category'] = array(1);

        wp_insert_post( $testCcron_post );
    }
}

if (is_admin()) $wpTC = new WP_TestCron();

?>

A: WP-Cron doesn't run in the admin scope - remove your if ( is_admin() ) condition.

A: I would also suggest not overwriting existing schedules.
The proper form would be to do:
function filter_cron_schedules( $schedules ) {
$schedules['fively'] = array(
    'interval' => 300,
    'display' => __('Once in Five minutes')
);

$schedules['in_per_minute'] = array(
    'interval' => 60,
    'display' => __('In every minute')
);

$schedules['in_per_ten_minute'] = array(
    'interval' => 600,
    'display' => __('Once in Ten minutes')
);

$schedules['three_hourly'] = array(
    'interval' => 10800,
    'display' => __('Once in three hours')
);
return $schedules;
}

Which would take the existing $schedules, add the 4 new intervals to it, and then return the updated array.
Mind you, I have had some serious problems with cron in class-based plugins before, a recent issue led me to this question.


text:
Q: Positive Expectancy with Random Chance A conversation came up at work about positive expectancy. I am having difficulty getting the same answer as the guys so I am throwing the question out to you folks...  Any help is appreciated.
A game costs €50 to play. If you win you get €100. You get 52 chances to pick the Ace of hearts from a deck of cards. Every time you pick a card it is then returned to the deck and the deck is shuffled again. You pay the €50 once and you then have up to and including 52 tries to get the Ace of Hearts. Is there a positive expectancy on this game?
I worked it that you have a 1/52 chance of winning every time you pick a card. While you do get to pick 52 times your chance of winning is still 1/52 each time you play.
( 1/52 * 100 ) - ( 51/52 * 50) = (200 - 4750) {I used rounded 2% for 1/52 and rounded 98% for 51/52}
What do you folks think?

A: To clarify for OP. The expected return of the game is
$E[R] = 100 \cdot P(\text{win}) - 50$
Where the probability that you lose is
$P(\text{lose}) = (51/52)^{52}$
and the probability that you win is
$P(\text{win}) = 1 - P(\text{lose}) = 1 - (51/52)^{52}$
Hence
$E[R] = 100 \cdot P(\text{win}) - 50$
$E[R] = 100 \cdot (1 - (51/52)^{52}) - 50 \approx \$13.7$
So this is a fantastic game :)

A: You fail each time with probability $51/52$. Since you return the card to the deck, the draws are independent so you fail all and lose the game with probability $(51/52)^{52} \approx 0.36$. Since you win with probability greater than one half, the odds are good for you.


text:
Q: DROPPING TABLE FROM DIFFERENT SCHEMA I wrote a Procedure which essentially used to drop table.
It works as expected , but the problem is As this Procedure is in "DW" schema and dropping table is in "SCRATCH".
Because of this, we get insufficient privileges.
Any way we can achieve this and solve the "privilege" issue?
CREATE OR REPLACE PROCEDURE   DW.PROC AUTHID CURRENT_USER IS
V_TABLE_NAME  VARCHAR2(255);
V_DELETE_DT NUMBER(33);
V_LIST SYS_REFCURSOR;
BEGIN
    SELECT TO_NUMBER(VALUE) INTO V_DELETE_DT FROM DW.LIST_OF_TABLE
    OPEN V_LIST FOR
    SELECT OBJECT_NAME FROM ALL_OBJECTS WHERE OBJECT_TYPE= 'TABLE' AND
    OBJECT_NAME LIKE '%DLY_BKP%' AND CREATED <=SYSDATE - V_DELETE_DT;

     LOOP
        FETCH V_LIST
        INTO V_TABLE_NAME;
        EXIT WHEN V_LIST%NOTFOUND;
        EXECUTE IMMEDIATE 'DROP TABLE SCRATCH.'||V_TABLE_NAME ;
     END LOOP;
    CLOSE V_LIST;
END;

A: To drop a table in another schema, you must do one of the following:

*

*Be granted the "DROP ANY TABLE" system privilege. This is highly elevated and it is likely your DBAs will balk at it, but it'll work.

*Create a procedure owned by the table owner that accepts a table name as a parameter and issues the drop DDL on your behalf. Grant execute privs on the procedure to your connect user. This is usually the better choice. You can further enhance it to table-drive a list of tables or table name patterns that are white-listed or black-listed for drop, whatever makes sense.
At it's most simplest:
CREATE OR REPLACE PROCEDURE scratch.drop_table(in_table_name IN varchar2)
AS
BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE "'||in_table_name||'"';
END;
/
GRANT EXECUTE ON scratch.drop_table TO dw;
/

Then DW calls it:
BEGIN
  scratch.drop_table('TABLE_TO_DROP');
END;

If for any reason you cannot create this procedure under the SCRATCH schema (which is an unreasonable restriction), you can create it under a privileged account like SYSTEM and also add the table owner name as an additional parameter. Then you most definitely will want to table-drive a set of white-listed owners to prevent misuse of the procedure.


text:
Q: How To Regen Farm On BTD5 Mobile I was wondering how can I regen farm the most efficiently on BTD5 mobile, while also having a back-up option in case I start to get over run by regrows to end the farm. Thanks for any help you guys can provide.

A: Regrow farming requires many different conditions to work right.

*

*Round: Obviously, regrow farming needs to be on a round with a large regrow rush. Round 49 is the best, because, being before round 50, and containing a regrow rainbow rush, you get full XP and Money.

*Farming Towers: These are the towers that are going to keep the farm running. Recommended is a 3-X wizard, if you have a good computer upgrade to 4-X after a minute and even place more. If for some reason wizards won't work (Restricted tower on a special mission, Glitches...), Ninjas with distraction, Bloonchippers, and the Banana Farmer pro will work okay if needed.

*Popping Towers: During Regrow farming, things can quickly get out of control. In order to control the bloons, a tower is needed that can pop the rush near the end, without destroying the farm. The Ring of Fire tower is, despite what you may think, very bad at controlling the bloons. 4-X Cannons can pop Zebra and blacks, and I strongly recommend them. A few of them can power through any rainbow rush

A: A good idea for XP, I'll show to prepare:
Use a 1/0 Engineer Monkey, and get 7 or 8 farms over the next 22 rounds. Upgrade the farms to at least 3/0. Getting hard? Upgrade the engineer with 9-inch nails and get a 2/2 or 2/3 Apprentice. When reaching any of the rounds that are only regrows, like round 42, use some towers that will knock back the bloons (Like Downdraft), Slowers (Glue gunners at level x/4), Multipliers (Ice Monkeys at Artic Wind), Poppers (The Ray of Doom's good for popping, but DO NOT TRY TO SWIPE AT ALL THE BLOONS!.), and Farmers (Like some Sprockets Engineers).


text:
Q: Shopify Application Proxy giving CORS error Hello I just configured Application proxy for shopify application.
My proxy URL is: testbypradip.myshopify.com/admin/apps/proxy
I'm running local dev environment in with ngrok. So my origin would be https://aa0ef495.ngrok.io
As per shopify docs if I make get request to my proxy url I should not be getting CORS error but I am getting it.
My request looks like:
axios({
  url: `https://testbypradip.myshopify.com/apps/proxy/Product?upc=${query}`,
  method: 'GET',
  withCredentials: true,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
})
  .then(response => {
    dispatch(requestCompleteAction(response.data));
  })
  .catch(error => {
    dispatch(requestErrorAction(error));
  });

I've enabled CORS in express as well

A: You need to do the following. Make an endpoint in your App running in the cloud (or localhost)... reachable by ngrok or forward. You seem to have that. In Shopify App setup, create a Proxy that points at your end-point. Eg for you... app/proxy. So make that point at
https://aa0ef495.ngrok.io/fooblefuzz/dingbat

or whatever you need.
Now in your front-end code, post to the Proxy! ie)  /app/proxy
Not https://testbypradip.myshopify.com/apps/proxy/ as this is non-existant. You should not have any CORS issues as you are not doing any XHR to your cloud App. Instead, you are handling a simple POST from Shopify that you secure and act on.


text:
Q: How to store changed array into object property while using splice() I am writing a switch statement for a reducer and would like to update the spliced version of a given property when returning the overall object.
How can I properly store the updated array into the object?
Here is a function that simulates the problem:
const newData = {
  id: 1,
  url: "url",
  query: "mangoes",
  title: "this title"
}

const target = [
  {
    id: 0,
    url: "",
    query: "mangoes",
    title: "old title"
  }
]

const switchCase = () => {
    return {
        targetProp: target.splice(0, 1, newData)
    }
}

The returned object has the initial unchanged target as the "targetProp" rather than an updated one


text:
Q: iOS : how to launch app automatically I have a requirement where my app should launch automatically when user unlocks the phone (passcode).
I did some googling but that didn't help me much.

A: This isn't possible on iOS.
App can only be launched (i.e. enter in the foreground) from:

*

*Taping the icon

*A link in another app/web page using custom URL schemes

*A notification (User unlocking the phone from a received push notification)


text:
Q: Display complex JSON with use of jquery .each I was having trouble trying to make this code work. I really don't see anything wrong with the javascript. When I debug, I don't find errors either.

ppt presentation

here is the JSON:
{
    "title": "presentation",
    "date_created": "",
    "last_modified": "",
    "author": "By: Someone online",
    "slides": [
        {
            "Slide": "1",
            "header": "first header",
            "src": "ssss.jpg",
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd"
        },
        {
            "Slide2": "2",
            "header2": "header 2",
            "src2": null,
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd"

        },
        {
            "Slide3": "3",
            "header3": "header3",
            "src3": "sdfdsf.jpg",
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd",
            "Content": "dddddddddddddddddddddddddddddddddddd"
        }
    ]
}

I really want to make this work and don't want to use other methods such as jquery templates.
Is there anything that jumps out?

A: You're closing .each too soon :
$.each(entry['slides'],function(slideIndex, slides){
    html += '
' + slides['Slide'] + '
';
    html += '
' + slides['header'] + '
';
 });
 if(slides['Content']){
 // ...

That way you only access the last value of slides['Content'].
You need to put that if and what it contains into your loop like this :
 $.each(entry['slides'],function(slideIndex, slides){
    html += '
' + slides['Slide'] + '
';
    html += '
' + slides['header'] + '
';
    if(slides['Content']){
    // ...

 });


text:
Q: Identifying a Math Font I recently stumbled upon this:

(From page 13 of this PDF.)
Can anyone identify where the math symbols are coming from? It looks similar to the default LaTeX math font, but it's not quite. The curly braces, in particular, have real curl to them, and the asterisk and angle brackets are also different. I'd like to copy some of these features, if anyone can help me find where they've come from.


text:
Q: Changing enum value of struct in iterator pub struct Server {
  devices: Vec<Device>,
}

pub struct Device {
  configuration: Configuration,
}

pub enum Configuration {
    Gradient {
        stops: Vec<String>,
        brightness: f32,
        duration: i32,
        random_starting_point: bool,
    },
}

I want to update the configurations of certain devices dynamically through the method:
fn update_configuration(&mut self, devices: Vec<Device>, configuration: Configuration) {
    self.devices
        .iter_mut()
        .filter(|device| devices.contains(device.get_id()))
        .for_each(|device| {
            (*device).configuration = configuration;
        });
}

The compiler outputs:
error[E0507]: cannot move out of `configuration`, a captured variable in an `FnMut` closure

device.update_configuration(configuration);
                           ^^^^^^^^^^^^^ move occurs because `configuration` has type `device::Configuration`, which does not implement the `Copy` trait

And since I have a Vec<String> in that enum value I can't implement the Copy trait. I do have a basic understanding of memory management (stack, heap) and pointers but I can't quite wrap my head around it completely.
My questions

*

*How do I achieve such a field change?

*Is this the idiomatic way to update such a field in a struct?

A: In Rust every piece of data can have at most 1 unique owner. You're taking a single instance of Configuration and trying to share it across potentially multiple Devices. The simplest way to solve your problem would be to derive an implementation of Clone which will allow you to make clones of the Configuration enum whenever you try to share it.
#[derive(Clone)]
pub enum Configuration {}

And then clone it in your loop:
self.devices
    .iter_mut()
    .filter(|device| devices.contains(device.get_id()))
    .for_each(|device| {
        (*device).configuration = configuration.clone();
    });

Note: this will give a unique clone of Configuration to every Device which is what I'm assuming you want.


text:
Q: How to use swift categories in objective-c project? I got a swift category for UIImage, but I can't figure out how to make it work.
This is the swift category i'm trying to use:
import UIKit

 extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
    color1.setFill()

    let context = UIGraphicsGetCurrentContext()! as CGContextRef
    CGContextTranslateCTM(context, 0, self.size.height)
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, CGBlendMode.Normal)

    let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
    CGContextClipToMask(context, rect, self.CGImage)
    CGContextFillRect(context, rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
    UIGraphicsEndImageContext()

    return newImage
    }
}

In my objective C View Controller code I Tried to import:
#import "UIImage+Overlay.swift"

And xcode gives me a lot of errors, it's looks like Objective C errors. It seems it doesn't understand swift code.
Errors:
unexpected '@' in program when I declare the first property:
@property (nonatomic, strong) NSArray *contentImages;

As suggested by Leo Natan, I did try to import, but I think is because the name of my App. I did try all this kind of import, but still saying can't find it.
#import <ProductName/ProductModuleName-Swift.h>
#import <Say_Cheese_/Say_Cheese_-Swift.h>
#import <Say Cheese!/Say_Cheese_-Swift.h>
#import <Say Cheese!-Say_Cheese_-Swift.h>
#import <Say Cheese!-Bridging-Header.h>

My Product Name is "Say Cheese!"
My Product Module Name is Say_Cheese_, but behind is $(PRODUCT_NAME:c99extidentifier)
I'm afraid to change the Product Module Name, is it safe?

A: Do not import the Swift file. Instead, import the compiler generated "ProductModuleName-Swift.h" file.

Importing Swift into Objective-C
When you import Swift code into Objective-C, you rely on an
  Xcode-generated header file to expose those files to Objective-C. This
  automatically generated file is an Objective-C header that declares
  the Swift interfaces in your target. It can be thought of as an
  umbrella header for your Swift code. The name of this header is your
  product module name followed by adding "-Swift.h". (You'll learn more
  about the product module name later, in Naming Your Product Module.)
By default, the generated header contains interfaces for Swift
  declarations marked with the public modifier. It also contains those
  marked with the internal modifier if your app target has an
  Objective-C bridging header. Declarations marked with the private
  modifier do not appear in the generated header. Private declarations
  are not exposed to Objective-C unless they are explicitly marked with
  @IBAction, @IBOutlet, or @objc as well. If your app target is compiled
  with testing enabled, a unit test target can access any declaration
  with the internal modifier as if they were declared with the public
  modifier by prepending @testable to the product module import
  statement.
You don't need to do anything special to create the generated header
  file—just import it to use its contents in your Objective-C code. Note
  that the Swift interfaces in the generated header include references
  to all of the Objective-C types used in them. If you use your own
  Objective-C types in your Swift code, make sure to import the
  Objective-C headers for those types before importing the Swift
  generated header into the Objective-C .m file you want to access the
  Swift code from.

In your project's target, find the product module name. Usually, it has the same name as the target. This will be the name of the compiler generated header file.
In your Objective C source file, import this header.
#import <ProductModuleName-Swift.h>

This header file is generated every time you build your project, so any changes to Swift files will require a compilation before being able to use in Objective C.

A: I got some tips at this link:
How to import Swift code to Objective-C
But to solve this, I did use "" instead <> on #import
#import "SayCheese-Swift.h"

and then I define the Product Module Name to "SayCheese" without special chars and spaces.
Thanks Leo.


text:
Q: javascript: add class to  which is clicked and remove all elements with specific tag Okay so I have a navigation sidebar and I want it so that when a link is clicked, the .clicked class gets added to the link clicked and the .clicked class gets removed from all other tags, if other tags of a .clicked class. Here is my javascript
$('#sidebar ul a').click(function(){
    $('#sidebar ul .clicked').removeClass('.clicked');
    $(this).addClass('clicked');
});

here is my css
.clicked {
    background: url(../images/liHover.png) no-repeat;
    background-position: -5px 0px;
    color: white;
}

and here is my html

top

First

Second

Third

Fourth

But it doesn't seem to work. When I click a link /
 it does add the class however it does not remove the .clicked class from the other elements. Any idea why?

A: your html is invalid for starters, try putting the li first in the list

First

        // repeat for other items

your jquery is also invalid, your missing the hashtag '#sidebar' to reference an id element
finally your jquery function removeClass doesn't need a period before the class removeClass('clicked');

A: First of all,
Is your code wrapped in
$(document).ready(function() {
});

or
$(function() {
});

If not, your code may be executing before the DOM is ready, in which case it will not bind properly.
Next,
$('sidebar ul a')

should be
$('#sidebar ul a')

and
$('sidebar ul .clicked').removeClass('.clicked');

should be
$('sidebar ul .clicked').removeClass('clicked');

On the CSS side of things, the background won't display on the link unless you set display: block and give it a width. Finally, the image URL inside the parentheses should be in quotes, and as the previous poster stated, the background position should be part of "background" since it's a shortcut.

A: may be because the a  tag in inline
if you try out  to put it  like a block
#sidebarHeader{
  display:block;

}

and you should remove the clicked from a element
like this
  $('sidebar ul a').removeClass('.clicked');


text:
Q: Twilio hanging up after 45 minutes I'm a newby using twilio to play an audio recording of the Sunday service for those people who do not have internet access.  They dial a number, get a message to hang on, then the application plays an audio file of the service.  Seems to work well, EXCEPT that for many users, the system hangs up on them after approximately 45 minutes into the 55 minute service.
Based on the logs, the hang-up seems quite consistent.  Is there a setting somewhere that I'm missing that is causing this?

A: Twilio developer evangelist here.
In the documentation for the <Play> element, under "Hints and Advanced Uses", it says:

<Play>ing a file that is longer than 40 minutes can result in a dropped call. If you need to <Play> a file longer than 40 minutes, consider splitting it up into smaller chunks.

I'd advise splitting the service up into two chunks of 27.5 minutes and playing them one after another, to avoid this issue.


text:
Q: Is there a way to get all the previous version of a deleted s3 object I have a S3 bucket with versioning enabled. I have implemented rename functionality. For that first I am copying the object and then deleting the old one(Not permanently, only marked as deleted) as there is no direct method to rename a file in S3.
For e.g: We have an object as 'logo.jpg' that has multiple versions. Now I have renamed it as 'logo1.jpg'. After renaming, I am able to fetch version of 'logo1.jpg' but how to fetch all versions of 'logo.jpg' that has been deleted(Not permanently, marked as deleted in S3).
To fetch all version, using below code
   ListVersionsRequest request = new ListVersionsRequest()
                    .withBucketName(bucketName).withPrefix(
                            key);

            VersionListing versionListing = s3.listVersions(request);
            for (S3VersionSummary obj2 : versionListing
                    .getVersionSummaries()) {
               obj2.getKey();
               obj2.getVersionId();
            }

It is working when fetching the key and version for 'logo1.jpg'.
But when trying the same for 'logo.jpg'(deleted object), getting exception as:
com.amazonaws.services.s3.model.AmazonS3Exception with Error Code: 405
I am not able to fetch version and key of a deleted object in S3.


text:
Q: Looping over a list in Java to check for a value I have a list of an object
List<myObj> myObjList

Here, myObj is a class with the following structure:
public class myObj {
    private String id;
    private String pwd;
    private String type;
    //Getters/Setters
}

I want to loop through the list to check, if i have a particular id. I tried :
for (obj : myObjList) {
    if (MY_STRING.equals(obj.getId())) {
        aBooleanFlag = true;
    }
}

However, when i want to use, contains method, it is failing. The way i am using it is :
if(myObj.contains(MY_STRING)) {
    aBooleanFlag = true;
}

Can you suggest what is wrong and how to fix it

A: .contains() checks whether any object in the list is equal to the parameter.
A myObj instance will never equal a String.

A: Change
if(myObj.contains(MY_STRING)) {
    aBooleanFlag = true;
}

to
if (myObj.getId().contains(MY_STRING)) {
        aBooleanFlag = true;
    }

A: In your loop you use .equals(Object).
If you want to compare 2 String you should use .equalsIgnoreCase(String).
 You als neeed to define what obj is.
So this would be your code:
for (Object obj : myObjList) {
    if (MY_STRING.equalsIgnoreCase(obj.getId())) {
        aBooleanFlag = true;
    }
}

If you use the if method, you should check if the List contains the String.
Checking if a class contains a String would not help.
So your code there would be:
if(myObjList.contains(MY_STRING)) {
    aBooleanFlag = true;
}

Hope it helped

A: You are comparing a String to an entire MyObj object using equals. This is like asking whether your car is equal to a hubcap (one part of your car).
You can either iterate over the list:
boolean found = false;
for (MyObj obj : myObjList) {
    if (obj.getId().equals(MY_STRING)) {
        found = true;
        break;
    }
}

Or you can use Java 8 streams with anyMatch() and a predicate:
boolean found = myObjList.stream().anyMatch(obj -> obj.getId().equals(MY_STRING));

Or you can use a Map instead of a List, and look items up by id:
Map<String, MyObj> theMap = new HashMap<>();
// put MyObj's into the map by id
theMap.put(myObj.getId(), myObj);
// check for one using its id
boolean found = theMap.containsKey(MY_STRING);

I changed the name of the class from myObj to MyObj because the convention is that class names start with capital letters in Java.

A: You should be using a Map instead of a List.


text:
Q: Is there a way to match a sub matrix out of a bigger matrix? It is a 2D matrix matching problem. Given a bigger matrix find a smaller matrix, which matches the digits in the bigger matrix. Till here its easy, since I can use Rabin Karp matching and find the sub matrix, but here's the twist there can be alphabets in the sub matrix and the alphabets should match the same digits throughout the sub matrix matching.
eg.
Big Matrix:
[
      [2, 5, 2, 5, 2],
      [5, 1, 5, 2, 3],
      [1, 5, 2, 5, 4]
]

Sub matrix:
[
      [5, a],
      [a, e]
]

This should match a to the same digits, and e can be any digit.
So here the match is at (1, 0), because 5 matches 5 at (1, 0) and a=1 at [(1,1), (2,0)] and e=5.
Edit:
Added Constraints
Constraints:
1 <= length(Big Matrix) <= 50
1 <= length(any row in Big Matrix) <= 50
1 <= length(Sub Matrix) <= min(length(Board Matrix), length(Board Matrix[row size]))
Big Matrix will contain just digits, but Sub matrix can contain either alphabets or digits.
Conditions:

*

*Any digit should correspond to the same digit in the Big Matrix.

*Any letter should corresponding to a digit should correspond to the same digit throughout the submatrix.

*Any two distinct letters should correspond to two different digits. i.e no two characters can have the same digit mapped.

A: Provided your matrix contains single digits and the number of variables isn't too large, you could precompute the submatrix hashes for all possible values of a and e (in this case 100 of them) and store them in a data structure such as a hash set. Then as you compute your rolling hash as part of the Rabin-Karp matching algorithm, you can check if the hash is in the hash set at each step. This check should be O(1).

A: Thinking aloud:
Preprocess the pattern to list

*

*the digit entries;

*the letters, grouped by equal values, possibly setting singletons aside.
Perform a pattern search on the digits alone, using brute force (or possibly matrix search with don't care symbols ?). For every candidate,

*

*check that the letter assignments are compatible (condition 2.), not needed for singletons,

*check that the assignments are unique (condition 3.).


text:
Q: Java Program - Word Statistics I have created a Java program that goes out and returns search results from various social media API's based on a keyword text file and writes the returned results to another text file.
I am now trying to have another class separate class that will scan the search results text file and return statistics on how many times the 'keywords' were found in the search results. I am basically trying to run the search against the keywords.txt file.
I have been trying to get the below code to work but I can only get it to return all words, rather than just those from the keywords.txt file.
I have tried to get an input StreamReader to work but to no avail. Any help would be greatly appreciated.

package search;

import java.util.*; // Provides TreeMap, Iterator, Scanner
import java.io.*; // Provides FileReader, FileNotFoundException

public class SearchResults
{

    public static void main(String[] args)
    {
        TreeMap<String, Integer> frequencyData = new TreeMap<String, Integer>();
        readWordFile(frequencyData);
        printAllCounts(frequencyData);
    }

    public static int getCount(String word, TreeMap<String, Integer> frequencyData)
    {
        if (frequencyData.containsKey(word))
        { // The word has occurred before, so get its count from the map
            return frequencyData.get(word); // Auto-unboxed
        }
        else
        { // No occurrences of this word
            return 0;
        }
    }

    public static void printAllCounts(TreeMap<String, Integer> frequencyData)
    {
        System.out.println("-----------------------------------------------");
        System.out.println(" Occurrences Word");

        for(String word : frequencyData.keySet())
        {
            System.out.printf("%15d %s\n", frequencyData.get(word), word);
        }

        System.out.println("-----------------------------------------------");
    }

    public static void readWordFile(TreeMap<String, Integer> frequencyData)
    {
        Scanner wordFile;
        String word; // A word read from the file
        Integer count; // The number of occurrences of the word

        try
        {
            wordFile = new Scanner(new FileReader("SearchResults.txt"));
        }
        catch (FileNotFoundException e)
        {
            System.err.println(e);
            return;
        }

        while (wordFile.hasNext())
        {
            // Read the next word and get rid of the end-of-line marker if needed:
            word = wordFile.next();

            // Get the current count of this word, add one, and then store the new count:
            count = getCount(word, frequencyData) + 1;
            frequencyData.put(word, count);
        }
    }
}

A: There, I cleaned up your code and added filtering by all the keywords found in keywords.txt.
public static void main(String[] args) throws Exception {
  printAllCounts(
    readWordFile("SearchResults.txt", loadKeywords("keywords.txt")));
}

private static Map<String, Integer> readWordFile(
  String fname, Set<String> keywords) throws FileNotFoundException
{
  final Map<String, Integer> frequencyData = new TreeMap<String, Integer>();
  for (Scanner wordFile = new Scanner(new FileReader(fname));
    wordFile.hasNext();)
  {
    final String word = wordFile.next();
    if (keywords.contains(word))
      frequencyData.put(word, getCount(word, frequencyData) + 1);
  }
  return frequencyData;
}

private static void printAllCounts(Map<String, Integer> frequencyData) {
  System.out.println("-----------------------------------------------");
  System.out.println(" Occurrences Word");
  for(Map.Entry<String, Integer> e : frequencyData.entrySet())
    System.out.printf("%15d %s\n", e.getValue(), e.getKey());
  System.out.println("-----------------------------------------------");
}

private static int getCount(String word, Map<String, Integer> frequencyData) {
    return frequencyData.containsKey(word)? frequencyData.get(word) : 0;
}

private static Set<String> loadKeywords(String fname)
throws FileNotFoundException
{
  final Set<String> result = new HashSet<String>();
  for (Scanner s = new Scanner(new FileReader(fname)); s.hasNext();)
    result.add(s.next());
  return result;
}


text:
Q: How to get all mousemove events while main thread is busy Windows MFC C++ I have a long CPU operation on a mousemove event. It seems like no new mousemove events are sent to my application during that time, making for big jumps in mouse position.
I thought mouseevents would build up in a queue and then all get sent to my app, but this does not seem to be the case.
I would like as high resolution of mousemove events as is possible from the device - whether or not the app is busy processing something.
Should I put my application in a worker thread, and let my main thread just process events? Is there a simpler way to see 'raw' mouse input.

A: You have a few options:

*

*As you mentioned, put your processing in a worker thread and let Windows messages pump in your main thread. This is probably the most conventional method, the most logical design.

*Use GetCursorPos and GetAsyncKeyState to get mouse state whenever you want it, without depending on the Windows message loop. In other words, interrupt your busy task every N milliseconds to poll and record mouse state. I don't recommend this because you'll be polling, bypassing the system's message handling.

*Pump the message loop whenever you want to allow messages through. Think DoEvents from Visual Basic. I just don't recommend this; it's one of these things that "feels simple" but actually adds the kind of complexity that will make you just want to abandon your code and rewrite it correctly.


text:
Q: Trying to put array of anything into method parameter I have a little problem: I created this method
private static Dictionary<object, int> StuffToDictionary(IEnumerable<object> input)
{
    var dict = new Dictionary<object, int>();

    foreach (var word in input)
    {
        try
        {
            dict.Add(word, 1);
        }
        catch (ArgumentException)
        {
            dict[word]++;
        }
    }

    return dict;
}

and variable calling this method //not working yet ;)
var input = args[0];
Console.WriteLine("Character frequencies:\n" + StuffToDictionary(input));

How should I change my code (type of the input parameter, declaration of variable or whatever) so I can put there at least array of chars or ints not only object types variables array
I tried to convert input to almost everything but still did not found solution
Thanks

A: Something like this:
private static Dictionary<T, int> StuffToDictionary<T>(IEnumerable<T> input)
{
    var dict = new Dictionary<T, int>();

  foreach (var key in input)
  {
    if (dict.ContainsKey(key))
    {
        dict[key]++;
    }
    else
    {
        dict[key]=1;
    }
  }

  return dict;
}

However, you won't be able to use it in WriteLine and stuff as it has no meaningful ToString override. If you need such things, you better create a specialized StuffDictionary class instead of just a method.
On the other hand you should not use exceptions for such checks, although it works, it is a much expensive alternative and an antipattern if there is any direct approach.


text:
Q: How can I declare a struct of maps as a global variable? In order to declare a global map, I can directly initialize it at creation time:
package main

var a = map[string]string{}

func main() {
    a["hello"] = "world"
}

How can I initialize a global struct of maps? A similar approach is incorrect:
var db struct {
    Users   map[string]User{}
    Entries map[string]Entry{}
}

I also tried something like
var usersMap = map[string]User{}
var entriesMap = map[string]Entry{}

var db struct {
    Users   usersMap
    Entries entriesMap
}

but usersMap and entriesMap are not types.
I would be fine to initialize db from within main(), provided that it is still global.

A: A struct field declaration expects a type, not a value.  The composite literal expressions   map[string]User{} and map[string]Entry{} are values, not types.
Fix by separating the field type declarations from the field value initializations:
var db = struct {
    Users   map[string]User
    Entries map[string]Entry
}{
    Users:   map[string]User{},
    Entries: map[string]Entry{},
}


text:
Q: React Hooks, Conditionally change state inside onClick function, updates on the next click Hello I have a single list component which render some <Card> components that has a prop isSelected . Because alot of things happens when a <Card> Component has isSelected === true I added the state on the <List> component, and I want when someone clicks a card to check:
1) If there are no previously selected items ( state===null to add that item's id to state )
2) If someone clicks the same item or another item while there is already an item selected in state, to just unselected the active item.
import {Card} from "./Card";
import cloneDeep from 'lodash/cloneDeep';

const List = () => {
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.debug(selectedCard, id)
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if (newSelectedCard !== null || newSelectedCard === id) {
            setSelectedCard(null)
        } else {
            setSelectedCard(id)
        }
        console.debug(selectedCard, id)
    }

    return (

            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}

    )
}

export const CardList = () => (
    <List/>
);

The issue is that the 2 console.debugs print the same values which means that the state doesnt update imediately and Im experiencing some strange behaviours here and there. Am I missing something here?

A: Basically you need to follow 3 condition as below
if(newSelectedCard === null){
        setSelectedCard(id)
    }
    else if(newSelectedCard === id){
        setSelectedCard(null);
    }
    else{
        setSelectedCard(id)
    }

Here is the Complete example:
import cloneDeep from 'lodash/cloneDeep';
import React, {useState} from "react";

const List = () => {
    const [cardData, setCardData] = useState([
        {id: 1, title: 'First Card'},
        {id: 2, title: 'Second Card'},
        {id: 3, title: 'Third Card'},
        {id: 4, title: 'Fourth Card'},
    ]);
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.log(selectedCard, id);
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if(newSelectedCard === null){
            setSelectedCard(id)
        }
        else if(newSelectedCard === id){
            setSelectedCard(null);
        }
        else{
            setSelectedCard(id)
        }
        console.log(selectedCard, id)
    };

    return (

            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}

    )
};

export const CardList = () => (
    <List/>
);

const Card = (props) => {
    const backColor = props.isSelected? '#F9740E' : '#3FB566';
    return (

 props.onClick()}>

{props.id}

{props.title}

    );
};

Update
Here is Code SandBox

A: Not sure why you need to use cloneDeep.
const onCardClick = id => {
   if (selectedCard === id) {
       setSelectedCard(null);
   } else {
       setSelectedCard(id);
   }
}


text:
Q: How do you call master page methods from a content page when the button is inside an update panel? I have a masterpage and a content page. In the content page I have a script manager and an update panel. In the update panel I want to be able to click a button which would hit a public method on the master page to show a message.  This works if I don't have an update panel on the content page but is there a way to get it to work when the button is in an update panel?
Master Page:
public void ShowMessage(string Message)
{
    lblError.Text = Message;
    lblError.Visible = True;
}

Content Page:
Master.ShowMessage("something");

A: Function which define in masterpage:
public void Mesaj(string msj)
{
        lbl_Mesaj.Text = msj;
}

Function which define in content page
protected void Page_Load(object sender, EventArgs e)
{
    MasterPageWeb master = (MasterPageWeb)this.Master;
    master.Mesaj("www.zafercomert.com");
}

You can call masterpage's function from content page like this.

A: I ended up just sucking it up and putting the script manager on the master page and putting the label on the master page inside an update panel.

A: I think it's a bit late , but for those who are looking for the solution,
Assuming your master page class like:
public MyMAsterPage: MasterPage
{
    public void ShowMessage(string Message)
    {
       // DO SOMETHING
    }
}

from your content page you can easily call any public method as follow:
(this.Master as MyMasterPage).ShowMessage("Some argument");

A: <%@ MasterType VirtualPath="~/masters/SourcePage.master" %>
Master.Method(); (in code behind)

A: You'll need to
this.button1 = this.Master.FindControl("UpdatePanel1").FindControl("Button1") as Button;

Here's a blog post to help describe the process. Basically you're drilling down into your controls.
EDIT
Sorry I just re-read your question.  The code above will allow you to FIND a Button on your Masterpage from your Content Page codebehind.
It's a little more difficult to execute the Masterpage codebehind method from your content page. A better way might be to a JavaScript event to your button (or just use jQuery), and put the code for a JavaScript modal window in your Masterpage.

say something meaningful

    <button id="opener">open alert</button>

HOWEVER
If you're really hooked on calling a masterpage method from your content page, you need to make the method public
Find info in  Step 4: Calling the Master Page's Public Members from a Content Page

There are two ways that a content page can programmatically interface with its master page:

*

*Using the Page.Master property, which returns a loosely-typed reference to the master page, or

*Specify the page's master page type or file path via a @MasterType directive; this automatically adds a strongly-typed property to the page named Master.

A: Based on Amin's solution, i used an extension method to solve this more often.
public static T GetMasterPageObject<T>(this MasterPage masterPage) where T : MasterPage
{
    return (T)masterPage;
}

Example:
this.Master.GetMasterPageObject<MasterPageClass>().MethodYouNeed("Parameters");


text:
Q: How to change whole UI on an ASP.NET website? I am working on asp.net website and i want to implement themes on my site. If i select any theme then it will change whole UI not only colors. After Change it will show a new User interface. Like change in div size, width and location same for controls and same all html tag that is used in page.
I got lot of example of themes where it it changing only UI color. Can any buddy suggest me the any example where whole UI can change.
Thanks

A: Two suggestions spring to mind, they are separate but combined at the same time. They are Master pages and CSS.
Master pages would allow you to implement significantly different HTML markup for the page structure while CSS allows you to implement differing attributes (size, location, colour, border, font, etc) for the markup elements.
So, if you are just looking to rearrange the elements on a page then CSS alone can help. Look at CSS Zen Garden for loads of examples of what's possible.
If, however, you are looking to completely change the interface, perhaps by representing data using different controls then Master pages is probably your first stop.


text:
Q: Index datetime in numpy array I have a numpy array roughly like so:
data
array([(datetime.datetime(2009, 1, 6, 2, 30), 17924.0, 0.0),....
           (datetime.datetime(2009, 1, 29, 16, 30), 35249.2, 521.25],
         dtype=[('timestamp', '|O4'), ('x1', '<f8'), ('x2', '<f8')])

I would like to be able to index the data based on the first column (i.e. with the datetime objects), so I can access a particular year / month / day worth of data, with something like this:
data[data['timestamp'].year == 2009]

This obviously doesn't work. The only thing I can think of doing is adding additional columns (e.g. a "year" column), so this would work:
data[data['year'] == 2009]

Seems like a fairly inefficient way of doing things (and would duplicate a lot of data) - particularly if I want to index on all the other time intervals as well... is there a better way to do this?
Thanks in advance.

A: Use pandas. "pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language."
There are tons of examples in the documentation but you can do what you are looking to do like this:
import pandas
import numpy as np
import datetime as dt

# example values
dates = np.asarray(pandas.date_range('1/1/2000', periods=8))

# create a dataframe
df = pandas.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

# date you want
date=dt.datetime(2000,1,2)

# magic :)
print df.xs(date)

I suggest learning this module ASAP. It is absolutely exceptional. This is a very simple example. Check out the documentation which is very thorough.

A: Okay so I think I solved the problem (using pandas, as suggested by strimp099 above), specifically, using the "GroupBy" object (pandas: Group By: split-apply-combine)
To elaborate on the example used above:
import pandas
import numpy as np
import datetime as dt

# example values
dates = np.asarray(pandas.DateRange('1/1/2000', periods=200))

# create a dataframe
df = pandas.DataFrame(np.random.randn(200, 4), index=dates, columns=['A', 'B', 'C', 'D'])

# create a GroupBy object
grouped_data = df.groupby(lambda x: x.month)

#magic
grouped_data.mean()
              A         B         C         D
month
1     -0.492648 -0.038257 -0.224924  0.130182
2     -0.178995  0.236042 -0.471791 -0.369913
3     -0.261866 -0.024680 -0.107211 -0.195742
4      0.215505  0.077079 -0.057511  0.146193
5     -0.097043 -0.335736  0.302811  0.120170
6      0.187583  0.221954 -0.290655 -0.077800
7     -0.134988  0.013719 -0.094334 -0.107402
8     -0.229138  0.056588 -0.156174 -0.067655
9      0.043746  0.077781  0.230035  0.344440
10    -0.533137 -0.683788  0.395286 -0.957894

(i.e. averages of the data grouped by month)
Also, to do multiple groupings, (i.e. in my case year and month), this might help:
grouped_data = df.groupby(lambda x: (x.year,x.month))

Cheers!

A: You can also make use of the datetime dtype in numpy. I haven't benchmarked the two approaches but they might be pretty close. Here is an example:
import datetime
import numpy as np

def data_in(dates, year=2009):
    """ Return the dates within the given year.
    Works only with dates being a numpy array with a datetime dtype.
    """

    from_date = np.array(('{}-01-01'.format(year), ), dtype='M8')
    to_date = np.array(('{}-12-31'.format(year),), dtype='M8')

    return dates[(dates > from_date) & (dates < to_date)]

if __name__ == '__main__':

    data = np.array(
        [
            (datetime.datetime(2009, 1, 6, 2, 30), 17924.0, 0.0),
            (datetime.datetime(2009, 1, 29, 16, 30), 35249.2, 521.25),
            (datetime.datetime(2011, 1, 29, 16, 30), 35249.2, 521.25),
        ],
        dtype=[('timestamp', 'M8'), ('x1', '<f8'), ('x2', '<f8')]
    )

    for year in [2009, 2010, 2011]:
        print ' Timestamps in {}:\n {}'.format( year, data_in(data['timestamp'], year))


text:
Q: Loading Saved cookies in CookiesManager i have a problem with loading saved cookies to CookiesManager, Error message : Invalid Cookies Date formate.
the saves cookies :
ds_user_id=7459742257; Path=/; Domain=Testing.com; Max-Age=7775999; Expires=Sat, 07-Jul-2018 17:52:03 GMT
 i dont know how to solve this
UPDATE
the error shows up because of the 10000 in rur=FTW; Path=/; Domain=Testing.com; Max-Age=251879107499; Expires=Sat, 01-Jan-10000 06:59:59 GMT
so i changed it to 2019, now it loads successfully,
     var
      S: string;
      Cookies: TIdCookieList;
      Cookie: TIdCookie;
      Uri: TIdURI;
      CookiesList : TStrings;  i : integer;
    begin
      CookiesList := TStringList.create;
      CookiesList.LoadFromFile('path\CookiesList.txt');

      Cookies := IdCookieManager1.CookieCollection.LockCookieList(caReadWrite);
      try
        for I := 0 to CookiesList.count -1 do
        begin
          // read S as needed
          S := CookiesList.Strings[i];
          Uri := TIdURI.Create('testing.com');
          try
            Cookie := IdCookieManager1.CookieCollection.Add;
            try
              Cookie.ParseServerCookie(S, Uri);
              Cookies.Add(Cookie);
            except
              Cookie.Free;
              raise;
            end;
          finally
          Uri.Free;
         end;
        end;
      finally
        IdCookieManager1.CookieCollection.UnlockCookieList(caReadWrite);
        Memo2.TExt := CookiesList.text;
        Cookieslist.free;
      end;
    end;


text:
Q: Update leaflet provider tile options without adding and removing I'm using leaflet in a shiny app to display my data along with several base layers. One of the layers is the very nice daily MODIS satellite imagery provided by NASA GIBS.
The issue is that I cannot figure out how to update the date of the NASA image gracefully.
Below is an example of my first approach.
library(shiny)
library(leaflet)

ui <- fluidPage(
        dateInput("date", label = "Date"),
           leafletOutput("map", width = "600px")
)

server <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Esri.WorldGrayCanvas", group = "Gray") %>%
      fitBounds(-130, 23, -60, 50)
  })

  observe({

    leafletProxy("map", session) %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date)) %>%
      addLayersControl(baseGroups = c("Gray", "MODIS"))
  })

}

# Run the application
shinyApp(ui = ui, server = server)

This "works," but the problem is evident if you change the date a few times while on the gray map (go backwards in time, since future satellite data doesn't exist) and then switch the view to MODIS. You will see the tiles load for each of the dates you selected in turn.
Another approach I tried was to add the MODIS tiles on the initial loading:
server_v2 <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Esri.WorldGrayCanvas", group = "Gray") %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date)) %>%
      addLayersControl(baseGroups = c("Gray", "MODIS")) %>%
      fitBounds(-130, 23, -60, 50)
  })

  observe({

    leafletProxy("map", session) %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date))

  })

}

This also "works," and solves the problem of all past selected dates loading, but creates a different problem. In this case, switching the date will now cause the map to revert to its original default state (gray basemap and original zoom level), which really hinders use.
What I really want (I think) is an updateProviderTiles function, but that doesn't exist in the leaflet R package. Can you see a solution or workaround?

A: Joe Cheng provided the answer when I posted the question to Github:
If you call addProviderTiles with a layerId argument (just make up an identifier), then any previous addProviderTiles with the same layerId are removed before the new one is added.
See http://rstudio.github.io/leaflet/shiny.html#understanding-layer-ids for more details.


text:
Q: Duplicating rows based on multiple condition in r Below is sample of how my data looks:
    pid    time mut  percent dat
1   1004-A  W1  NV   1.02    V600E
2   1004-A  W1  NV   0.51    E17K
3   1004-A  W1  NV   0.19    R175C
4   1004-A  W1  NV   0.10    S752F
5   1004-A  W3  NV   1.25    E17K
6   1004-A  W3  NV   0.79    V600E
7   1004-B  W1  NV   0.68    2V3290D
8   1004-B  W1  NV   0.20    CAH1047R
9   1004-B  W3  NV   0.49    2V3290D
10  1004-B  W3  noNV 0.06    TP53
11  1004-C  W1  NV   11.60   CAE545K
12  1004-C  W1  NV   1.93    TERT
13  1004-D  W1  NV   20.61   CAN345K
14  1004-D  W1  NV   0.19    3M35
15  1004-C  W1  NV   11.60   CAE545K
16  1004-C  W1  NV   1.93    TERT
17  1004-D  W1  NV   20.61   CAN345K
18  1004-D  W1  NV   0.19    3M35
19  3005-A  W23 NV   2.82    139K
20  3005-A  W23 NV   2.79    R181C
21  3005-A  W23 NV   1.93    L536H
22  3005-A  W23 NV   0.26    D538G
23  3005-A  W23 noNV 1.61    3F392fs
24  3005-A  W1  noNV 0.07    3F392fs
25  3005-A  W1  noNV 0.04    1V247fs
26  3005-B  W8  NV   0.47    R282W
27  3005-B  W8  NV   0.28    CAH1047R
28  3005-B  W1  NV   24.89   CAH1047R
29  3005-B  W1  NV   17.63   R282W
30  3001-A  W3  NV   0.55    R130Q
31  3001-B  W1  noNV 0.09    1905fs
34  3005-A  W23 NV   2.82    139K
35  3005-A  W23 NV   2.79    R181C
36  3005-A  W23 NV   1.93    L536H
37  3005-A  W23 NV   0.26    D538G
38  3005-A  W23 noNV 1.61    3F392fs
39  3005-A  W1  noNV 0.07    3F392fs
40  3005-A  W1  noNV 0.04    1V247fs
41  5001-A  W1  NV   0.10    Q947*
42  5001-A  W1  noNV 13.32   E171fs
43  5001-A  W3  NV   0.17    D400N
44  5001-A  W3  noNV 13.24   E171fs
45  5001-B  W1  NV   0.13    I200S
46  5001-B  W3  NV   0.24    TP53
47  5001-B  W3  NV   0.23    I200S
48  5001-B  W41 NV   0.95    R548C
49  5001-B  W41 NV   0.56    Q947*
50  5001-B  W41 NV   0.07    D538G
51  5001-B  W41 NV   0.04    Y537S
52  5001-B  W41 noNV 0.23    TK11
53  5001-B  W41 noNV 0.13    E542_L544del

I want to duplicate the rows where pid is matching (so group_by pid) and dat is not duplicated also change time to the level that is not there and percent to 0.
My output should look like below
    pid    time mut  percent dat
1   1004-A  W1  NV   1.02    V600E
2   1004-A  W1  NV   0.51    E17K
3   1004-A  W1  NV   0.19    R175C
4   1004-A  W1  NV   0.10    S752F
5   1004-A  W3  NV   1.25    E17K
6   1004-A  W3  NV   0.79    V600E
7   1004-A  W3  NV   0.00    R175C
8   1004-A  W3  NV   0.00    S752F
9   1004-B  W1  NV   0.68    2V3290D
10  1004-B  W1  NV   0.20    CAH1047R
11  1004-B  W1  noNV 0.00    TP53
12  1004-B  W3  NV   0.49    2V3290D
13  1004-B  W3  NV   0.00    CAH1047R
14  1004-B  W3  noNV 0.06    TP53

I have tried using a for loop with if statements but it misses the rows that don't need to be duplicated
Below is on of the testcode I have been trying
testID <- unique(datatest$pid)
for (i in testID) {
  test5 <- rbind(datatest,
        datatest %>%
        filter(datatest$dat == datatest$dat[!(duplicated(datatest$dat)|duplicated(datatest$dat,
        fromLast=TRUE))]) %>%
        mutate(datatest$dat = datatest$dat[!(duplicated(datatest$dat)|duplicated(datatest$dat,
        fromLast=TRUE))],
        datatest$time = datatest$time[datatest$dat != unique(datatest$dat)],
        Percentage = 0))
}

A: We can do complete after grouping by 'pid'
library(dplyr)
library(tidyr)
datatest %>%
     filter(time %in% c("W1", "W2", "W3")) %>%
     group_by(pid) %>%
     complete(time, nesting(dat, mut), fill = list(percent = 0))  %>%
     ungroup
# A tibble: 18 x 5
#   pid    time  dat      mut   percent
#   <chr>  <chr> <chr>    <chr>   <dbl>
# 1 1004-A W1    E17K     NV       0.51
# 2 1004-A W1    R175C    NV       0.19
# 3 1004-A W1    S752F    NV       0.1
# 4 1004-A W1    V600E    NV       1.02
# 5 1004-A W3    E17K     NV       1.25
# 6 1004-A W3    R175C    NV       0
# 7 1004-A W3    S752F    NV       0
# 8 1004-A W3    V600E    NV       0.79
# 9 1004-B W1    2V3290D  NV       0.68
#10 1004-B W1    CAH1047R NV       0.2
#11 1004-B W1    TP53     noNV     0
#12 1004-B W3    2V3290D  NV       0.49
#13 1004-B W3    CAH1047R NV       0
#14 1004-B W3    TP53     noNV     0.06
#15 1004-C W1    CAE545K  NV      11.6
#16 1004-C W1    TERT     NV       1.93
#17 1004-D W1    3M35     NV       0.19
#18 1004-D W1    CAN345K  NV      20.6

For the updated dataset
out <- datatest2 %>%
           filter(time %in% c("W1", "W2", "W3")) %>%
           group_by(pid) %>%
           complete(time, nesting(dat, mut), fill = list(percent = 0))  %>%
         ungroup %>%
         as.data.frame

out %>%
   filter(pid %in% head(unique(pid), 2))
#      pid time      dat  mut percent
#1  1004-A   W1     E17K   NV    0.51
#2  1004-A   W1    R175C   NV    0.19
#3  1004-A   W1    S752F   NV    0.10
#4  1004-A   W1    V600E   NV    1.02
#5  1004-A   W3     E17K   NV    1.25
#6  1004-A   W3    R175C   NV    0.00
#7  1004-A   W3    S752F   NV    0.00
#8  1004-A   W3    V600E   NV    0.79
#9  1004-B   W1  2V3290D   NV    0.68
#10 1004-B   W1 CAH1047R   NV    0.20
#11 1004-B   W1     TP53 noNV    0.00
#12 1004-B   W3  2V3290D   NV    0.49
#13 1004-B   W3 CAH1047R   NV    0.00
#14 1004-B   W3     TP53 noNV    0.06

data
datatest <- structure(list(pid = c("1004-A", "1004-A", "1004-A", "1004-A",
"1004-A", "1004-A", "1004-B", "1004-B", "1004-B", "1004-B", "1004-C",
"1004-C", "1004-D", "1004-D"), time = c("W1", "W1", "W1", "W1",
"W3", "W3", "W1", "W1", "W3", "W3", "W1", "W1", "W1", "W1"),
    mut = c("NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV",
    "noNV", "NV", "NV", "NV", "NV"), percent = c(1.02, 0.51,
    0.19, 0.1, 1.25, 0.79, 0.68, 0.2, 0.49, 0.06, 11.6, 1.93,
    20.61, 0.19), dat = c("V600E", "E17K", "R175C", "S752F",
    "E17K", "V600E", "2V3290D", "CAH1047R", "2V3290D", "TP53",
    "CAE545K", "TERT", "CAN345K", "3M35")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14"))

datatest2 <- structure(list(pid = c("1004-A", "1004-A", "1004-A", "1004-A",
"1004-A", "1004-A", "1004-B", "1004-B", "1004-B", "1004-B", "1004-C",
"1004-C", "1004-D", "1004-D", "1004-C", "1004-C", "1004-D", "1004-D",
"3005-A", "3005-A", "3005-A", "3005-A", "3005-A", "3005-A", "3005-A",
"3005-B", "3005-B", "3005-B", "3005-B", "3001-A", "3001-B", "3005-A",
"3005-A", "3005-A", "3005-A", "3005-A", "3005-A", "3005-A", "5001-A",
"5001-A", "5001-A", "5001-A", "5001-B", "5001-B", "5001-B", "5001-B",
"5001-B", "5001-B", "5001-B", "5001-B", "5001-B"), time = c("W1",
"W1", "W1", "W1", "W3", "W3", "W1", "W1", "W3", "W3", "W1", "W1",
"W1", "W1", "W1", "W1", "W1", "W1", "W23", "W23", "W23", "W23",
"W23", "W1", "W1", "W8", "W8", "W1", "W1", "W3", "W1", "W23",
"W23", "W23", "W23", "W23", "W1", "W1", "W1", "W1", "W3", "W3",
"W1", "W3", "W3", "W41", "W41", "W41", "W41", "W41", "W41"),
    mut = c("NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV",
    "noNV", "NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV", "NV",
    "NV", "NV", "NV", "noNV", "noNV", "noNV", "NV", "NV", "NV",
    "NV", "NV", "noNV", "NV", "NV", "NV", "NV", "noNV", "noNV",
    "noNV", "NV", "noNV", "NV", "noNV", "NV", "NV", "NV", "NV",
    "NV", "NV", "NV", "noNV", "noNV"), percent = c(1.02, 0.51,
    0.19, 0.1, 1.25, 0.79, 0.68, 0.2, 0.49, 0.06, 11.6, 1.93,
    20.61, 0.19, 11.6, 1.93, 20.61, 0.19, 2.82, 2.79, 1.93, 0.26,
    1.61, 0.07, 0.04, 0.47, 0.28, 24.89, 17.63, 0.55, 0.09, 2.82,
    2.79, 1.93, 0.26, 1.61, 0.07, 0.04, 0.1, 13.32, 0.17, 13.24,
    0.13, 0.24, 0.23, 0.95, 0.56, 0.07, 0.04, 0.23, 0.13), dat = c("V600E",
    "E17K", "R175C", "S752F", "E17K", "V600E", "2V3290D", "CAH1047R",
    "2V3290D", "TP53", "CAE545K", "TERT", "CAN345K", "3M35",
    "CAE545K", "TERT", "CAN345K", "3M35", "139K", "R181C", "L536H",
    "D538G", "3F392fs", "3F392fs", "1V247fs", "R282W", "CAH1047R",
    "CAH1047R", "R282W", "R130Q", "1905fs", "139K", "R181C",
    "L536H", "D538G", "3F392fs", "3F392fs", "1V247fs", "Q947*",
    "E171fs", "D400N", "E171fs", "I200S", "TP53", "I200S", "R548C",
    "Q947*", "D538G", "Y537S", "TK11", "E542_L544del")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "34", "35", "36", "37",
"38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48",
"49", "50", "51", "52", "53"))


text:
Q: Socket keep returning double string value So i made a simple server-client with socket in python and i have this problem is that the server keep returning double of the string from client can anyone help me? thanks.
Server:
def new_user(client,addr):

    while True:
        data = client.recv(10030)
        client.settimeout(5.0)
        if not data:
            break
        if data == ("-quit-"):
            break
        data = data.upper()
        print("Client ->",data)
        data = raw_input("Admin ->")
        client.send(data)
    client.close()

def main():

    start_user()

def start_user():

    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    print("Socket Telah Dibuat")
    try:
        s.bind(('',4303))
        print("Bind telah dibuat")
    except:
        print("Bind failed"+str(sys.exc_info()))
        sys.exit(1)
    s.listen(1)
    while True:
        client , addr = s.accept()
        print("Client telah connect:"+str(addr))
        Thread(target=new_user,args=(client,addr)).start()
    s.close()

Client:
def main():

    s = socket.socket()
    print("Socket Telah Dibuat")
    try:
        s.connect(('',4303))
        print("telah connect")
    except:
        print("connection failed"+str(sys.exc_info()))
        sys.exit(1)
    print("Untuk Quit Masukkan--quit--:")
    message = raw_input("->")
    while message != ("--quit--"):
        s.send(message)
        data = s.recv(10030)
        if not data:
            break
        data = data.upper()
        print("Admin ->",data)
        message = raw_input("->")
        s.send(message)
    s.close()

server run
('Client ->', 'HELLO')-- from here
Admin ->yes
('Client ->', 'WHAT UP')
Admin ->yo too
('Client ->', 'WHAT UP')
Admin ->what -- to here is still working
('Client ->', 'LETS MEET UPLETS MEET UP') <--this where its start to get error

client run
Socket Telah Dibuat
telah connect
Untuk Quit Masukkan--quit--:
->hello
('Admin ->', 'YES')
->what up
('Admin ->', 'YO TOO')
->lets meet up
('Admin ->', 'WHAT ')

A: May be you can change to:
message = ""
while message != ("--quit--"):
    message = raw_input("->")
    s.send(message)
    data = s.recv(10030)
    if not data:
        break
    data = data.upper()
    print("Admin ->",data)

A: The client is sending the message twice.:
while message != ("--quit--"):
    s.send(message)  // HERE
    data = s.recv(10030)
    if not data:
        break
    data = data.upper()
    print("Admin ->",data)
    message = raw_input("->")
    s.send(message) // AND HERE


text:
Q: Bootstrap v3 make exports empty css files I'm trying to preview bootstrap v3, and I've followed the instructions in the README.md, but the two css files that get exported are empty. The steps I took were:

*

*Download & unzip the lastest 3.0.0-wip

*cd /Workspace/bookstrap-3.0.0-wip/

*npm install

*make

*make bootstrap
The javascript files export just fine. The fonts are junk (but the "source" files are also junk, so I'm not too concerned about that).
P.S. I opened a question here rather than an issue on github because I think I might be doing something wrong.

A: There was a syntax error in bootstraps source which recess silently ignores. commit ced641b has fixed it (and I was able to compile). Lessc reports these errors. I suggest troubleshooting with lessc when encountering this sort of issue:
cd bootstrap_parent_dir/
npm install lessc
lessc less/bootstrap.less

A: Make sure that all the correct dependencies are installed
sudo npm install recess connect uglify-js jshint -g


text:
Q: Regex expression for parsing SQL Server schema and tablename I am trying to parse schema and table name using a regular expression. I am using C# (.NET Core) and System.Text.RegularExpressions.
Here are examples how the input can look like:
Schema.TableName
Schema . TableName
[Schema].[TableName]
[Schema] . [TableName]
Schema. [TableName]
[SchemaPart1.Part2.Part  3].[Table . Name]

And of course other variations that SQL Server accepts when you want to create a table using table and schema name.
Also, I am supporting other databases (MySql & Postgres), so I will reuse the same regex, but replace the [] with the right quotation character (` or " ). But I used the Sql Server examples because the start and ending quotation character are different.
My current regular expression looks like this:
\.?\[.+?\]|[^\[]+?(?=\.)|[^\[]+

This does work most of the times. But e.g. in this case [Schema] . [TableName] I get a match for whitespaces in between which I am not quite sure how to filter out.
Any help would be appreciated.

A: One possible way is to match schema, table and delimiters at once and use capturing groups to get the names separated from surrounding fluff. For example:
`/^(\[[^]]+]|\w+) *\. *(\[[^]]+]|\w+)/gm`

See regex demo.
C# example:
using System;
using System.Text.RegularExpressions;
// ...
String text = "Schema.TableName\nSchema . TableName\n[Schema].[TableName]\n[Schema] . [TableName]\nSchema. [TableName]\n[SchemaPart1.Part2.Part  3].[Table . Name]";
Regex re = new Regex(@"^(\[[^]]+\]|\w+) *\. *(\[[^]]+\]|\w+)", RegexOptions.Multiline);
Match match = re.Match(text);

while (match.Success) {
    Console.WriteLine("( '{0}', '{1}' )", match.Groups[1].Value, match.Groups[2].Value);
    match = match.NextMatch();
}

Output:
'Schema', 'TableName'
'Schema', 'TableName'
'[Schema]', '[TableName]'
'[Schema]', '[TableName]'
'Schema', '[TableName]'
'[SchemaPart1.Part2.Part  3]', '[Table . Name]'

OR
If you want to match schema or table without differentiating between them, you could try a variation of your expression. Be advised that this would also match simple strings like foo. For example:
`/\.? *(?:\[[^]]+\]|\w+)/g`

See regex demo.
C# example (using and text same as above):
MatchCollection matches = Regex.Matches(text, @"\.? *(?:\[[^]]+\]|\w+)");
foreach (Match m in matches) Console.WriteLine("'{0}'", m);

Output:
'Schema'
'.TableName'
'Schema'
'. TableName'
'[Schema]'
'.[TableName]'
'[Schema]'
'. [TableName]'
'Schema'
'. [TableName]'
'[SchemaPart1.Part2.Part  3]'
'.[Table . Name]'

A: or with labelling the parts , and removing the brackets
(?:(?:\[(?<server>[^\]]*)\]|(?<server>[^\.]*))\.)?(?:(?:\[(?<catalog>[^\]]*)\]|(?<catalog>[^\.]*))\.)?(?:(?:\[(?<schema>[^\]]*)\]|(?<schema>[^\.]*))\.)?(?:\[(?<object>[^\]]*)\]|(?<object>[^\.]*))$

!this needs righttoleft parsing
public static Regex regex = new Regex(
"(?:(?:\\[(?<server>[^\\]]*)\\]|(?<server>[^\\.]*))\\.)?(?:(?" +
":\\[(?<catalog>[^\\]]*)\\]|(?<catalog>[^\\.]*))\\.)?(?:(?:\\[" +
"(?<schema>[^\\]]*)\\]|(?<schema>[^\\.]*))\\.)?(?:\\[(?<objec" +
"t>[^\\]]*)\\]|(?<object>[^\\.]*))$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
| RegexOptions.CultureInvariant | RegexOptions.Compiled
| RegexOptions.RightToLeft );


text:
Q: Place XML entries at the top using SimpleXML I'm using SimpleXML to add new images childs for a slideshow tool on my website, the code is something like this:
$xml_toload = $_SERVER['DOCUMENT_ROOT']. '/xml/'.$country.'/compact.xml';
$xml = simplexml_load_file($xml_toload); //This line will load the XML file.

$sxe = new SimpleXMLElement($xml->asXML());
//In this line it create a SimpleXMLElement object with the source of the XML file.
//The following lines will add a new child and others child inside the previous child created.
$image = $sxe->addChild('image');
$image->addAttribute('imageURL',$file);
$image->addAttribute('thumbURL',$file);
$image->addAttribute('linkURL',$linkurl);
$image->addAttribute('linkTarget',$linkurl);
$image->addChild('caption',$caption);

$sxe->asXML($xml_toload);

Which is working perfectly to add the new
<image attr="blabla">
imageinfo
<image>
child, inside of <imagegallery></imagegalley>
However, I need this childs to go just after <imagegallery>, not before  the tag is closed, (one after other), this makes to appear new images, at the last place on the imagegallery slideshow.
So the newest childs that I add, should go before the last it has added to the xml, like
<imagegallery>
<image attr="HEREGOESTHENEWST">

description

</image>
<image attr="THEOLDONE">

description

</image>
</imagegallery>

How can I achieve this?

A: i'd suggest using DOM api instead of simplexml. insertBefore seems to be what you're looking for.

A: SimpleXML doesn't support that kind of manipulation. Currently, it can only append children. To insert children at arbitrary places in the tree, you need DOM and DOMNode::insertBefore() specifically. The problem is that DOM is verbose and it makes it annoying to use, that's why when I have to do that kind of things, I use a mixture of SimpleXML and DOM. The result became a library aptly named SimpleDOM: use DOM methods with SimpleXML grammar.
Also, here's a few tips that I recommend as good practice:

*

*Whenever you create a SimpleXMLElement object, name it after the node it represents. Never name it $xml. "XML" is a markup language, it's text. If I'd see an $xml var I'd think it contains text.

*The same applies to your $xml_toload var. It doesn't contain XML, it contains a filepath. Therefore, it should be named something like $filepath.

*You don't have to use addAttribute() or addChild() for everything. It's often simpler to use the array notation and/or the object notation.

The result script:
include 'SimpleDOM.php';

// create an <image/> element
$image = new SimpleXMLElement('<image/>');
$image['imageURL']   = $file;
$image['thumbURL']   = $file;
$image['linkURL']    = $linkurl;
$image['linkTarget'] = $linkurl;
$image->caption      = $caption;

// load the file
$path_to_file = $_SERVER['DOCUMENT_ROOT']. '/xml/'.$country.'/compact.xml';
$imagegallery = simpledom_load_file($path_to_file);

// insert the new element before the first <image/>
$imagegallery->insertBefore($image, $imagegallery->image[0]);

// save the file
$imagegallery->asXML($path_to_file);


text:
Q: Best way to structure a complicated web-based quiz I have a web project that requires I build a quiz and am having some difficulty working out how to efficiently code it. I'd like to create some sort of json template system so that the quizzes can be defined in a config file, my problem is that almost every question on the quiz is structured differently.
So some questions are simple yes/no answers, some have text input, some are multiple choice. Now this is not too difficult to do by defining the question attributes in json but there is also some logic involved. For example:
If question 2 is answered no and question 3 is answered no, then go back to question 2 and ask it again but only ask it twice, otherwise go to question 4.
This is where I am struggling, as I've said I'd like to create some sort of json template system so that the quizzes can be defined in a config file but I cannot think of a way to do that with logic in the quiz.
Any ideas?