text:
Q: CloudKit push notifications on record update stopped working EDIT:
Retested today 27.08.2015 and it works again, Apple has fixed it.
I have an application in development mode. The application uses CKSubscription to get notified on changes on the server, configured for all three options: create, update, delete. Everything was working fine but recently during regression tests I have discovered the application does not receive notifications on record updates, the create and delete notifications are still working. The susbcription types are set correctly for all three options as I checked on the dashboard and the application is registered for CKSubscription as it was a couple of days ago when it was working like charm. I am not getting any errors from CloudKit. The reset of development environment did not help. I have re-tested with the version with which I am sure it was working and got the same results.
Any idea what might be causing this issue, what else should I check / try?
Additional Info:
I guess something might go wrong at the server side. I have not changed anything in the code where I am subscribing for CloudKit events and handling push notifications - anyway also the version where it was working is not getting update notifications any longer. The application I am working on is published, thus changing container is no go. Not sure if this might be causing the issue, just want to mention: the app is using the same container for storing the Core Data in the cloud - the goal of the app upgrade is to migrate data to the CloudKit and use it as the cloud storage exclusively. It is confusing that everything was working fine for weeks and suddenly stopped working without any clear reason, probably as the effect of the load by intensive testing, adding record types...
Test with app developed from scratch:
I have written a simple test app to check receiving notifications. I can receive only the notification on record creation. What is wrong with my code:
import UIKit
import CloudKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

let container = CKContainer.defaultContainer()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()

    return true
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    println("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    println("didRegisterForRemoteNotificationsWithDeviceToken: \(deviceToken)")
    subscribe()
}

func subscribe() {
//        let predicate = NSPredicate(format: "text != %@", argumentArray: [""])
//        let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
    let predicate = NSPredicate(value: true)
    let subscription = CKSubscription(recordType: "Note", predicate: predicate, options: .FiresOnRecordDeletion | .FiresOnRecordUpdate | .FiresOnRecordCreation)
    let notificationInfo = CKNotificationInfo()
    notificationInfo.alertBody = ""
    subscription.notificationInfo = notificationInfo
    let publicDatabase = container.publicCloudDatabase
    println("subscribing with CloudKit...")
    publicDatabase.saveSubscription(subscription, completionHandler: { (returnedSubscription, error) -> Void in
        if let error = error {
            println("subscription error \(error.localizedDescription)")
        } else {
            println("subscription ok")
        }
    })
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    let ckNotification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo)
    println("didReceiveRemoteNotification: \(ckNotification)")
}

func applicationWillResignActive(application: UIApplication) {}

func applicationDidEnterBackground(application: UIApplication) {}

func applicationWillEnterForeground(application: UIApplication) {}

func applicationDidBecomeActive(application: UIApplication) {}

func applicationWillTerminate(application: UIApplication) {}

}

A: I have experienced this behavior in the past. In my case I could solve it by just deleting the subscription and creating it again. You should do that from code and not the dashboard. Doing it from the dashboard only works for the account that you are loged in into the dashboard.


text:
Q: Phonegab/Cordova - Launch app on GCM notification like whatsup call I use the phonegap-plugin-push to send GCM notification on a mobile device but I'can't find anything how to start an activity when a notification is triggered.
This plugin do the follow:

*

*if the activity is started and is in forderground then the notification message will be display directy into the activity (this is OK)

*if the activitiy is started and is in background a notification will be displayed and only by clicking on the notification the activity will take into forderground and show the message (should do without click).

*if activity is not starting, nothing is happend

What I want is that the activity should be run in forderground when notification is triggerd, even if the lock screen is active.
Is this scenario even possible with phonegab?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android NFC tag with URL opening browser, not my app I followed instructions to setup NFC to launch my app on Android.  The first record in the tag is a url to my website.  ex. example.com
The AndroidManifest.xml file has the following intent filter:
<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <data android:host="example.com" android:scheme="http" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

But for whatever reason when I scan the tags, the android browser opens, not my app. Android documentation for nfc doesn't appear to have any additional steps https://developer.android.com/guide/topics/connectivity/nfc/nfc.html
For what it's worth, I'm using Apache Cordova and the phonegap-nfc plugin.

A: Your intent filter looks good and works a sample app I wrote. I get prompted to open the tag with my app or Chrome.

I expect at one point you told Chrome to open http://example.com tags or all URL tags and now Chrome grabs the intent before your app can launch.
If fixed this by resetting all app preferences.
Settings -> Device -> Apps -> Menu -> "Reset App Preferences"
See https://support.google.com/nexus/answer/6271667?hl=en
After resetting the preference Android prompted me again to choose an app when I scanned the tag. I chose complete action using NFCLaunch (my app) always. Now tags with http://example.com open my app but other tags with http://android.com will still open in Chrome.
Another option is to: disable Chrome, scan the tag, choose the app, re-enable Chrome.


text:
Q: Please define the grammar errors (by their generally accepted terms) in this sentence My goal in asking this question is to learn to name my errors.  I write many sentences and think, "that's not right," and then I change it to make it sound better.  It usually works well (and my boss is happy) but I want to know why they are not right.
My current problem sentence is in bold: We dream of the day when our services are no longer needed, but know that the demand continues to increase.  Furthering this demand is the ever-expanding awareness of our resources.
I would change it to: This demand is furthered by the ever-expanding awareness of our resources.  (Feel free to provide suggestions on this one to, or tell me what grammar terms you would use to define how I have changed this).
Context: I am writing a fundraising proposal and trying to explain why the demand for our published resources is increasing.  We provide services to the poor.

A: I see no grammatical errors in the sentence.
However, I find it very hard to make sense of.
I would initially parse it as a copular sentence: [furthering this demand] is [the ever...], with 'furthering this demand' as the subject: parallel to "Giving gifts is a sign of generosity".
But that doesn't make a lot of sense, and from your paraphrase (which has a horrible, horrible, passive), it seems to me that the sentence is inverted, with [the ever-expanding ... ] as the subject. Again, grammatical, though rather literary: like "Walking along the road was a man".
Given that the awareness is the subject, I would prefer either:

The ever-expanding awareness of our resources furthers this demand.

which is still a bit unclear, though would be made more readable by an adverb such as "constantly" before "furthers"; or the cleft sentence:

What furthers this demand is the ever-expanding awareness of our resources.

(or 'something that furthers this demand' if the "what" is too inclusive).


text:
Q: Trying to transfer big file docker container Error response from daemon: ApplyLayer exit status 1 stdout: stderr: unexpected EOF Hi im trying to transfer the bitcoin blockchain files into my docker container, I can docker cp the files no problem into my docker container but when i commit the changes into the docker image i get the following error:
Error response from daemon: ApplyLayer exit status 1 stdout:  stderr: unexpected EOF

The folder is about 80gb in size. What do i have to do to get this to work?
docker info:
Containers: 8
Images: 8
Storage Driver: btrfs
Build Version: Btrfs v4.2.2
Library Version: 101
Execution Driver: native-0.2
Logging Driver: json-file
Kernel Version: 4.6.0-1-amd64
Operating System: Debian GNU/Linux stretch/sid (containerized)
CPUs: 6
Total Memory: 15.59 GiB
Name: debian
ID: UV2L:CG6Y:NQ4W:K7KY:6VN5:DIMN:SYED:BIQK:ZYBZ:HH4I:NE5Y:4ACN
Username: hamiltino
Registry: https://index.docker.io/v1/
WARNING: No memory limit support
WARNING: No swap limit support


text:
Q: Magento 1.6.1: type vs. type_id, categories vs. category_ids? They seem to bear the same value in the results returned by product.info API call. For example:
[type] => simple
[type_id] => simple

[categories] => Array
    (
        [0] => 4
    )
[category_ids] => Array
    (
        [0] => 4
    )

So which one of them am I supposed to use when creating or updating products? Or should I just stick to both of them and set the same value for both of them when creating or updating products?
Thanks!

A: The "id" values are what is stored in the database, their shorter equivalents are set by the product model for convenience and it is responsible for copying changes back to the "id" field. In theory you can use either interchangeably.


text:
Q: Why is my CSS style not being applied correctly? When the width> 959px I want to display is a column. 500px < width <959px, it will be 2 columns. <500px width will be a column.
width >959px

500px < width <959px

width <500px

.img-wi{
        width:100%;
        display: inline-block;
        border:2px solid #13aff2;
     margin-top:10px;
    }
    @media only screen and (max-width:959px) {
       .left-w{
     float:left;
     width:49%
    }
       .right-w{
     float:right;
     width:49%
    }}
.text-wi{
        border-top:2px dashed #13aff2;
        padding: 5px 0 0 20px;
    }
    @media only screen and (max-width:500px) {
       .left-w{
     float:none;
     width:100%
    }
       .right-w{
     float:none;
     width:100%
    }}

    AAAA

    – A
– B
– C

AAAA

    – A
– B
– C

What I am doing wrong?
Any help is appreciated


text:
Q: When I have to use @section scripts?
My current structure has a layout with header, body and footer. Inside the body load a view using ajax to call for a action controller returning a Json and painting a tree view. When user click on the tree view the footer should load the detailed information. But isnt working, my guess is because the scripts section isnt render properly.
Right now the script are in the layout without bundles or anything and work ok on the Main body because I use Jquery and a Tree to load the Json data.
But in the partial View get an error. I could write a @section scripts area and copy all the script from the layout in the Partial View but why should I duplicate the code?

The worst part is only give me problem in the production enviroment ... on my devolpment enviroment works ok.

So the questions:

*

*Why the main view can see the scripts define on the Layout but the Partial View Doesnt?

*Why my development enviroment work ok, but productions doesnt?

*What should I do to solve this?
EDIT: More testing.
This is a test View, this render in the Body. But I need include script section otherwise the dialog doesnt show, even when layout have the scripts too.
@{
    ViewBag.Title = "TreeDetails";
}

    <title>@ViewBag.Title</title>

TEST PAGE

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

@section scripts {
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

}

A: It seems a run time error due to an unrecognized jquery function.. try to move your link reference to jquery from your view @section area in the layout header..


text:
Q: Presenting ViewController behind another one I have image picker which collects data for another view controller (TTMessageController from three20) and I want this message composer to appear behind image picker, so when image piker slides out there will be already appeared message controller with pre-filled data.
Code like this
[self.navigationController presentModalViewController:composeController animated:NO];
[picker dismissModalViewControllerAnimated:YES];

and vice-versa wont work at all. What to do? How to present composeController behind already presented picker controller?
Thanks in advance.

A: Edit:
Ok I think the problem here is the modal bit, as the iPhone really appears to not like you having 2 views set to modal, or even animating from one modal view to another.
Do they definitely have to be modal?  How about adding them to the normal navigation stack?
You could add the message view to the stack first (non-animated) so that it's there when you pop back one.
Try this:
The order in which you add views to the stack affects the order that they will display in when you dismiss them.
This part adds the composeController to the stack and then animates the picker going on top.  Use this code to display the picker controller (ie instead of modal dialog):
[self.navigationController pushViewController:composeController animated:NO];
[self.navigationController pushViewController:picker animated:YES];

Then, when you are done with the picker, you can "pop" the view back to the message composer:
[self.navigationController popViewControllerAnimated:YES];

You should now have no references to any modal dialogs remaining in your code.  I believe this should work much better than modal, which really is for displaying one view above every other one, not for switching from view to view.
Hope that helps!

A: Actually removing animation from both viewController help.
[picker dismissModalViewControllerAnimated:NO];
[self presentModalViewController:composeNavController animated:NO]; // If YES it crashes

But it's not to iPhone-ish if get what I mean, even fade throw black or just some visual effect will make it look much, much nicer. Technically tho, it works.

A: Instead of trying to present another viewController behind the picker, you could dismiss the image picker modal view controller, push the Message controller (both with animated:NO), and then use a CATransition to perform your own Cocoa-like animation of the image picker animating off screen.

A: You need to split these animations up so they don't execute in the same runloop. I've run into a situation where the OS does not like dismissing and presenting modal views back to back.
Try this:
- (void)myCallbackMethod{

[picker dismissModalViewControllerAnimated:YES];
[self performSelector:@selector(presentMessage) withObject:nil afterDelay:0.25];

}

- (void)presentMessage{

[self.navigationController presentModalViewController:composeController animated:YES];

}


text:
Q: Simple Vault with assembly design proteus Please help me - how to change "masterkey"
change to lcd
add alarm (wrong entry) ----(if it was possible)----
The project is at this link
https://github.com/osemrt/8086-Microprocessor/tree/master/03_Simple_Vault#readme


text:
Q: how to put gap between y axis and first bar in vertical barchart matplotlib I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar?
def plot_graph1():
    xvals = range(4)
    xnames=["one","two","three","four"]
    yvals = [10,30,40,20]
    width = 0.25
    yinterval = 10
    figure = plt.figure()
    plt.grid(True)
    plt.xlabel('x vals')
    plt.ylabel('y vals')
    plt.bar(xvals, yvals, width=width)
    plt.xticks([ x+(width/2) for x in  xvals],[x for x in xnames])
    plt.yticks(range(0,max(yvals),yinterval))
    figure.savefig("barchart.png",format="png")
    plt.show()
if __name__=='__main__':
    plot_graph1()

The output is as below

Any help appreciated
thanks
mark

A: In your specific case, it's easiest to use plt.margins and plt.ylim(ymin=0).  margins will act like axis('tight'), but leave the specified percentage of "padding", instead of scaling to the exact limits of the data.
Also, plt.bar has an align="center" option that simplifies your example somewhat.
Here's a slightly simplified version of your example above:
import matplotlib.pyplot as plt

def plot_graph1():
    xvals = range(4)
    xnames=["one","two","three","four"]
    yvals = [10,30,40,20]
    width = 0.25
    yinterval = 10

    figure = plt.figure()
    plt.grid(True)
    plt.xlabel('x vals')
    plt.ylabel('y vals')

    plt.bar(xvals, yvals, width=width, align='center')
    plt.xticks(xvals, xnames)
    plt.yticks(range(0,max(yvals),yinterval))
    plt.xlim([min(xvals) - 0.5, max(xvals) + 0.5])

    figure.savefig("barchart.png",format="png")
    plt.show()

if __name__=='__main__':
    plot_graph1()


text:
Q: How to replace default register route with plug in I want to replace default route for recently add product page on nopcommerce 3.0.
Now I try to develop plugin that contains new controller and new model to replace controller and model classes for recently add products page(New Products).
But I can't replace default routing for new products.
How can I replace default routing path in nopcommerce?

A: All you need to do is to create a controller (and action) of the same name in your plugin (with a different namespace). Then put a higher priority on your route than nopCommerce's route. I've actually just answered the same question in nopCommerce forum, you can check it here: Click to read


text:
Q: No password to run command as root for fixed command? Is it possible to define a rule in sudoers to allow one user to run one well defined command as root, without password or other authentication except being the right user?
Are there alternatives to solve this (or something very similar)?
Use suid permission bit?
Maybe make use of ssh keys somehow?

A: The sudoers file allows specifying commands to permit:
username ALL=(root) NOPASSWD: /bin/foo bar baz

Here username is the user you want to permit, and the command goes at the end of the line. If you specify arguments to the command, the user can only run it with exactly those arguments, but if you don't specify them here, the user can run the command with any arguments they choose. You can specify multiple commands separated by commas, or just as separate lines.
Edit the sudoers file with visudo (as root) and add a line in that format, with the appropriate details changed, and the user will be allowed to run exactly the command you specify with elevated privileges.

NOPASSWD: allows the user to run the command without prompting. The ALL is a host restriction, which you can probably ignore (you'll know if you can't). (root) means they can only run the command as the root user.

Since you ask, it is strictly possible to do this with ssh too, although sudo is better. You can put COMMAND=something at the start of a line in /root/.ssh/authorized_keys and give the user a special-purpose SSH key corresponding to that command. The only possible reasons that would be better than sudo are if you didn't want the user to have any other access to the machine, or if you didn't want them to have to write the command out themselves.


text:
Q: If $A$ is nilpotent, why is $A$ non-invertible? Here $A$ is a square matrix. I'm confused as to why $A$ would be non-invertible as well.

A: If $A$ is invertible, $A^n$ is invertible for all $n$. But $0$ is not invertible.

A: Since $A$ is square and nilpotent
$$
\det (A^n) = \left( \det(A) \right) ^n = \det(0) = 0,
$$
so $\det(A) = 0$ and $A$ is singular.

A: If $\,BA = 1\,$ and $\,n\,$ is least with $\,A^n = 0\overset{\large\,  B \times_{\phantom I}}\Rightarrow A^{n-1} = 0\,\Rightarrow\!\Leftarrow$

A: Suppose there were an inverse matrix $B$ such that, where $I$ is the identity:
$$AB=I$$
It follows that
$$A^nB^n= A(A(\cdots A(AB)B\cdots)B)B=I$$
But if $A^n = 0$ then
$$0B^n=I$$
$$0=I$$
Hey wait...


text:
Q: Python Updating Object in 2D List I am making Conway's Game of Life using pygame and am trying to update the state of the position when the board is clicked. Each position on the board is a Cell object with a  variable 'state' set to 0 by default.
This is how the 2D list of Cell() objects 'board' is created.
block_size = 25
board = []
rows, cols = (int((window_height - 100)/ block_size), int(window_width / block_size))
for i in range(rows):
    cell = Cell()
    col = []
    for j in range(cols):
        col.append(cell)
    board.append(col)

This is the code to update the position. mouse_round() is used to round the mouse_pos down to a multiple of 25 and block_size is the size in pixels of the squares on the screen.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    if mouse_pos[1] < window_height - 100:  # if a square in the board is clicked
        block_size = 25
        x, y = pygame.mouse.get_pos()
        rect = pygame.Rect(mouse_round(x), mouse_round(y), block_size, block_size)

        board_pos_x = int(mouse_round(y) / block_size)
        board_pos_y = int(mouse_round(x) / block_size)

        current_pos = board[board_pos_x][board_pos_y]

        if current_pos.state == 0:  # if the color where they clicked is black, make it white
            current_pos.state = 1
            pygame.draw.rect(window, white, rect)

        else:  # if the color where they clicked is white, make it black
            pygame.draw.rect(window, black, rect)
            current_pos.state = 0

The problem I am encountering is the state of every cell object in the row is being changed to 1 when a black square is clicked and I cannot for the life of me figure it out.

A: because only 1 cell gets created per row. that same cell then gets appended to every column for that row. move the cell creation inside the column loop. i.e.
for i in range(rows):
    col = []
    for j in range(cols):
        cell = Cell()
        col.append(cell)

A: Your problem is here :
for i in range(rows):
    cell = Cell()
    col = []
    for j in range(cols):
        col.append(cell)
    board.append(col)

for each row, you create a cell that will be added cols times to the column (and since Python lists are height first, I guess your whole column of identical references to the same cell becomes a row).
The cell init should be in the second loop :
for i in range(rows):
    col = []
    for j in range(cols):
        cell = Cell()
        col.append(cell)
    board.append(col)


text:
Q: How can I get rid of Jarate? In what ways can I get rid of Jarate? It seems to be quite annoying when I get hit by one; I end up dying very quickly because enemies do a ton of damage to me.

A: Getting healed by a medic or a dispenser removes Jarate very quickly, according to the TF2 wiki.
Unconfirmed accounts suggest jumping into water also 'rinses it off' ;)

A: Instant Removal

*

*Resupply cabinet

*Going underwater

*Ubercharges (it clears effects like jarate, fire, milk on the target)

Expedited Removal

*

*Standing by a dispenser for a while

*Getting healed by a medic over time


text:
Q: trouble using angularjs with slim in a rails project I've finally decided to give angularjs a whirl and i'm running into some early trouble.
I'm using Rails 3.2 and the Slim template gem for the view.
I'm just trying the example from the angularjs site here: http://angularjs.org/#todo-html
Here's the relevant bit:

   {{remaining()}} of {{todos.length}} remaining

Which in slim would be something like:
div(ng-controller="TodoCtrl")
  span {{remaining()}} of {{todos.length}} remaining

The problem is Slim just prints:
{{remaining()}} of {{todos.length}} remaining

literally as a string.
Anyone able to get Slim and Angular to play together?

A: You can also do it like so:
html [ng-app]

Or:
div [ng-app]
  div [ng-controller="TodoCtrl"]
    span {{remaining()}} of {{todos.length}} remaining

A: I finally got it to work.
I had to go into my layout and do this:
html(ng-app='')

You can probably add that to a div on the particular page also.
div(ng-app='')
  div(ng-controller="TodoCtrl")
    span {{remaining()}} of {{todos.length}} remaining

Hopefully this helps someone.  It took me a bit to figure out.


text:
Q: How to copy an image from a folder temporarily and delete it afterwards in PHP? I have a folder on a NAS containing several images.
I would like to make a local copy of the images in a folder, display the images and then delete them so that they don't take over the local on the server.
How can I delete the photos after viewing them?
I made this code but it deletes the following image, so it can't be displayed :
<?php
$file = '//Alcyons/it/PhotoShoot/Photos_Outil/A1111_0070_1.jpg';
$newfile = 'A1111_0070_1.jpg';

if (!copy($file, $newfile)) {
    echo "La copie $file du fichier a échoué...\n";
}

echo "			";

unlink($newfile);

?>

A: What do you solve by copying the file?
How does it make sense if you delete it instantly?
According to your code structure, that one will be better:
<?php

$file = '//Alcyons/it/PhotoShoot/Photos_Outil/A1111_0070_1.jpg';
$type = pathinfo($file, PATHINFO_EXTENSION);

?>

  <img src="<?php echo "data:image/$type;base64,",
     base64_encode(file_get_contents($file)) ?>" border=0 width="180">


text:
Q: Unable to update OptionSetValue field on CRM 2011 custom Entity I'm getting a "Specified cast is not valid." Exception when trying to update an OptionSetValue attribute of a custom field on a custom entity.
This works:
data = new Xrm.Xyz_data()
{
  Xyz_dataId = (Guid)entity["xyz_dataId"],
  // Xyz_dataStatus = new OptionSetValue(5),
  Xyz_IsSyncReqd = true
};

service.Update(data);

But uncomment the OptionSetValue line and it throws this exception:
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Specified cast is not valid. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).

With this stack trace:
Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Xrm.Sdk.IOrganizationService.Update(Entity entity)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.UpdateCore(Entity entity)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Update(Entity entity)

A: That looks right to me - I don't use early bound which it looks like you are doing but can you verify that the data context has been refreshed since the picklist attribute was created and published?
If this is a built in state field you will probably need to first do the update and then perform a UpdateStateValueRequest.  Excerpt from CRM 2011 SDK -

#region How to update state value
// Modify the state value label from Active to Open.
// Create the request.
UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
{
    AttributeLogicalName = "statecode",
    EntityLogicalName = Contact.EntityLogicalName,
    Value = 1,
    Label = new Label("Open", _languageCode)
};

// Execute the request.
_serviceProxy.Execute(updateStateValue);

#endregion How to update state value

A: So I finally figured out what was happening.  I turned on server side debugging using the same registry settings as CRM 4.0:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM]
"TraceEnabled"=dword:00000001
"TraceCategories"="*:Error"
"TraceCallStack"=dword:00000001
"TraceRefresh"=dword:00000001

I reran my test that was failing, and found this error:
[2011-10-24 18:19:37.990] Process: w3wp |Organization:00000000-0000-0000-0000-000000000000 |Thread:   14 |Category: Platform |User: 00000000-0000-0000-0000-000000000000 |Level: Error | ExceptionConverter.ConvertMessageAndErrorCode
    at ExceptionConverter.ConvertMessageAndErrorCode(Exception exception, Int32& errorCode)
    at ExceptionConverter.ToSingleFaultOther(Exception exception)
    at ExceptionConverter.ToSingleFaultUntyped(Exception exception)
    at ExceptionConverter.ConvertToFault(Exception exception)
    at ExceptionConverter.TryConvertToFaultExceptionInternal(Exception exception, Boolean createNewFaultException, FaultException`1& faultException)
    at FaultHelper.ConvertToFault(Exception exception)
    at OrganizationSdkServiceInternal.Update(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
    at
    at SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
    at DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
    at ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
    at ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
    at MessageRpc.Process(Boolean isOperationContextSet)
    at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
    at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
    at ChannelHandler.AsyncMessagePump(IAsyncResult result)
    at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at AsyncResult.Complete(Boolean completedSynchronously)
    at ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
    at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at AsyncResult.Complete(Boolean completedSynchronously)
    at AsyncQueueReader.Set(Item item)
    at InputQueue`1.Dispatch()
    at ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
    at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
    at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
>System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #9F125FAE: System.InvalidCastException: Specified cast is not valid.
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.IntentionalRethrow(Exception chainException, Exception originalException)
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.RethrowRecommended(Exception chainException, Exception originalException)
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.Handle(Exception exceptionToHandle)
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl.HandleException(Exception exceptionToHandle)
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName, ExceptionPolicyFactory policyFactory)
>   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
>   at Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
>   at XYZ.CRM.Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
>   at XYZ.CRM.Plugin.Common.PluginBase.OnError(Exception ex)
>   at XYZ.CRM.Plugin.Common.PluginBase.Execute(IServiceProvider serviceProvider)
>   at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
>   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)

And since I was debugging my plugin via a unit test, I realized that another plugin was getting fired when those fields were updated by my plugin, and that plugin was apparently causing an exception.  But even worse was that the exception handler was causing another exception, that was getting returned, masking the true exception.  I tested a really simple fix by eating any exceptions that the exception handler might throw, and it is working great now!  Now to discover why my other plugin is failing...


text:
Q: ElasticSearch: Root mapping definition has unsupported parameters I'm trying to add in a new field mapping, categories, in Kibana:
PUT testcats/items/_mapping
{
    "settings": {
},
    "mappings": {
    "items" : {
        "_meta" : {
        "version" : "33"
        },
        "dynamic_templates" : [
        {
            "numbers" : {
            "match_mapping_type" : "long",
            "mapping" : {
                "type" : "double"
            }
            }
        },
        {
            "floats" : {
            "match_mapping_type" : "double",
            "mapping" : {
                "type" : "double"
            }
            }
        },
        {
            "strings" : {
            "match_mapping_type" : "string",
            "mapping" : {
                "fields" : {
                "raw" : {
                    "ignore_above" : 256,
                    "type" : "keyword"
                }
                },
                "type" : "text"
            }
            }
        }
        ],
        "properties" : {
        "categories": {
            "properties": {
            "audio": {
                "properties": {
                "category": {
                    "type": "text",
                    "fields": {
                    "raw": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                    }
                },
                "source": {
                    "type": "text",
                    "store": false,
                    "fields": {
                    "raw": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                    }
                }
                }
            },
            "user_generated": {
                "type" : "text",
                "fields" : {
                "raw" : {
                    "type" : "keyword",
                    "ignore_above": 256
                }
                },
                "copy_to" : [
                "all_search_data_items"
                ],
                "analyzer" : "autocomplete"
            },
            "visual": {
                "properties": {
                "category": {
                    "type": "text",
                    "fields": {
                    "raw": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                    }
                },
                "source": {
                    "type": "text",
                    "store": false,
                    "fields": {
                    "raw": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                    }
                }
                }
            }
            }
        }
        }
    }
    }
}

But then I get the response:
{
"error": {
    "root_cause": [
    {
        "type": "mapper_parsing_exception",
        "reason": "Root mapping definition has unsupported parameters:
[settings : {}] [mappings : {items={_meta={version=33},
dynamic_templates=[    {numbers={match_mapping_type=long, mapping= .
{type=double}}}, {floats={match_mapping_type=double, mapping= .
{type=double}}}, {strings=    {match_mapping_type=string, mapping= .
{fields={raw={ignore_above=256, type=keyword}}, type=text}}}],
properties={categories={properties=     {audio={properties={category= .
{type=text, fields={raw={type=keyword, ignore_above=256}}}, source= .
{type=text, store=false, fields={raw=    {type=keyword,
ignore_above=256}}}}}, user_generated={type=text, fields={raw= .
{type=keyword, ignore_above=256}}, copy_to=   [all_search_data_items],
analyzer=autocomplete}, visual={properties={category={type=text,
fields={raw={type=keyword, ignore_above=256}}},    source={type=text,
store=false, fields={raw={type=keyword, ignore_above=256}}}}}}}}}}]"
    }
    ],
    "type": "mapper_parsing_exception",
    "reason": "Root mapping definition has unsupported parameters:
[settings : {}] [mappings : {items={_meta={version=33},
dynamic_templates=[    {numbers={match_mapping_type=long, mapping= .
{type=double}}}, {floats={match_mapping_type=double, mapping= .
{type=double}}}, {strings=    {match_mapping_type=string, mapping= .
{fields={raw={ignore_above=256, type=keyword}}, type=text}}}],
properties={categories={properties={audio=    {properties={category= .
{type=text, fields={raw={type=keyword, ignore_above=256}}}, source= .
{type=text, store=false, fields={raw={type=keyword,
ignore_above=256}}}}}, user_generated={type=text, fields={raw= .
{type=keyword, ignore_above=256}}, copy_to= . [all_search_data_items],
analyzer=autocomplete}, visual={properties= . {category={type=text,
fields={raw={type=keyword, ignore_above=256}}}, source={type=text,
store=false, fields={raw={type=keyword, ignore_above=256}}}}}}}}}}]"
},
"status": 400
}

I've been banging my head on this for a while.  I can't determine which parameter is unsupported.  Any help is appreciated!  Also, is there any way to get more detail from Kibana on the specific parameter is unsupported?

A: Try with only PUT testcats as action. You are passing settings that are also at the index level, not only at the mapping level.


text:
Q: php header file path I'm asking for a solution how to make PHP download a file without redirect and without reading file source like in this example:
if(1 == 1)
{
    header("Content-Type: application/xml");
    header("Content-Transfer-Encoding: binary");
    header("Cache-Control: private",false);
    header("Content-Disposition: attachment; filename=example.xml;" );
    $file = file_get_contents("file.ext");
    echo file;
}

I need solution for download witout file_get_contents make the download like mod_rewrite.
Thanks

A: You could use Apache with the X Send File module https://tn123.org/mod_xsendfile/

mod_xsendfile is a small Apache2 module that processes X-SENDFILE
  headers registered by the original output handler.
If it encounters the presence of such header it will discard all
  output and send the file specified by that header instead using Apache
  internals including all optimizations like caching-headers and
  sendfile or mmap if configured.
It is useful for processing script-output of e.g. php, perl or any
  cgi.

A: header("Pragma: public");
header("Content-Type: application/xml");
header("Cache-Control: private",false);
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=file.ext;" );
readfile("file.ext");

A: You can have PHP send the file straight out the output, instead of into a var with readfile
EDIT
I would recommend instead to read and pass-through the data block at a time, which should perform better because it doesn't have to read the whole file before starting output.
if ($f = fopen($file, 'rb')) {
    while(!feof($f) and (connection_status()==0)) {
        print(fread($f, 1024*8));
        flush();
    }
    fclose($f);
}


text:
Q: How to convert a hexadecimal char into a 4-bit binary representation? I wish to compare a SHA-256 hash which is stored in u8[32](after being calculated in kernel-space) with a 64 char string that the user passes as string.
For eg. : User passes a SHA-256 hash "49454bcda10e0dd4543cfa39da9615a19950570129420f956352a58780550839" as char* which will take 64 bytes. But this has to be compared with a hash inside the kernel space which is represented as u8 hash[32].
The hash inside the kernel gets properly printed in ASCII by the following code:
int i;
u8 hash[32];

for(i=0; i<32; i++)
    printk(KERN_CONT "%hhx ", hash[i]);

Output :
"49 45 4b cd a1 0e 0d d4 54 3c fa 39 da 96 15 a1 99 50 57 01 29 42 0f 95 63 52 a5 87 80 55 08 39 "
As the complete hash is stored in 32 bytes and printed as 64 chars in groups of 2 chars per u8 space, I assume that currently one u8 block stores information worth 2 chars i.e. 00101111 prints to be 2f.
Is there a way to store the 64 bytes string in 32 bytes so that it can be compared?

A: Here is how to use scanf to do the conversion:
char *shaStr = "49454bcda10e0dd4543cfa39da9615a19950570129420f956352a58780550839";
uint8_t sha[32];
for (int i = 0 ; i != 32 ; i++) {
    sscanf(shaStr+2*i, "%2" SCNx8, &sha[i]);
    printf("%02x ", sha[i]);
}

The approach here is to call sscanf repeatedly with the "%2" SCNx8 format specifier, which means "two hex characters converted to uint8_t". The position is determined by the index of the loop iteration, i.e. shaStr+2*i
Demo.

A: Characters are often stored in ASCII, so start by having a look at an ASCII chart. This will show you the relationship between a character like 'a' and the number 97.
You will note all of the numbers are right next to each other. This is why you often see people do c-'0' or c-48 since it will convert the ASCII-encoded digits into numbers you can use.
However you will note that the letters and the numbers are far away from each other, which is slightly less convenient. If you arrange them by bits, you may notice a pattern: Bit 6 (&64) is set for letters, but unset for digits. Observing that, converting hex-ASCII into numbers is straightforward:
int h2i(char c){return (9*!!(c&64))+(c&15);}

Once you have converted a single character, converting a string is also straightforward:
void hs(char*d,char*s){while(*s){*d=(h2i(*s)*16)+h2i(s[1]);s+=2;++d;}}

Adding support for non-hex characters embedded (like whitespace) is a useful exercise you can do to convince yourself you understand what is going on.


text:
Q: What is an efficient way to concatenate lists? When we have two lists a and b, how can one concatenate those two (order is not relevant) to a new list in an efficient way ?
I could not figure out from the Scala API, if a ::: b and a ++ b are efficient. Maybe I missed something.

A: In Scala 2.9, the code for ::: (prepend to list) is as follows:
def :::[B >: A](prefix: List[B]): List[B] =
  if (isEmpty) prefix
  else (new ListBuffer[B] ++= prefix).prependToList(this)

whereas ++ is more generic, since it takes a CanBuildFrom parameter, i.e. it can return a collection type different from List:
override def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That = {
  val b = bf(this)
  if (b.isInstanceOf[ListBuffer[_]]) (this ::: that.seq.toList).asInstanceOf[That]
  else super.++(that)
}

So if your return type is List, the two perform identical.
The ListBuffer is a clever mechanism in that it can be used as a mutating builder, but eventually "consumed" by the toList method. So what (new ListBuffer[B] ++= prefix).prependToList(this) does, is first sequentially add all the elements in prefix (in the example a), taking O(|a|) time. It then calls prependToList, which is a constant time operation (the receiver, or b, does not need to be taken apart). Therefore, the overall time is O(|a|).
On the otherhand, as pst pointed out, we have reverse_::::
def reverse_:::[B >: A](prefix: List[B]): List[B] = {
  var these: List[B] = this
  var pres = prefix
  while (!pres.isEmpty) {
    these = pres.head :: these
    pres = pres.tail
  }
  these
}

So with a reverse_::: b, this again takes O(|a|), hence is no more or less efficient that the other two methods (although for small list sizes, you save the overhead of having an intermediate ListBuffer creation).

In other words, if you have knowledge about the relative sizes of a and b, you should make sure that the prefix is the smaller of the two lists. If you do not have that knowledge, there is nothing you can do, because the size operation on a List takes O(N) :)

On the other hand, in a future Scala version you may see an improved Vector concatenation algorithm, as demonstrated in this ScalaDays talk. It promises to solve the task in O(log N) time.


text:
Q: How to long poll the Azure service bus topic/subscription I cannot find clarification whether or not it's possible to use the long poll option with the topic/subscription model. It is possible with service bus queues but I'd have to create thousands of separate queues to enable each client to receive their own messages. So is it possible and if so can you point me toward an implementation example?
Thanks.

A: Actually I think just found the answer. In case anyone else is stuck the syntax is:
`serviceBusClient.receiveSubscriptionMessage(topicListener, subscriber,
{timeoutIntervalInS: 120 },
        function (error, message) {...});`

for 120 seconds but, you know, don't hard code magic numbers. This is limited to 230 seconds due to azure returning an error for http requests that receive no data in this period of time. If anyone knows a way to extend this timeout I'd appreciate the insight.


text:
Q: Can anyone give me an example of sdpTransform option in simplepeer Hi I've been searching for an example of how to use sdpTransform feature in simple peer and haven't found anything yet. Also is there any way to check what codecs were used in mediaStream object. Is there anyway to create custom sdp offer in SimplePeer.

A: the parameter must contain a function that returns the transformed sdp. Found this github issue as example. github


text:
Q: Is there a particular configuration for WebStorm/SQLite I start a project in Express/SQLite on WebStorm but my IDE don't find the sqlite3 Database class (sqlite3 library already install with NPM)
How can I configure the IDE to find sqlite3 Database class?
Code :
const express = require("express")
const sqlite3 = require("sqlite3")

const db = new sqlite3.Database("database.db")

Database is underlined in my IDE.

*

*WebStorm 2020.2

*Windows 10

*Node 12.18.3

*NPM 6.14.6

A: Installing TypeScript stubs should help: put cursor on sqlite3 in const sqlite3 = require('sqlite3'), hit Alt+Enter and choose Install TypeScript definitions for better type information to install typings - see https://www.jetbrains.com/help/webstorm/configuring-javascript-libraries.html#ws_jsconfigure_libraries_ts_definition_files


text:
Q: What does !function do or imply? Looking at the contents of a transpiled JavaScript file, from a site which appears to use MeteorJS, I saw some odd syntax with which I was unfamiliar. I didn't find any search results which explained what was going on.
!function(){var n = Package.meteor.Meteor, e=Package.meteor.global...

This appears many times and references a number of libraries (meteor-babel-helpers, for example), so I can guess that this has something to do with loading dependencies, but what does this accomplish?
In the spirit of testing, I opened up a console and prepended the ! to a simple function, and as expected it simply coerces the function to a false value. Why would I ever use this? Is it a way to force the function to be executed?


text:
Q: How to understand this code in terms of building and evaluating a stack? I was recently trying to solve a challenge on Hackerrank which asked us to figure out whether a string containing brackets (e.g. {}, (), and [] ) was balanced or not (source: https://www.hackerrank.com/challenges/balanced-brackets). I wanted to solve this using the following approach that also integrated the initial format Hackerrank provided:
import sys

def isBalanced(s):
     #insert code here

if __name__ == "__main__":
    t = int(raw_input().strip())
    for a0 in xrange(t):
        s = raw_input().strip()
        result = isBalanced(s)
        print result

I should also note that site has configured the following as being the standard input in order to test the functionality of the code:
3
{[()]}
{[(])}
{{[[(())]]}}

In order to get the following output:
YES
NO
YES

However, I didn't understand how to approach this code, chiefly because I did not understand why Hackerrank used the if __name__ == "__main__": clause, as I thought that this clause was only used if someone wanted their module to be executed directly rather than executed through being imported in another script (source: What does if __name__ == "__main__": do?). I also did not understand the for loop containing for a0 in xrange(t): since a0 is not used within the for loop for anything, so I'm really unsure how the standard input would be processed.
So I ended up looking up the solution on the discussion page, and here it is below:
lefts = '{[('
rights = '}])'
closes = { a:b for a,b in zip(rights,lefts)}

def valid(s):
    stack = []
    for c in s:
        if c in lefts:
            stack.append(c)
        elif c in rights:
            if not stack or stack.pop() != closes[c]:
                return False
    return not stack  # stack must be empty at the end

t = int(raw_input().strip())
for a0 in xrange(t):
    s = raw_input().strip()
    if valid(s):
        print 'YES'
    else:
        print 'NO'

This code also confuses me, as the writer claimed to utilize a data structure known as a "stack" (although it seems to be just a Python list to me). And although the writer removed the if __name__ == "__main__": statement, they retained the for a0 in xrange(t):, which I'm not sure how it processes the standard input's integer and corresponding strings.
Furthermore, although the isBalanced function confuses me because it returns not stack. In a hash comment on the return statement of the function, the writer also states the # stack must be empty at the end. What does that mean? And how could this list be empty if, during the clause if c in lefts:, the stack is appended with the character of the string that is being iterated in the for-loop. So why would the function return not stack? Wouldn't it be consistent to return True so that the function would act as a Boolean tester (i.e. would return true if a certain object adhered to certain criteria, and false if the the object did not)?
I am still relatively new to coding so there are a lot of principles I am not familiar with. Can anyone illuminate as to how this would work?

A: iam not sure how your code works ..  if name == "main": do?). just exlained where you use of Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value "main". If this file is being imported from another module, name will be set to the module's name


text:
Q: Calculate mean change in values one day later I have a dataframe with values and their timestamps. The data looks like this:
library(lubridate)
df <- data.frame(date1= dmy_hms(c("01.08.2019 12:11:32", "01.05.2019 10:01:17")),
                 value1= c(60, 70),
                 date2= dmy_hms(c("01.08.2019 12:41:38", "01.05.2019 11:51:17")),
                 value2= c(80, 60),
                 date3= dmy_hms(c("02.08.2019 12:01:09", "02.05.2019 10:11:34")),
                 value3= c(10, 40),
                 date4= dmy_hms(c("02.08.2019 12:41:38", "02.05.2019 11:51:17")),
                 value4= c(30, 80))
df
                date1 value1               date2 value2               date3 value3               date4 value4
1 2019-08-01 12:11:32     60 2019-08-01 12:41:38     80 2019-08-02 12:01:09     10 2019-08-02 12:41:38     30
2 2019-05-01 10:01:17     70 2019-05-01 11:51:17     60 2019-05-02 10:11:34     40 2019-05-02 11:51:17     80

I need to find out how the values changed after one day, caring only about the hour.
First row from data above: value1 (60) and value2 (80) are both recorded at 12:XX:XX o'clock at the same day, so the mean of 12:XX:XX o'clock for this day is 70. The mean of 12:XX:XX o'clock of the next day is 20. This means a change of -50 for the first row.
Second row: Here value1 is 70 at 10:XX:XX o'clock and one day later at 10:XX:XX o'clock the value is 40, so the change is -30. The change for 11:XX:XX o'clock from one day to the next is +20. So the mean change is (-30 + 20)/2 = -5.
Thus, my expected output is
mean_change <- matrix(c(-50, -5), ncol= 1)
mean_change
     [,1]
[1,]  -50
[2,]   -5

A: I would change the data structure into long. At least for me, this makes the task more intuitive.
Is this what you are looking for?
library(lubridate)
library(dplyr)

df <- data.frame(date1= dmy_hms(c("01.08.2019 12:11:32", "01.05.2019 10:01:17")),
                 value1= c(60, 70),
                 date2= dmy_hms(c("01.08.2019 12:41:38", "01.05.2019 11:51:17")),
                 value2= c(80, 60),
                 date3= dmy_hms(c("02.08.2019 12:01:09", "02.05.2019 10:11:34")),
                 value3= c(10, 40),
                 date4= dmy_hms(c("02.08.2019 12:41:38", "02.05.2019 11:51:17")),
                 value4= c(30, 80))
df

df.long <- as.data.frame(matrix(t(df), ncol=2, byrow=T))
df.long$Date <- as.Date(df.long$V1)
df.long$Time <-  format(as.POSIXct(df.long$V1) ,format = "%H")
df.long <- df.long[c(2:4)]
df.long$V2 <- as.numeric(as.character(df.long$V2))
daychange <- df.long %>% group_by(Date, Time) %>% summarise(d.h.mean = mean(V2))
daychange$Date <- strftime(daychange$Date,format = "%Y-%m")

daychange %>% group_by(Date, Time)  %>% mutate(change = d.h.mean-lag(d.h.mean))

# A tibble: 6 x 4
# Groups:   Date, Time [3]
Date    Time  d.h.mean change
<chr>   <chr>    <dbl>  <dbl>
  1 2019-05 10          70     NA
2 2019-05 11          60     NA
3 2019-05 10          40    -30
4 2019-05 11          80     20
5 2019-08 12          70     NA
6 2019-08 12          20    -50


text:
Q: 403 access denied on site variation root I moved a site from one server to another. Site is using variations.
On new server if I open page directly for e.g. http://myserver/en/Pages/default.aspx then it opens the page but if I just go to http://myserver OR http://myserver/Pages/VariationRoot.aspx then I get 403 access denied error.
I am both a farm admin and site collection administrator of this site. It's working fine on previous server. What could be the reason of this problem?

A: Ok I fixed it by enabling Anonymous access on web application and then disabling it again.


text:
Q: display lines at required position using stroke-dasharray I want to display 6 ticks at 0,20,40,60,80,100 from line x1="0" to x2="100" but last line is not display only first 5 are displayed.
I am using the following code

  <svg width="200">
    <line x1="0" x2="100" stroke-width="30" stroke="black" stroke-dasharray="1 19 1 19 1 19 1 19 1 19 1"/>
    <line x1="0" x2="100" stroke-width="15" stroke="black" stroke-dasharray="0 9 1 19 1 19 1 19 1 19 1 10"/>
  </svg>

Is there a way to accomplish without changing the line length. And what happens when dash-array has 0 in it? I was not sure

A: I think this might be the end result you are expecting

  <svg width="200">
    <line x1="0" x2="100" stroke-width="30" stroke="black" stroke-dasharray="1 19 1 19 1 19 1 19 1 19 1"/>
    <line x1="0" x2="80" stroke-width="15" stroke="black" stroke-dasharray="0 9 1 19 1 19 1 19 1 19 1 10"/>
  </svg>


text:
Q: for-loop to compare the two-dimensional array???Help! I am currently developing a game in which a player plays slot machine.The game is based on that the user stops in money, 100sek, 300sek or 500sek. Then the user makes a bet for each game. The one-armed bandit randomly spits out 3 different symbols in nine pieces fields. See figure:

The goal of the game is to obtain as many rows, columns, and diagonals as possible of the same symbol. In the above example that I made, obtained a profit when the upper and lower line have equal symbols, 2 simbles of the same in a row (aaa).
The following profit system is depending on the number of rows with the same symbol as:
•A series provides 2 * bet
•Two lines giving 3 * bet
•Three rows giving 4 * bet
Four rows gives 5 * bet
•Five lines gives 7 * bet
•Fully playing field gives 10 * bet
I dont know how to solve this problem with the paying? What code can I use? Should I use a for-loop? I'm new with c++ so I'm having trouble with this. I' been spending a lot of hours on this game and I just can't solve it. Please help me! Here's a small part of my code for now: I just want to compare the results. Can somone help me to compare the result after the previous goals I just described. Im thankfull for all the help I get!
 srand(time(0));
 char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};

 for (int i = 0; i < 3; ++i)
 {
 int r = rand() % 3;
 cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
 cout << "___|___|___\n";
 }

 //.....compare the two-dimensional array????

A: You can use comparison operators to check if elements in your matrix are equal to each other. You already know how to access each element of your matrix (game[r][0], etc.).
Now, all you have to do is check if elements along a row, diagonal, etc. are equal.
Additionally, you need to store your randomly generated symbols. You should create a new matrix (or 2D array) called, say, results.
E.g.
char results[3][3];

Now when you're displaying the slot machine results, store it in this 2D array:
for(int i = 0; i < 3; ++i)
{
   int r = rand() % 3;
   cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
   cout << "___|___|___\n";
   // Store
   for(int j = 0; j < 3; ++j) results[r][j] = game[r][j];
}

Above, I've just used another loop to store what you've displayed.
To get you started, here's how to check along a horizontal line for all 3 rows of your matrix:
bool horz_equal[3];
for(int r = 0; r < 3; ++r)
{
  horz_equal[r] = (results[r][0] == results[r][1] && results[r][1] == results[r][2]);
}

Additionally, you should think about the method you have for randomly generating symbols. There are better ways!

A: I'm not sure that I understand your requirements perfectly but have decided to interpret them as best I can. This code does what I think you want. I've used 0, 1 and 2 as the characters but you can easily swap them for whatever you want in the output. I've also not bothered calculating the payout since you've written the pseudo-code for that in your question.
int game[3][3];
int x, y;
int lines = 0;

// select a random grid
srand(time(0));
for(x = 0; x < 3; x++) {
    for(y = 0; y < 3; y++) {
        game[x][y] = rand() % 3;
        cout << game[x][y];
        if (y == 2)
            cout << '\n';

    }
}

// count horizontal lines
for (y = 0; y < 2; y++)
    if (game[0][y] == game[1][y] && game[0][y] == game[2][y])
        lines++;

// vertical
for (x = 0; x < 2; x++)
    if (game[x][0] == game[x][1] && game[x][0] == game[x][2])
        lines++;

// diagonal
if (game[0][0] == game[1][1] && game[0][0] == game[2][2])
    lines++;
if (game[0][2] == game[1][1] && game[0][2] == game[2][0])
    lines++;

cout << lines << " lines\n";

By the way that's my first ever c++ program.


text:
Q: How do I use the same functions on different data frames? I have 30 data sets for everyday of month and i want to analysis them individually, giving me one result value for every day. Is it possible to loop the data sets, that operations are conducted on each data set and 30 resultant values are complied together in a new data frame.
More specifically, i have 96 readings for every day and for example i want to know there mean, max and min. So, using apply i can get it for 1 day then i will have to do it 30 times or i can create a function and call it 30 times. is there any simpler way around repetitive work.

A: This is pretty easy.  Set your working directory to where the files are.  The get the files with list.files() and store them.  Then write a function which reads in a file and returns a data.frame with the info you want.  Then use sapply on the list of files calling the function you made, e.g.:
setwd("C:\some_dir")
days = list.files()
someFunction = function(day){
    data = read.csv(day)
    return(data.frame(Mean=mean(data),SD=sd(data)))
}
sapply(days,someFunction)


text:
Q: An error has occured like this "local variable 'words' referenced before assignment" already tried putting words global I'm getting this error:

An error has occured like this "local variable 'words' referenced before assignment"

How can I solve it? This is my code:
def bag_of_words(sentence):
    sentence_words = clean_up_sentence(sentence)
    bag = [0] * len(words)
    for w in sentence_words:
        for i, words in enumerate(words):
            if word == w:
                bag[i] = 1
    return np.array(bag)

A: In this line:
bag = [0] * len(words)

you are using the variable words but it doesn't exist in this context


text:
Q: Ruby (rails) - including module in model I'm missing something stupid.  Help?
lib/api.rb
require 'httparty'

module API
  def self.call_api(query)
    base_url = "http://myapi.com"
    return HTTParty.get("#{base_url}/#{query}.json")
  end
end

models/job.rb
require 'api'

class Job
  include API

  def self.all(page=1)
    self.call_api "jobs?page=#{page}"
  end

end

Job::all
  NoMethodError: undefined method `call_api' for Job:Class

If I move my "call_api" directly into the Job class, it works. What am I missing?

A: I believe what you need is to define call_api as an instance method in your module, then extend API instead of include API. In general, include is for instance methods and extend is for class methods.

A: The other answers have pointed out your issue you should have extend instead of include:
class Job
  extend API

You might also like to consider using the following pattern which aside from being useful can also help to alleviate the confusion, since you can tell straight away that your class methods are in the ClassMethods module while your instance methods are directly in the MyModule module.
module MyModule

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def my_class_method
    end
  end

  def my_instance_method
  end
end

This uses Ruby's included callback (which is fired every time a module in included in a class), we redefine the callback (which normally doesn't do anything), to extend the class in which the module was included with the ClassMethods sub module. This is a very common metaprogramming pattern in Ruby. If you use this pattern you no longer have to worry about extend, just use include:
class MyClass
  include MyModule

then:
MyClass.my_class_method
MyClass.new.my_instance_method

You can also take this pattern a little bit further:
module MyModule
  include ClassMethods

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def my_class_method
    end
  end

  def my_instance_method
  end
end

Notice that the parent module includes its child ClassMethods module directly. This way  my_class_method becomes both an instance and a class method:
class MyClass
  include MyModule

MyClass.my_class_method
MyClass.new.my_class_method

You have to be a bit careful if you do that about how you code your method in the ClassMethods child module. But I have found this pattern extremely handy on occasion.

A: The problem is that you are defining the method call_api directly on the API module, rather than on the inheritance chain of the Job class.
You can call API.call_api just fine, but the problem is that API's "instance methods" are not part of the inheritance chain (not instance methods defined for the receiver of the included module, but API's singleton instance methods - remember API is an instance of the class Module with its own methods)
This is way of doing what you are trying to do:
module API
  def self.included(base)
    def base.call_api(...)
      ...
    end
  end
end

but there may be cleaner ways using extend rather than include on your classes.


text:
Q: 2 DataGridView ao clicar no primeiro jogar o registro no 2? Estou usando WinForms, já tenho um Gridview populado, agora preciso que quando o usuário dar um duplo clique sobre determinada linha, ele retire esse registro do primeiro grid e jogue o mesmo registro no segundo grid.
Se for possível poderia fazer isso com mais de 1 registro por vez?
Exemplo aperto o Shift e vou clicando nos registro logo após clico no botão e ele manda para o segundo Grid.

A: Para o botão de mover os registros podes fazer assim:
var selectedRowCount = dataGridView1.SelectedRows.Count;
if (selectedRowCount > 0)
    for (int i = 0; i < selectedRowCount; i++)
    {
        var obj = dataGridView1.SelectedRows[0].DataBoundItem;
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
        pessoaBindingSource2.Add(obj);
    }

Note que eu tive que armazenar a quantidade de registros selecionados antes de entrar no for, pois o DataGridView sempre seleciona o próximo elemento quando um é eliminado... se não for assim, o que acontece é que acaba se excluindo tudo dali para baixo.
Para o duplo clique é muito mais fácil:
if (dataGridView1.SelectedRows.Count == 1)
{
    var obj = dataGridView1.SelectedRows[0].DataBoundItem;
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    pessoaBindingSource2.Add(obj);
}

É necessário configurar de antemão, o data-binding de cada um dos DataGridView. Eu criei um BindingSource para cada grid.
EDIT
Como configurar o BindingSource:

*

*

*

*
Para preencher a BindingSource basta iterar os elementos da lista e adicioná-los ao BindingSource:
foreach (var item in minhaLista)
    pessoaBindingSource1.Add(item);

Ou assim, como meu interlocutor me ensinou num dos comentários:
new BindingSource() { DataSource = lista };

A:     private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.RowCount > 0)
        {
            CODIGO = Convert.ToInt32(dataGridView1[0,   dataGridView1.CurrentRow.Index].Value);
            CLIENTE = dataGridView1[1, dataGridView1.CurrentRow.Index].Value.ToString();

   dataGridView2.Rows.Add(CODIGO,CLIENTE );

        }
    }


text:
Q: Lock wait timeout exceeded on INSERT I have a table Contact on MySQL 5.7 (running on AWS RDS Aurora) that looks like this:
CREATE TABLE Contact (
    id BIGINT NOT NULL AUTO_INCREMENT,
    email VARCHAR(255) NOT NULL UNIQUE,
    firstname VARCHAR(255) NOT NULL,
    lastname VARCHAR(255) NOT NULL,
    createdAt DATETIME,
    updatedAt DATETIME
);

The table has 4 other tables connected to it via Contact.id but the relation is not enforced with a foreign key.
The production table contains over 10M rows. I recently wrote a NodeJS script that grabs a list of contact ids and runs DELETE queries on the Contact table. The important part looks like this:
await this.query("DELETE FROM AssociatedTableA WHERE contactId=?", contactId);
await this.query("DELETE FROM AssociatedTableB WHERE contactId=?", contactId);
await this.query("DELETE FROM AssociatedTableC WHERE contactId=?", contactId);
await this.query("DELETE FROM AssociatedTableD WHERE contactId=?", contactId);
await this.query("DELETE FROM Contact WHERE contactId=?", contactId);

The above part runs for every contact id that is parsed from a series CSV files containing 2.5M rows. Multiple worker processes parse the CSV files and execute the snippet.
It's not part of a transaction and there are no explicit locks
While this script is running the application is live on production and users are registering Contacts. After a few deletes though, INSERTS were blocked with the following error:
ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded - try restarting transaction

No new contact could be added, even after stopping all worker processes and restarting the database. I had to put the app on maintenance mode and kill any remaining connections to MySQL.
So my question is, what type of lock could possibly block an Insert query? Isn't MySQL InnoDB supposed to never lock the entire table?

A: First of all, Aurora is not MySQL. It has a lot of code in common, but they rewrote a lot particularly in the storage engine, which is where row-level locking is implemented. Aurora is not open-source, and we can't run it other than in the managed Amazon environment, so it's hard to test or debug. So who knows what locking behavior of InnoDB they have changed?
For InnoDB, INSERTs can be blocked by gap locks, next-key locks, auto-increment locks, or metadata locks. In my experience, the former two of those are most likely to give the ER_LOCK_WAIT_TIMEOUT error if there's an outstanding lock blocking them.
See https://dev.mysql.com/doc/refman/5.7/en/innodb-locking.html#innodb-gap-locks


text:
Q: Django view/method called repeatedly without any actual calls for i in xrange(1,NUM_USERS+1):
            print i
            private = RSA.generate(3072,Random.new().read)
            public = private.publickey()
            new_user = User(public_rsa=public.exportKey(), secret_rsa=private.exportKey())
            new_user.save()

In the above loop, I have given the value of NUM_USERS=100 but the loop is iterating till 200 instead of 100. What might be the possible reason for this ?
EDIT:
I am so sorry guys, I accidentally figured out that the whole python method is being called twice, I don't know why though, so I will describe in detail. I am writing a django based server side, which has methods as following:
def index(request):
    return HttpResponse("CREST Top Dir: " + PROJECT_ROOT)

def server_setup(request):
    try:
        process = subprocess.check_output(BACKEND+"mainbgw setup " + str(NUM_USERS), shell=True,\
                                          stderr=subprocess.STDOUT)

        for i in xrange(1,NUM_USERS+1):
            print i

Now what happens is when I call the server_setup view sometimes it executes more than once. Similarly if I call index view sometimes server_setup is also called in simultaneously. So the problem is not with xrange but with method calling. What could be the reason for this problem ?

A: Check if NUM_USERS is 100.
for i in xrange(1,NUM_USERS+1):

    print 'NUM_USERS:', NUM_USERS  # check it

    print i
    private = RSA.generate(3072,Random.new().read)
    public = private.publickey()
    new_user = User(public_rsa=public.exportKey(), secret_rsa=private.exportKey())
    new_user.save()


text:
Q: How do you get a package manager in the Minikube VM (KVM2)? I've created a simple kubernetes cluster with minikube using minikube start --driver=kvm2 and then ssh'd into the VM with minikube ssh.
I'm using a volume mount between the minikube VM and some pods so that I can share a large dataset. However, I need to install python to download this dataset (onto the VM). Normally I would use apt-get to install python, but the VM does not have this installed. I can't install apt-get using dpkg either, because dpkg also doesn't exist.
The output of uname -r is 4.19.114 and the output of cat /etc/os-release is:
NAME=Buildroot
VERSION=2019.02.11
ID=buildroot
VERSION_ID=2019.02.11
PRETTY_NAME="Buildroot 2019.02.11"

Does anybody know how I install a package manager inside the VM?

A: There is a way to have custom configuration with the minikube image but that would require to configure the image.  This document show how to build the image and modify buildroot components.  You can add kernel modules or some third-party packages. You might also want to check out this case whereas tcpdump is need into minikube image.
Alternative way to to have mount the files using the minikube mount:
minikube mount <source directory>:<target directory>

or use one of the local driver mounts (KVM does not support this at the moment):

| Virtualbox  | Linux   | /home | /hosthome
| Virtualbox  | macOS   | /Users | /Users
| Virtualbox  | Windows   | C://Users | /c/Users |
| VMware Fusion  | macOS   | /Users | /Users

Third option is to use initContainer

Specialized containers that run before app containers in a Pod. Init containers can contain utilities or setup scripts not present in an app image.

You can use init container to pre-populate some volume with data you require for your pod/deployment.  Here is a good document that shows how to do that.


text:
Q: Changing dtype object to int I have a column named property size in a dataset I'm working on. The values are in m^2.This is an example of a value in the column (100m^2).
How can I change the values in this column from dtype object to int. So I basically want to remove the m^2 from the values.

A: If it's always the same unit, you can just use string slicing to cut it off:
import pandas as pd

df = pd.DataFrame(["1m^2", "20m^2"], columns=["area"])

df["area"] = df["area"].str[:-3].astype(int)

results in:
   area
0     1
1    20


text:
Q: Solving equation involving cdf of standard normal distribution How do I solve the following equation for $n$ using Maple:
$$2\Phi\left(\frac{0.01}{\sqrt{\frac{\pi^{5}-2\pi^{4}}{2\pi^{2}n}}}\right)-1=0.95,$$
where $\Phi(x)$ denotes the cdf of a standard normal distribution.
Thanks in advance

A: I don't have a working Maple at home, so based on Distributions:Normal and solve, try
with(Statistics)
solve( 2 * PDF( RandomVariable(Normal(0,1)), 0.01/sqrt((Pi^5 - 2 Pi^4)/(2*Pi^2 * n)) ) - 1 = 0.95, n)

Now maybe Maple's solve doesn't know how or recognize that it can apply the inverse CDF, norminv, so we have to do that manually...
with(Statistics)
first = solve( 2*phi - 1 = 0.95, phi)
solve( 0.01/sqrt((Pi^5 - 2 Pi^4)/(2*Pi^2 * n)) = norminv(first), n)

Again, I don't have Maple handy, so these may require a few rounds of tweaking to get right, so feel free to comment with progress or results.

A: The explicit solution is
$$n=10000\dfrac{\pi^{3}-2\pi^{2}}{2}\left(\Phi^{-1}(0.975)\right)^2\approx216400$$
using $\Phi^{-1}(0.975)=1.9600$ from a table.

A: In Maple the inverse of the CDF is implemented as the Quantile command from the Statistics package. For example,
restart; with(Statistics):
Quantile( RandomVariable(Normal(0,1)), 0.975 );

             1.95996398453944

If you prefer you can skip several easy steps and directly write down the reformulated equation,
restart;
with(Statistics):
X:=RandomVariable(Normal(0,1)):
0.01/sqrt((Pi^5-2*Pi^4)/(2*Pi^2*n))=Quantile(X,0.975):
fsolve(%);

                216409.8864

Or it can all be done starting from the originally supplied equation, with no mental rearrangement of the equations required.
restart;
with(Statistics):
X:=RandomVariable(Normal(0,1)):
eq:=2*Phi(0.01/sqrt((Pi^5-2*Pi^4)/(2*Pi^2*n)))-1=0.95:
new1:=isolate(eq,indets(eq,specfunc(anything,Phi))[1]):
new2:=eval(map((Phi@@(-1)),new1),
           (Phi@@(-1))=(p->Quantile(X,p))):
fsolve(new2,{n});

             {n = 216409.8864}

I'll break down some of those steps, for explanation.
restart;
with(Statistics):
X:=RandomVariable(Normal(0,1)):

I'll start with the eq as given.
eq:=2*Phi(0.01/sqrt((Pi^5-2*Pi^4)/(2*Pi^2*n)))-1=0.95:

The only function call to Phi, in eq,
indets(eq,specfunc(anything,Phi))[1];

    Phi(.1e-1*2^(1/2)*Pi/(1/n*(Pi^5-2*Pi^4))^(1/2))

Isolating eq for that call to Phi
new1 := isolate(eq,indets(eq,specfunc(anything,Phi))[1]);

    Phi(.1e-1*2^(1/2)*Pi/(1/n*(Pi^5-2*Pi^4))^(1/2))
    = .9750000000

Applying the inverse of Phi to both side of that new equation.
map((Phi@@(-1)),new1);

    .1e-1*2^(1/2)*Pi/(1/n*(Pi^5-2*Pi^4))^(1/2)
    = (Phi@@(-1))(.9750000000)

The same as previous, but following up by replacing the generic inverse Phi call with a call to Quantile (using R.V. X).
new2:=eval(map((Phi@@(-1)),new1),
           (Phi@@(-1))=(p->Quantile(X,p)));

    .1e-1*2^(1/2)*Pi/(1/n*(Pi^5-2*Pi^4))^(1/2)
    = 1.95996398453944232

Solving that, numerically,
fsolve(new2,{n});

           {n = 216409.8864}

or, if preferred,
fsolve(new2,n);

               216409.8864


text:
Q: Adjacent JSX elements must be wrapped in an enclosing tag with bootstrap columns I am using React Bootstrap and trying to loop through content which is in two separate columns like this:
  <Container>
    <Row>
      {this.state.products.map(product => (
      <Col md={8}>

{product.name}

{product.description}

      </Col>
      <Col md={4}>

{product.price}

      </Col>
      ))}
    </Row>
  </Container>

I have my closing  tags so not sure why I a getting the error?

A: The return of your map also needs to be wrapped in a containing tag, you can use React fragment tags <>  https://reactjs.org/docs/fragments.html#short-syntax
<Container>
    <Row>
      {this.state.products.map(product => (
         <>
           <Col md={8}>

{product.name}

{product.description}

           </Col>
          <Col md={4}>

{product.price}

          </Col>
      </>
      ))}
    </Row>
  </Container>

A: Try this:
The problem is, your map on the products Array is returning two components of type Col, and React only accepts one returned element.
Explained here.
Also, <React.Fragment></React.Fragmint> Component Wrapper can also be written with this syntax: <></>
  <Container>
    <Row>
      {this.state.products.map(product => (
        <React.Fragment>
          <Col md={8}>

{product.name}

{product.description}

          </Col>
          <Col md={4}>

{product.price}

          </Col>
        </React.Fragment>
      ))}
    </Row>
  </Container>


text:
Q: need help in this ( mute picture box problem ) iam working in media player for my own every thing in code is working but if i pressed on mute picture box to mute sound and re-open another video or music file the sound is playing and the sign in mute picture box is show that iam in mute mode
this is the code for mute picture box :
Private Sub Volume_PictureBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Volume_PictureBox.Click
    Try
        If MuteBol = False Then
            AxWindowsMediaPlayer1.settings.mute = True
            MuteBol = True
            Volume_PictureBox.Image = My.Resources.Muted_Volume_Hover'mute picture
            MuteToolStripMenuItem.Checked = True
            Me.ToolTip1.SetToolTip(Volume_PictureBox, "UnMute")

        ElseIf MuteBol = True Then
            AxWindowsMediaPlayer1.settings.mute = False
            MuteBol = False
            Volume_PictureBox.Image = My.Resources.Volume_Hover'un-mute picture
            MuteToolStripMenuItem.Checked = False
            Me.ToolTip1.SetToolTip(Volume_PictureBox, "Mute")
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message & ex.Source)
    End Try
End Sub

A: Not to answer for Hans, but if what you need is for newly opened songs to be muted if mute is already selected, it looks like you just need something simple, like:
If [a new song is opened or the current file changes or something like this]
    If MuteBol = True Then AxWindowsMediaPlayer1.settings.mute = True
End If

Seems simple enough, unless this isn't what you're looking for. Hope this works!


text:
Q: Ecto - casting an array of strings to integers in a fragment In an Ecto query I'm running against Postgres (13.6), I need to interpolate a list of ids into a fragment - this is generally not something I have a problem with, but in this case, the list of ids is being received as a list of strings that need to be cast to integers (or, more specifically, BIGINT). The query that I think that I need is as follows, which the troublesome bit being ANY(ARRAY?::BIGINT[]):
ModelA
|> where(
  [ma],
  fragment(
    "EXISTS (SELECT * FROM model_b mb WHERE mb.a_id = ? AND mb.c_id = ANY(ARRAY?::BIGINT[]))",
    a.id,
    ^c_ids
  )
)

where c_ids would be a list like ["1449441579", "2345556834"]
However, when I run this, I get the error
(Postgrex.Error) ERROR 42703 (undefined_column) column "array$4" does not exist

referring to the generated SQL
ANY(ARRAY$4::BIGINT[])

Of course, I could convert the array of c_ids to integers beforehand in my app code, but I'd like to see if I can get it to cast in the query itself.
Writing the fragment in straight SQL works out just fine:
SELECT * FROM model_b mb WHERE mb.a_id = 1 AND mb.c_id = ANY(ARRAY['1449441579', '2345556834']::BIGINT[]);

What is the idiomatic way to get this kind of array casting to work in an Ecto fragment? Many thanks.

A: Just to codify my comment, I would do the integer conversion before the query.  You can use the dynamic macro to support IN queries:
import Ecto.Query

alias YourApp.Repo
alias YourApp.SomeSchema, as: ModelA

strs = ["1", "2", "3"]

ids = Enum.map(strs, fn x -> String.to_integer(x) end)

conditions = dynamic([tbl], tbl.id in ^ids)

Repo.all(
  from ma in ModelA,
  where: ^conditions
)
|> IO.inspect()

A: I did find a post that led me to a potential solution here - https://elixirforum.com/t/interpolating-lists-into-ecto-query-fragment-1/16690/7 - however, I'm not convinced that this is optimal for me.
By using Enum.join and converting my initial array of strings into a string and then allowing Postgres to cast that string to an array of bigints, it worked out:
ModelA
|> where(
  [ma],
  fragment(
    "EXISTS (SELECT * FROM model_b mb WHERE mb.a_id = ? AND mb.c_id = ANY(ARRAY?::BIGINT[]))",
    a.id,
    ^Enum.join(c_ids, ",")
  )
)

So I'm posting it here for reference and because it does "work", but I feel sort of silly doing this, because I specifically was trying to avoid processing the list before passing it to PG... so yeah I'd still really like to hear about the "right" way to do this...


text:
Q: HDInsight word count map reduce program stuck at mapper 100% and reducer 0% I am new to Hadoop and I have a very similar problem as posted here. Only thing is OP runs hadoop on linux where as I am  running it on Windows.
I have installed Hadoop Azure HDInsight Emulator on my local machine. When I run a simple  word count program. Mapper jobs runs perfectly 100% but Reduce job gets stuck at 0%.

I tried debugging it as suggested by Chris (In response to this que) and found the problem with hostname on which reducer jobs run (which was the exact problem as of OP)

Reduce is not running on localhost instead it runs on some hostname 192.168.17.213 which is not getting resolved and reducer can not progress from there.
These are error logs
copy failed: attempt_201402111921_0017_m_000000_0 from 192.168.17.213
2014-02-12 01:51:53,073 WARN org.apache.hadoop.mapred.ReduceTask:
java.net.ConnectException: Connection timed out: connect

OP got that issue resolved by chaning \etc\hosts file setting to localhost.
But that seems to be a linux config.. How do I set my hostname to localhost in my Hadoop Azure HDInsight Emulator?

A: There is an article showing you how to run the word counting MapReduce program on HDInsight emulator.  The article is Get started with HDInsight emulator located at http://www.windowsazure.com/en-us/documentation/articles/hdinsight-get-started-emulator/.


text:
Q: Entity Framework mapping two table columns to same related table Key I'm in a situation where I have a table called Elements. Now I'm creating a table called Divergences that will store basically pairs of Elements. The purpose of Divergence is to check if two Elements have diverging answers.
Element               Divergence
---------             ----------
ElementId             ElementId1
                      ElementId2

In the above table schema, ElementId1 and ElementId2 are Foreign Keys mapping to ElementId in Elements table and form the composite primary key for the Divergence table.
I use Database First approach where I create the tables in SQL Server Management Studio and later I do a Update Model from Database... in Entity Framework Designer.
The problem I'm facing is that when EF Designer generates the model it creates 2 sets ICollection<Element> inside the Element class namely Elements and Elements1.

This doesn't give me a Divergences DbSet.
What I'd want to have is a Divergence class where I'd do something like this in code:
Divergence d = new Divergence();
d.Element1 = element1;
d.Element2 = element2;

Database.Divergences.Add(d);
Database.SaveChanges();

and later on:
Element e = Database.Elements.Single(e => e.ElementId == 7);

var divergences = e.Divergences;

I tried adding a new column to the Divergence table like this:
Element               Divergence
---------             ------------
ElementId             DivergenceId
                      ElementId1
                      ElementId2

This correctly leads to a 1 <-> * relationship in Entity Framework Designer. I finally get a Divergences DbSet but DivergenceId property is useless in the code and I still get the 2 sets in the Element class. It's important to note that ElementId1 and ElementId2 still form the composite primary key.
What do you think is the correct way of mapping this specific situation? Thanks for the input.

A: Instead of...
Divergence d = new Divergence();
d.Element1 = element1;
d.Element2 = element2;

Database.Divergences.Add(d);
Database.SaveChanges();

... you could actually use:
element1.Elements = new List<Element>();
// if that collection isn't already instantiated, for example in the constructor
element1.Elements.Add(element2);

Database.SaveChanges();

This will create exactly the same SQL INSERT statements to the link table without the need of having a Divergence entity. (Change tracking will recognize that you changed the relationship by adding an item to the collection and infer the necessary SQL commands from this change. element1 and element2 must be attached to the context in state Unchanged, but that is also required for your original code in order to work correctly.)
Also, instead of ...
Element e = Database.Elements.Single(e => e.ElementId == 7);
var divergences = e.Divergences;

... you can fetch the columns from the Divergences table like so:
var divergences = Database.Elements.Where(e => e.ElementId == 7)
    .SelectMany(e1 => e1.Elements.Select(e2 => new
    {
        ElementId1 = e1.ElementId,
        ElementId2 = e2.ElementId,
    }))
    .ToList();

So, you will get your desired results without the Divergence entity and honestly I would use it this way. I'm not aware of a way to force EF to create that entity with database first approach, unless you introduce some artificial additional column like you did. If there is a way it is probably a hack or more difficult to achieve and maintain than just working with EF's default, that is without a Divergence entity.
However, you could consider to remove one of the collections (just delete it in the model surface). Having both is a bit confusing in this model in my opinion. Or at least rename them to SourceElements and TargetElements for example :)


text:
Q: MERN stack authentication and authorization I am creating a MERN(Mongo, Express, React-redux, Node) stack app where I am adding authentication, authorization and access control features. I know how to implement the authentication service but don't know how to implement the authorization and access control. For example: when user login then he will be able to create, edit and delete todo on his dashboard and no one will be able to see or edit that. How can I implement that? Any links, code or help would much be appreciated. Thanks a bunch!

A: This is a great question. And the answer is long :-) I just replied to a similar question here so you could start reading that.
TL;DR
What you are looking for is called externalized / dynamic authorization management. The formal model is called Attribute-Based Access Control (abac / Wikipedia). It was formalized by the Nat'l Institute of Standards & Technology (NIST).
More in depth
You stated:

When user login then he will be able to create, edit and delete todo on his dashboard and no one will be able to see or edit that.

You need to write a policy using attributes that will allow users to do such things and prevent them from doing other things. If we rewrite your requirement, it becomes:

*

*A user can create, edit, and delete a TODO item on a dashboard they own.

*No one can see items on a dashboard they do not own.

Looking at the requirements, you realize you have:

*

*a subject (or user) with their attributes (e.g. role, department...)

*an action (e.g. view, edit, delete...)

*an object or resource (the "TODO" item) and its container (the dashboard).

This means you can start rewriting your requirement in terms of attributes. This becomes:

*

*A user can do action == "view" on object of type == "TODO" if user.username == object.dashboard.owner
You can then add:

*

*deny all access if object.dashboard.owner != user.username
The language to write such policies is called ALFA (alfa / Wikipedia, the abbreviated language for authorization. It's a standard defined by OASIS XACML.
Once you've defined your policies, you'll need to deploy them, run them, and enforce them. This is where the ABAC architecture kicks in:

*

*Policy Administration Point (PAP): where policies are written

*Policy Decision Point (PDP): where policies are run / executed

*Policy Enforcement Point (PEP): where policies are enforced - this could be an API gateway, an interceptor...

*Policy Information Point (PIP): where additional metadata & attributes can be retrieved

The question then becomes: where do you want to enforce? What does your MERN architecture look like? Do you want to authorize:

*

*in the web UI? (functional authZ)

*in the API layer (transactional authZ)

*in the data layer (data-centric authZ / filtering)

For instance, do you want to filter data from MongoDB and only show allowed results? Do you want to apply authorization on the API layer? API gateways (e.g. Kong) can help you achieve that with authorization plugins e.g. Axiomatics-Kong.
There are open-source and commercial ABAC implementations and a standards body too (I'm the editor of some of the specs such as the JSON/REST request/response)

*

*A Java Policy Enforcement Point in JSON/REST - open source

*AuthZForce - an open-source PDP

*Axiomatics - a commercial ABAC platform


text:
Q: SyntaxError: non-keyword arg after keyword arg python I'am working a project about hot clouds volcano mountain simulation with Titan2D v4.0.0 but I got error when I try to run the simulation.py
sim.setGIS(
   gis_format='GIS_GRASS',
   gis_main='/home/dinar/Downloads/titan2d-v4.0.0/grass',
   gis_sub='newLocation',
   gis_mapset='PERMANENT',
   gis_map='merapi8m.grass',
   gis_vector=None,
   region_limits==(417661e+05, 9143861e+06, 4611590e+05, 9176061e+06)
)

it said non-keyword arg after keyword arg python

A: It was a human error, I didn't check the syntax.
Here is the correct one
sim.setGIS(
       gis_format='GIS_GRASS',
       gis_main='/home/dinar/Downloads/titan2d-v4.0.0/grass',
       gis_sub='newLocation',
       gis_mapset='PERMANENT',
       gis_map='merapi8m.grass',
       gis_vector=None,
       region_limits=[4.17661e+05, 9.143861e+06, 4.611590e+05, 9.176061e+06]
)