text:
Q: Python EEL + wxpython: open "parentless" file dialog in front of all other windows and programs I am developing an EEL project, and I needed to create a file dialog on the python side in order to preprocess data before sending it to javascript.
I tried to use tk.filedialog.askopenfilename, but that somehow froze the javascript event loop.
I found an answer on StackOverflow that used wxpython to create a non-blocking file picker. However, when I run the code below, the file picker always starts minimized.
However, once you use the file picker once, it works perfectly the second time.
Any help appreciated.
import base64
import json
from tkinter import Tk
Tk().withdraw()
from tkinter.filedialog import askopenfilename

import PIL.Image
import eel
import numpy as np
import wx

# Reusable wxpython App instance for the creation of non-blocking popup dialogs
app=wx.App(None)

eel.init("public")

def encode(bts):
    return base64.b64encode(bts)

def array_to_json(array):
    return json.dumps({
        "shape": list(array.shape),
        "dtype": str(array.dtype),
        "data":list(np.ravel(array).astype(float)) # not efficient but quite clean
    })

@eel.expose
def load_image(path):
    return array_to_json(np.asarray(PIL.Image.open(path)))

@eel.expose
def pick_image():
    # return askopenfilename()
    """ --- Adapted from https://stackoverflow.com/a/59177064/5166365"""
    style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.STAY_ON_TOP | wx.DIALOG_NO_PARENT | wx.MAXIMIZE
    dialog = wx.FileDialog(None, "Open File", wildcard="*", style=style)
    dialog.Iconize(False)
    dialog.Maximize()
    dialog.Raise()
    path = ""
    if dialog.ShowModal() == wx.ID_OK:
        path = dialog.GetPath()
    else:
        path = ""
    return path
    """ --- """

eel.start("index.html")

A: I was able to get it working with the following code. I used a regular window instead of a wx.Dialog or similar class.
class FancyFilePickerApplication:

    def __init__(self):
        self.app = wx.App()
        self.frame = wx.Frame(None,title="Fancy File Picker")
        self.build_ui()
    #@private
    def build_ui(self):

        self.vertical_sizer = wx.BoxSizer(wx.VERTICAL)
        self.control_panel = wx.Panel(self.frame,wx.ID_ANY)
        self.horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.control_panel.SetSizer(self.horizontal_sizer)
        self.frame.SetSizer(self.vertical_sizer)
        self.dir_ctrl = wx.GenericDirCtrl(self.frame,wx.ID_ANY,wx.EmptyString,wx.DefaultPosition,wx.Size(400,300))
        self.vertical_sizer.Add(self.dir_ctrl,wx.SizerFlags().Expand())
        self.vertical_sizer.Add(self.control_panel,wx.SizerFlags().Expand())
        self.scale_factor_label = wx.StaticText(self.control_panel,wx.ID_ANY,"Scale Factor: ")
        self.scale_factor_textbox = wx.TextCtrl(self.control_panel,wx.ID_ANY)
        self.open_button = wx.Button(self.control_panel,wx.ID_ANY,"Open")
        self.horizontal_sizer.Add(self.scale_factor_label,wx.SizerFlags().Expand())
        self.horizontal_sizer.Add(self.scale_factor_textbox,wx.SizerFlags().Expand())
        self.horizontal_sizer.Add(self.open_button,wx.SizerFlags().Expand())
        self.open_button.Bind(wx.EVT_BUTTON,lambda evt:self.submit())

        self.frame.Bind(wx.EVT_CLOSE,self.cancel)

    def open(self, file_picked_callback):
        self.file_picked_callback = file_picked_callback
        self.frame.Fit()
        self.frame.Center()
        self.frame.Show()
        self.frame.Raise()
        self.frame.ToggleWindowStyle(wx.STAY_ON_TOP)
        self.app.MainLoop()

    #@private
    def submit(self):
        filepath =self.dir_ctrl.GetFilePath()
        scale_factor_text = self.scale_factor_textbox.GetValue()
        scale_factor = 1.0 if not scale_factor_text.strip() else float(scale_factor_text)
        self.file_picked_callback(filepath,scale_factor)
        self.frame.Destroy()

    #@private
    def cancel(self,evt):
        self.file_picked_callback("",0)
        self.frame.Destroy()


text:
Q: How can one use git-flow effectively on a project in which more than one major version is being maintained? I've migrated several of my projects over to the git flow work flow, and I'm loving it.  However, I haven't found a best practice that keeps things flowing as smoothly when working with a project in which more than one major version is maintained at a time.
Specifically, I'm not maintaining a "free version" and a "paid version" or any other parallel model, I'm talking about a project in which Version 1 gets released, and remains supported with minor versions (1.1, 1.2, etc.) until Version 3 has been released, at which point 2 and 3 would be maintained, until 4 is released...you get the idea.
How have you, or would you, maintain two or more supported versions of a project at once in a gitflow workflow?

A: man gitworkflows, the grand daddy of the 'git flow' workflow, describes general git workflow guidelines; the use of pu, next, master and maint branches; and how maint is managed. If you have multiple maintenance branches, you can name them, for instance, maint/1.x, maint/2.x and so forth.
The key is not so much how to use the git commands, but how to build a reasonable process. Decide what things are important to you (ease of backporting?) and build (and document) a workflow that satisfies those constraints.

A: Basically, you would duplicate the master, release, and develop branches for every major version you are maintaining.  How they interact with each other remains the same.  For feature branches, just make sure to branch from the oldest branch you intend to merge back into, which prevents pulling in unwanted dependencies.  Then when you merge your feature branch back in, you just do additional merges into each appropriate newer major version branch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: :active pseudoclass with animations sometimes prevents postbacks in Chrome and IE Has anyone else ran into this issue? I have a web forms site and I wanted to add an :active pseudo class to a link button, basically to animate it before doing some action. However, for some reason that I cannot figure out, animations in the :active state sometimes prevent a postback (other times it posts back just fine). Other effects (ie not animations or transformations) work just fine. So, this works just fine, EVERY time:
.mylinkbuttonclass:active
{
    width:75%;
}

Whereas the following only causes a postback about 40-50% of the time. The other times there is no postback at all (I put breakpoints in my page load and prerender events which never get hit)
.mylinkbuttonclass:active
{
    animation: flip 200ms linear 1;
    -moz-animation: flip 200ms linear 1;
    -o-animation: flip 200ms linear 1;
    -ms-animation: flip 200ms linear 1;
    -webkit-animation: flip 200ms linear 1;
}

@keyframes flip{
    0% {
       transform:  rotateY(0deg);
    }
    50%
    {
        opacity: 0.10;
        transform:  rotateY(180deg);
    }
    100% {
       transform:  rotateY(180deg);
    }
}

Does anyone know why this happens, or how to fix it? I didn`t think it was possible for a pseudo class to prevent a postback! On the times where the postback fails, the animation still runs just fine; there is just no postback to the server.
Edit: Haven`t tested on Firefox yet but the failure is reproducible on both Chrome and IE 11.
Edit2: Wow so this actually works really well in Firefox; it`s Chrome and IE that have the issues.

A: Since I am a bit short on time on this one I ended up simply changing the link button class on button click to a new class which contains the animation. It works 100% of the time on all 3 major browsers but I would love to hear if anyone knows why it doesn`t work with the :active selector


text:
Q: Android Array List uncaught exception I'm trying to pull in a list of locations from my DB into an Array list which I can later use to create a dialog box but when I call the below method I can the errors below. Can anyone see what I'm doing wrong and why I get an uncaught exception when I am catching it? I would really appreciate the help!
public void allLocations() {

    try{
        Cursor mCursor = mDb.rawQuery("SELECT * FROM " + TABLE_LOCATION, null);
        ArrayList<String> mArrayList = new ArrayList<String>();
        mCursor.moveToFirst();
        while(!mCursor.isAfterLast()) {
             mArrayList.add(mCursor.getString(mCursor.getColumnIndex(LOCATION)));
             mCursor.moveToNext();
        }
    }catch (SQLiteException e){
        Log.e("All Locations", "Error getting locations: " + e.toString());
    }
}

// Errors
06-05 03:36:29.345: D/dalvikvm(2110): GC_EXTERNAL_ALLOC freed 655 objects / 51272 bytes in 77ms
06-05 03:36:30.185: V/one(2110): locationSelection
06-05 03:36:31.805: D/AndroidRuntime(2110): Shutting down VM
06-05 03:36:31.805: W/dalvikvm(2110): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-05 03:36:31.825: E/AndroidRuntime(2110): FATAL EXCEPTION: main
06-05 03:36:31.825: E/AndroidRuntime(2110): java.lang.NullPointerException
06-05 03:36:31.825: E/AndroidRuntime(2110):     at com.myapp.sqlite.Location.allLocations(Location.java:137)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at com.myapp.Options.displayLocations(Options.java:178)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at com.myapp.Options$1.onClick(Options.java:69)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.view.View.performClick(View.java:2408)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.view.View$PerformClick.run(View.java:8816)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.os.Handler.handleCallback(Handler.java:587)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.os.Looper.loop(Looper.java:123)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at java.lang.reflect.Method.invokeNative(Native Method)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at java.lang.reflect.Method.invoke(Method.java:521)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-05 03:36:31.825: E/AndroidRuntime(2110):     at dalvik.system.NativeStart.main(Native Method)

//The whole class
public class Location {

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private final Context mCtx;

    private static final String location = ("CREATE TABLE " + TABLE_LOCATION
            + " (" + LOCATION + " TEXT," + LOCATION_ID + " TEXT " + ");");

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(location);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
            onCreate(db);

        }
    }

    public Location(Context ctx) {
        this.mCtx = ctx;
    }

    public Location open() throws SQLException {
        this.mDbHelper = new DatabaseHelper(this.mCtx);
        this.mDb = this.mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        this.mDbHelper.close();
    }

    public long addLocation(String locations, String location_id) {

        ContentValues values = new ContentValues();

        values.put(LOCATION, locations);
        values.put(LOCATION_ID, location_id);

        return this.mDb.insert(TABLE_LOCATION, null, values);
    }

    public String getLocation(long l) throws SQLException {

        String[] columns = new String[] { LOCATION, LOCATION_ID };
        Cursor c = mDb.query(TABLE_LOCATION, columns, null, null, null, null,
                null);
        String result = "";

        int gLocation = c.getColumnIndex(LOCATION);
        int gLocationID = c.getColumnIndex(LOCATION_ID);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(gLocation) + " "
                    + c.getString(gLocationID) + " " + "\n";
        }
        return result;
    }

    /** Delete all from the location table */
    public void deleteAllLocations() {
        mDb.delete(TABLE_LOCATION, null, null);
    }

    /** Check that there are locations stored */
    public boolean countLocation() {

        Cursor count = mDb.rawQuery("SELECT COUNT(*) FROM " + TABLE_LOCATION,
                null);

        if (count == null) {
            return true;
        }
        return false;
    }

    public void allLocations() {

        try{
            Cursor mCursor = mDb.rawQuery("SELECT * FROM " + TABLE_LOCATION, null);
            ArrayList<String> mArrayList = new ArrayList<String>();
            mCursor.moveToFirst();
            while(!mCursor.isAfterLast()) {
                 mArrayList.add(mCursor.getString(mCursor.getColumnIndex(LOCATION)));
                 mCursor.moveToNext();
            }
        }catch (SQLiteException e){
            Log.e("All Locations", "Error getting locations: " + e.toString());
        }
    }
}

A: mDb is null at least in the code shown here.
do you have some other code where you are initializing the mDb reference?
EDIT :]
The change actually probably needs to be made in the Activity class that is using this class.
You need to make sure in your activity you are calling location.open(), before any other methods.


text:
Q: Indicating multiple clusters with ceph-ansible I am working through a Ceph course right now (ceph learning path from packtpub). The course is ok, but has a lot of errors, and isn't always the most accurate. The course expects that you use ceph-ansible to do a lot of the work. You start by creating a 3 node cluster.
So, the starting value of /etc/ansible/hosts is:
[mons]
ceph-node1
ceph-node2
ceph-node3
[osds]
ceph-node1
ceph-node2
ceph-node3
[clients]
client-node1

Now, the current section has you create a second 3-node cluster to serve as a remote backup.
To do this, the course has you modify the /etc/ansible/hosts file to the following:
#Primary site (ceph-node1):
[mons]
ceph-node1
ceph-node2
ceph-node3
[osds]
ceph-node1
ceph-node2
ceph-node3
[clients]
client-node1

#Secondary site (ceph-node5):
[mons]
ceph-node5
ceph-node6
ceph-node7
[osds]
ceph-node5
ceph-node6
ceph-node7

The installation of ceph-ansible is done via ceph-node5 with a different all.yml file, indicating a different cluster name. What I am trying to understand is how this would indicate to ceph-ansible that there are two separate clusters. If the /etc/ansible/hosts file is in .ini format, which ansible hostfiles are, any lines that begin with a # should be parsed as comments.
So, does ceph-node5 see the other installations on nodes 1,2,3 and ignore them as a separate cluster? After all, ceph-node5 has it's own all.yml with instruction that the hosts should be part of the backup cluster. Will it try to add 1,2,3 as nodes?
The text I am working with is really sparse on details, and trying to dig into the ceph-ansible github page hasn't been especially helpful.
I'm just trying to understand the mechanics of how this works. Any help would be appreciated, thank you!

A: Duplicate groups names in one inventory does not make sense. Further, you can store inventory files in different places.
Consider this YAML format inventory/siteA.yml:
---
all:
  vars:
    datacenter: a
  children:
    cephnodes:
      hosts:
        ceph-node1:
        ceph-node2:
        ceph-node3:
    osds:
      children:
        cephnodes
    mons:
      children:
        cephnodes

    clients:
      children:
        client-node1:

Because each node has an osd and a mon, I did the DRY thing and made that reference one list via child groups.
inventory/siteB.yml would naturally be the same thing with 3 different nodes.
If you wish to target multiple inventories for one play, you can specify a directory of them as inventory: ansible-playbook -i inventory/. osds will then target 6 nodes. However, if you need to target the A and B site separately in one play, you may want to restructure the groups a bit to distinguish those.


text:
Q: Determine if one-point samples are significantly different from a set-of-values sample Well, I have a sample x made up of 28 cases, sample y -> one case, sample z -> one case. I would like to determine if y and/or z are significantly different from x.
It's not possible to take more measurements for neither y or z.
Data look as follows:
x             y            z

0.72981354    37.13        67.4
1.518328503
1.655629139
2.563412415
3.027129131
4.480875623
4.545650835
4.762517086
5.065794539
5.643197549
6.674587177
7.019766786
7.687576876
8.321129011
9.798331225
19.22282133
25.73062098

I would like to know what would be the most appropriate statistical test to use?
I know that in order to use one-way ANOVA, I need at least two measurements per sample. So, is there another way to do it?

A: If your $x$ cases are i.i.d. and you are willing to assume a parametric distribution $F_X(\cdot|\theta)$, you could

*

*estimate the parameters $\theta$ using the observations $x$ and then

*calculate the "tail probability" that an observation is as large as or greater than $y$: $1-F_X(y|\theta)$.

If the tail probability is very small, $y$ seems unlikely to have been generated by $X$. However, the estimation uncertainty associated with $\theta$ will make the "tail probability" uncertain. You could account for that by, for example,

*

*obtaining bootstrap samples from the original sample and

*estimating $\theta$ and calculating $F_X(y|\theta)$ for each bootstrap sample.

You would obtain a "cloud" of "tail probabilities", so you would have some idea about their distribution. But that could create a false sense of reliability; recall that you only have one $y$! Therefore, the inference will be quite uncertain anyway.
However, it seems that $x$ are not i.i.d. as they are increasing (unless you have ordered them increasingly before posting), so the above method will not work as is. Perhaps you could modify and adapt the underlying idea, though.


text:
Q: Pass a common data in all $http services in angularjs I wish to send a particular data in all the $http calls. Can i define it somewhere so that i need not alter all the $http calls.
For example,
  $http({
      method: 'POST',
      url: serviceUrl,
      data: {
          "key1": data1,
          "key2": data2,
      }
  })

Add a data3 as default in all my $http calls. Thanks in advance for your response.

A: You can transform or intercept the $http object with $httpProvider
var app = angular.module('test', []);
app.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        data.key3 = "This will always be set in a POST";

        return $.param(data);
    }
});

I've never tried to append the POST data like this, but it should work.
For GET params transforming...
$httpProvider.interceptors.push(function() {
  return {
   'request': function(config) {
       //config.params contains query/request parameters
       if (config.params){
         config.params.key3 = "Hello World"
       }
       return config;
    }
  };
});


text:
Q: Memory allocation of a Class auto properties I have a class with multiple properties. For example
public class Customer
    {
        public int id { get; set; }
        public string abc{ get; set; }
        public bool abcd { get; set; }
        public string abcde { get; set; }
        public string abcdef { get; set; }
        public string abcdefg { get; set; }
        public string abcdefgh { get; set; }
        public string xyz { get; set; }
    }

Now I want to know how much memory space is consumed by the get set properties.
I only require few of the properties in one of my API call and all of these properties for another API call.
So I want to know whether I should create two different classes and use them for my separate API calls or just use one common class with multiple get set properties and use it for my API calls.
Any guidance will be much appreciated. Thanks

A: the int and bool will typically be packed together into 8 bytes; the string references take 4 (32-bit) or 8 (64-bits) for the references. If the strings have non-null values, then that space will be allocated separately and will be whatever the string needs.
But frankly: unless you're allocating millions of them, splitting it into 2 different types won't save you anything real - it will just be yak shaving. Especially for the scenario where the strings are null.

A: We have to exclude the string. This one can be anywhere from "null" to "whatever Max Lenght for string was today".
Theoretically a Autoimplement Property should cost as much as a minimal, manual property: One backing field. One get and one set function for the entire type. The single most important rule about properties is to not accidentally access the backing field in class code. And Autoimplement Properties do that, by simply not giving the Backing Field a name you could use. It is still there. It propably has a name derived from the Property name for Reflection. But your code has no realy way to access it.
Theoreitically, because now coems in the JiT. The JiT can do a lot of Optimisations:

*

*Those Automatic accessors are very little code. So there is a decent chance that the cost of Inlining them is below the cost of calling them. So I give it a 90% chance the JiT will inline those.

*If you create a temporary variable to use it the next line, this one might run into DeadCode detection. Wich means it will be cut out and replaced by the originall access.

*But of coruse it goes the other way too. In order to get around the overhead inherent in ArrayBounds Checks, the JiT might detect "redundant Acesses" with teh same Index and create a temporary variable to use.

While I have not read about it yet, I would not rule out that the JiT can even cut unused properties from classes. It is all just runtime optimisations. It at least can cut unaccessed varriables (and their initialsiation) out as dead code. As I found out when I tried forcing a 2 GiB OOM:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOM_32_forced
{
    class Program
    {
        static void Main(string[] args)
        {
            //each short is 2 byte big, Int32.MaxValue is 2^31.
            //So this will require a bit above 2^32 byte, or 2 GiB
            short[] Array = new short[Int32.MaxValue];

            /*need to actually access that array
            Otherwise JIT compiler and optimisations will just skip
            the array definition and creation */
            foreach (short value in Array)
                Console.WriteLine(value);
        }
    }
}

I agree that this is Micro Optimisations. But even more, those might be ones the JiT can do for you already. So you might save nothing at all. Personally I prefer read- and debugability of code way before such Optimisations. I can often do something "ineffective" because I can rest in the knowledge the JiT will propably deal with it.


text:
Q: Auto-delete queue not recreated after broker outage I have a question regarding the use of spring-amqp through XML wiring and through creation of the various objects in java code.
Doing this via XML and via Java code is pretty simple and has been working well for me in most cases. However, after an outage of the broker (simulated by shutting down and restarting my broker) I get two different results.
When using XML wiring to create the spring-amqp objects, everything works fine. The connection is re-established, the queue is recreated and reception of messages resumes.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd">

    <rabbit:connection-factory id="connectionFactory"
        addresses="192.168.1.10:5672"
        username="guest"
        password="guest"
    />

    <rabbit:admin connection-factory="connectionFactory"/>

    <rabbit:queue name="testQueue" id="testQueue" auto-declare="true" auto-delete="true" exclusive="false"/>

    <rabbit:fanout-exchange name="testExchange" id="testExchange" >
        <rabbit:bindings>
            <rabbit:binding queue="testQueue" />
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <bean class="TestConsumer" id="testConsumer" />

    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener queues="testQueue" ref="testConsumer" method="inbound" />
    </rabbit:listener-container>

</beans>

However, when using Java to create the spring-amqp objects, I run into issues. The connection is re-established, but then I immediately hit exceptions reporting that the queue is not found. The admin does not attempt to re-create the queue and after a few exceptions, the listener container is stopped.
public static void main(String[] args) {

    CachingConnectionFactory cf = new CachingConnectionFactory("192.168.1.10", 5672);

    RabbitAdmin admin = new RabbitAdmin(cf);

    FanoutExchange testExchange = new FanoutExchange("testExchange", true, false);
    admin.declareExchange(testExchange);

    Queue testQueue = new Queue("testQueue", true, false, true);
    admin.declareQueue(testQueue);

    admin.declareBinding(BindingBuilder.bind(testQueue).to(testExchange));

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(cf);
    container.setRabbitAdmin(admin);

    container.setQueues(testQueue);
    container.setMessageListener(new MessageListenerAdapter() {
        public void handleMessage(String text) {
            System.out.println("Received : " + text);
        }
    });
    container.afterPropertiesSet();

    container.start();

    try {
        Thread.sleep(600000L);
    } catch(Exception e) {
        e.printStackTrace();
    }

    container.stop();
    container.destroy();

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

This is the exception that I see (three or four times) after the connection is re-established and before the listener container exits:
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'testQueue' in vhost '/', class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:478)
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:315)
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:144)
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:91)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:552)

I would assume that the XML wiring case and the pure Java case should work equivalently, but clearly this is not the case. I am not sure if
 there is something that I am missing in my Java case, or whether this is just not supported.
I can of course detect the failure of the listener container and use the admin to re-declare the queues, but seeing as this is not necessary with the XML wired example, I am wondering what I might be missing.
Using org.springframework.amqp.spring-rabbit 1.4.5.RELEASE

A: The admin needs a Spring Application Context to automatically declare the elements (queues etc).
It registers a connection listener with the connection factory and, when a new connection is established, it looks for all the queues etc in the application context and registers them.
Since you are using "pure" java (no Spring Application Context), this mechanism can't work.
You can either use Spring Java Configuration to replace your XML (using @Bean definitions), or you will have to register your own class with the connection factory to perform the declarations.
See the admin source code for how he registers the listener and the initialize method for how he does the declarations.
You would simply need to do your
FanoutExchange testExchange = new FanoutExchange("testExchange", true, false);
admin.declareExchange(testExchange);

Queue testQueue = new Queue("testQueue", true, false, true);
admin.declareQueue(testQueue);

within the listener.

A: Spring AMQP only reconnects queues and exchanges registered using the @Bean annotation.
Queues and Exchanges registered directly by the RabbitAdmin will not be reconnected automatically. You need to set resetAllManualDeclarations() to true before declaring them.
Example:
RabbitAdmin admin = new RabbitAdmin(cf);

// enable auto reconnect when connection fails
admin.resetAllManualDeclarations(true);

FanoutExchange testExchange = new FanoutExchange("testExchange", true, false);
admin.declareExchange(testExchange);

Queue testQueue = new Queue("testQueue", true, false, true);
admin.declareQueue(testQueue);

Note: you need spring-rabbit 2.4+.


text:
Q: gawk nextfile with compressed input I'm trying to use awk's nextfile statement with multiple gzipped input files.
I've googled for this before posting but it looks like I'm the only one who want to do this :D
This is what i need to do:
awk '
BEGIN{
print "start",strftime();
}
/match/{
print FILENAME,"->",$0
count++
nextfile
}
END{
print count
print "stop",strftime();
}
' /var/log/*.2015-01-23.gz

Suddenly awk can't read by itself gzipped files, so I have to use zcat and I've modified my syntax as follow:
zcat /var/log/*.2015-01-23.gz | awk '
BEGIN{
print "start",strftime();
}
/match/{
print FILENAME,"->",$0
count++
nextfile
}
END{
print count
print "stop",strftime();
}
'

But this way nextfile statement won't work because awk see just one input data flow.
My awk version:
# awk --version
GNU Awk 3.1.7

Note: what exposed is a resume of what I need to do in the END action, so don't propose to use zgrep or something else. I need awk.
Note2: Files will be elaborated togheter.
Thanks

A: You can fetch the files one by one, hold the Name of the file in a shell variable and print this in awk:
#!/bin/bash
for LOGFILE in /var/log/*.2015-01-23.gz
do
    zcat "$LOGFILE" |
    awk '
        BEGIN{
            print "start",strftime();
        }
        /match/{
            print "'$LOGFILE'","->",$0
            last
        }
        END{
            print "stop",strftime();
        }
    '
done


text:
Q: Blazor - Web assembly loading time I have developed Blazor Server Server application and customers obviously do not like the message "Could not reconnect to the server. Reload the page to restore functionality". This is the reason I am trying to explore migration to Web Assembly.
I am struggling, how to speed up web assembly loading time , because home page cannot be loaded several seconds. Is there a chance to load initial Server page and in the background load Web assembly and "redirect" user to web assembly once it is fully loaded ?
Explanation of business functionality needed ( not working in Server mode ):

*

*User is in the middle of filling the form ( e.g. Applying for membership filling all personal information )

*Connection is dropped (e.g. for 30 seconds)

User would like to fill the form without any disruption even offline. Once user is back online form is Submitted by the user. Obviously , when submit is processed, user needs to be back on line.
Edit: I have accepted perfect answer to my question. Thanks for pointing this article to @MrCakaShaunCurtis.
But I have asked wrong question, because my (and customer's)  concern was annoying overlay message "Could not reconnect to the server. Reload the page to restore functionality". My questions was supposed to be: "How to disable this message". The answer is described here https://github.com/dotnet/aspnetcore/issues/10325

A: There's an article here that explains how to first load in Server mode and then switch to Web Assembly.


text:
Q: Google Python API spreadsheet row /column count The question is, can I retrieve a count of the columns? I mean, I can get a worksheet feed using this:
feed = self.gd_client.GetWorksheetsFeed( self.spreadsheet_id )

and take it's <ns1:rowCount> or <ns1:colCount> tags values, but is there a way to retrieve it directly? Like feed.entry[ number ].rowCount or something?

A: I believe this will work
num_rows = int( feed.entry[ number].row_count.text )


text:
Q: How do I create a table there cells flow/wrap rather than using a rigid grid? I'm having trouble creating the layout I would like for a website. I don't have too much experience with web design and the only software I have is FrontPage which doesn't seem to do what I want.
I'm trying to create a page with a number of "cells," each containing an image on top with text centered below. I want each cell to have a fixed width and I'd like to have the cells follow a normal "flow," placed besides each other (for example, as inline images would), and have these cells wrap if there isn't enough width to fit them all on one line (again, as inline images would).
The first thing that comes to mind is a table, but a table has a rigid structure of rows and columns rather than flowing and wrapping.

A: HTML:

Capture 1

Capture 2

Capture 3

CSS:
.cell {text-align:center;
       width:200px; /* or whatever you want */
       float:left;
       /* add margin, padding, border style if you wish */
}

See demo.

A: I think the customary approach to achieve this look, at this point in history, is a ul (unordered list).  Take a look at the demos for the Galleria Plugin.  Each of these has a group of thumbnails that render almost exactly as you describe (you'll have to add text below).


text:
Q: Which C# data structure to use? I was just wondering what do you think would be the best C# data structure for problem like this.
So I will have an array of keys, and for each key array of arrays.
Sounds complicated does it :)
Anyway the simplest solution that comes to my mind, note that I never did any formal C# training. It was more I am C++ programmer and then for some stupid project did C# application. Therefore I might have missed out on a good structure I could use.
So Dictionary<string, List<Dictionary<string, double>> is what I had in mind. But is there anything better?

I will have set of data points for each key, but more than one set of data points.
So I was just wondering if anyone has better design suggestion.

A: Sounds like you might want to create a custom object to encapsulate your datapoint, then store that in a dictionary keyed by whatever value makes sense.
From what you've said, the object you store as the value in the dictionary, might itself be a collection of datapoints.
So you might create an object which encapsulates your List<Dictionary<string, double>>

A: I assume that since you are using some sort of key to access the internal arrays, that you don't intend to just loop through the data object and pull out every value. If that is the case then you are right, a Dictionary is probably your best choice.

A: There is good data structure: Trie(http://en.wikipedia.org/wiki/Trie). For our c# project we have used TopCoder implementation.


text:
Q: Magento output (lowest) price of grouped products in view.phtml I try to output the lowest price of grouped products in the file view.phtml.
The lowest price should be inserted near the top. For now we use a additional
attribute to display it. But that is just a workaround.
I tried different codes but no one is working:
<?php echo $this->getPriceHtml($_product, true) ?>
or
<?php $_finalPriceInclTax = $this->helper('tax')->getPrice($_item, $_item->getFinalPrice(), true) ?>

but nothing seems to work.
Maybe you have some idea how to display the price, thank you in advance!
Christian

A: This gets the children and should return the lowest price of the groupedProduct.
I did not test this.
public function prepareGroupedProductPrice($groupedProduct)
{
$aProductIds =    $groupedProduct->getTypeInstance()->getChildrenIds($groupedProduct->getId());

$prices = array();
foreach ($aProductIds as $ids) {
    foreach ($ids as $id) {
        $aProduct = Mage::getModel('catalog/product')->load($id);
        $prices[] = $aProduct->getPriceModel()->getPrice($aProduct);
    }
}

krsort($prices);
$prices = array_shift($prices);
return $prices;
}


text:
Q: boost::fusion accessing key type of joint view as map I'm trying to convert the ash framework to c++ to incorporate to my project, my development environment is Vista 32, and Visual C++ 2008 Express, and I'm using boost_1_37_0 libs, im not planning on upgrade the environemt until i reach some results...
Given:
typedef Component Pcomponent;
typedef WaitForstart2 Pcomponent2;
typedef boost::fusion::pair<ComponentWONTEXISTS,Pcomponent> component_pair1;
typedef boost::fusion::pair<WaitForstart2,Pcomponent2> component_pair2;

typedef boost::fusion::map<component_pair1> componentDictType1;
typedef boost::fusion::map<component_pair2> componentDictType2;

typedef boost::fusion::joint_view<componentDictType1, componentDictType2>joincomponentDictType;

I'm unable to solve how to access on of the types, using at_key
boost::fusion::at_key<ComponentWONTEXISTS, dictionaryjoint>(boost::fusion::as_map(dictionaryjoint));

Thanks,
P.S: I'm on a hurry but I'll try to reformat the question on a while
Regards,

A: It's funny but i think i managed to find the solution:
    typedef boost::fusion::result_of::as_map<boost::fusion::joint_view<componentDictType1, componentDictType2> >::type MAPTYPE;
    MAPTYPE aDict;
    Pcomponent ptempj3 = boost::fusion::at_key<ComponentWONTEXISTS,MAPTYPE>(aDict);


text:
Q: How to handle form submission using ajax (jQuery) I've a php form
<form action="" method="POST">
    <input id="input1" name="key" type="text">
    <input id="input2" name="name" type="text">
    <button id="btn" type="button">Enter</button>
</form>

I want to submit the form using ajax so this is how I do it
$('#btn').click(function(){
    var input1 = $('#input1').val();
    var input2 = $('#input2').val();
    var pass = 'val1='+input1+'&val2='+input2;
    $.ajax({
        type: "POST",
        url: "process.php",
        data: pass,
        success: function(data){
          //success;
        }
     });
});

My problem is, when the form has several input items, I've to give an id for every item apart from retrieving it's value using $('#input1').val() and I think this is a cumbersome method.
So is there a way better than this to handle the form in ajax, probably which does not needing to give an id for every input item and instead retrieve the values at the processing file using the input item name just like a php normal form submission works using a submit button?

A: The jQuery Form plugin is very nice to handle such case.


text:
Q: Docker image with Maven fails to run I want to use Maven in my Docker image.
After looking here https://hub.docker.com/_/maven/, I tried using this Dockerfile:
FROM openjdk:7

RUN apk add --no-cache curl tar bash

ARG MAVEN_VERSION=3.3.9
ARG USER_HOME_DIR="/root"

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

COPY mvn-entrypoint.sh /usr/local/bin/mvn-entrypoint.sh
COPY settings-docker.xml /usr/share/maven/ref/

VOLUME "$USER_HOME_DIR/.m2"

ENTRYPOINT ["/usr/local/bin/mvn-entrypoint.sh"]
CMD ["mvn"]

However, I'm getting:
lstat mvn-entrypoint.sh: no such file or directory

I tried different Dockerfiles from the same repositories but they all throw this error.
What's wrong with this dockerfile?
How can I use Maven with Docker?

A: I just ran into the same problem, I have forgotten to download the "mvn-entrypoint.sh" file.. https://github.com/carlossg/docker-maven/tree/322d0dff5d0531ccaf47bf49338cb3e294fd66c8/jdk-8 .. also the settings-docker.xml was required..

A: Try this:
Dockerfile:-
FROM openjdk:8u111-jdk-alpine

COPY assets/settings.xml /tmp/settings.xml
ENV PATH=$PATH:/opt/maven/bin

RUN apk add --no-cache curl tar bash && \
  curl -SsL -o /tmp/maven.tar.gz http://www-us.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz && \
  mkdir -p /opt && \
  tar xzf /tmp/maven.tar.gz -C /opt/ && \
  ln -s /opt/apache-maven-3.3.9 /opt/maven && \
  rm /tmp/maven.tar.gz && \
  mv /tmp/settings.xml /opt/maven/conf/settings.xml

You need to put this Dockerfile in a new directory, with a subdirectory called 'assets', and you need to put a maven settings file (settings.xml) in that directory. If you don't have a custom settings file then remove the COPY and the mv.
Build it with something like
docker --tag ajava8 .

You can run maven in your current directory using something like:
docker run -it --rm -v /$PWD:/work -w /work ajava8 mvn clean install

Or, you can get a bash shell with something similar, like this:
docker run -it --rm -v /$PWD:/work -w /work ajava8 bash

A: You need the files copied in the Dockerfile mvn-entrypoint.sh and settings-docker.xml.
You can git clone from https://github.com/carlossg/docker-maven


text:
Q: CSS Keyframes Infinite Transform Rotation It is an infinite animation for the mobile menu. It breaks when I go to another page but not always. When I use the Inspector Mode in Chrome and go through the pages it never breaks. On mobile sometimes it just gets bugged and the "transform" property from the @keyframes is not applied but at the same time, all other properties are here.
That is the link - https://athelloworkingg.webflow.io/
That is how it looks when it gets bugged - Bug
Here is my CSS
.navmenu-navlink > span {
transition: all 300ms ease;
}

.navmenu-navlink-mobile:nth-child(odd) {
  animation-name: spinClockwise;
  animation-duration: 90000ms;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}
.navmenu-navlink-mobile:nth-child(even) {
  animation-name: spinAntiClockwise;
  animation-duration: 90000ms;
  animation-iteration-count: infinite;
  animation-timing-function: linear; }

@keyframes spinClockwise {from {-webkit-transform:rotate(0deg);}to {-webkit-transform:rotate(360deg);}}
@keyframes spinAntiClockwise {from {-webkit-transform:rotate(360deg);}to {-webkit-transform:rotate(0deg);}}

I tried using -WebKit- and -moz-, also tried to delay the animation, to play it on document.ready(). I also tried to put as a default state - animation-play-state: paused, then to make it run when you click on the hamburger and to pause it again when you click on one of the menu items.
All these things did not help me. I would be very thankful if someone can assist me with that.


text:
Q: Tweepy can't get video clip info from Tweets
Traceback (most recent call last):   File "./tweets_fetch.py", line
  22, in
      for media in i.extended_entities['media']['video_info']: TypeError: list indices must be integers, not str

How exactly can I extract video mp4 file link from User123 tweets?
tweets_message = api.user_timeline(screen_name = 'User123', count = 1, include_rts = True)
for i in tweets_message:
        for media in i.extended_entities['media']['video_info']:
                print (media)

expecting to a list of mp4 files at different bitrates


text:
Q: Interacting with a SwiftUI view below a UIKit PKCanvasView I have a view Structure as follows:
ZStack {
    UIKitView //PKCanvasView
        .zIndex(1)
    SwiftUIView //SwiftUI view which has a gesture recogniser
        .zIndex(0)
}

I wanted to know what the best way was to allow simultaneous interaction to the SwiftUI view below the UIKit view.
This would work best if the SwiftUI view had a higher priority gesture over the UIKit view on top.
My UIKit representable view is as follows:
struct CanvasView: UIViewRepresentable {

    @Binding var canvasView: PKCanvasView
    @Binding var isFirstResponder: Bool

    @State var toolPicker = PKToolPicker()

    func makeUIView(context: Context) -> PKCanvasView {

        canvasView.drawingPolicy = .pencilOnly
        canvasView.backgroundColor = .clear
        canvasView.isOpaque = false
        canvasView.alwaysBounceVertical = true
        canvasView.alwaysBounceHorizontal = true

        toolPicker.setVisible(true, forFirstResponder: canvasView)
        toolPicker.addObserver(canvasView)
        //canvasView.becomeFirstResponder()

        return canvasView
    }

    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        if isFirstResponder != uiView.isFirstResponder {
           if isFirstResponder {
               uiView.becomeFirstResponder()
           } else {
               uiView.resignFirstResponder()
           }
       }
    }

}

Ideally I would like to handle the layering of views in SwiftUI as in reality a have multiple SwiftUI views below the canvas view which when held & dragged (that is the compound gesture I am applying to them) should appear above it. (This is achieved using dynamic zIndexs). I'm not comfortable enough with UIKit to know how to do this there with subviews and a UIViewRepresentable structure.
Any help would be greatly appreciated!


text:
Q: Spring Web Service create DomPoxMessage instead of SaajSoapMessage I am using Spring web service and the spring web service/xml version is 2.1.3, yet the other spring core version is 3.2.3.  I need to access the soap header and set the response header the same as the request header.  I extended the PayloadValidationInterceptor to add extra logic as below:
@Override
public void afterCompletion(MessageContext messageContext, Object endpoint,
        Exception ex) {
    //System.out.println("afterCompletion");
    SaajSoapMessage soapRequest = (SaajSoapMessage) messageContext
            .getRequest();
    SoapHeader reqheader = soapRequest.getSoapHeader();
    SaajSoapMessage soapResponse = (SaajSoapMessage) messageContext
            .getResponse();
    SoapHeader respheader = soapResponse.getSoapHeader();
    if( reqheader !=null ){
        TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
        try {
            Transformer transformer = transformerFactory.newTransformer();
            Iterator<SoapHeaderElement> itr = reqheader
                    .examineAllHeaderElements();
            while (itr.hasNext()) {
                SoapHeaderElement ele = itr.next();
                transformer.transform(ele.getSource(), respheader.getResult());
            }
        } catch (Exception e) {
            LOG.error(Toolkit.getStackTrace(e));
        }
    }

}

And in the spring web service configuration, I have added the following message factory to make sure that SAAJ Soap message is used.
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="soapVersion">
        <util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12" />
    </property>
</bean>

When testing, thing are normal.  But now in production when the work load is high, I started to receive ClassCastException as messageContext.getRequest() returns a DomPoxMessage instead of SaajSoapMessage.  Does anyone know why it happens like that.

A: Based upon the information that you have provided, I cannot get to the exact reason. But to avoid this problem you can use the constructor of SAAJSOAPMessageFactory that takes the message factory as the argument. This way you can be sure that only SaajSoapMessageFactory is used. The way jdk looks for an appropriate soap factory is by searching first for jaxm.properties in java home or else looks up a suitable implementation in classpath ref.


text:
Q: Dynamics CRM Linq validation I'm trying to update some records in CRM online. When the record is saved, there is some other existing data in the case record that doesn't validate. Can I somehow override validation and just do the update for the single field I"m updating?  this is the code:
var closedCases = (from o in xrm.IncidentSet
                where o.StateCode == 1
                               select o).Take(5).ToList();
            foreach (var c in closedCases)
            {
                var numDays = ((TimeSpan)(c.new_ClosedDate - c.CreatedOn)).Days;
                Console.WriteLine("case age: {0}, closed case:{1}", numDays, c.Description);
                c.new_caseage = numDays;
                xrm.UpdateObject(c);
                xrm.SaveChanges();
            }
            Console.WriteLine("changes saved");

A: first you need to use also UpdateObject if you want to save your changes:
c.new_caseage = numDays;
xrm.UpdateObject(c);
xrm.SaveChanges();

second you can't update closed cases, you need to reopen the records first in order to update.


text:
Q: Detect when wearable connected/disconnected to/from Android phone The Pebble watch has a Intent that is globally sended when the Pebble is connected/disconnected. This allow the phone apps to know if the watch is connected or not.
I have searched but I'm not capable to locate info about a similar feature for Android Wear.
How know if a wearable is connected to the phone? Is possible to receive a event like with Pebble?
Thanks

A: Have you tried NodeApi, you can use getConnectedNodes

Gets a list of Nodes to which this device is currently connected.

or addListener(GoogleApiClient client, NodeApi.NodeListener listener) which

Registers a listener to receive all node events.

Then you can use callbacks from NodeApi.NodeListener
onPeerConnected(Node peer) and onPeerDisconnected(Node peer)

A: As akmal said you can get devices which are connected to the phone, But to know whether the wearable currently connected with handheld
List<Node> connectedNodes =
    Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await().getNodes();

The list contains data like this:
Node{Moto 360 6BBF, id=3b6d19bf, hops=1, isNearby=true}

A: You can easily do this by extends the WearableListenerService and override onConnectedNodes() method.
Wearable Side
public class DisconnectListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks {

/* the capability that the phone app would provide */
private static final String CONNECTION_STATUS_CAPABILITY_NAME = "is_connection_lost";

private GoogleApiClient mGoogleApiClient;

@Override
public void onCreate() {
    super.onCreate();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .build();
}

@Override
public void onConnectedNodes(List<Node> connectedNodes) {
    if (mGoogleApiClient.isConnected()) {
        updateStatus();
    } else if (!mGoogleApiClient.isConnecting()) {
        mGoogleApiClient.connect();
    }
}

private void updateStatus() {
    Wearable.CapabilityApi.getCapability(
            mGoogleApiClient, CONNECTION_STATUS_CAPABILITY_NAME,
            CapabilityApi.FILTER_REACHABLE).setResultCallback(
            new ResultCallback<CapabilityApi.GetCapabilityResult>() {
                @Override
                public void onResult(CapabilityApi.GetCapabilityResult result) {
                    if (result.getStatus().isSuccess()) {
                        updateConnectionCapability(result.getCapability());
                    } else {
                        Log.e(TAG, "Failed to get capabilities, " + "status: " + result.getStatus().getStatusMessage());
                    }
                }
            });
}

private void updateConnectionCapability(CapabilityInfo capabilityInfo) {
    Set<Node> connectedNodes = capabilityInfo.getNodes();
    if (connectedNodes.isEmpty()) {
        // The connection is lost !
    } else {
        for (Node node : connectedNodes) {
            if (node.isNearby()) {
                // The connection is OK !
            }
        }
    }
}

@Override
public void onConnected(Bundle bundle) {
    updateStatus();
}

@Override
public void onConnectionSuspended(int cause) {

}

@Override
public void onDestroy() {
    if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) {
        mGoogleApiClient.disconnect();
    }
    super.onDestroy();
    }
}

Phone Side
create a xml file in values/ directory named wear.xml
<resources>
    <string-array name="android_wear_capabilities">
        <item>is_connection_lost</item>
    </string-array>
</resources>

For more, checkout the my solution in this Stack Overflow Question


text:
Q: Convert base64 string to HTML (C#) I have code that downloads HTML file from AWS S3 and convert it to base64
Here is code
 public async Task<string> DownloadFromS3(string bucketName, string fileName)
    {
        var getObjectRequest = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = fileName
        };

        var getObjectResponse = await _s3Client.GetObjectAsync(getObjectRequest);

        using (var fileMemoryStream = new MemoryStream())
        {
            await getObjectResponse.ResponseStream.CopyToAsync(fileMemoryStream);

            var imageBytes = fileMemoryStream.ToArray();

            return Convert.ToBase64String(imageBytes);
        }
    }

after this, in some part of code, I need to convert it back to HTML (not file, just plain HTML)
How I can do this?

A: First of all we need to convert from base64 string to byte[] and than get string from it
var attachmentString = await _awsService.DownloadFromS3(Environment.GetEnvironmentVariable("S3_BUCKET_EMAIL_TEMPLATES"),url);
var bytes = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(attachmentString));


text:
Q: How to combine podSelector with ports in Kubernetes Network Policy? I have a pod called mysql-1 with ports 3306 and 3307 open.
I want to create a network policy that allow ingress connection from backend-1 to 3306 and backend-2 to 3307.
Right now all I could come up with is this policy:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: mysql-ingress-policy-1
  namespace: v2ci
spec:
  podSelector:
    matchLabels:
      app: mysql-1
      release: v2
  types:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    ports:
    - protocol: TCP
      port: 3306
    - protocol: TCP
      port: 3307

The problem is that with this policy each backend pod has access to both ports.
Is it possible to combine ports with podSelector somehow or should I just create one network policy for each backend pod?

A: There is no backend-2 mentioned in your yaml file, but changing only that would not lead to the desired result.
You have to provide two different - from sections, one per backend:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: mysql-ingress-policy-1
  namespace: v2ci
spec:
  podSelector:
    matchLabels:
      app: mysql-1
      release: v2
  types:
  - Ingress
  ingress:
  # route backend-1 to port 3306
  - from:
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    ports:
    - protocol: TCP
      port: 3306
  # route backend-2 to port 3307
  - from:
    - podSelector:
        matchLabels:
          app: backend-2  # really apply a different pod than in the other "from"
          release: v2
    ports:
    - protocol: TCP
      port: 3307


text:
Q: After update from Jenkins 1.3.x to Jenkins 1.44 the jobs could not found any more After I did the update (just replaced the .war and deleted the unzipped folder in tomcat) I could not see the jobs any more. They are still on the file system in the right place. If I create a new test-job the job folder is correctly created next to the jobs that are not displayed any more.
In the tomcat log I could find a hint:
04.01.2012 15:38:53 jenkins.InitReactorRunner$1 onTaskFailed
SCHWERWIEGEND: Failed Loading job XXX
hudson.util.IOException2: Unable to read /var/lib/tomcat5.5/hudson/jobs/XXX/config.xml
    at hudson.XmlFile.read(XmlFile.java:137)
    at hudson.model.Items.load(Items.java:114)
    at jenkins.model.Jenkins$14.run(Jenkins.java:2360)
    at org.jvnet.hudson.reactor.TaskGraphBuilder$TaskImpl.run(TaskGraphBuilder.java:146)
    at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:259)
    at jenkins.model.Jenkins$5.runTask(Jenkins.java:800)
    at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:187)
    at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:94)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

Whats going wrong?
Thanks!
EDIT:
I guess I messed up my jobs, while I accidently installed a hudson version during the update. The way I fixed it: restore the backup...

A: Sounds strange. Maybe you could use the "Job Import Plugin" to restore your jobs?
See Here Job Import Plugin

A: The version 1.3XXX is called Hudson which has a different location of the jobs (.hudson) whereas the newer versions (1.4..) are called jenkins which have the location .jenkins...This can be solved by defining the JENKINS_HOME environment variable before starting Jenkins to use the old location..


text:
Q: Difference between dates I have a script for members and it has 2 tables (users and msgs).
I want to get the top member for posting messages per day. I used this code but it is not working:
$start = TIMENOW - TIMENOW % 86400;
$end = $start + 86400;
$maxposter = mysql_query("SELECT users.name,users.id,count(*) total FROM users AS users,msgs AS msgs WHERE users.id=msgs.userid AND msgs.added_date BETWEEN $start AND $end GROUP BY msgs.userid ORDER BY total DESC LIMIT 1")or die(mysql_error());
$maxmsg=mysql_fetch_assoc($maxposter);
echo $maxmsg[name];

The row added_date is being stored like 2011-05-05.

A: instead that , try
SELECT DATE_ADD('2011-05-05', INTERVAL 1 DAY);

Reference


text:
Q: Check if keys in TreeSet start with String, and get that key I have a TreeSet filled with Strings that I want to use to see if any of the keys inside it start with a string outside the set, and be able to get that specific key and do something with it (put it in a string) For example my String is test 1 2 3 and I have a key in the set that is test 1 2 which should return true and tell me the key. The reason I am using a TreeSet is because I need a case-insensitive way to read the keys in my yaml file. I have used an iterator on the set before using
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext())
if (myString.startsWith(itr.next())){ }

but I could not the key that made the if statement true.

A: You're really close... it's this line that is wrong
if (myString.startsWith(itr.next())){ }

it should be this - because the key should start with the myString.
String theKey = null;
while(itr.hasNext()) {
  theKey = itr.next();
  if (theKey.startsWith(myString)) {
    return theKey;
  }
}
return null;

A: Call subSet() is more proper way for tree set than iterating over it.
myTreeSet.subSet(str, str + "\uffff")

A: I am not sure to get what you want:
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext()) {
     String myString = itr.next()
     if (myString.startsWith(myString)){
         System.out.println(myString);
     }
}


text:
Q: Find bound for inverse of linear map Let $H$ be a Hilbert space and let $B:H\times H\to \mathbb F$ a sesquilinear form, where $\mathbb F $ is either $\mathbb R$ or $\mathbb C$.
Suppose $B$ is bounded, i.e. there is some $c>0$ such that $\vert B(x,y)\vert \le c\Vert x\Vert \Vert y\Vert \forall x,y\in H$. Then one can show that there exists one(!) linear mapping $T:H\to H$ with $B(x,y)=\langle x,Ty\rangle$ for all $x,y\in H$ and $\Vert T\Vert \le c$ . Assume there exists some $ 0<c_0\le c$ such that for all $x\in X$ holds $$\operatorname{Re}(B(x,x))\ge c_0\Vert x\Vert^2.$$

Show T is boundedly invertible with $\Vert T^{-1}\Vert \le \frac{1}{c_0}$

I do not see how to start here. Probably one first has to show that $T$ is injective and surjective.
Injectivity is clear. Let $x \in \ker(T)$. Then, $$c_0\Vert x\Vert^2=\operatorname{Re}(B(Tx,x))=\operatorname{Re}(\langle Tx,Tx\rangle=\operatorname{Re}(\Vert Tx\Vert^2)=\Vert Tx \Vert^2$$
Righthandside is zero, lefthand side is zero iff $x=0$. Thus the kernel is trivial. Further one can show that $T$ is surjective, too. So $T^{-1}$ exists.
Question: How can one proceed then with the problem?

A: You are just missing the boundedness part of the conclusion.
You can write $$c_0 \|x\|^2 \leq \operatorname{Re}(\langle x, Tx \rangle) \leq \|x\| \|Tx\|$$ by Cauchy-Schwarz. This then implies that $\|x\| \leq c_0^{-1} \|Tx\|$. Taking $x = T^{-1}y$ will give you that $\|T^{-1} y \| \leq c_0^{-1} \|y\|$ which gives the boundedness part of the conclusion.


text:
Q: Wireshark can capture packets from machine 2 to machine 3 communication? I got an idea there were 3 machines. machine 1,2 amd 3.
Machine 2 ping to machine 1,  i can capture the packets by using tcpdump. But mchine 2 ping to machine 3 , then machine 1 can't capture by using tcpdump.  This process is same like wireshark ?
there wont be any packets received at machine one, when there is a communication initiated between Machine2 and Machine3.
Wireshark is a tool same like tcpdump.
There wont be any packet reaching to Machine1 from when machine 2 and machine 3 are communicating.
Is it correct ?

To make it more clear. Open two terminals in Machine 1 and initiate a
  tcpdump in each terminals for source as machine 2 and machine 3. Keep
  this for a few hours and lets analyse the packets..  So I conclude
  that wireshark is same like tcpdump. It can't capture the request from
  machine 2 to machine 3

tcpdump -n src host 192.168.1.m2 -w output-m2-and-m3.pcap

tcpdump -n src host 192.168.1.m3 -w output-m3-and-m2.pcap

Please tell me your comment

A: machine 1 will not notice any communication between machine 2 and machine 3 on Wireshark.
Wireshark hooks up to the network driver stack and sifts through all packets recieved by that network adapter.
In a swichted environment, packets from machine 2 to machine 3 will never reach machine 1 because the switch will not send those packets to the port that machine 1 is connected to.
In a hub environment (okay, who really uses a hub out there?) the packet gets transmitted to machine 1 as all packets get transmitted to all machines connected to the hub. However the network card might drop it (because it's not intended for that machine) internally before it even reaches the driver stack, depending on the card. Anyways, even if a hub still is in use, WireShark will likely also not be aware of these packets.


text:
Q: ZPL: Multiple textboxes under each other I would like to print a label with multiple text boxes (something like^FB600,3,0,c,0) under each other. The text boxes need to have different fonts and each of them might have variable number of rows.
The issue is how to position these two textblocks under each other so that they don't overlap.
To demonstrate the problem, I use this tool: http://labelary.com/viewer.html
Please try following code:
^XA

^FO0,0
^CF0,50
^FB600,4,0,c,0
^FDLorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer vulputate sem a nibh rutrum consequat. Etiam egestas wisi a erat. Fusce tellus.
^FS

^FO0,300
^CF0,40
^FB600,3,0,c,0
^FDNulla quis diam. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. In convallis.
^FS

^XZ

The problem is the ^FO0,300 as it is absolute, I need to position the second block according to the first one.


text:
Q: Cómo separar un String en Java. Cómo utilizar split() A partir de un String, "123-654321", lo que deseo es dividirlo en dos Strings:
string1=123
string2=654321

A: Para eso se usa el método String#split() en el cual defines un separador, que en caso de esta String es "-".
String string = "123-654321";
String[] parts = string.split("-");
String part1 = parts[0]; // 123
String part2 = parts[1]; // 654321

El método toma como parámetro una expresión regular. Si se quiere utilizar un separador textual, se deben escapar los caracteres \ ^ $ . | ? * + ( ) [ { antecediéndolos con una \.
String[] parts = string.split("\\|"); // Separar por "|"

O se puede utilizar el método Pattern#quote().
String separador = Pattern.quote("|");
String[] parts = string.split(separador);

¿Tienes problemas al usar un caracter como separador?
Existen caracteres para "uso especial" llamados metacaracteres,

Los metacaracteres son caracteres no alfabéticos que poseen
  un significado especial en las expresiones regulares. que son :
\ , ^ , $ ,  . , | , ? , * , + , ( , ) , { , } , [

Si estos son usados directamente para separar una cadena no funcionaran adecuadamente, ejemplo:
String cadena = "Hola|Stackoverflow|en|español";
String[] parts = cadena.split("|");
System.out.println(Arrays.asList(parts));

Salida incorrecta:
[H, o, l, a, |, S, t, a, c, k, o, v, e, r, f, l, o, w, |, e, n, |, e, s, p, a, ñ, o, l]

estos caracteres deben ser escapados antecediendo el caracter "\", ejemplo:
String cadena = "Hola|Stackoverflow|en|español";
String[] parts = cadena.split("\\|");
System.out.println(Arrays.asList(parts));

Salida correcta:
[Hola, Stackoverflow, en, español]

Para poder aplicar el separador en cualquiera de los casos se puede usar el siguiente método, en el cual se define la cadena y el separador, si detecta que el carácter separador es metacaracter aplica un escape:
private static String[] separaCaracteres(String cadena, String separator){
    System.out.println("Separator: " + separator);
    String[] parts = null;
    if(separator.equals("|")|| separator.equals("\\")||separator.equals(".")||separator.equals("^")||separator.equals("$")
            ||separator.equals("?")||separator.equals("*")||separator.equals("+")||separator.equals("(")||separator.equals(")")
            ||separator.equals("{")||separator.equals("[")){
        //Es metacaracter!
        parts = cadena.split("\\"+separator);
    }else{
        //No es metacaracter.
        parts = cadena.split(separator);
    }
    return parts;
}

Ejemplo llamando el método anterior:
   System.out.println(Arrays.asList(separaCaracteres("Hola\\Stackoverflow\\en\\español", "\\")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola^Stackoverflow^en^español", "^")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola$Stackoverflow$en$español", "$")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola.Stackoverflow.en.español", ".")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola|Stackoverflow|en|español", "|")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola?Stackoverflow?en?español", "?")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola*Stackoverflow*en*español", "*")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola+Stackoverflow+en+español", "+")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola(Stackoverflow(en(español", "(")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola)Stackoverflow)en)español", ")")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola{Stackoverflow{en{español", "{")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola}Stackoverflow}en}español", "}")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola[Stackoverflow[en[español", "[")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola Stackoverflow en español", " ")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola½Stackoverflow½en½español", "½")).toString());
   System.out.println(Arrays.asList(separaCaracteres("Hola-Stackoverflow-en-español", "-")).toString());

Salida:
Separator: \
[Hola, Stackoverflow, en, español]
Separator: ^
[Hola, Stackoverflow, en, español]
Separator: $
[Hola, Stackoverflow, en, español]
Separator: .
[Hola, Stackoverflow, en, español]
Separator: |
[Hola, Stackoverflow, en, español]
Separator: ?
[Hola, Stackoverflow, en, español]
Separator: *
[Hola, Stackoverflow, en, español]
Separator: +
[Hola, Stackoverflow, en, español]
Separator: (
[Hola, Stackoverflow, en, español]
Separator: )
[Hola, Stackoverflow, en, español]
Separator: {
[Hola, Stackoverflow, en, español]
Separator: }
[Hola, Stackoverflow, en, español]
Separator: [
[Hola, Stackoverflow, en, español]
Separator:
[Hola, Stackoverflow, en, español]
Separator: ½
[Hola, Stackoverflow, en, español]
Separator: -
[Hola, Stackoverflow, en, español]

A: split() método de división de cadenas() String
Este método tiene dos variantes y divide esta cadena alrededor de las coincidencias de la expresión regular dada.
La sintaxis de este método seria:
public String[] split(String regex)

Detalle de los parámetros:
Regex - la expresión regular delimitadora.
Valor de retorno
Devuelve la matriz de cadenas calculada dividiendo esta cadena en torno a las coincidencias de la expresión regular dada.
Ejemplo
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("123-654321");
      System.out.println("Return Value :" );

      for (String retval: Str.split("-")) {
         System.out.println(retval);
      }
   }
}

Esto producirá el siguiente resultado:
Salida
Return Value :
123
654321

A: Lo que puedes hacer es usar el metodo substring, es decir, extraer ciertos caracteres por su posición o rango de posiciones.
    String cadena = "004-034556";
    String sCadena = cadena.substring(0,3);
    String sCadenaD = cadena.substring(4, cadena.length());
    System.out.println(sCadena);
    System.out.println(sCadenaD);

Si ese no es el único formato que utilizas, puedes usar el metodo indexOf, que te va a servir para extraer todo lo que viene después del guión.
    int guion = cadena.indexOf("-");
    System.out.println(guion);
    String ej = cadena.substring(guion+1, cadena.length());

Espero te sea de ayuda, este es un ejemplo de lo que hice yo con esa misma cadena
public class main{
public static void main (String [] args){
    String cadena = "004-034556";
    String sCadena = cadena.substring(0,3);
    String sCadenaD = cadena.substring(4, cadena.length());
    System.out.println(sCadena);
    System.out.println(sCadenaD);
    int guion = cadena.indexOf("-");
    System.out.println(guion);
    String ej = cadena.substring(guion+1, cadena.length());
    System.out.println(ej);
}        }

A: split() es el método
El método más apropiado para dividir una cadena es  String#split().
String string = "123-654321";
String[] parts = string.split("-");
String part1 = parts[0]; // 123
String part2 = parts[1]; // 654321

No obstante, a la hora de usar split debemos tener en cuenta algunas cosas.

Los caracteres especiales
Al hacer split de cualquier cadena hemos de considerar que éste método toma una expresión regular, por lo que será necesario escapar los caracteres especiales cuando el caso lo amerite.
Hay 12 caracteres con significados especiales: la barra invertida \, el recuadro ^, el signo de dólar $, el punto ., La barra vertical o el símbolo de tubería |, el signo de interrogación ?, el asterisco o la estrella *, el signo más + , el paréntesis de apertura (, el paréntesis de cierre ) y el corchete de apertura [, la llave de apertura {. Estos caracteres especiales a menudo se llaman "metacaracteres". (Ver este enlace)
Por lo tanto, si desea dividir, por ejemplo esta cadena: período/punto, lo cual significa "cualquier carácter" en regex, utilice la barra invertida \ para escapar del carácter especial individual. Algo así: split("\\."), o utilice la clase de caracteres \[\] para representar caracteres literales como split("[.]"), o use Pattern#quote() para escapar de toda la cadena como si fuese split(Pattern.quote (". ")).
String[] parts = string.split(Pattern.quote(".")); // Split on period.

Se puede hacer una prueba previa
Para probar de antemano si la cadena contiene ciertos caracteres, use String#contains().
if (string.contains("-")) {
    // Hacer split.
} else {
    throw new IllegalArgumentException("String " + string + " no contiene -");
}

Pero este código no toma una expresión regular. Para ello, utilice String#matches() en su lugar.

Conservar el caracter de división en alguna de las partes
Si desea conservar el carácter de división en las partes resultantes, haga uso de la apariencia positiva. En caso de que desee tener el carácter de división en el lado izquierdo del último split, use lookbehind (mirada hacia atrás) positivo prefijando el grupo ?<= en el patrón.
String string = "123-654321";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 123
String part2 = parts[1]; // -654321

En caso de que desee tener el carácter de división al final, en el lado derecho del primer split, use lookahead (mirada hacia adelante) positivo prefijando el grupo ?= en el patrón.
String string = "123-654321";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 123-
String part2 = parts[1]; // 654321

Limitar el número de partes resultantes
Si desea limitar el número de partes resultantes, puede proporcionar el número deseado como segundo argumento del método split().
String string = "123-654321-789";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 123
String part2 = parts[1]; // 654321-789

Cadenas vacías
Hay casos en que los elementos del array String devuelto tienen cadenas en blanco.

*

*Prefijo: - cuando la cadena comienza con el delimitador, el primer elemento se convierte en cadena vacía.
String[] items = ",A,B,C".split(",");

Es equivalente a:
    String[] items = { "", "A", "B", "C" };

*

*Medio: - cada ocurrencia adicional del delimitador en el medio de la Cadena resultará en una cadena vacía correspondiente:
String[] items = ",A,B,,,C".split(",");

Es equivalente a:
    String[] items = { "", "A", "B", "", "", "C" };

*

*Sufijo: toda la ocurrencia del delimitador al final de la cadena será ignorada.
String[] items = "A,B,C,,,,,,,,,,".split(",");

Es equivalente a:
    String[] items = { "A", "B", "C" };

Sin embargo, podemos forzar división para contar todos los delimitadores adicionales al final de la cadena pasando -1 como límite:
    String[] items = "A,B,C,,,".split(",", -1);

Es equivalente a:
    String[] items = { "A", "B", "C", "", "", "" };

Fuentes:

*

*How to split a string in Java

*Java String Split Tutorial And Examples

A: Es importante tener en cuenta que al realizar el .split()
el primer elemento empieza en [0]
String value= "123-654321";
String[] parts = value.split("-");

System.out.println(parts[0]); //out --> 123

Si el resultado no es conseguido por el separador, la posición [0] será igual al string original
String value= "123-654321";
String[] parts = value.split("p");

System.out.println(parts[0]); //out --> 123-654321

A: Tres formas diferentes de hacerlo:
1. Utilizando la función String.split() :
 String str = "123-654321";
 String[] parts = str.split("-");

Esta solución utiliza expresiones regulares, así que no es lo más eficiente si no estas trabajando con ellas.

2. Utilizando la clase StringTokenizer :

static private List<String> fastSplit(final String text, final String separator, final boolean emptyStrings){
    List<String> result = new ArrayList<String>();
    final StringTokenizer st = new StringTokenizer(text, separator, true);
    String token = null;
    String lastToken = separator;
    while (st.hasMoreTokens()) {
            token = st.nextToken();
            if (token.equals(separator)) {
                    if (lastToken.equals(separator) && emptyStrings) {
                            result.add("");
                    }
            } else {
                    result.add(token);
            }
            lastToken = token;
    }

    return result;
}

El problema con este método es que solo funciona bien cuando el delimitador tiene longitud 1.

3. Implementarlo usando String.indexOf() :

En este caso si funcionará correctamente para delimitadores de cualquier longitud.
static private List<String> fastSplit2(final String text, final String separator, final boolean emptyStrings) {
    final List<String> result = new ArrayList<String>();

    if (text != null && text.length() > 0) {
        int index1 = 0;
        int index2 = text.indexOf(separator);
        int sepLen = separator.length();
        while (index2 >= 0) {
            String token = text.substring(index1, index2);
            if (!token.isEmpty() || emptyStrings){
                result.add(token);
            }
            index1 = index2 + sepLen;
            index2 = text.indexOf(separator, index1);
        }

        if (index1 < text.length() - 1) {
            result.add(text.substring(index1));
        }
    }

    return result;
}

A: Usando StringTokenizer: en el constructor de tal detallamos el delimitador "-", new StringTokenizer(nombre,"-");
import java.util.StringTokenizer;
    public class Separador
    {
      public static void main(String[] args)
      {

        String nombre="004-034556";
        StringTokenizer tokens=new StringTokenizer(nombre,"-");
        while (tokens.hasMoreTokens()) {
             System.out.println(tokens.nextToken());
         }

      }
    }


text:
Q: Hyper-V Performance Monitor Counters Is there any ultimate Hyper-V Performance Monitor Counters guide from Microsoft I can use to see the official (not blog-posted) information of what each counter does and how it should be used?
It is felt that google doesn't know any, some people say it doesn't even exist.

A: Not so official but still looks legit: https://blogs.technet.microsoft.com/chrisavis/2013/03/25/performance-management-monitoring-cpu-resources/

A: Found this (using DuckDuckGo ;) https://learn.microsoft.com/en-us/windows-server/administration/performance-tuning/role/hyper-v-server/detecting-virtualized-environment-bottlenecks
Is this what you are looking for?


text:
Q: Rails i18n how to get all keys for a locale file? I want to create translation overrides for customers in my app. I want a list of locale section's key to render for a form.
In Rails I18n, how do I get all keys for a given locale file?
en:
  foo:
    bar:
      some_term: "a translation"
      some_other_term: "another translation"
  baz:
    bizz: "hello"

Results would look something like
[
  "foo[bar][some_term]",
  "foo[bar][some_other_term]",
  "baz[bizz]"
]


text:
Q: the minimum of a differentiable function I'm trying to prove the following claim:
$f:\left[p,q\right]\:\to\mathbb R,\ f$ is differentiable at $p$ and $p$ is a minimum of $f$. prove or disprove: $f'(p) \ge  0$.
When I draw a graph, it seemed obvious that the claim is true. the minimum is at the left edge of the function, so the function must go up afterwards.
but as I know, the derivative at minimum / maximum equals to $0$. So why am I being asked about $f'(p) \ge  0$ ?
Tryed to prove using rolle theorem, but I don't know if the function is differentiable at $q$ (and maybe it isn't).

A: $$f'(p) = \lim_{x \to p \\ x > p} \frac{\overbrace{f(x) - f(p)}^{\ge 0}}{\underbrace{x-p}_{\ge 0}} \ge 0$$


text:
Q: JQuery to Mootools Can anybody help me converting this jquery code into mootools, please?
$("#" + '<%= txtInput.ClientID %>').parent().find(".textboxlist-bit-box-deletebutton").each(function(){
    $(this).click();
});

A: document.id('<%= txtInput.ClientID %>')
    .getParent()
    .getElements(".textboxlist-bit-box-deletebutton")
    .each(function(button) {
         button.fireEvent("click");
    });

Trivially converted from reading the MooTools docs


text:
Q: gem uninstall rake-10.1.0 error (couldnt remove from gem list and im trying to use rake-0.8.3) gem list shows rake (10.1.0, 0.8.3),trying to uninstall rake 10.1.0 by gem uninstall rake -v '10.1.0' getting ..INFO:  gem "rake" is not installed showing rake 10.1.0 in gem list...my goal is to use rake-0.8.3 So any one can help (using rails-2.3.5)?

A: I think if you just do gem uninstall rake, you should then be prompted to determine which version you'd like to uninstall. I'd just do that and uninstall all of the versions that you're not wanting to use.
Another solution might be to just specify which version of rake you'd like to use in your gemfile.


text:
Q: Python capture mouse inside 3D environment I'm trying to create data files for behavorial cloning in reinforcement learning and I need to capture mouse movement inside a first person 3D game. I've researched in multiple sites already and only found mouse functions (like from pyautogui and mouse libraries) that capture the mouse movement in 2D environments, like the desktop; in those cases, moving mouse on 3D envs causes starting mouse coords to be equal to final mouse coords.

A: Forget it, got it:

import win32api

x, y = win32api.GetCursorPos()
mouse_x, mouse_y = 0, 0
for j in range(5):
    last_x, last_y = win32api.GetCursorPos()
    if (x, y) != (last_x, last_y):
        #count = count +1
        #print("Pos:, ", (last_x - x),(last_y - y))
        mouse_x += last_x - x
        mouse_y += last_y - y

        x, y = last_x, last_y
        #print("Mouse Movement # ", count)
    sleep(0.01)


text:
Q: Double Click is not working on Image but working on white space near image in Tile List in Flex I'm facing a typical problem . Tile list getting data from array collection which are SWF images.
When user click on image it doesn't go to the itemDoubleClick(event) handler. But If user click on white space near Image, Control goes inside itemDoubleClick(event) handler.
If i use itemClick(event) , then it is working fine.
Expected Result:
When User double click on image it should load on different layout.
Code Demo is
Mxml Part is :->
<mx:TileList id="imgView"
                 columnCount="3"
                 width="100%"
                 height="292"
                 styleName="tilelistContainer"
                 dataProvider="{imageArr}"
                                 itemRenderer="com.Images"
                 itemDoubleClick="{imageGalleryClickHandler(event)}"
                 doubleClickEnabled="true"
                 dragEnabled="true"
                 />

ActionScript Code is :->
public function imageGalleryClickHandler(evnt:ListEvent):void
{
   Alert.Show("Control is in double click handler"):

}

I'm fed of this, please help.
As per your Comment, I'm updating the Code of ItemRenderer. Please check this.
Updated Code
<utils:LoadingImage source="{data.value}"
                        width="100%"
                        verticalAlign="middle"
                        horizontalAlign="center"
                        height="100%"
                        maintainAspectRatio="true"
                                            doubleClickEnabled="true"
                        scaleContent="true"
/>

A: This link might explain what is going on - not a solution but what might be causing it:
Flex tilelist itemrender instance not match the dataprovider length
This link explaining about possibly using ITEMCLICK might help:
http://andymatthews.net/read/2009/09/20/Beginning-Flex:-TileList-using-the-itemClick-vs-click-events

A: Try this will work for event handing { } binding notation not need here try remove those braces like
itemDoubleClick="{imageGalleryClickHandler(event)}" to itemDoubleClick="imageGalleryClickHandler(event)"
<mx:TileList id="imgView"
                     columnCount="3"
                     width="100%"
                     height="292"
                     styleName="tilelistContainer"
                     dataProvider="{imageArr}"
                     itemRenderer="com.Images"
                     itemDoubleClick="imageGalleryClickHandler(event)" //Remove Curly braces
                     doubleClickEnabled="true"
                     dragEnabled="true"
                     />

Based on your comments
you need set doubleClickEnabled="true" for your itemRenderer and Image aswell inside itemRenderer else double click event won't propagate(trigger).


text:
Q: Script that handles opening a non-existing file, 'unknown_file.txt', and prints the message File not found. to the user
*

*I am trying to write a script in Python that handles opening a
non-existing file, 'unknown_file.txt', and prints the message File
not found. to the user.

*Use try ... except clauses. Print the user message inside except
clause.

The code which I tried was :
try:
  f= open("unknown.txt")

except FileNotFoundError as e:
    print(e)

Actual result basis above code:
[Errno 2] No such file or directory: 'unknown_file.txt'

A: The below should work for you:
import os

file_exists = os.path.isfile('FILEPATH')
if file_exists:
   print('File Exists')
else:
    print('File Does Not Exist')

A: The message is coming due to the description that written inside FileNotFoundError exception class. For your actual intended message to appear in screen, try the below code:
try:
    f = open("unknown_file.txt")
except FileNotFoundError as e:
    print("File not found")

A: try:
    fname = "unknown.txt"
    fopen = open(fname, "r")
except FileNotFoundError:
    print("File not found")


text:
Q: why are the probabilities so high in this probability mass function table I was trying to replicate this exercise to generate a Normal Distribution Curve using Excel.
    x                    y
0.014452026         2.041422596
0.025093415         2.773027064
0.036616595         3.690210953
0.048419685         4.70609312
0.063687414         5.983995012
0.065477198         6.121209906
0.065497115         6.122714773
0.067684709         6.284810609
0.085710482         7.300373495
0.098747318         7.564268139
0.101472876         7.56198632
0.124308524         6.791278772
0.127989314         6.558494815
0.133802085         6.145728814
0.16080235          3.87480258
0.161364785         3.827066422
0.165609825         3.47247356
0.171043079         3.03728475
0.178465274         2.486521044

Column x is a column of random numbers generated using Excel's Rand() function
The mean of Column x is 0.099802319 and the standard deviation is: 0.052729812
Column y is generated using Excel's Norm.Dist() function, with the last argument set to "False" (the probability mass function option)
I was able to generate a nice Normal Distribution Chart.

My question for you: Why are the values in Column y so large? I thought these were going to be probabilities and expected them to be <1.

A: To elaborate on Alex R.'s point: You're assuming that the normal distribution represents the probability of a given point $x$. But the probability of obtaining any particular real number is zero. Rather, probabilities are obtained from the normal distribution by looking at the area under the curve. For instance, the area from 0.05 to 0.15 is roughly $0.1\times 7=0.7$. So this normal distribution will produce a result between 0.05 and 0.15 about 70% of the time, which is a perfectly sensible result. (A more precise computation, taking the average as $\mu=0.1$ and the standard deviation as $\sigma=0.05$, gives a probability of about 68%. This is a characteristic result of normal distributions: About 68% of the samples are within one standard deviation of the mean.)


text:
Q: How do I ignore the initial load when watching model changes in AngularJS? I have a web page that serves as the editor for a single entity, which sits as a deep graph in the $scope.fieldcontainer property. After I get a response from my REST API (via $resource), I add a watch to 'fieldcontainer'. I am using this watch to detect if the page/entity is "dirty". Right now I'm making the save button bounce but really I want to make the save button invisible until the user dirties the model.
What I am getting is a single trigger of the watch, which I think is happening because the .fieldcontainer = ... assignment takes place immediately after I create my watch. I was thinking of just using a "dirtyCount" property to absorb the initial false alarm but that feels very hacky ... and I figured there has to be an "Angular idiomatic" way to deal with this - I'm not the only one using a watch to detect a dirty model.
Here's the code where I set my watch:
 $scope.fieldcontainer = Message.get({id: $scope.entityId },
            function(message,headers) {
                $scope.$watch('fieldcontainer',
                    function() {
                        console.log("model is dirty.");
                        if ($scope.visibility.saveButton) {
                            $('#saveMessageButtonRow').effect("bounce", { times:5, direction: 'right' }, 300);
                        }
                    }, true);
            });

I just keep thinking there's got to be a cleaner way to do this than guarding my "UI dirtying" code with an "if (dirtyCount >0)"...

A: The first time the listener is called, the old value and the new value will be identical. So just do this:
$scope.$watch('fieldcontainer', function(newValue, oldValue) {
  if (newValue !== oldValue) {
    // do whatever you were going to do
  }
});

This is actually the way the Angular docs recommend handling it:

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization

A: I realize this question has been answered, however I have a suggestion:
$scope.$watch('fieldcontainer', function (new_fieldcontainer, old_fieldcontainer) {
    if (typeof old_fieldcontainer === 'undefined') return;

    // Other code for handling changed object here.
});

Using flags works but has a bit of a code smell to it don't you think?

A: During initial loading of current values old value field is undefined. So the example below helps you for excluding initial loadings.
$scope.$watch('fieldcontainer',
  function(newValue, oldValue) {
    if (newValue && oldValue && newValue != oldValue) {
      // here what to do
    }
  }), true;

A: Just valid the state of the new val:
$scope.$watch('fieldcontainer',function(newVal) {
      if(angular.isDefined(newVal)){
          //Do something
      }
});

A: set a flag just before the initial load,
var initializing = true

and then when the first $watch fires, do
$scope.$watch('fieldcontainer', function() {
  if (initializing) {
    $timeout(function() { initializing = false; });
  } else {
    // do whatever you were going to do
  }
});

The flag will be tear down just at the end of the current digest cycle, so next change won't be blocked.


text:
Q: Canceling alarm when activity is destroyed I have a service running in my Android app. This service was started using an AlarmManager with a repeating alarm. When a certain event occurs, the service sends out a broadcast, which is received within a Fragment. There the alarm is canceled (alarm.cancel(pendingIntent)).
So far, so good. But what do I do if the activity/fragment gets destroyed? How can I still cancel the service?

A: Just call this alarm.cancel() with the same pendingIntent you've used to start it at the onDestroy method of Activity/Fragment:
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent)

From the description of cancel() method:
Remove any alarms with a matching Intent. Any alarm, of any type, whose Intent matches this one (as defined by filterEquals(Intent)), will be canceled.


text:
Q: Prove that $\lim_{n \to \infty} \sup (x_n) =\min\{A \in \Bbb{R} : \forall\epsilon>0 \{n \in \mathbb{N}: x_n \geq A+ \epsilon \} $ set is finite} Any tips solving this?
I think I need to firstly show that $\lim \sup x_n$ is element of the given min{...} set and secondly there are no smaller elements in the given set.
Should I open the set with minimum definition? Or something like this:
$x_n > a+ \epsilon$ for finite number of sequence $x_n$ elements $\forall \epsilon$...
Thanks!
Edit: sequence $x_n$ is bounded.

A:
Definition $1$ : $\limsup x_n$ is the supremum of the set of all (extended real) limit points of $x_n$ (and $-\infty$ if the set is empty). If real, then it is also a limit point, by the fact that the set of limit points of any set is closed.

If you do not know definition $1$ then proceed to definition $2$. You must be knowing at least one of these, and it is not difficult to show they are equivalent.
The boundedness of $x_n$ ensures that the limit supremum is a real number, hence we need not worry about infinities.
With this in mind, let us call the set $\{a \in\mathbb R : \forall \epsilon > 0 \mbox{,the set } \{n \in \mathbb N : x_n \geq a + \epsilon\} \mbox { is finite} \} = S$. We want to show that $\inf S \geq \limsup x_n$, and that $\limsup x_n \in S$. This will show that $\limsup x_n$ is the minimum of $S$, as desired.

Suppose $t < \limsup x_n$. Let $\epsilon = \frac{\limsup x_n - t}2$ . Then, take the subsequence $x_{n_k}$ which converges to $\limsup x_n$ : note that there exists $N$ such that $K > N $ implies  $x_{n_K} > t + \epsilon$ eventually,  since $t + \epsilon < \limsup x_n$, and $x_{n_k}$ is converging to the right hand side. This forces that $\{n \in \mathbb N : x_n \geq t+\epsilon\}$ is infinite, since $n_N, n_{N+1}$ etc. belong to this set.
Consequently, we have shown that $t \notin S$. In otherwise, for every $s \in S$, we must have $s \geq \limsup x_n$. This also gives $\inf S \geq \limsup x_n$.

We will now show that $\limsup x_n \in S$. Suppose not. Then, there exists $\epsilon > 0$  such that the set $\{n \in \mathbb N : x_n \geq \limsup x_n  + \epsilon\}$ is infinite. Now, take the elements of this set and order them like $m_1,m_2,...$. So we have $x_{m_i} \geq x_n + \epsilon$ for all $i$. The $x_{m_i}$ is a subsequence of $x_n$, hence bounded, but then any limit point of $x_{m_i}$ is a limit point of $x_n$, which must be strictly larger than $\limsup x_n$, since every element of $x_{m_i}$ is larger than $\limsup x_n + \epsilon$. This contradicts the definition of $\limsup x_n$, showing that $\limsup x_n \in S$.
Consequently, we have shown that $\limsup x_n \in S$ and every other element of $S$ is larger than $\limsup x_n$. It follows that $\limsup x_n = \min S$ as desired.

Definition $2$ : $\limsup x_n = \lim_{n \to \infty} (\sup_{k \geq n} x_k)$.

Notation is the same as for definition $1$. We will use the same proof plan as for definition $1$ as well. Note that the sequence $\sup_{k \geq n} x_k$ is  a decreasing sequence, since the set over which supremum is being taken is getting smaller with increasing $n$.

Let $t \in S$. Then, fix $\epsilon > 0$. By definition of being in $S$, we see that $\{n \in \mathbb N : x_n \geq t + \epsilon\}$ is finite. Therefore, $t + \epsilon\geq \sup_{n \geq N+1} x_n$ for $N$ being the maximum of this set. But since $\sup_{k \geq N} x_k$ is decreasing, the right hand side is automatically greater than $\limsup x_n$, which is the limit of the decreasing sequence it is part of. So $t + \epsilon \geq \limsup x_n$, for all $\epsilon$, giving $t \geq \limsup x_n$.

Now, to show that $\limsup x_n \in S$, fix $\epsilon > 0$. Suppose $\{n : x_n \geq \limsup x_n + \epsilon\}$ is infinite. Order the elements of this set as $m_1,m_2,...$, then note that $\sup_{k \geq m_i} x_{k}\geq x_{m_i} \geq \limsup x_n + \epsilon$ for all $i$.  As a subsequence of the sequence $\sup_{k \geq n} x_k$ , this sequence must also converge to $\limsup x_n$, but it cannot be always greater than $\limsup x_n + \epsilon$, so there lies the contradiction.
Hence, we complete our proof in the same way.


text:
Q: real time series, differences in numpy ifft v. irfft I want to generate a random time series with a prescribed spectral shape.  To do this I will draw random complex Fourier coefficients with from the appropriate spectral distribution then transform the frequency to the time domain.
To generate a real time series, the Fourier spectrum must have real DC and Nyquist coefficients and have symmetric negative frequencies.
When I do this, I get different behavior from numpy's ifft versus its irfft.
As an example, here's a 32 sample white spectrum:
import numpy as np

Nsamp = 2**5
Nfreq = (Nsamp-1)//2 # num pos freq bins not including DC or Nyquist

DC = 0.
f_pos = np.random.randn(Nfreq) + 1j*np.random.randn(Nfreq)
Nyquist = np.random.randn() # this is real
f_neg = f_pos[::-1] # mirror pos freqs

f_tot = np.hstack((DC, f_pos, Nyquist, f_neg))
f_rep = np.hstack((DC, f_pos, Nyquist))

t1 = np.fft.ifft(f_tot)
t2 = np.fft.irfft(f_rep)

print(t1)
print(t2)

I would expect both t1 to be real and t1 and t2 to agree (within machine precision).  Neither is true.
Am I using the ifft correctly?  Looking at the frequencies output by np.fft.fftfreq(Nsamp), makes me think I'm building f_tot correctly for input.
irfft is the correct result, so I'll use that... but I'd like to know how use ifft for the future.

from the numpy.fft docs:

A[0] contains the zero-frequency term (the sum of the signal), which is always purely real for real inputs. Then A[1:n/2] contains the positive-frequency terms, and A[n/2+1:] contains the negative-frequency terms, in order of decreasingly negative frequency. For an even number of input points, A[n/2] represents both positive and negative Nyquist frequency, and is also purely real for real input.


text:
Q: SimpleInjector named parameter registration I have a service constructor with multiple same-type parameters dependencies
class Service{
    public void Service (String connectionStringOne, string connectionStringTwo)
    {}
}

How can I do this registration in SimpleInjector container.
I assumed I would use RegisterConditional providing the predicate.
e.g.
Container.RegisterConditional(typoef(string),"SQLConnectionString",Leftstyle.Singleton, pc => pc.ParameterName == "connectionStringOne")
Container.RegisterConditional(typoef(string),"MDXConnectionStribng",Leftstyle.Singleton, pc => pc.ParameterName == "connectionStringTwo")

However the PredicateContext does not provide 'ParameteName'

A: You should register your service using a factory delegate:
container.Register<IService>(() => new Service("str1", "str2"));