Is there a way to change format from text to Date given in an excel file for MailMerge purposes?

Question: Hope you are keeping safe,
I'm trying to do a mailmerge that will capture the data from an excel file named 'source1' and create word templates using the template.doc file.
the output is fine, but the format needs to be fixed for some columns in the excel file such as dates. for some reasons dates are including hours
example the output in the template generated is 2020-12-12 00:00:00 while the required format must be 12 Dec 2020.
below is the code
from mailmerge import MailMerge

import openpyxl

import datetime

wb=openpyxl.load_workbook('source1.xlsx')

sheet= wb['Sheet1']

max_col = sheet.max_row

sheet.delete_rows(sheet.min_row,1)

for i in range(1, max_col):

    template='template.docx'

    document1=MailMerge(template)

    document1.merge(

        first_name = str(sheet.cell(row=i,column=1).value),

        last_name = str(sheet.cell(row = i, column = 2).value),

        salary = str(sheet.cell(row = i, column = 3).value),

        Date = str (sheet.cell(row = i, column =4 ).value),

        date1='{:%d-%b-%Y}'.format(Date),

      #  country = str ( sheet.cell(row = i, column = 5). value),

       # Title = str(sheet.cell(row = i, column = 6).value),

       # item = str(sheet.cell(row = i, column = 7).value),

      # price = '$'+str(sheet.cell(row = i, column=8).value),

      #  quantity = str(sheet.cell(row=i, column = 9).value),

       # total = str(sheet.cell(row = i, column = 10).value),

        )

    document1.write('Letter for ' +str(sheet.cell(row=i, column=1).value)+'.docx')

I tried to use
    Date = str (sheet.cell(row = i, column =4 ).value),

    date1='{:%d-%b-%Y}'.format(Date),

but it gave me error 'Date is not defined' !
Comment: Can you please provide reproducable code? It will make it easier for people to simulate and answer you question. Pls avoid references to external files
Comment: thanks for that but this doesn't work because the date will not be visible as it does mail merge.
Answer: There are two issues:

You are incorrectly attempting to convert the date format. For this, you will want to use the datetime library, not string formatting.
Date is a named argument to document1.merge() so you can't access it within the function call. You can see from the example usage of the library that document.merge takes kwargs that correspond to the merge fields, but you're trying to create regular variables within this function call.

To fix this, you should do the date conversion before the function call:
import datetime as dt

...

for i in range(1, max_col):

    # Convert the format here
    Date = str(sheet.cell(row = i, column =4 ).value) # Assuming format e.g. 2020-05-01
    date1 = dt.datetime.strptime(Date, '%Y-%m-%d').strftime('%d-%b-%Y')

    template = 'template.docx'
    document1 = MailMerge(template)
    document1.merge(first_name = str(sheet.cell(row=i,column=1).value),
                    last_name = str(sheet.cell(row = i, column = 2).value),
                    salary = str(sheet.cell(row = i, column = 3).value),
                    date1 = date1)

    document1.write('Letter for ' +str(sheet.cell(row=i, column=1).value)+'.docx')


How to add to index unpublished content by apachesolr?

Question: I use apachesolr module for index content.
As I understand, this module does not provide indexing unpublished content.
Is it some trick to avoid that?
I try to use this hook and change status callback, but it does not work.
<code>function hook_apachesolr_entity_info_alter(&$entity_info) {
  // Validate each entity if it can be indexed or not. Multiple callbacks are
  // allowed. If one of them returns false it won't be indexed
  $entity_info['node']['status callback'][] = 'apachesolr_index_node_status_callback';
}
</code>
p.s. it duplicate with this issue, but there no activity and it's very old.
Answer: You may want to follow this thread: Index unpublished nodes. There is no available patch right now but you'll find some hints to build your own custom module if you need to.
Comment: I saw that before. Unfochenatlly, it's not relevant for current version.


Elasticsearch in Docker No route to host

Question: I have a problem with Elasticsearch 5 in Docker.
Stack compose file:
version: "3.4"

services:
    elastic01: &elasticbase
        image: docker.elastic.co/elasticsearch/elasticsearch:5.6.7
        networks:
             - default
        restart: always
        environment:
            - node.name=elastic01
            - cluster.name=elastic
            - network.host=0.0.0.0
            - xpack.security.enabled=false
            - xpack.monitoring.enabled=false
            - xpack.watcher.enabled=false
            - bootstrap.memory_lock=false      ## Docker swarm does not support that
            - discovery.zen.minimum_master_nodes=2
            - discovery.zen.ping.unicast.hosts=elastic02,elastic03
        volumes:
            - /var/docker/elastic:/usr/share/elasticsearch/data
        deploy:
            placement:
                constraints: [node.hostname == node1]

    elastic02:
        <<: *elasticbase
        depends_on:
            - elastic01
        environment:
            - node.name=elastic02
            - cluster.name=elastic
            - network.host=0.0.0.0
            - xpack.security.enabled=false
            - xpack.monitoring.enabled=false
            - xpack.watcher.enabled=false
            - bootstrap.memory_lock=false      ## Docker swarm does not support that
            - discovery.zen.minimum_master_nodes=2
            - discovery.zen.ping.unicast.hosts=elastic01,elastic03
        volumes:
            - /var/docker/elastic:/usr/share/elasticsearch/data
        deploy:
            placement:
                constraints: [node.hostname == node2]

    elastic03:
        <<: *elasticbase
        depends_on:
            - elastic01
        volumes:
            - /var/docker/elastic:/usr/share/elasticsearch/data
        environment:
            - node.name=elastic03
            - cluster.name=elastic
            - network.host=0.0.0.0
            - xpack.security.enabled=false
            - bootstrap.memory_lock=false      ## Docker swarm does not support that
            - discovery.zen.minimum_master_nodes=2
            - discovery.zen.ping.unicast.hosts=elastic01,elastic02
        deploy:
            placement:
                constraints: [node.hostname == node3]

    networks:
        default:
            driver: overlay
            attachable: true

When I run stack file, it works like a charm. _cluster/health shows that nodes are up and running a the status is "Green" but after while, periodically, system goes down with exception Elastic exception
Feb 10 09:39:39 : [2018-02-10T08:39:39,159][WARN ][o.e.d.z.UnicastZenPing   ] [elastic01] failed to send ping to [{elastic03}{2WS6GPu8Qka9YLE_PWfVKg}{AD_Nw1m9T-CZHUFhgXQjtQ}{10.0.9.5}{10.0.9.5:9300}{ml.max_open_jobs=10, ml.enabled=true}]
Feb 10 09:39:39 : org.elasticsearch.transport.ReceiveTimeoutTransportException: [elastic03][10.0.9.5:9300][internal:discovery/zen/unicast] request_id [5167] timed out after [3750ms]
Feb 10 09:39:39 :   at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:961) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:39 :   at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:39 :   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_161]
Feb 10 09:39:39 :   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_161]
Feb 10 09:39:39 :   at java.lang.Thread.run(Thread.java:748) [?:1.8.0_161]
Feb 10 09:39:40 : [2018-02-10T08:39:40,159][WARN ][o.e.d.z.UnicastZenPing   ] [elastic01] failed to send ping to [{elastic03}{2WS6GPu8Qka9YLE_PWfVKg}{AD_Nw1m9T-CZHUFhgXQjtQ}{10.0.9.5}{10.0.9.5:9300}{ml.max_open_jobs=10, ml.enabled=true}]
Feb 10 09:39:40 : org.elasticsearch.transport.ReceiveTimeoutTransportException: [elastic03][10.0.9.5:9300][internal:discovery/zen/unicast] request_id [5172] timed out after [3750ms]
Feb 10 09:39:40 :   at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:961) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:40 :   at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:40 :   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_161]
Feb 10 09:39:40 :   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_161]
Feb 10 09:39:40 :   at java.lang.Thread.run(Thread.java:748) [?:1.8.0_161]
Feb 10 09:39:41 : [2018-02-10T08:39:41,159][WARN ][o.e.d.z.UnicastZenPing   ] [elastic01] failed to send ping to [{elastic03}{2WS6GPu8Qka9YLE_PWfVKg}{AD_Nw1m9T-CZHUFhgXQjtQ}{10.0.9.5}{10.0.9.5:9300}{ml.max_open_jobs=10, ml.enabled=true}]
Feb 10 09:39:41 : org.elasticsearch.transport.ReceiveTimeoutTransportException: [elastic03][10.0.9.5:9300][internal:discovery/zen/unicast] request_id [5175] timed out after [3751ms]
Feb 10 09:39:41 :   at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:961) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:41 :   at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.6.7.jar:5.6.7]
Feb 10 09:39:41 :   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_161]
Feb 10 09:39:41 :   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_161]
Feb 10 09:39:41 :   at java.lang.Thread.run(Thread.java:748) [?:1.8.0_161]

And sometimes:
Feb 10 09:44:10 [2018-02-10T08:44:10,810][WARN ][o.e.t.n.Netty4Transport  ] [elastic01] exception caught on transport layer [[id: 0x3675891a, L:/10.0.9.210:53316 - R:10.0.9.5/10.0.9.5:9300]], closing connection
Feb 10 09:44:10 java.io.IOException: No route to host
Feb 10 09:44:10     at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[?:?]
Feb 10 09:44:10     at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[?:?]
Feb 10 09:44:10     at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[?:?]
Feb 10 09:44:10     at sun.nio.ch.IOUtil.read(IOUtil.java:197) ~[?:?]
Feb 10 09:44:10     at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) ~[?:?]
Feb 10 09:44:10     at io.netty.buffer.PooledHeapByteBuf.setBytes(PooledHeapByteBuf.java:261) ~[netty-buffer-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100) ~[netty-buffer-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372) ~[netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123) [netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644) [netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.nio.NioEventLoop.processSelectedKeysPlain(NioEventLoop.java:544) [netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:498) [netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) [netty-transport-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.13.Final.jar:4.1.13.Final]
Feb 10 09:44:10     at java.lang.Thread.run(Thread.java:748) [?:1.8.0_161]

Strange thing is that all the time it happens I am able to ping the container and resolve the name from the container where it happens. No packet loss, no timeouts. The only bad thing is the transport layer in the Elastic. All other services are running in the same cluster without issues (MongoDB, Redis, Internal microservices)
Does anybody have a clue?
Answer: I found the issue.
Elasticsearch must be binded to a one single interface, not to 0.0.0.0. Once I binded it to eth0, it started to work. Also it looks, there cannot be named volume - it throws another error during the time. It must be mounted to a local drive directly.
This works:
services:
    elastic01:
        environment:
            network.host=_eth0_


How to code for an iOS style rotating animation

Question: !(https://th.bing.com/th/id/OIP.ChQ6m89PO_1Dm_FexkwrUAAAAA?pid=ImgDet&dpr=2)
I would like to code this in Jetpack compose and have seen various other implementations already on stack overflow.
Please answer it in Jetpack Compose only.
Answer: By looking into the code it seems you remove these slots intentionally:
    // Update the current time to be the end time of the chosen slot
    currentTime = chosenSlot.split("-")[1]
    currentMinutes = timeToMinutes(currentTime)

You can't choose slots at earlier time than already chosen slots. You can only go forward in time. Remove these lines of code to allow it.
But even then, I believe it won't work correctly. You add e.g. 21:00-22:00 to booked, but then you check e.g. for 21:00-21:30 and 21:30-22:00, so you detect them as not booked. Instead, I suggest storing the info always in 30-minute slots and then when checking e.g. 21:00-22:30 you have to make sure all 3 required 30-minute slots are free.


Sampling variance when the largest observation is removed

Question: I have the sampling variance of the sample mean: $V_1=\frac{1}{N-1}\sum_i (x_i-\bar{x})^2$. Now if the largest observation is removed, I have a new variance, $$V_2=\frac{1}{N-2}\sum_{i=0}^{n-1} (x_i-\bar{\bar{x}})^2$$ where $\bar{\bar{x}}$ is the new (reduced) mean of the $N-2$ observations.
Depending on the data, I could see $V_1$ could be greater or lesser than $V_2$.
An intuitive example of $V_1>V_2$ is when you consider one anomalous large value and mostly small observations.
Is there an intuitively clear example where I can visually understand the case where $V_1<V_2$?
Comment: For a simple example let $x=(2,20,20)$.
Comment: @whuber: I was teaching some MBA kids there. I was able to give a numerical example, but they wanted something visually understandable, like what they get for $V_1>V_2$...
Comment: So, more generally, it sounds like you are seeking a way to *visualize* variance (and changes thereof).  Please indicate that in your question so you get appropriate answers.
Comment: When you say "largest sample" do you mean 'largest observation'? In statistics a [sample](http://en.wikipedia.org/wiki/Sample_%28statistics%29) is a collection of observations. Your largest observation is a member of your sample.
Answer: Consider ${\bf x}=(1,8,9,10)$: $\bar x = 7$, $s^2 = 16 \frac23$. When you remove the highest value $x_4=10$, it only increases the influence of the low outlier $x_1=1$: $\bar x =6$, $s^2 = 19$. Feel free to play with numbers more to get all the results in integers :).


Get the View of UIBarButtonItem in Swift

Question: Hopefully, this is an easy question.  I am trying to obtain the UIView of a UIBarButtonItem.  Looking at the following StackOverflow question I came up with the following code:
let notificationButton = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)

let notificationView = notificationButton.value(forKey: "view") as? UIView

However, notificationView is nil.  So, thoughts on what I failed to interpret from the linked StackOverflow question?
Comment: Why do you need it?
Comment: NRitH: I want to modify the image to add a badge
Comment: Did you added notificationButton  into navigationItem?
Comment: DS Dharma: You don't add the navigationButton into a navigationItem, you assign it like this: self.navigationItem.rightBarButtonItem = notificationButton
Answer: Starting from iOS 11 this code will not work cause line of code below will not cast UIView. Also it's counting as private API and seems to be will not pass AppStore review.
guard let view = self.value(forKey: "view") as? UIView else { return }

Thread on: forums.developer.apple
Answer: So, DS Dharma gave me a idea which ended up working.  The "view" value is only available after it is assigned to the toolbar navigation item like this:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)

self.navigationItem.rightBarButtonItem?.addBadge(number: 0, withOffset: CGPoint(x: 7.0, y: 0.0) , andColor: UIColor.black, andFilled: true)

where the addBadge() function needs the UIView.  BTW, if anyone is wondering, the addBadge function was taken from this post:  http://www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem
Highly recommended if you need this piece of functionality.
Comment: Unfortunately this doesn't work when you have multiple bar items. e.g. self.navigationItem.rightBarButtomItems.append(barBtn)


WCF Data Service Change Tracking: How to cancel save changes and revert to original values for an object

Question: I have a WCF Data Service that is wrapping an Entity Framework 4 data model. I am connecting a WPF client to the service using the WCF Data Services Client library.
Is it possible in WCF Data Services to undo / cancel changes to tracked objects ?
scenario : In the UI I allow a user to edit an object. I have save and cancel buttons. If the user chooses to save I call SaveChanges() on my WCF context and changes are sent to the database via the WCF service. If the user clicks cancel I want to undo the changes and revert to the original property values of the current object.
I know that the WCF data services client library has change tracking built in - but I cannot find any way at accessing this information.
In Entity Framework the context supports the Refresh method and you can specify RefreshMode.StoreWins and pass in the object - this will effectively cancel / undo any changes.
documented here  : http://msdn.microsoft.com/en-us/library/bb896255.aspx
Any suggestions on how I can achieve the same thing in WCF DataServices in my client application ?
cheers
Chris
Answer: The only "solution" I know of is:
<code>var oldMergeOption = _service.MergeOption;
_service.MergeOption = MergeOption.OverwriteChanges;
try {
    _service.YourQueryable.Where(x => x.Id==oldObject.Id).Single();
} finally {
    _service.MergeOption = oldMergeOption;
}
</code>
This should replace the values of "oldObject" with the values stored in the DB. However, I'm not sure if the object returned by Single() will always be the same as "oldObject".
Comment: FYI: I currently work around this problem using a BindingGroup with BeginEdit, CancelEdit, and (ValidateWithoutUpdate and) CommitEdit. Just do a BeginEdit in the DataContextChanged event and a CancelEdit in the Cancel buttons Click-Event. In the OK buttons Click-Event, try a validation first (ValidateWithoutUpdate) and the execute a CommitEdit when the validation succeeded.
Answer: I typically refrain from operating on entities within the DataServiceContext until I'm ready to commit those changes to the database.  I don't treat my entities as part of my domain model so I create a specific domain model that adapts my model objects to entity objects using adapters and a repository class.  This way, all operations within by domain model are self-contained until I'm ready to commit them to the database.  A fantastic article from Ben Day on what I'm referring to can be found here: http://visualstudiomagazine.com/articles/2011/04/01/pfcov_silverlight-mvvm-tips.aspx


Is Webform using datepicker.js?

Question: I am trying to create an alert when a date is selected that falls within 30 days of today using the following script:
(function ($) {
  $('#edit-select-date').datepicker({

    onSelect: function () {
      var date = $(this).datepicker('getDate');
      var today = new Date();

      if ((new Date(today.getFullYear(), today.getMonth(), today.getDate() + 30)) > date) {
        // Do something here.
        alert(123);
      }
    }
  });
}(jQuery));

Unfortunately this is not working and am getting a $(...).datepicker is not a function in dev console. If datepicker.js is not being used is there a way I can have an alert trigger when the date select is +30 days from today?
Comment: Try to take a look here, https://stackoverflow.com/questions/1212696/jquery-ui-datepicker-datepicker-is-not-a-function
Answer: Webform provides a fieldable form entity type. And when you add a date field to it (you didn't specify what date field exactly, core, contrib, custom), this date field may make use of a datepicker library.
Speaking of core it most likely is core's core/jquery.ui.datepicker library. Which is used for #type => 'date' form elements for example.
When you in your custom script want to make use of this datepicker library you need to add it as a dependency. Same as core does:

drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/core.libraries.yml#L142-150.

And maybe you also make your JavaScript look more like in the examples in the docs.

Is Webform using datepicker.js?


Sources tab in chrome dev tools is not displaying the right files

Question: Im trying to debug and set breakpoints in my code, but whenever I navigate to the Sources tab, it displays files that are not the actual code, always formatted like:
<code>import { render, staticRenderFns } from "./Index.vue?vue&type=template&id=e99f4d94&scoped=true&"
import script from "./Index.vue?vue&type=script&lang=js&"
export * from "./Index.vue?vue&type=script&lang=js&"

/* normalize component */
import normalizer from "!../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js"
var component = normalizer(
  script,
  render,
  staticRenderFns,
  false,
  null,
  "e99f4d94",
  null

)

/* vuetify-loader */
import installComponents from "!../../../node_modules/vuetify-loader/lib/runtime/installComponents.js"
import { VCol } from 'vuetify/lib/components/VGrid';
import { VRow } from 'vuetify/lib/components/VGrid';
installComponents(component, {VCol,VRow})

/* hot reload */
if (module.hot) {
  var api = require("D:\\vue-hot-reload-api\\dist\\index.js")
  api.install(require('vue'))
  if (api.compatible) {
    module.hot.accept()
    if (!api.isRecorded('e99f4d94')) {
      api.createRecord('e99f4d94', component.options)
    } else {
      api.reload('e99f4d94', component.options)
    }
    module.hot.accept("./Index.vue?vue&type=template&id=e99f4d94&scoped=true&", function () {
      api.rerender('e99f4d94', {
        render: render,
        staticRenderFns: staticRenderFns
      })
    })
  }
}
component.options.__file = "src/views/adas/Index.vue"
export default component.exports
</code>
No matter what I do, I cannot find the actual Vue files that I am trying to debug
I have tried setting a debugger in my Vue code, have tried clicking the link to the screen in the Console tab that redirects to the above code still, and tried searching for the file in dev tools and still directing me to the above code.
Answer: You need to activate sourcemap.
If you are using vue-cli, you can do it like this.
<code>// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    devtool: 'source-map',
  }
})
</code>
Comment: Trying this, I cant compile now: TypeError: defineConfig is not a function. Also I have had sourcemap activated this whole time, minus the transpileDependencies line.  I should add that the dev tools work fine on everybody elses machines except mine so its weird that it would be something i havent activated.


Chrome OS bash script if statement error

Question: Im running Chrome OS in dev mode, and I am creating a bash file. The code looks like so:
echo -n "Username: "
read username: "
if [ $username == "mycroft" ]; then
    echo "Correct!"
fi

My problem is that when I run the code in crosh with /bin/sh ./login.sh, after I type
in mycroft, I get this error:
[: 4: mycroft: unexpected operator
What did I do wrong?
Comment: Is the command `read username: "` with the colon (:) and the double quote (") in your actual code, or just a copy paste error?
Comment: Also your quotes are the wrong way. It should be `if [ "$username" == mycroft ];`
Comment: shell `[`/`test` equality is `=` not `==`.
Comment: you forgot a hashbang
Comment: @EtanReisner `==` is OK in `bash`, though not recommended.
Comment: The code you posted, with or without the extraneous `: "` in the second line, would produce different errors than you one you show.
Comment: @chepner Indeed. The first two comments by user000001 are almost certainly the root of the problem. I just figured to add an additional detail.
Comment: Yes. The : " was a copy paste error.
Comment: @user3861375 Then you should edit your question to include your *actual* code, if the issue is still unresolved (prepend each line with four spaces, to format the code).
Answer: Your problem is on the second line
echo -n "Username: "
read username
if [ $username = "mycroft" ]; then
  echo "Correct!"
fi

Comment: Well, [according to the OP](http://stackoverflow.com/questions/24869727/chrome-os-bash-script-if-statement-error#comment38630436_24869727) the code in the question is not the actual code he is using, so it is rather difficult to tell when is the real issue in question.


Recurrence relation for the sequence of numbers $3, 15, 57, 195, ...$

Question: Is there any systematic way to calculate a recurrence relation for a sequence of numbers?
For instance, I am trying to solve the recurrence relation for $3, 15, 57, 195, ...$ but cannot seem to define an acceptable recurrence relation.
The context for this question is I have to find the recurrance relation for the number of n digit ternary sequences (i.e. strings of  $0, 1$ and $2$) that contain at least two consecutive digits that are the same.
I cannot find a way to define this so I have "manually" calculated the ways this would work out to for $n = 2, 3, 4$ and $5$ which are the four sequences provided above.
Comment: I'm voting to close this question because it is at par with *guess the next number* -questions.
Comment: If you just want the answer, https://oeis.org/A210448 says it's $3(3^n-2^n)$.  (Possible offset by $1$ from the definition given at OEIS.)
Comment: @BrianTung $\displaystyle\left.11n^{3} -51n^{2} + 88n - 45\,\right\vert_{\ n\ =\ 1,2,3,\ldots}\quad$ is fine too$\ldots$
Answer: One can easily calculate an explicit formula for the number of such sequences. The number of $n$-digit sequences with no pair of consecutive digits the same is $3\cdot 2^{n-1}$ (the first digit can be anything; subsequent digits cannot be the same as the previous one).
So the number of $n$-digit sequences with at least one pair of consecutive digits the same is $3^n-3\cdot 2^{n-1} = 3(3^{n-1}-2^{n-1})$.
If you want, you can work backwards from this to derive a recursion. Let $a_n$ be the number of such sequences, so that $a_n = 3(3^{n-1}-2^{n-1})$. Then
\begin{align*}
a_{n+1}-2a_n &= 3^{n+1}-3\cdot 2^n - 6(3^{n-1}-2^{n-1})\\
&= 3^{n+1}-3\cdot 2^n - 2\cdot 3^n+3\cdot 2^n \\
&= 3^{n+1}-2\cdot 3^n \\
&= 3^n.
\end{align*}
Comment: I'd say this answers the question.  Not everything is best solved with a recurrence, after all!
Answer: Define $a_{i}$ as the number of $i$  - digit ternary numbers with at least one consecutive repeating number.
For any $n$ - digits ternary numbers ($3^{n}$ of them), we can attach a number equal to the last digit at the end and get $n+1$ - digits ternary number with at least one consecutive repeating number.
In addition, for any $n$ - digits ternary numbers with at least one consecutive repeating number ($a_{n}$ of them), we can attach a number different from the last digit ($2$ possibilities) at the end and get $n+1$ - digits ternary number with at least one consecutive repeating number.
$a_{n+1}=3^{n}+2\cdot a_{n}$
Answer: It's actually possible to guess a recurrence just from the values of $a_2,a_3,a_4$, and $a_5$ calculated by hand: I did it after reading just the title of the question (and adjusting slightly when I finally read the question and learned the indexing). Of course one must then either prove that the recurrence is correct or solve it and prove that the closed form is correct.
The numbers $3,15,57$, and $195$ seem to be growing very roughly exponentially, and each is a little more than $3$ times the previous number. In fact, a little quick arithmetic reveals that $15=3\cdot3+6$, $57=3\cdot15+12$, and $195=3\cdot57+24$, and the numbers $6,12$, and $24$ are encouragingly systematic: we might venture the guess that $a_n=3a_{n-1}+3\cdot2^{n-2}$. This recurrence is easily solved by unwinding:
$$\begin{align*}
a_n&=3a_{n-1}+3\cdot2^{n-2}\\
&=3(3a_{n-2}+3\cdot2^{n-3})+3\cdot2^{n-2}\\
&=3^2a_{n-2}+3^2\cdot2^{n-3}+3\cdot2^{n-2}\\
&=3^2(3a_{n-3}+3\cdot2^{n-4})+3^2\cdot2^{n-3}+3\cdot2^{n-2}\\
&=3^3a_{n-3}+3^3\cdot2^{n-4}+3^2\cdot2^{n-3}+3\cdot2^{n-2}\\
&\;\;\vdots\\
&=3^ka_{n-k}+\sum_{i=1}^k3^i\cdot2^{n-1-i}\\
&\;\;\vdots\\
&=\sum_{k=1}^{n-1}3^i\cdot2^{n-1-i}\qquad(\text{since }a_1=0)\\
&=2^{n-1}\sum_{i=1}^{n-1}\left(\frac32\right)^i\\
&=2^{n-1}\frac{\left(\frac32\right)^n-\frac32}{\frac32-1}\\
&=3^n-3\cdot2^{n-1}
\end{align*}$$
Since $3^n$ is the number of ternary sequences of length $n$, it makes sense at this point to consider whether $3\cdot2^{n-1}$ can easily be interpreted as the number of unwanted sequences of length $n$, i.e., those that do not have at least two consecutive identical digits. And that turns out to be the case: there are $3$ ways to pick the first digit, and after that there are always $2$ choices for the next digit if each digit is to be different from its predecessor.
I really do think that it would be easier just to invest a bit of thought first and come up with this result directly, as in rogerl's answer: subtracting the number of 'bad' sequences from the number of possible sequences is one of the obvious approaches that should be tried early on. But the best of us have the occasional blind spot, and this is a possible approach if one is accustomed to playing with numbers and nothing better comes to mind.


How to render a @FormElement in Views area plugin

Question: I am doing a custom plugin area for displaying some data in a views footer (Drupal 8).
I do something about just like this : Create a custom area plugin
The only point is, instead of #markup in the return array of render() method, I would like to return some more complex stuff.
If I try to return a textfield if works:
return  [
  '#type' => 'textfield',
];

If I try another form API element (defined via a @FormElement): it does not render.
return  [
  '#type' => 'datetime',
];

Two questions:

Should it render ?
If not, I can render a block there using this (ViewsBlockArea) how to do the equivalent but with a FormElement instead ? (actually rendering a form API render array.)

EDIT: Here a the finality of what I want to render:
$element['form'] = [
  '#type' => 'commerce_coupon_redemption_form',
  '#order_id' => $order->id(),
  '#cardinality' => 1,
  '#element_ajax' => [
    [get_class($this), 'ajaxRefreshSummary'],
  ],
];

But you may see that more trivial render array like the datetime one given above does not work either.
Also notice that any element defined by a @FormElement annotation from within the namespace Drupal\Core\Render\Element is okay.
But @FormElement "from elsewhere" like datetime does not render.
Comment: If you want to render it as a form, don't you want to wrap it into a call to ```\Drupal::formBuilder()``` instead?
Comment: Can you post your entire code. The commerce_coupon_redemption_form requires the order_id to be set. Do you provide that?
Comment: I just edited the question to clarify with your request.
Comment: Ah, I see you edited the question just as I was writing my comment. It is often better to provide full code than some stripped pseudo code as important things tend to be left out, hence my question. It is much better like this :)
Answer: You can create block Form first. And from View UI, add a view object to your header or footer. And from View object configuration choose the form block you created.


Drawing a systematic sample

Question: Please clarify the following question:
If two independent systematic samples of size
four each from a population of 36 units have y-values of a characteristic y as:
24,26,22,28 and 27, 25, 23, 29
respectively, find the unbiased estimate of mean and variance.
My confusion: from several theories on systematic sampling, I read about this random interval k=N/n. In this case, k=36/4= 9. In the above samples nowhere I find a gap of 9 instead a gap of 2 is noticed. how could this happen? I can in no way relate the theory I read to the above given samples.
Kindly clarify.
Answer: There is no problem here:
You are mistaken in thinking that any patterns in the $y$ variable must somehow match the order (or index) of observations in the list. The two sets of number need have nothing to do with one another.  Let $i = 1 \ldots 36$ indicate the order in which each observation is listed in the frame. A systematic sample of size 4 begins by taking a random start between 1 and $k = 36/4 = 9$, then every 9-th observation after that.  However, the values of the $y$'s can be anything in general.
In some situations, the  $y$'s can be related to list order, as when observations are listed in date order and the $y$'s are dates.   However I don't see any kind of relation in your data. The gaps between adjacent observations in the first sample are +2, -4, +6.  In the second sample they are -2, -2, +6. Remember that "adjacent" in one of the systematic samples means "nine observations apart" in the original list.

Drawing a systematic sample


python match time format from re

Question: In the following string, how can I write a regular expression with respect to time. The output should be the timestamps only.
 l1=May 30, 2012 at 8:13 AM  Comment · 1Like Unlike · Bookmark Unbookmark
 l2=yesterday at 12:13 AM  2Comment  Like Unlike · Bookmark Unbookmark
 l3=Two days ago at 01:18 AM  Comment · 5Like Unlike · Bookmark Unbookmark
 l4=Two days ago at 15:54 PM  Comment · Like Unlike · Bookmark Unbookmark

EDIT
 l5=Two days ago at 15:54:51 PM · Comment · Like Unlike · Bookmark Unbookmark

Output:
 array1 = [May 30, 2012 at 8:13 AM ,yesterday at 12:13 AM ,Two days ago at 01:18 AM,Two days ago at 15:54 PM]

 array2=[Comment · 1Like Unlike · Bookmark Unbookmark,2Comment · Like Unlike · Bookmark Unbookmark,Comment · 5Like Unlike · Bookmark Unbookmark,Comment · Like Unlike · Bookmark Unbookmark]

EDIT:
p_date = re.compile(r'(\d{1,2}[:]\d{1,2}) but i wasnt sure how to do it if the timestamp was also like 23:12:29

Comment: This is not valid Python. Please show some effort.
Comment: p_date = re.compile(r'(\d{1,2}[:]\d{1,2}) but i wasnt sure how to do it if the timestamp was also like 23:12:29
Answer: >>> import re
>>> pattern = r'l\d+=(.*?)·(.*)'
>>> l1 = []
>>> l2 = []
>>> for line in s.split('\n'):
    m = re.match(pattern, line)
    if m:
        l1.append(m.groups()[0])
        l2.append(m.groups()[1])

>>> l1
['May 30, 2012 at 8:13 AM ', 'yesterday at 12:13 AM ', 'Two days ago at 01:18 AM ', 'Two days ago at 15:54 PM ']
>>> l2
[' Comment \xb7 1Like Unlike \xb7 Bookmark Unbookmark', ' 2Comment \xb7 Like Unlike \xb7 Bookmark Unbookmark', ' Comment \xb7 5Like Unlike \xb7 Bookmark Unbookmark', ' Comment \xb7 Like Unlike \xb7 Bookmark Unbookmark']
>>>

EDIT : added the matching of l1= to remove it from matching.
Comment: @Rajeev: Have you actually tried his solution? Why are you not happy with it?
Comment: What if also i have timestamps like 23:31:39 ??
Comment: No problem as long as it's between `=` and `·`.
Comment: @Rajeev: Yes it can. At least in your examples, it can. So please correct your question. It's still invalid Python, and it's useless trying to answer a question when it's not even clear what the actual question *is*.
Comment: Yes  i have removed the '.' that was separating the text.
Comment: @Rajeev: This is leading nowhere. *All* the Python code in your question is still syntactically invalid. You *still* haven't *defined clearly*  what *exactly*  you're expecting to split your strings on. Given this, it's impossible to answer your question with reasonable accuracy. Voting to close.
Answer: You can split your output by "." , if your input format is consistent.
Applying regular expressions to identify differently formed timestamp strings may be hectic task.

python match time format from re


Is there a danger in fake OpenID providers?

Question: I've been wondering. Since anybody can start an OpenID provider, and since there is no central authority that approves OpenID providers, why won't fake OpenID providers become a problem?
For example, a spammer could start an OpenID provider with a backdoor to let himself authenticate as any other user that was tricked into registering on his site. Is this possible? Is the provider's reputation the only thing that prevents this? Are we going to see OpenID provider blacklists and OpenID provider review sites in the future?
Probably I don't understand something about OpenID completely. Please enlighten me :)
Answer: It'd be pretty much the same as having "fake" email provider, that would hijack users confirmation emails etc. Only the reputation is preventing that. Poeple do register on gmail.com or hotmail.com, but do not register on joesixpack.org.
Comment: But they do register disposable e-mails on mailinator.com, and I'm looking myself for a disposable openid provider; I need register on a crappy site that requires openId, and I really don't care to register under my "real" G-account or FB.
Answer: OpenID is NOT an intrinsically safe protocol - it doesn't have the power to force a rogue provider to provide security, nor does it 'vet' each provider to ensure they are secure.
OpenID is a mechanism whereby you can store your credentials with a trusted provider, and they will then verify you to others.
If you choose an untrustworthy provider, they can see and use everything you might use your credentials for.
OpenID is not a replacement for trust.
-Adam
Comment: OpenID isn't meant to verify that the user is anything to the client website.  All it does is say, "The person that is signing in now is the same person that setup the -username- OpenID account here" which can be useful for centralized username/password tracking, but doesn't guarantee you anything about that user - merely that they had the appropriate credentials such that the OpenID provider is suitably convinced it's them.
Comment: But isn't an implicit trust required for the system to work? If I accept Google and Yahoo OpenID credentials, and one of them becomes untrustworthy, then aren't I now in a situation where I cannot trust that my users are who they say they are?
Comment: I am using the openid as a unique identifying string. Is there any possibility of a rogue provider giving me the same openid as some legit user on another provider, say Yahoo?
Answer: Jeff has a very nice (and lengthy) weblog post on this topic. If it doesn't answer your questions, it will certainly enlighten you. The comments also lead to very illustrative articles. Highly recommended.
Answer: There are some similar questions on stackoverflow.com that you might find interesting.
Answer: The only way I can see a "rogue" OpenID server being a problem isn't a web application security problem so much. What you are doing though is providing one website with your Identity. They tell people you are who you are, but they also have access to it. If a malicious person sets up an OpenID server and people start to use it, the owner of the malicious service could impersonate anybody using their server.
The question comes down to do you trust the owners of your OpenID server?
Answer: My problem with OpenID in general is that it's new and there aren't any standards (that I've heard about anywhere anyway) that define what makes a "good" OpenID provider. For credit card data, there's PCI-DSS standards for managing credit card info -- but no equivalent for identity.
Granted, it's a new technology that is generally used for applications with minimal "trust" requirements. But on sites like ServerFault, I think that you need a level of trust that's greater than that of a blog, but less than that of bank or online broker.
Comment: One potential framework for evaluating the suitability of an OpenID provider for your security needs is the Liberty Identity Assurance Framework, but there's currently very little awareness of this in the OpenID marketplace.

http://www.projectliberty.org/strategic_initiatives/identity_assurance
Answer: Adding to previous answers. Don't know yet about OpenID blacklists, but there is a volunteer initiative on OpenID whitelists. That whitelist is a distributed technology (just like e-mail, DNS, HTTPS certs), there is no single point of failure, there is no single point of trust. You may trust some guys' whitelist and he can fake it.
There is an opinion that those whitelists must be extended to provide more information (not to anybody, of course), like user activity, number of posts, number of warnings from moderators, etc. Since OpenID is a global identity, that would help to almost-instantly spread information like this user is a spammer. Which would force spammers to always use a new id. Imagine that 1000 reputation on ServerFault makes you as well trusted user on thousands of other websites.
Answer: To those who think OpenId consumers should let any OpenId provider be an authenticator, that's just crazy talk.  Let's say you have a list of authorized users based on an email passed from openid providers.  Some rogue person sets up their own OpenId provider service and knows the email of one of your previously authorized users.  That rogue person could then 'authenticate' himself as your accepted user.
If you are trying to secure with openId, you must have a white list of providers you trust, otherwise you're pretty much wide open to anybody who knows how to setup a provider service.
Comment: Your answer is incorrect. That's not how OpenID works. The OpenID provider does not pass the user's email address back to the site as the username.


Why doesn't a binomial GLM successfully fix violated assumptions of simulated binomial data?

Question: I generated binomial data showing a logistic correlation to a predictor. I analysed such dataset with a generalised linear model which assumes a binomial distribution of residuals and a "logit" link function, but the residuals of such a model still fail to respect the model assumptions: the quantile-quantile plot shows that the residuals' distribution departs from the theoretical one, and residuals seem heteroscedastic. This happens regardless of sample size. Why is that?
Here is my example, simulated and analysed in R. To give the data some realism: let's imagine that I am interested in the probability of bird predation under different degrees of vegetation cover (expressed as percentage). For each level of vegetation cover I tracked 15 birds and recorded if they had been killed by a predator by the end of the study (data coded as 1 or 0).
<code># Generate data:
set.seed(666)
predictor <- c(0, 20, 40, 50, 70, 90)
y = 4 - 0.2 * predictor # linear combination of the variables
pr = 1/(1+exp(-y)) # pass y through an inv-logit function to get probability

# build dataset:

df <- data.frame(vegetation.cover = rep(predictor, 15), prob = rep(pr, 15))
df$predation.01 <- rbinom(length(df[,1]), 1, pr)

# df$predation.01 refers to the probability of a bird to be killed by a predator.
# To model predation.01 vs vegetation.cover:

glm.01 <- glm(predation.01 ~ vegetation.cover,
    data= df,
    family=binomial(link="logit")
    )
</code>
These are the model diagnostic plots:

For comparison, these are the diagnostic plots for the same model fitted on a dataset with a replication of 1500 for each value of the predictor:

Here are the data together with the model predictions for n=15:

I added a pinch of artificial noise to the observations to avoid a perfect overlap of all the 0s and 1s in an attempt to aid the interpretation of the graph.
Comment: I suggest adding quantile residuals as implemented in the `DHARMa` package.
Comment: See: https://stats.stackexchange.com/questions/121490/interpretation-of-plot-glm-model/139624#139624 and https://stats.stackexchange.com/questions/307221/why-residual-plots-are-used-for-diagnostic-of-glm
Comment: You are using extraordinarily small probabilities at `cover` values greater than 40.  A quick check suggests that at `cover = 40` the probability is less than 0.02, and for the higher values it becomes increasingly infinitesimal (less than $10^{-6}$ at `cover = 90`).
Answer: It may help you to read my answer to Interpretation of plot (glm.model).  The plots that R is generating are not specific to a logistic regression.  They are the plots for a standard OLS regression.  For example, the qq-plot is not of the residuals vs a binomial distribution.  It shows them relative to a normal distribution.  However, there is no theoretical reason that the residuals from a logistic regression 'should' be normally distributed.  On the other hand, the residuals from a logistic regression very much should be heteroscedastic, because the variance is a function of the mean.  Your model seems fine, as far as I can tell.
Comment: Thanks! What confuses me is that if I generate y values with an exponential correlation to x values and a Poisson distribution, the diagnostic plots for the corresponding `glm(y~x, family=binomial(link="logit"))` model indicate normality and homoscedasticity of the residuals. How comes the diagnostic plots show normalisation and homogenization of residuals for a Poisson GLM fitted to Poisson-distributed data, but the same doesn't happen for a binomial GLM fitted to binomial data?
Comment: @MarcoPlebani, they aren't actually normal, but they're close.  The Poisson is much closer to a normal than a binomial.


Comparing subset of rows in pandas

Question: I was wondering if there is nice way to compare a subset of rows in pandas?
let's say I have a df with:

id
in_test
value

1
True
5

2
True
5

1
False
7

2
False
8

I would like the resulting df with id and difference (or percentage change) from in_test from true to false.
I know I could pivot the table and then perform row wise calculations, or create a filtered df and merge it with another filtered df and then compute it row wise.
I was wondering if there is python way of doing this in one line? With probably a pandas function?
The output for percentage diff would be :

id
value

1
+40%

2
+60%

The output for diff would be :

id
value

1
2

2
3

(or minus -2 & -3 i guess I would have top define some kind of order) )
Comment: Can you give such examples?
Comment: post the expected result
Comment: (I can't figure out why it's not rendering it properly )
Comment: Once you have grouped by `id`, you may find [.diff](https://numpy.org/doc/stable/reference/generated/numpy.diff.html) or [.ediff1d](https://numpy.org/doc/stable/reference/generated/numpy.ediff1d.html) helpful.
Comment: Do you always have 1 True and False per group?
Comment: Yes i have  True and False  but i would like the solution to work for a multitude of things time series, numbers or boolean
Answer: df.groupby('id')['value'].apply(lambda x: x.diff().values[1]).reset_index()

difference
df.groupby('id')['value'].apply(lambda x: x.pct_change().values[1] * 100).reset_index()

percentage difference

Comparing subset of rows in pandas


same variances of the error terms of residual analysis?

Question: The text book says the residual diagram suggests that the variances of the error terms are equal.But how the variances of the error equal?As You can see the variance on the right circle is greater than the left one
Answer: The textbook describes the ideal scenario. Your analysis has probably a few assumptions. Checking whether the variance of the residual is equal, is  a way to check whether some of them are met or violated. If they are equal, you're fine, if not, technically your analysis is not valid. Just from looking on your plot, I'd say that the variances are equal enough for the analysis to be acceptable, but in the end it is your decision. In general, the variances don't have to be exactly the same, as long as there is no large deviation and no systematic trend, you should be good.
btw. it would be a wise move, to give a bit more detail on the textbook, your problem, the analysis. The more detail you give, the better people can answer you.


Como compartilhar métodos entre presenters no Ruby on Rails 4

Question: Gostaria de adicionar métodos ao meu modelo através de um Presenter, porém alguns métodos são compartilhados entre outros presenters.
Ex: os métodos 'pode_ser_mostrado?', 'pode_ser_editado?', 'pode_ser_excluido?'

Qual é a melhor maneira, criar um presenter base para ser estendido pelos outros?, ou criar um mixin incluído pelos presenters?
Exemplo:
class ModeloPresenter < BasePresenter
end

ou
class ModeloPresenter
  include 'base_presenter'
end

No caso como implementar?
Exemplo de como usar os métodos:
<%= link_to 'Mostrar', show_usuario(usuario.id) if UsuarioPresenter.pode_ser_mostrado? %>

<%= link_to 'Mostrar', show_cliente(cliente.id) if ClientePresenter.pode_ser_mostrado? %>

<%= link_to 'Mostrar', show_local(local.id) if LocalPresenter.pode_ser_mostrado? %>

Aceito também se houver sugestão de melhores maneira de implementar o mesmo.
Answer: Fácil, fácil:
class MeuModelo << ActiveRecord::Base
  def pode_ser_mostrado?
    # implementação do método
  end
end

Comment: Pode elaborar melhor a resposta, caso ela realmente solucione o problema do OP?
Comment: ve se estar melhor explicado agora


Sort 2d array on C

Question: How I can write a program to sort 2D array using C language and without using pointer,
just looping and if statements and using only main function
the array
7  5  2
3  1  4
6  9  8

and will be
1  2  3
4  5  6
7  8  9

please if you can post a sample code :)
Thanks a lot
Comment: @Daniel, it is when it's formatted correctly :-)
Comment: This is not a 2D array. Also, this kind of "without using, without using..." questions is totally pointless, in my opinion.
Comment: what it's called ??
Yeah I will not use some thing because that is what I want :)
its a teaching way
Comment: Today, when just about every basic concept in CS can be done for you by some library or your framework, teaching using the "don't use this and that" concept is more relevant then ever. If I'll tell you to perform some complex action, and you return a paper with a single function call that uses some lib in the framework, I'll have done nothing but force you to google a bit
Answer: Try searching the web before posting such questions. Any ways this is a bubble sort implementation in c:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define ARRAY_SIZE 20

void print_array(int *array) {
    int x;
    for(x = 0; x < ARRAY_SIZE; x++) {
        if(x != ARRAY_SIZE-1)
            fprintf(stdout, "%d, ", array[x]);
        else
            fprintf(stdout, "%d\n", array[x]);
    }
}

int main() {
    int iarray[ARRAY_SIZE];
    int x, y, holder;

    // Seed rand()
    srand((unsigned int)time(NULL));

    for(x = 0; x < ARRAY_SIZE; x++)
        iarray[x] = (int)(rand() % 100);

    fprintf(stdout, "Before Sort\n---------------\n");
    print_array(iarray);

    // Bubble sort method.
    for(x = 0; x < ARRAY_SIZE; x++)
        for(y = 0; y < ARRAY_SIZE-1; y++)
            if(iarray[y] > iarray[y+1]) {
                holder = iarray[y+1];
                iarray[y+1] = iarray[y];
                iarray[y] = holder;
            }

    fprintf(stdout, "\nAfter Sort\n---------------\n");
    print_array(iarray);

}

Comment: hmmm, I think you don't understand me I am talking about 2D (Matrix) not vector array[3][3] not array[3], how you can help ?
Comment: @user1065588: This is a homework question, and there is more than I would have provided in this answer... you just need to make the loops more complicated to account for the fact that your array is 2D (or ignore it altogether... a 3x3 matrix is an array of 3 arrays and the memory layout will be compatible with an array of 9 elements... but I guess that falls into the *pointers* category)
Comment: Looks to me too as if it is a homework question. As far as the pointer issue is concerned, it could be completely eliminated by using the `iarray` as a global and not passing any value to the function altogether (which is not a good way to write actual programs though). It would require to modify the `print_array` function by replacing each occurence of `array` with `iarray` and removing the parameter to it.
Answer: I am guessing that you need help with the algorithm. For that you can consult http://www.learncpp.com/cpp-tutorial/65-multidimensional-arrays/
Comment: that page doesn't actually offer a sort for multidimensional arrays
Comment: My friend it actually gives links to the selection sort algorithm. I guess you didn't scroll a bit lower than expected
Comment: It's for a 1d array, but the question asked specifically for a 2d array.

Sort 2d array on C


NotifyPropertyChanged pode ou não pode existir nas propriedades publicas de uma Model?

Question: Oi, estou criando um App com o padrão MVVM porém algumas questões relacionadas não estou conseguindo esclarecer sobre o assunto, vou deixar o link do App aqui se alguém quiser ver para me apontar algum possível erro ou até mesmo se quiser usar para fins de estudo fique à vontade.
NotifyPropertyChanged pode ou não pode existir nas propriedades publicas de uma Model?
Se sim, sabe me dizer em que momento ou para qual situação este NotifyPropertyChanged seria utilizado na Model? Pode descrever em situações não necessariamente em código(embora seja melhor).
Valeu.
Answer: Olá, @MATCH.
Caso esteja se referindo à interface INotifyPropertyChanged, este é um contrato para garantir o sincronismo de alteração de dados entre a View e a ViewModel(neste caso não entra o model).
Quando a ViewModel possuí alguma proprieade alterada, este deve invocar o evento PropertyChangedEventHandler informando qual proprieade sofreu alteração através do argumento PropertyChangedEventArgs
Respondendo a sua dúvida:
NotifyPropertyChanged pode ou não pode existir nas propriedades publicas de uma Model?
A resposta é: Depende, pois sintaticamente você estaria quebrando os princípios do Design Pattern MVVM que diz que somente a ViewModel deve-se comunicar com a View, mas nada te impede de fazer isso, vai funcionar do mesmo jeito, desde que sua ViewModel esteja mapeada para alguma proprieade da Model.
Classe base para Comum uso entre as ViewModels
public class BaseViewModel : INotifyPropertyChanged
{
        ///
        /// Occurs when a property value changes.
        ///
        public event PropertyChangedEventHandler PropertyChanged;

        ///
        /// Raises this object's PropertyChanged event.
        ///
        /// <param name="propertyName">Name of the property used to notify listeners.
        /// that support <see cref="CallerMemberNameAttribute"/>.</param>
        protected void RaisePropertyChanged([CallerMemberName]string propertyName = null)
        {
            OnPropertyChanged(propertyName);
        }
}

Exemplo de Utilização
public class MinhaViewModel : BaseViewModel
{
   private string _minhaString;
   public string MinhaString
   {
     get => _minhaString;
     set
     {
       if(value == _minhaString) return;

       _minhaString = value;
       RaisePropertyChanged()
     }
   }
}

Agora MinhaString pode ser utilizada na View problemas.
Comment: Entendi Vinicius foi muito claro, obrigado pela resposta e o exemplo.


Concrete5 220.127.116.11 User is Logged in as Wrong User

Question: We have had an intermittent issue with Users of our site mysteriously being logged in as a different user.  The site is built on Concrete5 Version 184.108.40.206.  This seems to be a huge security flaw as we are displaying private and sensitive data and allowing for onsite credit card purchases.
Answer: The site implements forever cookies which seems to be causing the issue.  According to this, the collision rate for the hash used for the cookie is around 8%. The patch in the link on that page seems to mitigate the problem but not completely eliminate it.
The second patch attempts to add the user id to the identifier in order to make it unique and eliminate that collision risk.  Seems like it should read:
<code>public function getString($length = 12) {
    $str = str_repeat($this->letters, 10);
-       $hash = substr(str_shuffle($str), 0, $length);
+       $user = new User();
+       if($user->getUserID()) {
+           $hash = sprintf("%i:%s, $user->getUid(), substr(str_shuffle($str), 0, $length));
+       } else {
+           $hash = sprintf("%s%i:%s", substr(str_shuffle($str), 0, $length), mt_rand(999,9999), substr(str_shuffle($str), 0, $length));
</code>

Concrete5 5.6.3.4 User is Logged in as Wrong User


mdaemon bad mails queue

Question: i have been having a problem two days now...the emails are being redirected to the bad queues instead of sending them..this makes the retry queue to also have so many emails...please advice on how to stop this ...
secondly what happens if i delete the emails in the bad queue?
am using maemon vs 10.0.0.0
regards
Answer: You have to check the logs to find why the emails are going to the bad queue.
If you delete those messages then they will not be delivered.
Could you provide an extract of the logs and your configuration or at least
more info about the problem?
Comment: hea is a sample log file

mdaemon bad mails queue


Finding Energy of Signal

Question: I'm trying to calculate the energy $E$ of the signal $e^{-t^2/{2\sigma^2}}$ using the energy formula:
$$E_t = \int_{-\infty}^{+\infty}|e^{-t^2/{2\sigma^2}}|^2dt$$
But i'm not how to start the integral .... any help would be great.
Answer: $$E_t = \int_{-\infty}^{+\infty}e^{-t^2/{\sigma^2}}dt$$
$$E^2 = \int_{-\infty}^{+\infty}e^{-y^2/{\sigma^2}}dy\int_{-\infty}^{+\infty}e^{-x^2/{\sigma^2}}dx$$
$$E^2 = \int_{-\infty}^{+\infty}e^{-y^2/{\sigma^2}}e^{-x^2/{\sigma^2}}dxdy$$
$$E^2 = \int_{-\infty}^{+\infty}\int_{-\infty}^{+\infty}e^{-\frac{x^2+y^2}{\sigma^2}}dxdy$$
$$E^2 = \int_{0}^{2\pi}\int_{0}^{+\infty}e^{-\frac{r^2}{\sigma^2}}rdrd\theta$$
$$2\pi \frac{\sigma^2}{2}$$
$$E = \sigma \sqrt{ \pi}$$

Finding Energy of Signal


Using rhythmic solfege to count a dotted eighth - sixteenth rhythm

Question: I'm looking for a way to show the dotted eighth - sixteenth rhythm using a system of rhythmic symbols.
In standard notation, the rhythm looks like this:

In French, it is easy to teach this rhythm because we can say "saut-te" and then the name of whichever note follows, such as "noire".
In English, use the "1e&a" method of counting rhythms, and I find that the way this rhythm is represented using this system is ambiguous. Apparently in this system there is no difference between counting four sixteenths or counting a dotted eighth followed by a sixteenth.
For instance, if we count four sixteenth notes, we use all the syllables:

But now when we count the dotted eighth sixteenth rhythm, which only has two notes, we still apparently have to count all the syllables, making it identical to the four note example above:

So in desperation, I turned to the Orff system. This method of rhythmic solfege uses words to represent rhythms, such as "raspberry" to represent triplets, or "hippopotamus" for quintuplets. But still I can't find any examples of words to use with the dotted eighth-sixteenth-quarter rhythm.
What's in your experience the best and least ambiguous way using rhythmic syllables to count or sound out this rhythm?
Comment: Apple for triplets? What? Good question though.
Comment: Ok maybe not. I put a different fruit :)
Comment: I use the [Kodály method](https://www.musical-u.com/learn/talking-rhythm-the-kodaly-method/), which is international. Its only problem is that it doesn't really account for tuplets.
Answer: I know many people in the "English" system (not just in England, of course) who would say that the "e" and "+" should be silent, as if represented by rests. This method only emphasizes the attacks of notes, leaving duration ambiguous.
The method you describe focuses on the binary state of "sound is present" or "silence", and it represents this unambiguously. However, it of course does leave the attacks of notes ambiguous: two quarter notes would be the exact same as one half note.
The middleground I've seen is the system you mention, where either sound is played or not, but any syllables that are part of the same note would be "slurred" when spoken, so two quarter notes would be "one, two" and a half note would be "one two" (which is hard to imagine just looking at the words, I know). A better way to think about it is to emphasize every new note; "one, two, three, (four)" would be different from "one, two, three, (four)": the former being a dotted half note and a quarter rest, the latter being three quarter notes and a quarter rest.

The reason this isn't a huge deal threatening to shake the foundations of music theory is because as long as your system works for you and you understand it, you can conceptualise rhythms pretty easily and communicate them with minimal confusion. All the ways of conveying rhythm (I myself got taught a method using "ta, ti ti, tika tika" for uarters, eighths, and sixteenthsths) are easily understandable to experienced musicians who might not have ever trained in using them before.
Comment: The "ta, ti ti, ti-ka ti-ka" method is called the "Kodály method". Just in case you forgot ;)
Answer: This is a fairly old thread by now, but it makes perfect sense to say "one...a" while holding the "one" as if saying "ooooooone."
Answer: Personally I use a tatatata system where the example in question would be Taaa-ta
as seen on the following image:
Answer: From the drumset, please notice that relying on lengths of syllables is ... a quite unreliable way to produce perfect timing. It may even hide the rhythmic structure and feel.
I'd like to suggest two options to you.
Konnakol
It's from India, uses only syllables of same duration, is  and was applied for a very long time by musicians (all kinds of percussion), dancers (feet) and ... audience (hands).
Example for your example, following the convention, that the first syllable is emphasized (I'll capitalize to emphasize this emphasis)
||: Ta - ki - te  Ta :||

(E.g. clap or play the note only at the emphasis and be silent else, i.e. play a precise rest.)
Now this is a very simple rhythmic example. You'll find any complexity in rhythmic performance when you look for videos. The type of syllables used vary, and oftentimes mimicks the sound of the instrument used. And those musicians, dancers, audience can recall long and complex rhythm chains obviously precisely and with ease.
Drummers stick control
Envision the marching drummer, with his/her snare at the hip and a stick in each hand. A very natural motion for the sticks is alternating left and right, like so (which could reflect the 4 sixteenth notes of a quarter) :
R L R L

Try it by slapping lightly on your thighs and notice, how regular and precise timing can be, as the frequencies of left and right hand are (and they are out-of phase as needed, or call it "delayed"). // You can also assign 1e+a or Ta-ki-te Ta (or better Ta-ka-de-mi) to it; moving and counting in parallel doesn't hurt.
Now, once this "machine" runs fine, let's introduce some asymmetry by introducing emphasis, i.e. harder and lighter strokes or claps to your thighs, like so:
||: R l r L :||    (where "l" is a small caps L ...)

There you go. Following this approach you'll always be on-time, very close to a rhythm "machine".
The advantage here is that you can do these phantom-strokes, where you either just slap your thigh lightly, or hit into the air at a drum: your timing will just be alright.
Later you can do similar things e.g. on a piano keyboard. But a phantom-hit of a key is may be no good idea. Instead you'll have a better recognition and control about syncroneous movement of fingers, which includes precise delays (or phase shifts amongst keys, referenced to the metronome).
Referring to the 3 bars from Noah Miller
Measure-wise:
 RLRL rlrl RlRL rlrl | RlrL rlrl RLrL rlrl | rLRL rlrl RLRl rlrl ||

(Which are just 7 out of the 16 possible combinations of note and rest. Practice all 16, and you are prepared for any 4/4 rhythm.)
The most important take-away here is to hear, to know, how the various pattern do sound (or have to sound thythmically).


I want convert from string to date

Question: NSDate *LastBuildDate;
NSDate *PubDate;

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMddhhmmss"];
LastBuildDate = [formatter dateFromString:buttoninfoamtion.mLastdate];
PubDate=[formatter dateFromString:newsItem.mPubDate];

   if([PubDate compare:LastBuildDate])

buttoninfomation.mlastdate and newsItem.mPubDate is string from OpenAPI
ex)
buttoninfomation.mlastdate: Tue, 18 Oct 2011 15:54:43 +0900
newspub:Tue, 18 Oct 2011 15:58:00 +0900
but
  LastBuidDate = (null)
PubDate = (null)
I want to compare two factor .
So date- date or string- string but I think string - string is so complex.
what wrong up codes?
Answer: Well the format you've given of "yyyyMMddhhmmss" doesn't match "Tue, 18 Oct 2011 15:54:43 +0900" even slightly.
Try
EEE, dd MMM yyyy HH:mm:ss Z

as the format string - see the iOS documentation and the Unix TR#35 for more information.

I want convert from string to date


Unable to build WDK 10 samples with VC2015 without modifying Windows headers

Question: I am running a fresh installation of Windows. No other programs installed except VC and SDK's

Include Directories
C:\WinSDK10\Include\10.0.10586.0\shared;
C:\WinSDK10\Include\10.0.10586.0\km;
C:\WinSDK10\Include\10.0.10586.0\km\crt;
C:\WinSDK10\Include\wdf\kmdf\1.11
Target OS Version
Windows 8.1
Target Platform
Desktop
Run Wpp Tracing
No
Enable minimal rebuild
No

Source:
#include <ntddk.h>
#include <wdf.h>
DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD KmdfHelloWorldEvtDeviceAdd;

NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT  DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
    NTSTATUS status;
    WDF_DRIVER_CONFIG config;

    KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n"));
    WDF_DRIVER_CONFIG_INIT(&config, KmdfHelloWorldEvtDeviceAdd);
    status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);
    return status;
}

NTSTATUS KmdfHelloWorldEvtDeviceAdd(_In_ WDFDRIVER Driver, _Inout_ PWDFDEVICE_INIT DeviceInit)
{
    NTSTATUS status;
    WDFDEVICE hDevice;
    UNREFERENCED_PARAMETER(Driver);

    KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n"));
    status = WdfDeviceCreate(&DeviceInit, WDF_NO_OBJECT_ATTRIBUTES, &hDevice);
    return status;
}

Severity    Code    Description Project File    Line    Suppression State
Error   C2146   syntax error: missing ')' before identifier 'InformationClass'  Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2146   syntax error: missing ')' before identifier 'InformationClass'  Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2061   syntax error: identifier 'InformationClass' Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2061   syntax error: identifier 'InformationClass' Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2059   syntax error: ';'   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2059   syntax error: ';'   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2059   syntax error: ','   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2059   syntax error: ','   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2059   syntax error: ')'   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31792
Error   C2059   syntax error: ')'   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31792
Error   C2081   'EVENT_INFO_CLASS': name in formal parameter list illegal   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789
Error   C2081   'EVENT_INFO_CLASS': name in formal parameter list illegal   Test1   C:\WinSDK10\Include\10.0.10586.0\km\wdm.h   31789

Hack: The driver builds successfully if I edit wdm.h and remove #define _ETW_KM_
wdm.h
#ifndef _ETW_KM_
#define _ETW_KM_
#endif

#include <evntprov.h>

//
// Optional callback function that users provide.
//

typedef
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
NTAPI
ETWENABLECALLBACK (
    _In_ LPCGUID SourceId,
    _In_ ULONG ControlCode,
    _In_ UCHAR Level,
    _In_ ULONGLONG MatchAnyKeyword,
    _In_ ULONGLONG MatchAllKeyword,
    _In_opt_ PEVENT_FILTER_DESCRIPTOR FilterData,
    _Inout_opt_ PVOID CallbackContext
    );

typedef ETWENABLECALLBACK *PETWENABLECALLBACK;

Sorry for the length of this post!!
I'm pretty sure I am doing something wrong while following this MSDN Driver Example Link but I can't figure out what.
Thanks for your time,
Kris
Comment: driver annotations are defined in Driverspecs.h.  (for such things as `_IRQL_requires_same_` ).  Do you have this .h file included anywhere?
Comment: @ryyker I am not directly including `driverspecs.h` but I have included the directory that it is located in; namely `10.0.10586.0\shared`. Directly including it, above ``, has no effect.
Comment: The `syntax error: missing )` is common when a macro has not been defined.  you have to make sure all the identifiers are defined.  Once that is done, the rest of the error messages are likely to be resolved as well.
Comment: @ryyker Removing `_ETW_KM_` solves **all** errors because `EVENT_INFO_CLASS` in `evntprov.h` isn't reached otherwise. But that's a hack, something is wrong.
Comment: I followed the MSDN guide word by word on a clean windows installation, a bug in WDK maybe?
Comment: _Removing _ETW_KM_ _solves all errors_...  Yes, I read that in your post.  But the real question is that once built, does the driver do what it needs to do?  Have you tested that?  If not, then the identifiers that are not defined, must be defined before going on.  Can you do a grep through all of your existing project header files to see if the identifiers are defined in any other file, that you can then `#include`?
Comment: The first error listed refers to line 31789.  Can you confirm (post) the exact line in your source file corresponding to that line?
Comment: @ryyker My source file ~30 lines of code and it's the one posted above ^^. I tried deploying the test driver (Driver Install->Deployment) but VC crashes. I don't understand what's going on, this is a crystal clear windows installation yet everything seems to fail horribly.
Comment: Actually, the source code for your project is thousands of lines long :).  With Microsoft, sometimes you can grow your project exponentially by including just one header file.  Did you successfully execute step 14 in your MSDN Driver Example link?
Comment: @ryyker Had I completed step 14 I wouldn't be posting this since it means I wouldn't have had any errors.
Comment: Sorry - was trying to establish where in the steps of that procedure things went wrong.
Comment: @ryyker All ok, thanks for your time and effort (: !! I will reinstall Windows, VC, WDK and SDK again. If it persists I'll just file a bug report. You should try and relax a bit (friendly comment)
Comment: This is sometimes how I relax.  (sad commentary).  I wonder if the example needs to be updated (or retro-fitted)  for Windows 8.1?  In any case, the error messages you posted are indicative of an undefined identifier.  Sorry we could not get this resolved.  Good luck.  By the way, very nice question format :)
Answer: Encountered similar problem with next version of WDK (10.0.14393).
Looks like in both cases the problem is different versions of Win SDK and WDK.
Solved by installing the corresponding version of Win SDK.
More detail in this answer.
Comment: Versions of the WSDK and WDK don't always match.
Answer: The error indicates the definition for EVENT_INFO_CLASS (Defined in evntprov.h) was not found. Another interesting thing is you are getting this for line number  31789 for method EtwSetInformation. This method needs to be imported only for (NTDDI_VERSION >= NTDDI_THRESHOLD) and you are targeting Win8.1. Something is wrong here. Please share the diagnostic msbuild log. It would be helpful to analyze.
Answer: Looks like an undefined identifier or macro...
The first of your error messages ( syntax error: missing ')' before identifier ) is probably the best key to understanding the issue.
The rest likely are a consequence of that one, which may be complaining that _IRQL_requires_same_, (or one of the other identifiers) is not defined.
As suggested in the error message, look in the file C:\WinSDK10\Include\10.0.10586.0\km\wdm.h for a clue as to what is not defined before InformationClass.  Then include the header file that provides definition.
(Currently, There is no information in your post tying the line number 31789 listed in the error message to the exact corresponding line in your source code.)
This link has information on driver annotations (Microsoft Source Code Annotation Language (SAL)).
Comment: Your link is broken remove `).`
Comment: @I. - Yes, sorry.  Fixed.


Using to user_profile_form being used on a page thats not /user/#/edit

Question: I've found the post How to display one of Drupal's default forms which talks specifically about this issue. however I wanted to post comments on it to get more info, It didn't seem to let me. Mabey I missed a button somewhere.
Anyway, I have section of my Drupal 7 site for all account and user stuff. /my/ This is a portal so to speak, /my/account is a menu handler that originally called drupal_get_form('user_profile_form', $user); Everything works, except when trying to upload, My profile is customised with a field to upload a file and field to upload an image.
Neither field works, it just returns errors. after the ajax kicks in.
Using the method found in the above linked post my entire form refuses to save and gives me validation errors. Thew above link mentions that custom callbacks and/or validators may have to be added due to referencing issue so i was hoping that someone could point me in the direction of what those custom things are.
Thanks.
Answer: You're likely using module_load_include() to include modules/user/user.pages.inc.
However, you need to use form_load_include() whenever you attempt to load, build, process, and render a form that is defined and constructed in an entirely different include file.
form_load_include() requires to pass the $form_state in order to record the file to include (and automatically load it later, if needed). This needs to happen before the form structure is cached (which happens directly after invoking the constructor).
In order to do that, you can resemble what drupal_get_form() does, and inject the needed form_load_include() prior to building the form, like this:
$form_id = 'user_profile_form';
$form_state = array();
$form_state['build_info']['args'] = array($user);

// Load user.pages.inc and ensure it is automatically reloaded if
// this form is rebuilt via AJAX or other means.
form_load_include($form_state, 'inc', 'user', 'user.pages');

$form = drupal_build_form($form_id, $form_state);

More details:
Normally, Form API automatically takes over the include file to load (if any) from the menu router item definition in hook_menu().
In your case, your custom 'my/account' menu router item is not directly related to user.module, nor user.pages.inc, so the system does not know that this include file is required to build the form, especially when the form is submitted and rebuilt via AJAX — which happens on yet another system path/menu router item, namely 'system/ajax' (which, by default, would only know about an include file of your 'my/account' menu router item, if any).
In turn, Form API gets a request to rebuild user_profile_form, but the form constructor function user_profile_form() is not defined, because user.pages.inc was not loaded, since the cached $form_state does not contain a pointer that the file needs to be loaded.


Taxonomy terms are not linked to nodes

Question: I have a content type with a field term reference to a vocabulary using selection list widget.
When i fill the content type, i get in the output the term selected.
But i click on that term i have the message :
There is currently no content classified with this term.
Any help please ?
Answer: I think you have multi language site.
I suggest you use the Taxonomy display module, here is a quote from its project page:

The taxonomy display module allows administrative configurable term
  display pages. This allows administrators to override the default
  presentation of taxonomy term pages per vocabulary through the
  taxonomy term page's manage display form.

Taxonomy terms are not linked to nodes


WebStorm + webpacker debugging

Question: Hello StackOverflow community!
My team is working on a ruby on rails project, where some parts are written in react. We are using webpacker gem to bundle js files into packs.
I'm trying to set up WebStorm to work with our project, but I have problems with the debugger - webstorm is not hitting any breakpoints.
I'm launching rails s and ./bin/webpack-dev-server in separate terminal instances, installed chrome extension and created JavaScript Debug configuration, pointing to the view where react app resides (on the port 3000). Also added devtool: 'eval' to webpack configuration. In the chrome dev tools I see webpack:// source and I can successfully set breakpoints there.
How to configure this tooling to have breakpoints working?
Answer: normally all you need for debugging apps bundled with webpack is to make sure that sourcemaps are properly generated. The best choice here is devtool: 'source-map' (see https://webpack.js.org/configuration/devtool/). eval sourcemaps are not accurate and not too suitable for debugging (quality is "generated code" rather than "original code").
In some cases, you might also need to specify URL mappings - see https://blog.jetbrains.com/webstorm/2015/09/debugging-webpack-applications-in-webstorm/ for more info.
But there are no generic instructions that would work for each and every configuration - as you can configure webpack in dozens of ways. So I can hardly advise on exact steps unless you provide a project you are trying to debug

WebStorm + webpacker debugging


Assumptions behind cross-validation

Question: According to "no free lunch theorem" (also here and here), we cannot deduce just from the data alone (without any domain knowledge) which classifier is better. Of course, we use cross-validation to do precisely that.
So what are the assumptions that we implicitly make that make cross-validation a meaningful procedure?
Comment: For now just a comment: "we cannot deduce just from the data alone" seeing that superiority of algorithms is often claimed without even a practical specification what is suitable data and what is not, deducing from data is IMHO already a big step into the right direction.
Comment: Well first one is that your collected data is representative of future data. In particular, with large number of variables, much of the input space is unexplored by training data.
Comment: @seanv507 What is your definition of "representative"?
Answer: I had this question for myself and found three (really only two) assumptions that are important and could be violated in practice.  I decided to write what I found here since this question helped to think about it.
Representative of Future Data
I personally don't like when people bring this up because NO algorithm does well when your training data is different than the test data. This is the whole point of the "no free lunch" theorem that in order to do better than random guessing you must have additional information or anything can happen.
No Information Leakage
Okay assuming we are even in a universe where historical data is helpful then we have to make sure there is no information leakage.  By that I mean information from the validation set leaks to the training set. When we partition the data into K-folds and designate one fold to be the validation set then we have "lost" information.  K-fold cross validation uses that "lost" information to estimate test accuracy.
However, lets consider an extreme case.  What happens if the model you used could completely guess every single point in the validation set with just the training set?  Then instead of K-fold cross validation you are instead running your model k times getting exactly the same result.  Obviously that would be no help whatsoever on estimating test accuracy.
In practice you couldn't tell so easy because there could just be some information leakage.  A practical example is looking at the sales of different years of the same make and model of car.  Car models don't change much from year to year and so sales will be really similar from year to year. If you have information from 1990-2016 and then take out 2000 as your validation partition then you haven't lost much information in your model.
Bias vs Variance trade off
K-fold cross validation make any model more complicated.  That is because we believe the model is very biased by the training data.  We add variance into the model (which parameters to be picked) to decrease bias.  This is a known trade-off in statistics that has no clear cut optimal solution.  I think this is basically a corollary of information leakage assumption though.
TLDR (Summary)
K-fold cross validation assumes that the good historical data gives a very biased model and isn't too redundant. Otherwise we are now in the domain of the free lunch theorem where even "anti-cross validation" is a good way to go.
Some references:

This one claims information leakage is only assumption
Good paper with leave-one-out not working on Iris data
Interesting paper with samples not being representative

Assumptions behind cross-validation


Does it help if you learn to play certain instruments both right-handed and left-handed?

Question: I once heard that if you switch hands when the violin, guitar or any other instrument that each hand has a separate task, it enhances your technical capabilities in music, general technique, and is good for your brain, is that so?
Comment: I would guess that it's fun as a mental exercise, but I'm not sure it would make any difference in your technique, since you're doing the exact opposite of the regular technique.
Comment: It would be interesting to see the links to the original scientific data related to the question. The question is great.
Comment: If I switch my hands on guitar I'm completely and utterly useless.  I'm normally alright with swapping on other tasks (at one point I could throw a baseball properly with my off hand/arm) but I think spending time on this would just be a waste.
Answer: The only times I find myself doing this is when, as a teacher, I need to remember how it was to be a beginner. I don't think this is a particularly bad idea but I reckon there's much more useful ways to spend your practice time.
As a side-note:
This is just my opinion but I never really understood why would people play guitar left handed. The left hand is actually the one that does most of the work so lefties benefits from playing right-handed guitars.


Page keeps loading while recording through jmeter

Question: I'm trying to record a .net application through jmeter. While navigation the application manually, it's working. When I start recording through jmeter, page keeps loading.
I've checked the proxy, certificate as well.
Please help me on this.
Answer: Always take a look at jmeter.log file, normally it contains either the reason or at least a clue so you will be able to figure out what went wrong.
It worth enabling JMeter debug logging for the HTTP(S) Test Script Recorder by adding the next line to log4j2.xml file:
<code><Logger name="org.apache.jmeter.protocol.http.proxy" level="debug" />
</code>
Also pay attention to "Console" tab of your browser developer tools, if something is wrong on the client/browser side - it will tell you what exactly.
And last but not the least: there is an alternative way of recording a JMeter test: JMeter Chrome Extension, it's less "invasive" and you won't need to worry about proxies and certificates.


Statistic counter auto refresh div and mysql query

Question: We are building live statistics counter, refreshing numbers every 10sec. (similar like stackoverflow questions counter). We have simple html page, we tried to embed php and tried to use jquery, but no success. Any help? Thanks

        <?php
            global $conn;
            $query="SELECT count(*) as total FROM posts WHERE type='update'";
            $query2="SELECT count(*) as total FROM members WHERE USERID>0";
            $postnum = mysql_query($query);
            $posts = mysql_result($postnum,0);
            $chanid = mysql_query($query2);
            $channels = mysql_result($chanid,0);
            print "

 $channels

channels

";
            print "

 $posts

posts

";
        ?>

Comment: var_dump $conn, $postNum, $chanid and $channels and return the results here.
Answer: you're only fading the stats div out an in again. you have to make an ajax call to the php file getting the new data.
var auto_refresh = setInterval(
    function() {
        $.ajax(
            url:"counter.php",
            success:function(data){
                $('#stats').fadeOut('fast', function(){
                    $(this).html(data).fadeIn('fast');
                });
            }
        )
    },
    10000
);

Comment: I tried to move php script part to file counter.php and change script part as described. As result counter disappear - I suppose there should be some print or echo left in html part...
Comment: $(this).html(data).fadeIn('fast'); should print the data (content of the php file) to #stats and fade it in again. try alert(data); before this. does it alert anything? or maybe give the link to your page if possible.


iSCSI storage questions

Question: We are thinking about getting HP StorageWorks P2000 G3 iSCSI, but I would be very glad, if someone could respond to some of my questions. We would like to have two XenServer hosts connected with iscsi to this storage.
1) Is it possible to connect it with standard cat5e ethernet cable directly to NIC of Xen hosts?
2) Can I select what disks are raided0 and what are not ?
3) Please explain me, what is that storage in fact. Is there some linux, how does administrator access it ?
4) Can I export some NFS shares as well ?
5) Can multiple hosts access same iSCSI ? (live migration, backuping, ...)
Thank you very much.
Answer: 1) Is it possible to connect it with standard cat5e ethernet cable directly to NIC of Xen hosts?
Yes.
2) Can I select what disks are raided0 and what are not?
Yes.
3) Please explain me, what is that storage in fact. Is there some linux, how does administrator access it?
It has proprietry embedded controller/s - you manage it via a web interface accessed through a dedicated ethernet port at the rear of each controller.
4) Can I export some NFS shares as well?
No it's a block-level device offering both iSCSI and FC interfaces. You can share this block-level data as file-level shares by exposing the storage to a general purpose server offering SMB/CIFS/NFS etc. however.
5) Can multiple hosts access same iSCSI ? (live migration, backuping, ...)
Yes, very easily but be aware that sharing blocks/LUNS to multiple machines not setup with a cluster-aware file system will cause almost immediate data corruption of that entire block/LUN.
Comment: nitpicking: for live migration uses you typically don't share filesystems, just volume groups.  if done correctly, you don't need a cluster-aware filesystem
Answer:
1) Is it possible to connect it with
  standard cat5e ethernet cable directly
  to NIC of Xen hosts?
  yes, but it's not recommended. The proper setup would be to have a switch, or better - two, and have a cable from every host to every switch to every SAN port.
  This way, you will get a fully redundant multipath
2) Can I select what disks are raided0
  and what are not ?

You can create logical disks out of the physical ones, raid configurations are per logical disk. from those disks you can carve and export LUNs.

3) Please explain me, what is that
  storage in fact. Is there some linux,
  how does administrator access it ?

some kind of management console, usually they are GUI or web based. Ask HP for details

4) Can I export some NFS shares as
  well ?
  I doubt it, but again - ask HP
5) Can multiple hosts access same
  iSCSI ? (live migration, backuping,
  ...)

yes, if you set the SAN up in a clustered configuration.
Answer: For the multiple-access iSCSI issue, you would use lvm-over-iSCSI SRs, and the system should handle contention appropriately.
You won't want to share filesystems under iSCSI... even with read-only mounts you will end up with inconsistent filesystem status. But LVM should handle it pretty well.

iSCSI storage questions


How to retrieve data in a Fragment from Firestore

Question: I am trying to fetch data from Firestore in a fragment that is using a BottomNavigationBar, in that fragment I want to display the User details like Name, Email id, etc.  But I have no idea how to use Firestore in a Fragment to retrieve data. Can anyone please help me with this
public class ProfileFragment extends Fragment
{

public ProfileFragment()
{ }

FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
FirebaseUser user;
String userid;
EditText name, email, num;

Want to display the details in the EditTexts above
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile, container, false);
    ImageButton setting = (ImageButton) view.findViewById(R.id.settings);

    View view1 = inflater.inflate(R.layout.fragment_profile, container, false);
    name = (EditText) view1.findViewById(R.id.nameed);

    firebaseAuth = FirebaseAuth.getInstance();
    firestore = FirebaseFirestore.getInstance();

    userid = firebaseAuth.getCurrentUser().getUid();

    final DocumentReference documentReference = firestore.collection("users").document(userid);

Tried using the piece of code below to  write data on the editext but got an error
   documentReference.addSnapshotListener((Executor) this, new EventListener<DocumentSnapshot>()
    {
        @Override
        public void onEvent(@javax.annotation.Nullable DocumentSnapshot documentSnapshot, @javax.annotation.Nullable FirebaseFirestoreException e) {
            name.setText(documentSnapshot.getString("nameed"));
        }
    });

This was the error
      E/AndroidRuntime: FATAL EXCEPTION: main
    Process: gmail.rishabh.myapplication, PID: 8597
    java.lang.ClassCastException: gmail.rishabh.myapplication.ProfileFragment cannot be cast to java.util.concurrent.Executor
     setting.setOnClickListener( new View.OnClickListener()  {
        @Override
        public void onClick(View view)
        {
            Intent intent = new Intent(getActivity(),settings.class);
            intent.putExtra("some","some data");
            startActivity(intent);
            getActivity().finish();

        }
    });
  return view;
}

}
Comment: I think there is no need of first parameter, remove this code--> (Executor) this,
Answer: Another simple approach is
DocumentReference docRef = db.collection("users").document(userid);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        User user = documentSnapshot.toObject(User.class);
        name.setText(documentSnapshot.getString("nameed"));
    }
});

Answer: When you are trying to pass an Executor object and an EventListener object to addSnapshotListener() method, it means that you are trying to use the following flavor of this method:

  addSnapshotListener(Executor executor, EventListener listener)

This method helps you:

Starts listening to the document referenced by this DocumentReference.

However, in the following line of code:
documentReference.addSnapshotListener((Executor) this, new EventListener<DocumentSnapshot>()

You are trying to cast this, which actually represents your current activity to an Executor, which is no possible in Java. To solve this, you should use the other flavor:

addSnapshotListener(Activity activity, EventListener listener)

In which you should pass as the first argument, an Activity object. So simply remove the cast:
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>()