text:
Q: How to control packet generation rate and send interval I am trying to create an UDP application where the packet generation rate and packet send interval can be controlled separately.
My code is in https://github.com/11187162/udpApp
With the above code, I am not getting the expected outcome and getting the following runtime error:

scheduleAt(): Message (omnetpp::cMessage)sendTimer is currently
scheduled, use cancelEvent() before rescheduling -- in module
(inet::UdpOwnApp) SensorNetworkShowcaseA.sensor3.app[0] (id=176), at
t=0.058384669093s, event #10

The code for handleMessageWhenUp() is given below.
void UdpOwnApp::handleMessageWhenUp(cMessage *msg)
{
    if (msg->isSelfMessage()) {
        ASSERT(msg == selfMsg);
        switch (selfMsg->getKind()) {
            case START:
                processStart();
                break;

            case GENERATE:
                generatePacket();
                break;

            case SEND:
                processSend();
                break;

            case STOP:
                processStop();
                break;

            default:
                throw cRuntimeError("Invalid kind %d in self message", (int)selfMsg->getKind());
        }
    }
    else
        socket.processMessage(msg);
}

Would anyone please help me?
Thank you

A: You have written that "generation rate and packet send interval can be controlled separately" but you use the same self-message for control generation of packets as well as for sending of the packets. When a self-message is scheduled it cannot be scheduled again.
Consider adding a new self-message for generation of packets.
By the way: numGenerate is set to zero and it is never changed.
EDIT
Assuming that selfMsg1 is used for generating packets only the following code may be used:
void UdpOwnApp::handleMessageWhenUp(cMessage *msg) {
      if (msg->isSelfMessage()) {
        if (msg == selfMsg) {
          switch (selfMsg->getKind()) {
            case START:
                processStart();
                break;
            case SEND:
                processSend();
                break;
            case STOP:
                processStop();
                break;
            default:
                throw cRuntimeError("Invalid kind %d in self message", (int)selfMsg->getKind());
            }
        } else if (msg == selfMsg1) {
            if (selfMsg1->getKind() == GENERATE) {
                generatePacket();
        }
        }
      }
    else
        socket.processMessage(msg);
}

And in initialize() you should create an instance of selfMsg1.


text:
Q: Working with an Orchard CMS Theme I'm working to quickly build a site with Orchard CMS. My site will use a custom theme. I'm editing this theme in Visual Studio. It seems like my changes never take when I update my "Layout-url-homepage.cshtml" file. It seems like there has to be a more elegant way to make updates to a theme and test it more rapidly.
What am I doing wrong?

A: You probably didn't enable the url alternates feature. Or you set-up caching too aggressively. Changes to templates are immediately reflected otherwise.

A: You can also use the "Theme Editor" module, by Rickard Magnusson to change the layout of a specific page.
You can see in this article how to do it.
http://support.bind.pt/entries/21855492-Assigning-a-layout-to-a-single-page

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect pandas column(s) causing row uniqueness I am attempting to drop duplicate rows in a pandas DataFrame with many columns. The problem is that there must be some column with unique values, because
df.drop_duplicates(subset=None, keep='first', inplace=True)
does not drop all of the rows I would expect it to.
Selecting two rows that appear to me to be duplicates, I tried a visual comparison but was unable to identify a difference between them. Because there are many columns, visual inspection is time consuming and error-prone. I would like an automated way to find the columns for which there are differences across a list of rows. I am not sure how to do this in pandas, to which I am fairly new. I didn't find any previous questions on this topic.
Edit: I am interested in detecting the columns with unique values, as opposed to merely dropping duplicates based on a predetermined subset of columns.

A: For two rows, iterate over the values of each row to find out where they differ:
import pandas as pd
data = {'a': [1, 1], 'b': [1, 1], 'c': [1, 2], 'd': [1, 3]}

df = pd.DataFrame(data, index=['foo', 'bar'])

     a  b  c  d
foo  1  1  1  1
bar  1  1  2  3

differences = [i for i, (x,y) in enumerate(zip(df.loc['foo'].values, df.loc['bar',:].values)) if x!=y ]
df.iloc[:, differences]

     c  d
foo  1  1
bar  2  3

Now, for a set of rows, you would need to make all possible pairwise comparisons between rows, each time potentially with a different result.


text:
Q: Mass gap v.s. classical nonlinear Yang-Mills waves Why people said (Witten, p. 11),

"For Yang-Mills theory. the mass gap is the reason that we do not see classical nonlinear Yang-Mills waves. They are a good approximation only under inaccessible conditions"

*

*Above the energy / mass gap, should we still see the classical nonlinear Yang-Mills waves?

*In the spin system, for example, couldn't we still see the spin wave above the massive spin gap? Could it have linear dispersion or high order non-linear dispersion?


text:
Q: How to add auto complete to a table in php I need to add autocomplete function to a table when searchg by entering a keyword in a textbox. i have less expirience in php  laravel.
 My requirement is as below. In the interface there is a text box to search and a table is displaying below that.
For an example it's process is like if i enter "a" in the text box, all the records which starting from "a"  should display in the table and the displaing outputs in table should change acording to the entering input. If the search textbox is empty  all the records should display in the table.

A: There are two ways of solving this with DataTables.

*

*The whole table data is sent to client side on page load.

*The whole data is too big to be sent over to client in one page reload and you need to do this in chunks/pagination.

In case of 1st possibility, this is as simple as including the js,css files and then instantiating the dataTable after the dom has loaded, this will replace the static HTML table with a dynamic searchable table, no additional changes are needed on server end.
In case of 2nd possibility, you are going to need to use to implement dataTable with ajax pagination. But this requires a controller(since you are working with laravel) to output the data in json format for the datatables to process.
A live example of case 1,  case 2.


text:
Q: Writing from one instance of Excel to another open instance I am using a workbook to display operator data. This work book is always open and needs to stay open. Im trying to open a different instance of excel and have it write and update values on the open display workbook. The path to the workbook is G:\TLS-Shared\Maintenance\POWDER LINE DISPLAY\input.xlsm and the always open workbook is G:\TLS-Shared\Maintenance\POWDER LINE DISPLAY\display.xlsm I need to transfer 7 columns, 30 rows of each column from input.xlms sheet name "data" to the open book sheet name DisplayData. I will need this to regularly update or click a button to update.

A: Copy the data from the input workbook  and then in the display workbook (has to be in the same Excel instance) click Paste > Paste Link

Now in the Data tab you can click Refresh all to update the data when needed

You can also change the connection property to refresh every minute:

Works even if the input workbook is closed.

A: Can you simply record a Macro to do most of what you want and modify it a bit?  That should pretty much do it.


text:
Q: When I press backspace after logging out of a flask application, I am still able to access the restricted page using Flask + Dash from flask import session
from functools import wraps
import flask
from flask import Flask, redirect, url_for, render_template, session
from flask_dance.contrib.google import make_google_blueprint, google
from flask_login import LoginManager, login_user , logout_user , current_user , login_required
from flask_session import Session
import time, dash, os, json, flask, configparser, shutil, base64, io
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
from dash_table import DataTable
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_daq as daq
import plotly.graph_objs as go
from dash.exceptions import PreventUpdate
import dash_table.FormatTemplate as FormatTemplate
from dash_table.Format import Format
from dash_extensions import Download

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = dict(session).get('profile', None)
        # You would add a check here and usethe user id or something to fetch
        # the other data for that user/check if they exist
        if user:
            return f(*args, **kwargs)
        return render_template('index.html')
    return decorated_function

# AS simeple as possbile flask google oAuth 2.0
from flask import Flask, redirect, url_for, session
from authlib.integrations.flask_client import OAuth
import os
from datetime import timedelta
#dotenv setup
from dotenv import load_dotenv
load_dotenv()

# App config
server = Flask(__name__)
server.secret_key = 'xxxx'
server.config['SESSION_COOKIE_NAME'] = 'google-login-session'
server.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=120)

# oAuth Setup
oauth = OAuth(server)
google = oauth.register(
    name='google',
    client_id='xxxx',
    client_secret='xxxx',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    access_token_params=None,
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    authorize_params=None,
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo',  # This is only needed if using openId to fetch user info
    client_kwargs={'scope': 'openid email profile'},
)

@server.route('/')
@login_required
def index():
    email = dict(session)['profile']['email']
    return render_template('index.html')

@server.route('/login')
def login():
    google = oauth.create_client('google')  # create the google oauth client
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@server.route('/authorize')
def authorize():
    google = oauth.create_client('google')  # create the google oauth client
    token = google.authorize_access_token()  # Access token from google (needed to get user info)
    resp = google.get('userinfo')  # userinfo contains stuff u specificed in the scrope
    user_info = resp.json()
    user = oauth.google.userinfo()  # uses openid endpoint to fetch user info
    # Here you use the profile/user data that you got and query your database find/register the user
    # and set ur own data in the session not the profile from google
    session['profile'] = user_info
    session.permanent = False  # make the session permanant so it keeps existing after broweser gets closed
    return redirect('/Planner/')

@server.route('/Planner/logout')
def logout():
    for key in list(session.keys()):
        session.pop(key)
    return redirect('/')

app = dash.Dash(__name__, server = server,
                url_base_pathname='/Planner/')
app.scripts.config.serve_locally = False
app.title = 'Scenario Planner'
app.layout = html.Div([html.Div('Hey'), html.Br(), html.A('Logout', href = './logout')])

if __name__ == "__main__":
    server.run(debug=False)

This is my code. Basically there is a plotly dash application as well running in my code. Everything works except for restricting access to the dash application. If I use localhost:5000/Planner, irrespective of the authentication, my app is displayed.
If I follow the authentication flow, sign in, and then sign out and then click backspace, the dash application is still accessible. Is there a way I can modify this code to restrict such access.

A: Using a previous answer which somewhat solved this problem: Running a Dash app within a Flask app I have come up with this solution:
You can add this to your code:
@server.route('/plotly_dashboard')
@login_required
def render_dashboard():
    return flask.redirect('/Planner')


text:
Q: Elements In Table Moving When Text Added to Label I have a table on a cshtml page:

Upload File:

                            <input type="button" id="choose" value="Choose File" onclick="document.getElementById('file_upload').click();" />
                            <input type="file" class="form-control no-border" style="display:none;" id="file_upload" name="file_upload" onchange="addNew()" />

<input type="button" class="fbtn btn-custom btn-primary" onclick="submitFile(); return false;" value="submit" />

So the choose button is clicked, it opens a file chooser. When a file is chosen, it sets the text of the label 'file_upload_lbl' with the file name using juery:
    function addNew() {
        var file = document.getElementById('file_upload').files[0];
        if (file != null) {
            $("#file_upload_lbl").text(file.name);
        }
    }

The problem is, when the label text is set, it moves both the "Choose" and "Submit" buttons up about 5px, so the label and button are no longer aligned.
Is it because of the hidden file chooser? It shouldn't be, as style="display:none;" is supposed to ensure it takes up no space on the page. Is it because adding text is removing the css of the label? It doesn't move or change size, it seems like the buttons are moving...
Here's the css
    .fileLabel {
        border: 1px solid;
        width:400px;
        height:27px;
        margin-top:10px;
    }

Any ideas?

A: If you are including jquery with some other jquery files like jquery ui etc , It may cause this.without any extra package it works fine.

Upload File:

          <input
            type="button"
            id="choose"
            value="Choose File"
            onclick="document.getElementById('file_upload').click();"
          />
          <input
            type="file"
            class="form-control no-border"
            style="display: none"
            id="file_upload"
            name="file_upload"
            onchange="addNew()"
          />

<input
            type="button"
            class="fbtn btn-custom btn-primary"
            onclick="submitFile(); return false;"
            value="submit" />


text:
Q: Export variable to parent process When writing fish scripts, I'd like to be able to factor out common code into separate scripts. Something akin to this:
#! /usr/bin/fish

fish setup.sh

// Put rest of my code here.

but, as far as I can see, there's no way to export variables to parent processes, only children. Children can be done with set --export; is there a way to make variables visible to parents? I understand that the mechanisms are probably not similar, but it would be nice.

A: The UNIX process model makes it impossible for a process to affect the environment of any other process. This isn't a limitation of fish. The solution is to use the source command so the statements in setup.sh are executed in the context of the current process. If setup.sh is not a fish script the usual solution is to have it write export VAR=val statements to stdout then do setup.sh | source -.


text:
Q: How to prevent cross-user related objects How can I prevent cross-user related objects in multi-tenant shared-schema architecture?
For example:

*

*ModelA has foreign key parent to ModelB

*instance_a.parent == instance_b.

I can always check if instance_A.owner == instance_b.owner but that means an extra SELECT query for each INSERT query.
Is there any better way of validating related object?
My database is MySQL.

A: Use select_related('model_B') while making query..
https://docs.djangoproject.com/en/1.9/ref/models/querysets/#select-related


text:
Q: Checking for Value in JS Object I have a JS Object like so:
var ob{
  1 : {
        id:101,
        name:'john',
        email:'john@email.com'
      },
  2 : {
        id:102,
        name:'jim',
        email:'jim@email.com'
      },
  3 : {
        id:103,
        name:'bob',
        email:'bob@email.com'
      },
}

I want to check if this JS object already contains a record. If it doesn't then I want to add it. For example.
if(ob contains an id of 101){
//don't add john
}else{
//add john
}

Catch my drift? Pretty simple question. I just want to know the best way of doing it.
Thanks Guys!
W.

A: var found = false;
for(var nr in ob) {
  if(ob.hasOwnProperty(nr)) {
    if(ob[nr].id === 103) {
       found=true;
       break;
    }
  }
}
if(!found) {
  //add ...
}

It would've been easier if you could use the id as key for the object

A: Simple:
function contains_id(obj, id) {
   for(var key in obj)
     if(obj.hasOwnProperty(key) &&
        obj[key]['id'] && obj[key]['id'] == id)
        return true;
   return false;
}

var ob = ...
if(contains_id(ob, 2)) {
   //do something...
} else {
   //do something else...
}

A: Is it problem to use id as key of your object? Like that:
var ob{
  101 : {
        id:101,
        name:'john',
        email:'john@email.com'
      },
  102 : {
        id:102,
        name:'jim',
        email:'jim@email.com'
      },
  103 : {
        id:103,
        name:'bob',
        email:'bob@email.com'
      },
}

if(ob[101]){
//don't add john
}else{
//add john
}

A: I am quite certain you cant do that without a loop as far as IN is concerned is to check the object's em how to say it...properties for example if the "id" exists in your example and not the variable

A: Unless they are indexed by the value you are checking for, I believe you need to iterate over all elements in the object and check each one.
function recordExistsById(id, ob) {
    for (var key in ob) {
        if (ob[key].hasOwnProperty("id") && ob[key].id == id) {
            return true;
        }
    }
    return false;
}


text:
Q: Is there an application that will render the popular web video formats? I am trying to convert video to the formats commonly used for HTML5 embedding — that is, MP4 (H264 + AAC), OGV (Theora + Vorbis) and WebM (VP8 + Vorbis). I would like to use a GUI application to do this as simply as possible.
I have the Medibuntu repository installed, but it doesn't seem to help. Avidemux is missing the H264 video encoder, and Handbrake only does MP4 (not the other two). How can I configure these apps under 11.10 for my purposes, or alternatively, what else is there?

A: My answer to this question: How can I maximum compress video files? may be helpful for your case. In this answer I talk about Miksoft's Mobile Media Converter, but there are a few alternatives to this task which can easily be reached over the net.
Anyway, Mobile Media Converter will only work for 32 bit version OS's. And for both 32/64 bit version I suggest you to give a chance to
WinFF

Transmaggedon

Transcoder

Arista Transcoder

And there are some other useful Transcoding Software, which includes Non Linear Editing Systems like those mentioned on the answers to this question: What is an easy video editor? and command line using ffmpeg. (as mentioned by @tomodachi)
Nevertheless, the trick in compression (in order to make the videos lighter when loaded to/from the server) isn't in the software itself but the way you make your videos.
You must pay special attention to the Audio and Video Bitrates, which determines both the quality and file size for the resulting transcoded videos and remember that the higher bitrate will result in a higher quality but it will also drop "heavy" file sizes.
You should run as many tests as you need in order to feel comfortable with both the resulting quality and file size.
There is no a pre-defined set of parameters which will do always the same for your videos when you are trying to save something, let's say: quality and file size, or in the worst case: both them.
There is no such "magic codec" that will result in a better quality with small file sizes. Take in consideration that you could have a mpeg1 video file (VCD) with a high bitrate looking better than an mp4 video file with a lower bitrate.
Additionally and only for your consideration:
The FileInfo.com webpage related to "Video Formats" provides an extensive and really comprehensive list of video formats, its available software which can be used to play each one and the "popularity".
You may also wish to take a look to the "Digital Container format" and the table of "Comparison of container formats".
Good luck!
- Parts of this answer were took from Reduce avi size without losing too much quality

A: Install ffmpeg from source! It might take a bit longer, but then you will get all the best possible coverage of supported formats.


text:
Q: Jasig-CAS single sign out issue with Java clients I have a CAS 3.5 server and two Java clients (let's call them app1 and app2) and I'm having trouble getting single sign out to work.
app1 and app2 are deployed in different instances of JBoss AS7.
The test case scenario is:
1 - In a browser tab, login successfully to app1.
2 - In an other tab, upon accessing app2, user is already logged in. (Single Sign On works).
3 - Succesful logout of app1.
4 - However, user continues to be logged in app2 even after page refreshes. JSESSIONID cookie still exists.
When logging out of app1 (step3), this gets printed on app2's console (log level: debug):
08:15:42,806 DEBUG [org.jasig.cas.client.authentication.Saml11AuthenticationFilter] (http--0.0.0.0-8080-3) no ticket and no assertion found
08:15:42,807 DEBUG [org.jasig.cas.client.authentication.Saml11AuthenticationFilter] (http--0.0.0.0-8080-3) Constructed service url: http://myip:8080/app2
08:15:42,807 DEBUG [org.jasig.cas.client.authentication.Saml11AuthenticationFilter] (http--0.0.0.0-8080-3) redirecting to "https://mycasip:8443/cas/login?TARGET=http%3A%2F%2Fmyip%3A8080%2Fapp2"

Just for the record, both cas server's and app2's URL seem to be constructed fine, however, no actual redirection happens.
I can't see anything printed on cas server's console (again log level: debug)
Here's an extract from my web.xml (I use SAML to send an ldap attribute besides username):
<filter>
    <filter-name>CAS Single Sign Out Filter</filter-name>
    <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>
    <init-param>
        <param-name>artifactParameterName</param-name>
        <param-value>SAMLart</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CAS Single Sign Out Filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
    <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener>

There is no filter definition before SingleSignOutFilter, only the app display-name and welcome-file-list.
I have read similar questions like this one(Note: I don't use spring nor jsp and user is still logged in after opening app2 in a new tab) but solutions didn't work for me or weren't given at all.


text:
Q: Why isn't my code working in command line? I am using Python3.6 and I need to run my code in command line. The code works when I run it in PyCharm but when I use command line I get this error:
 File "path", line 43, in <module>
     rb = ds.GetRasterBand(1)
AttributeError: 'NoneType' object has no attribute 'GetRasterBand'

It seems that I have a problem with these lines:
ds = gdal.Open('tif_file.tif', gdal.GA_ReadOnly)
rb = ds.GetRasterBand(1)
img_array = rb.ReadAsArray()

Does anyone know what I might have done wrong?
EDIT
Some magic just happened. I tried to run my code this morning and everything seems fine. I guess what my computer needed was a restart or something. Thanks to you all for help.

A: from the gdal documentation:
from osgeo import gdal
dataset = gdal.Open(filename, gdal.GA_ReadOnly)
if not dataset:
    ...

Note that if GDALOpen() returns NULL it means the open failed, and
that an error messages will already have been emitted via CPLError().
If you want to control how errors are reported to the user review the
CPLError() documentation. Generally speaking all of GDAL uses
CPLError() for error reporting. Also, note that pszFilename need not
actually be the name of a physical file (though it usually is). It's
interpretation is driver dependent, and it might be an URL, a filename
with additional parameters added at the end controlling the open or
almost anything. Please try not to limit GDAL file selection dialogs
to only selecting physical files.

looks like the file you are trying to open is not a valid gdal file or some other magic is going on in the file selection. you could try to direct the program to a known good file online to test it.


text:
Q: Does systemctl enable also restart the service The systemctl enable command does a daemon-reload. If the service is already running, does that also result in a restart of the service?

A: No.
daemon-reload basically re-reads the configuration from all the unit files.  But it does not perform the restart (or even reload) actions on any unit.
For example, if you change the ExecStart= line for a service, it will not change the currently running process.  The new ExecStart= command will be used if you restart the service.


text:
Q: Almost obvious equivalent det relations?!? Show that, for all $A,B\in M_n(\mathbb{R})$ such that $(A-B)^2=O_n$, we have
$$
\det(AB-BA)=0 \Leftrightarrow \det A=\det B.
$$

A: This is the case $2 \times 2$.
The case $A = B$ being bona fide obvious, assume, without loss of generality, $N = A - B = \begin{bmatrix}0&1\\0&0\end{bmatrix}$.
Write
$$
B = \begin{bmatrix}b_{11}&b_{12}\\b_{21}&b_{22}\end{bmatrix}.
$$
Then
$$
A B - B A
=
(B + N) B - B (B + N)
=
B^{2} + N B - B^{2} - B N
=\\=
N B - B N = \begin{bmatrix}b_{21}&b_{22}-b_{11}\\0&-b_{21}\end{bmatrix}.
$$
So $\det(A B - BA) = - b_{21}^{2}$.
Now
$$
\det(A) = \det\left(\begin{bmatrix}b_{11}&b_{12}+1\\b_{21}&b_{22}\end{bmatrix}\right)
= \det(B) - b_{21}.
$$


text:
Q: jQuery alternative to Flash Mosaic Image gallery I'm looking for a jQuery alternative to the Flash Mosaic FX gallery here
http://www.flashxml.net/mosaic-gallery.html
I manged to get the images to tile using the Masonry jQuery plugin however  I'm having difficulty trying to keep them tiled when they scale as the user mouse overs them..
I was hoping to see some tutorial on this if available
Thanks

A: Look at Isotope:
http://isotope.metafizzy.co/demos/relayout.html
Click on the item to grow it and click again to shrink it.


text:
Q: how get message body when FCM notification message is tap? When app is in background,  the notification message is deliver by Notification, when the notification is tap, app is launch, how can i get the message body?
the intent is this:
    Bundle[{google.sent_time=1470813025421, from=568540028909,
google.message_id=0:1470813025865549%31bd1c9631bd1c96,
 collapse_key=com.google.firebase.quickstart.fcm}]

no message body in intent, only message id!
Thanks!

A: try this
  @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            // TODO(developer): Handle FCM messages here.
            // If the application is in the foreground handle both data and notification messages here.
            // Also if you intend on generating your own notifications as a result of a received FCM
            // message, here is where that should be initiated. See sendNotification method below.
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "From: " + remoteMessage.getData().get("message"));
    //        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
// if you sending data with custom key
 Log.d(TAG, "Notification Message of custom key: " +remoteMessage.getData().get("your key"));
            sendNotification(remoteMessage.getData().get("message"));
        }

A: I am sorry but what you are trying to do is not possible.
Currently it's not possible to access the (body, title, icon ...) information of a
notification-message from the activity that is launched when the notification is opened.
You can instead access the data component of the notification message.
One possible alternative is to use data-message messages and create your own custom notification and custom logic.
see notification-message vs data-message here:
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
PS: if would be useful if you could report a Feature Request through the firebase support page.
In this way the team can correctly prioritize future features.
https://firebase.google.com/support/contact/bugs-features/


text:
Q: F# Type mismatch on curried functions I'm having a bit of trouble with the following FSharp/F# code:
module File1

let api a =
    printf ("VALUE = %A") a

let router ops =
    [|
       api (ops (fun (list, _) -> list()))
       api (ops (fun (_, get) -> get 1))
    |]

let withContext ops handler =
    let context = "CONTEXT"
    handler (ops context)

let operations context =
    printf ("CONTEXT = %s") context

    let list () = [|1;2;3|]
    let get id = "Test"
    (list, get)

let setup() =
    let ops = withContext operations
    router ops

Results in the following error
Results in the following compation error
Error   1   Type mismatch. Expecting a
    ((unit -> int []) * (int -> int []) -> int []) -> 'a
but given a
    ((unit -> int []) * (int -> string) -> 'b) -> 'b
The type 'int []' does not match the type 'string'

I know the problem is that ops function has been bound to return a int[] but I want to be able to also return a string.
I think I'm missing a trick with some generic declarations but after hours of moving code around I can't seem to work it out.
(I've simplified the code to highlight my problem)

A: The error is because ops needs to have a return type of its handler resolved at compilation, and you want to return different types base on some run-time logic.
It is basically an equivalent of:
let fun1 switch arg2 arg3 =
  if switch then
     arg2
  else
     arg3

and you want to run it this way:
fun1 true 1 "string"

Of course, arg2 and arg3 need to have the same type, so it won't work
What you can do is to run "api" function on a handler result, before returning it (so it will always the same type - unit).
let router ops =
    [|
        ops (fun (list, _) -> api <| list()))
        ops (fun (_, get) -> api <| get 1))
    |]

Alternatively, you could return objects of discriminated union type (then you will need some more logic in api function).
(Technically, you could also return obj).
Bonus
You don't need the array of units to be returned in a router function, returning one unit is just fine:
let router ops =
    ops (fun (list, _) -> api <| list()))
    ops (fun (_, get) -> api <| get 1))

In this way, setup function will also return unit and you will be able to run it without a need to run ignore on the result to get rid of This expression should have type 'unit', but has type 'unit[]' warning.

A: Your code is hard for me to understand, but I think the basic issue is that you want withContext to have a "rank 2" type (so that the universal quantification of the type variable 'b can happen after the application of the first argument).  In F#, this can be accomplished by creating a new type with a generic method and using that:
let api a =
    printf ("VALUE = %A") a

type Handler<'a> = abstract Handle<'b> : f:('a->'b) -> 'b

let router (ops:Handler<_>) =
    [|
       api (ops.Handle (fun (list, _) -> list()))
       api (ops.Handle (fun (_, get) -> get 1))
    |]
let withContext ops =
    let context = "CONTEXT"
    { new Handler<_> with member __.Handle f = f (ops context) }

let operations context =
    printf ("CONTEXT = %s") context

    let list () = [|1;2;3|]
    let get id = "Test"
    (list, get)

let setup() =
    let ops = withContext operations
    router ops


text:
Q: setting up Hadoop YARN on ubuntu (single node) I setup Hadoop YARN (2.5.1) on Ubuntu 13 as a single node cluster.  When I run start-dfs.sh, it gives the following output and the process does not start (I confirmed usng jps and ps commands).  My bashrc setup is also copied below.  Any thoughts on what I need to reconfigure?
bashrc additions:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export HADOOP_INSTALL=/opt/hadoop/hadoop-2.5.1
export PATH=$PATH:$HADOOP_INSTALL/bin
export PATH=$PATH:$HADOOP_INSTALL/sbin
export HADOOP_MAPRED_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_HOME=$HADOOP_INSTALL
export HADOOP_HDFS_HOME=$HADOOP_INSTALL
export YARN_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_INSTALL/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_INSTALL/lib"

start-dfs.sh output:
14/09/22 12:24:13 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Starting namenodes on [localhost]
localhost: starting namenode, logging to /opt/hadoop/hadoop-2.5.1/logs/hadoop-hduser-namenode-zkserver1.fidelus.com.out
localhost: nice: $HADOOP_INSTALL/bin/hdfs: No such file or directory
localhost: starting datanode, logging to /opt/hadoop/hadoop-2.5.1/logs/hadoop-hduser-datanode-zkserver1.fidelus.com.out
localhost: nice: $HADOOP_INSTALL/bin/hdfs: No such file or directory
Starting secondary namenodes [0.0.0.0]
The authenticity of host '0.0.0.0 (0.0.0.0)' can't be established.
ECDSA key fingerprint is cf:e1:ea:86:a4:0c:cd:ec:9d:b9:bc:90:9d:2b:db:d5.
Are you sure you want to continue connecting (yes/no)? yes
0.0.0.0: Warning: Permanently added '0.0.0.0' (ECDSA) to the list of known hosts.
0.0.0.0: starting secondarynamenode, logging to /opt/hadoop/hadoop-2.5.1/logs/hadoop-hduser-secondarynamenode-zkserver1.fidelus.com.out
0.0.0.0: nice: $HADOOP_INSTALL/bin/hdfs: No such file or directory
14/09/22 12:24:58 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable

The bin directory has the hdfs file and its owner is hduser (I am running the process as hduser).  My $HADOOP_INSTALL setting points to the hadoop directory (/opt/hadoop/hadoop-2.5.1).  Should I change anything with the permissions, configuration or simply move the directory out of opt and perhaps onto /usr/local?
Update:
When I run start-yarn.sh, I get the following message:
localhost: Error: Could not find or load main class org.apache.hadoop.yarn.server.nodemanager.NodeManager

Update
I moved the directory to /usr/local but I get the same warning message.
Update
I have ResourceManager running as per jps command.  However, when I try to start yarn, it fails with the error given above.  I can access the resourcemanager UI on port 8088.  Any ideas?

A: Try running namenode with the following (as opposed to using the start-dfs.sh) and see if that works.
    hadoop-daemon.sh start namenode
    hadoop-daemon.sh start secondarynamenode
    hadoop-daemon.sh start datanode
    hadoop-daemon.sh start nodemanager
    mr-jobhistory-daemon.sh start historyserver


text:
Q: How to get the app bundle id from javaScript in iOS? How can I get the iOS application bundle id from WebView (no matter which one) in Javascript.
I've tried so far to get it from the Navigator and Location objects (JS objects), but without success.
Any help?
Thanks in advance!


text:
Q: How to take value of a LINQ query in a model List I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :Error Message
This is the model :
public partial class tblArtist
    {
        public tblArtist()
        {
            this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>();
            this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>();
            this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>();
            this.tblArtistRatings = new HashSet<tblArtistRating>();
            this.tblArtistOverviews = new HashSet<tblArtistOverview>();
            this.tblArtistSchedules = new HashSet<tblArtistSchedule>();
        }

        public int ArtistId { get; set; }
        public string ArtistName { get; set; }
        public Nullable<System.DateTime> DateOfBirth { get; set; }
        public string Sex { get; set; }
        public string HouseNumber { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Pin { get; set; }
        public string Email { get; set; }
        public string Website { get; set; }
        public string Phone { get; set; }
        public string Mobile { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public Nullable<bool> IsGroup { get; set; }
        public Nullable<bool> IsFeatured { get; set; }
        public Nullable<System.DateTime> AddedOn { get; set; }
        public string AboutMe { get; set; }
        public Nullable<decimal> MinmumRates { get; set; }
        public string FB_FanLink { get; set; }
        public Nullable<int> FK_UserId { get; set; }
        public Nullable<bool> IsApproved { get; set; }

        public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; }
        public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; }
        public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; }
        public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; }
        public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; }
        public virtual tblUser tblUser { get; set; }
        public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; }
    }

In Controller page I take a list like :
List<tblArtist> artistList = new List<tblArtist>();

This is the query :
artistList = (from ta in context.tblArtists
                                    join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId
                                    join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId
                                    join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId
                                    where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true
                                    select new
                                    {
                                        ta.AboutMe,
                                        ta.AddedOn,
                                        ta.Address,
                                        ta.ArtistId,
                                        ta.ArtistName,
                                        ta.City,
                                        ta.Country,
                                        ta.DateOfBirth,
                                        ta.Email,
                                        ta.FB_FanLink,
                                        ta.FK_UserId,
                                        ta.HouseNumber,
                                        ta.IsActive,
                                        ta.IsApproved,
                                        ta.IsFeatured,
                                        ta.IsGroup,
                                        ta.MinmumRates,
                                        ta.Mobile,
                                        ta.Phone,
                                        ta.Pin,
                                        ta.Sex,
                                        ta.State,
                                        ta.Website
                                    }).ToList();

A: You select an anonymous type with this:
select new
    {
        ta.AboutMe,
        ta.AddedOn,
        // ..
    }

Linq cannot convert that anonymous type implicitly to tblArtist which it expects in the list of List<tblArtist>.
Instead of creating a new anonymous type, just create the tblArtist:
select new tblArtist
    {
        AboutMe = ta.AboutMe,
        AddedOn = ta.AddedOn,
        // ..
    }

EDIT
Or even better, I suspect that your context.tblArtists already is a collection of the type tblArtist, so you can just change the select new to select ta , then the result already is of the type you need.

A: If you want records of only "tblArtists" table, then you can write like this;
artistList = (from ta in context.tblArtists
                                    join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId
                                    join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId
                                    join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId
                                    where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true
                                    select ta).ToList();


text:
Q: Remove white space between table cells I am using ITextSharp 5.5.7.   I have the following code and everything is working.  However, I need to remove the white space between each cell.  I have tried all the suggestions found and still the white spaces are not removed.  Here is the code:
private PdfPTable createTable()
        {

            // Table (No border, just to hold all objects)
            PdfPTable sheetTable = new PdfPTable(1);
            sheetTable.WidthPercentage = 100;
            sheetTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            sheetTable.SpacingBefore = 0f;
            sheetTable.SpacingAfter = 0f;

            // Add Heading One
            sheetTable.AddCell(createHeadingOne());

            // Add Heading two
            sheetTable.AddCell(createHeadingTwo());

            return sheetTable;

        }

        private PdfPTable createHeadingOne()
    {

        PdfPCell cell = new PdfPCell();

        PdfPTable headingTable = new PdfPTable(2);

        // Set widths of columns
        int[] headingTablewidths = { 50, 50 }; // percentage
        headingTable.SetWidths(headingTablewidths);

        cell = new PdfPCell(new Phrase("col1row1", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
        headingTable.AddCell(cell);

        cell = new PdfPCell(new Phrase("col2row1", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
        headingTable.AddCell(cell);

        return headingTable;

    }

    private PdfPTable createHeadingTwo()
    {

        PdfPCell cell = new PdfPCell();

        PdfPTable headingTable = new PdfPTable(2);

        // Set widths of columns
        int[] headingTablewidths = { 50, 50 }; // percentage
        headingTable.SetWidths(headingTablewidths);

        cell = new PdfPCell(new Phrase("col1row2", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
        headingTable.AddCell(cell);

        cell = new PdfPCell(new Phrase("col2row2", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
        headingTable.AddCell(cell);

        return headingTable;

    }

Update #1 The blue lines is the area were I need to remove the spacing:

Update #2,  Fixed.  Here is the code Bruno provided:
PdfPCell cell;
cell = new PdfPCell(createHeadingOne());
cell.Padding = 0;
sheetTable.AddCell(cell);
cell = new PdfPCell(createHeadingTwo());
cell.Padding = 0;
sheetTable.AddCell(cell);

A: I would solve this like this:
PdfPCell cell;
cell = new PdfPCell(createHeadingOne());
cell.Padding = 0;
sheetTable.AddCell(cell);
cell = new PdfPCell(createHeadingTwo());
cell.Padding = 0;
sheetTable.AddCell(cell);


text:
Q: Alternative to Google Timezone API (Node.js or Javascript) I'm using the Google Timezone API right now but it has gotten too expensive. I'm using it in the backend and wanted to find either a free API or offline package that returns these three things (timeZoneName, rawOffset, dstOffset) like the example of desired output below.
My current inputs are coordinates and a timestamp so that'd be amazing if that existed too. Any recommendations would be amazing! Thank You
{
 "dstOffset" : 0,
 "rawOffset" : -28800,
 "status" : "OK",
 "timeZoneId" : "America/Los_Angeles",
 "timeZoneName" : "Pacific Standard Time"
}

However I can get away without having timeZoneId
my input looks like this:
location=${latitude},${longitude}&timestamp=${timestamp}

So latitude, longitude, and timestamps


text:
Q: Bundler::GemNotFound Issue after installing Redmine on Debian I am trying to install Remine on Debian server. Apache is the Http Server and MySql as database. Installation is complete. Its shows an error Could not find nokogiri-1.8.4 in any of the sources (Bundler::GemNotFound).
I haven't hosted an Ruby application before.
Tried most of the commands found on internet about this issue.
This is the URL where you can see the issue.

A: During the deployment of the app, there should be a step bundle install. This step is performed by a gem called bundler, that needs to be installed prior to this step. Add gem install bundler to install it. It looks at the files Gemfile and Gemfile.lock and install all the missing dependencies. Like a package.json for npm install. Remine must have a Gemfile somehwere. You should probably refer to their deployment wiki or contact them otherwise.
You can also check that the Gemfile specifies the right version of Nokogiri. Specify it otherwise.
Nokogiri is also known to fail installing randomly. You can try adding a manual sudo gem install nokogiri 1.8.4 after bundle install, see if that helps.


text:
Q: find largest value from webelement list Currently i'm able to print all of them but i want to find out the largest and print only that value.
Can anyone please help me in building the code for this in Selenium Webdriver & Java.
Here is my code:
List <WebElement> Rating  =  oBrowser.findElements(By.xpath("//span[contains(@class, 'rating-out-of-five')]");
try{
  for(WebElement starRating:Rating)
   {
     System.out.println(starRating.getText());
   }
 catch(Exception e){
   System.out.println("Rating not found");
 }

A: Before your loop, introduce the variable that will hold the max value like so;
int max = Integer.parseInt(Rating.get(0).getText());

Note it is wrong to do something like int max = 0; (consider a list of negative values).
Then, in your for loop you can check if the current value is greater than the max value like so;
int tmp = Integer.parseInt(starRating.getText());
if (tmp > max) max = tmp;

Sure you could make an oneliner out of it, but this is more readable.
Now, after your loop, max will hold the greatest value of your list, so you can simply print
System.out.println(max);

By the way, I don't know the methods of your WebElement class, but if it has a method such as getValue which returns an int it would make things simpler.


text:
Q: In VBA/Access get value from current record when changing records I have an Access database. I have a map control embedded in a form (using MapInfo, but that's not important). When a user goes from one record to another I would like the map to re-centre on the appropriate coordinates. To do this I need to get the coordinates which are stored in the current row of the table which is the data source for the form. My question is how I access this value. This is pretty simple, right?
I have worked out that the "On Current" event is triggered when the record is changed but I can't seem to refer to the xcoord and ycoord fields in the current row.
This page seems to suggest that I need to create a module to do this. Surely there's a simpler way?
Thanks in advance!
Update: If I put a pair of textbox controls in the form that display the x and y coordinates then I can access them by doing Me.x_coord. Is this the answer?

A: In Access VBA you can reference the fields of a bound form's recordsource with the syntax:
Forms!your_form_name!your_field_name

In your case, you can grab the current x_coord with Me!x_coord.  No need to bind it to a control to get the data.


text:
Q: Meeting of people | Combinatorics In a group of $k$ people, some are acquainted with each other and some are not. Every evening, one person invites all his acquaintances to a party and introduces them to each other (if they are not acquainted). Suppose that after each person has arranged at least one party, some $2$ people don't know each other. Prove that they don't meet each other in the next meeting.
Can this be solved using PHP?
I began by assuming that some arbitrary person out of the $k$ available has thrown a party, then everybody who comes there will know everybody else, so if they are not acquainted after this party, it means they won't meet at the next party.
Is my working right?

A: This question has been satisfactorily answered in the comments to the question.


text:
Q: Getting the css width as a number instead of a percentage In this simplified version of my code, I'm trying to extract the css width as a number without the percentage attached. Researching a solution, I found this: Get a number for a style value WITHOUT the "px;" suffix which solves the problem. However, on trying to reproduce the same result, I'm getting
barSize:  NaN

instead of
barSize: 90;

Update: This question isn't asking how the get the property as in
document.querySelector('.defaultBar').style.width

which gives:
barSize: 90%

but how to get the property without the suffix as in
parseInt(document.querySelector('.defaultBar').style.width, 10);

which should give:
    barSize: 90
without the % suffix but gives NaN instead.

<!DOCTYPE html>

  <meta charset="utf-8">


text:
Q: SignalR clients not aware of connection failure I'm having some trouble with SignalR.. Everything seems to be working fine server-side. The problem is when my javascript clients lose internet connection for some time: when they reconnect to the internet they never try to establish a new connection to SignalR server.
I think this is happening because they are never aware that they lost internet connection in the first place. When I check for $.signalR.connectionState it gives me a value of 1, as if they were connected.
Any help is highly appreciated.

A: In this sample, javascript client first subscribes to all events (error, stateChanged, etc) before starting the connection. Also, check javascript console in your browser to have a better idea of what SignalR is doing.


text: Q: Is there a direct access to raw numpy bytes? The term "direct" here means "without making a copy" In documentation, I only found numpy.ndarray.tobytes. However, in other languages like Java I used to have direct access to the internal memory of matrices in math libraries, avoiding making a copy.


text:
Q: No matching function for call to object of type 'const RadioMap::comp' struct comp
{
    bool operator()(const CartesianLocation& loc1, const CartesianLocation& loc2)
    {
        //Compare the 2 locations, return true if loc1 is less than loc2
        return loc1.id < loc2.id;
    }
};

std::map<CartesianLocation, std::list<RadioSignal<RadioDevice>>, comp> radioMap;

public:
  void add(CartesianLocation location, std::list<RadioSignal<RadioDevice>> observedSignals) {
    radioMap[location] = observedSignals;
  }

On this line radioMap[location] = observedSignals; I am getting below error:

No matching function for call to object of type 'const RadioMap::comp' on this line if (__tree_.value_comp().key_comp()(__k, __nd->__value_.__cc.first))

Any idea where I may be wrong?

A: You are missing the const qualifier on the call operator of comp:
bool operator()(const CartesianLocation& loc1,
                const CartesianLocation& loc2) const { }
                                               ^^^^^


text:
Q: Extact images using ItextSharp I have a question regarding PDF. If I use the code below with a PDF with 5 images on it, it works perfectly fine. The same with a PDF having 10 to 15 images throws an error.
var fields=[];

for (var i = 0; i <= this.numFields - 1; i++) {
   fields.push(this.getNthFieldName(i));
}

this.submitForm({
cURL: "http://localhost/W.svc/Imagesonpdf",
aFields: fields,
cSubmitAs: "FDF" // the default, not needed here
});

Is there any way we can call the Web Service with Images. If I call the web Service from the Submit button, it works, but not able to get the images on the pdf.


text:
Q: Is it possible to spin another process from within an iOS application? In others words reaching out to the command line and running another command while capturing the standard output.
The reading that've been doing so far seems to indicate that this is a clear violation of the sandbox model and therefore not possible.
You can easily do this is in Android:
//This is just an example don't get hanged up on the actual command.
Process process = Runtime.getRuntime().exec("cat somefile.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
while ((line = bufferedReader.readLine()) != null) {
    logCatTraces.append(line);
    logCatTraces.append("\r\n");
}


text:
Q: Mail - server name issues? I asked some time ago a question Send emails with a custom From: field
However, still can't get exim4 running. It does send emails, but it is unable to receive any. I'm quite sure this might be because of mail server name and MX configuration.
In my control panel I can set Preference, TTL, and Mail Server values for MX. I leave two first ones as default (0, 6400), and the Mail Server I set to "url.com" (I substituted my domain name with "url" name).
But when I send an email to myself, I get:
Unroutable address

in the main log.
When I run from my linux console " host -t mx url.com" I get:
;; connection timed out; no servers could be reached

It seems like my MX had no effect at all? What can I do to get it work?
I am very noobie in the subject and even not sure what does "Mail server" refer to? Is it the name that I get by command "host", or maybe "host -f", or maybe "host -i", or maybe even something else? I'm really confused. :/
Here's /etc/exim4/update-exim4.conf.conf content:
# /etc/exim4/update-exim4.conf.conf
#
# Edit this file and /etc/mailname by hand and execute update-exim4.conf
# yourself or use 'dpkg-reconfigure exim4-config'
#
# Please note that this is _not_ a dpkg-conffile and that automatic changes
# to this file might happen. The code handling this will honor your local
# changes, so this is usually fine, but will break local schemes that mess
# around with multiple versions of the file.
#
# update-exim4.conf uses this file to determine variable values to generate
# exim configuration macros for the configuration file.
#
# Most settings found in here do have corresponding questions in the
# Debconf configuration, but not all of them.
#
# This is a Debian specific file

dc_eximconfig_configtype='internet'
dc_other_hostnames='url.com; mail.url.com; url; localhost;  localhost.localdomain'
dc_local_interfaces='127.0.0.1; my_ip'
dc_readhost=''
dc_relay_domains=''
dc_minimaldns='false'
dc_relay_nets=''
dc_smarthost=''
CFILEMODE='644'
dc_use_split_config='true'
dc_hide_mailname=''
dc_mailname_in_oh='true'
dc_localdelivery='maildir_home'

For any case, I substituted my domain with url and ip with my_ip.
And /etc/email-addresses is very short:
root: contact@url.com

And /etc/mailname
url.com

Update: When I do from Windows:
nslookup -type=mx url.com

I get something like:
Server:  UnKnown
Address:  probably_my_internet_provider's_gate_ip

Non-authoritative answer
url.com  MX preference = 0, mail exchanger = url.com

Update 2:
Now I really am confused. I tried to run "dig mx url.com" and "host -t mx url.com" from the other mail linux server (not mine), and it seems to be ok, e.g. the last one results in:
url.com mail is handled by 0 url.com

But where are my e-mails then?? I can't see in ~/Maildir anything. And when I run "mail" I get msg that there's "No mail for root". So does it work, or it doesn't... or what?
Update 3: IS THIS A ROUTING PROBLEM?
Now I can see that when I'm trying to send an e-mail from contact@url.com, it fails with the following message:
"Unroutable adress"
concerning the contact@url.com address (so it's not the target "TO" one, but the "FROM" one). It didn't happen before (say a month ago), so I probably messed up some config. :/
When I do, as suggested by some net tutorial:
exim4 -d -bt mail

I get a lot of different "routers" (I'm not even sure if I do understand them properly, though I've read a section in the exim4 documumentation), specifically:

*

*hubbed_hosts router ("router skipped: domains mismatch")

*dnslookup_relay_to_domains router ("router skipped: domains mismatch")

*dnslookup router ("router skipped: domains mismatch")

*real_local router ("router skipped: prefix mismatch")

*system_aliases router ("system_aliases router declined for mail@url.com")

*userforward router ("router skipped: file check")

*procmail router ("router skipped: file check")

*maildrop router ("router skipped: file check")

*lowuid_aliases router ("router skipped: condition failure")

*local_user router (see below):

The last one ends with quite a long response:
--------> local_user router <--------
local_part=mail domain=url.com
checking domains
cached yes match for +local_domains
cached lookup data = NULL
url.com in "+local_domains"? yes (matched "+local_domains" - cached)
checking local_parts
mail in "! root"? yes (end of list)
checking for local user
seeking password data for user "mail": using cached result
getpwnam() succeeded uid=8 gid=8
R: local_user for mail@url.com
calling local_user router
local_user router called for mail@url.com
  domain = url.com
set transport maildir_home
    queued for maildir_home transport: local_part = mail
domain = url.com
  errors_to=NULL
  domain_data=NULL localpart_data=NULL
routed by local_user router
  envelope to: mail@url.com
  transport: maildir_home
  mail@url.com
  router = local_user, transport = maildir_home
search_tidyup called
>>>>>>>>>>>>>>>> Exim pid=31821 terminating with rc=0 >>>>>>>>>>>>>>>>

I wonder now, why does it use "mail@url.com", not "contact@url.com" here? Is this something normal?
And foremost: Which ROUTER is the one I should be interested in my case, that is when I'm attempting to send a message with (now) a "mail" command from the command line to the foreign e-mail address?

A: Solved. Thanks for all your suggestions. The problem was connected to Name Servers, and after all they now correctly resolve names.


text:
Q: Finding equivalent polynomials (mod n) During some casual investigation of polynomials over an integer ring $\mathbb{Z}_n$ (or $\mathbb{Z}/n\mathbb{Z}$ if you prefer), I noticed that some polynomials induce the same map. I'm curious about how one could tell if two polynomials are equivalent in this way without checking directly.
For example, in $\mathbb{Z}_8$, $f(x) = 2x^3 + 5x + 3$ is the same as $g(x)=x^4 + 3x^2 + 3x + 3$. They are bijective and act on $\mathbb{Z}_8$ as the permutation $(3, 2, 5, 0, 7, 6, 1, 4)$.
My main question is: What are the criteria for two polynomials to induce the same map on $\mathbb{Z}_n$?
I'm also interested in other information about this, such as: For a given polynomial, are there infinitely many equivalent polynomials? Will the lowest-degree polynomial in an equivalence class always have a degree less than $n$? Does it matter what kind of number $n$ is (e.g. prime or composite)? Are there unique polynomials with $deg\geq1$ having no equivalent?
Without knowing much about this situation, my guess is that the Chinese Remainder Theorem, Euler's Theorem, and/or Fermat's Little Theorem will come into play. I'm exploring a bit outside of my mathematical comfort zone and I have very little experience with number theory, so this is where I get kind of lost.

A: Two polynomials induce the same function iff their difference induces the zero function.
Here is a general result about polynomials that induce the zero function:

If $r$ is the maximum exponent in the prime factorization of $n$, then $x \mapsto x^{r+\lambda (n)}-x^r$ is the zero function mod $n$. [Wikipedia]

Here, $\lambda$ is the Carmichael function.
I don't know whether this is the polynomial of least degree that induces the zero function mod $n$.

A: As proved in another answer, two polynomials $f$ and $g$ induce the same function on $\mathbb{Z}/n\mathbb{Z}$ precisely when, written in the form
$$f(x) = \sum_{k} b_k x^{\underline k}$$
and
$$g(x) = \sum_{k} c_k x^{\underline k},$$
they satisfy the property that
$$b_k \equiv c_k \mod {\frac{n}{\gcd(n, k!)}}$$ for each $k$.
Here, $x^{\underline k}$ is the "falling factorial": $x^{\underline k} = x(x-1)\cdots(x-k+1)$. Any polynomial can be written in this form (i.e. using the "falling factorial basis" instead of the monomial basis) using the identity $x^n = \sum_k {n \brace k} x^{\underline k}$ where ${n \brace k}$ is a Stirling subset number ("Stirling number of the second kind"). See Wikipedia on Stirling numbers, for example.


text:
Q: Provider data is becoming null after app is backgrounded I am noticing that dataLength variable of my User object becomes null after my app is backgrounded. It works perfectly across all the widgets that uses it when the variable is initially set. But once I background the app and bring it back to the foreground it becomes null until the stream rebuilds. Can anyone help out, thanks!
Widget build(BuildContext context) {
    final myUserData = Provider.of<MyUser>(context, listen: false);
    final User myUser = myUserData.getUser();
    return Scaffold(
      backgroundColor: Colors.white,
      body: StreamBuilder<dynamic>(
        stream: _stream,
        builder: (context, snapshot) {
          if (snapshot.data == null || snapshot.data.docs.isEmpty) {
            myUser.results = 0;
            return Container();
          } else {
           List<Data> myDataList = [];
             snapshot.data.docs.forEach(
              (element) async {
                Data myData = Data.fromMap(element.data());
                myDataList.add(myData);
                             })
           myUser.dataLength = myDataList.length;
              },...

class MyUser with ChangeNotifier {
  User _myUser = User(
  );

  User getUser() {
    return _myUser;
  }...

class User {
    int? dataLength;

  User({
    this.dataLength,
  });...


text:
Q: SwiftUI can't hide navigationBar on pushed view when previous view search bar active I have a problem when pushing to a new view with a search bar active.
In the pushed view I want the navigation bar to be hidden.  It works in all cases except when the search field is active on the pushing view AND the navigation style is StackNavigationViewStyle.
In the example project below if you select a row, the new view is pushed and the navigation bar is hidden as expected.  However, if you first select the search bar to make it active and then press a row, the navigation bar is no longer hidden on the pushed view.
Removing the StackNavigationViewStyle, everything will work fine however I need to have StackNavigationViewStyle.
struct ContentView: View {

    @State var searchString = ""

    var body: some View {
        NavigationView {
            List {
                NavigationLink {
                    PushedView()
                } label: {
                    Text("Press Me")
                }
            }
            .listStyle(PlainListStyle())
            .searchable(text: $searchString)
            .navigationTitle("First View")
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct PushedView: View {

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View {
        Button {
            self.presentationMode.wrappedValue.dismiss()
        } label: {
            Text("Pop View")
        }
        .navigationTitle("Second View")
        .navigationBarHidden(true)
    }
}

A: This might be a solution for now:
import SwiftUI

struct ContentView: View {

    @State var searchString = ""

    @FocusState private var focusedField: Bool
    @State private var isHidden: Bool = false
    var body: some View {
        NavigationView {
            List {
                NavigationLink { PushedView(isHidden: $isHidden).onAppear { isHidden = true}.onDisappear {
                    isHidden = false
                } } label: { Text("Press Me") }
            }
            .navigationTitle("First View")
            .searchable(text: $searchString)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct PushedView: View {

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    @Binding var isHidden: Bool

    var body: some View {
        Button {
            self.presentationMode.wrappedValue.dismiss()
        } label: {
            Text("Pop View")
        }
        .navigationTitle("Second View")
        .navigationBarHidden(isHidden)
    }
}


text:
Q: Possible to programmatically decompile stored procedures using C# When most of us want to see the definition of a SQL Server stored procedure, we fire up SSMS, find the object, right-click and select Modify or one of the other scripting options. This works fine, manually.
Some people also have the good fortune to get licensed for Redgate products that let you search, compare, and analyze the compiled database objects.
But supposing I would like to write desktop utilities that analyze stored procedures or other objects compiled on a SQL Server instance. There seems to be very little in the mainstream that is designed to accommodate that kind of software design.
So my question is: is it even possible, using C# and readily available NuGet packages, to connect to a SQL database and return the same DDL script that would be rendered into a query window using SSMS?
I know that there are lots of utilities already out there to cover almost anything I could want, but this is a programming question, not a request for a product recommendation.

A: You can take a peek at the code via sys.sql_modules
Example
SELECT [schema_name] = OBJECT_SCHEMA_NAME([object_id])
      ,[object_name] = OBJECT_NAME([object_id])
      ,*
 FROM  sys.sql_modules
--WHERE  OBJECT_SCHEMA_NAME([object_id]) = 'dbo'
--  AND OBJECT_NAME([object_id]) = '<<some store procedure or UDF>>'

A: You can use sp_helptext 'sp_name' for stored procedures. See here


text:
Q: Log aborted downloads How can I configure nginx to log aborted downloads, i.e. the connection timing out because of client inactivity and/or the client sending an RST, while an HTTP response was being sent?
Even sending sending the error_log level to debug, I don't see anything if a client terminates prematurely.
I want to monitor how many connections are aborted during a download, to detect network interruptions and client problems.


text:
Q: How to stop popup asking to authenticate for everything Ever since installing lightdm to fix the login password loop issue, I receive a popup asking me to authenticate from everything to wifi scans, to color profile, to refresh system repositories. I've tried dozens of different guides, advice, and nothing seems to work.
This problem started when I followed this answer and changed my /etc/default/grub file by modifying the GRUB_CMDLINE_LINUX_DEFAULT from "quite splash" to "nomodset", then installed lightdm. I reverted it back to it's default value of quiet splash acpi_backlight=vendor. I also tried changing the permissions of the .Xauthority file, but that didn't work. Also, my brightness buttons seems to be screwed up in that I have to hold them for very long before I notice the brightness changing.
I just want to stop the popup that asks me to authenticate for everything, and am hoping the community here has some advice.


text:
Q: How to get a specific array position after numpy.where condition? I am using the where condition to my array and get back the array position array_string[0,0] with 'A' but I need the position array_string[0,1] with 200.
array_string = np.array([['A', 200],['B', 100]])

array_string[ np.where( array_string == 'A' ) ]

A: First of all, there is no need to use the np.where. Secondly, you can get your desired answer like this:
array_string[array_string[0,:]=='A', :]

> array([['A', '200']], dtype='<U3')

Translated into human language: check the first row in all columns, and if it is equal to A, get me the entire row (all the columns of this row).

A: This happens, because np.where return indices for each dimension where element was found.
array_string = np.array([['A', 200], ['B', 100]])

rows_found, cols_found = np.where(array_string == 'A')
rows = array_string[rows_found]  # returns [['A', 200]]
print(rows[0][1])  # prints 200

# Another example
array_string = np.array([['A', 200], ['B', 100], ['A', 500]])

rows_found, cols_found = np.where(array_string == 'A')
rows = array_string[rows_found]  # returns [['A' 200], ['A' 500]]
print(rows[:, 1])  # prints [200, 500]


text:
Q: Linkedin Oauth Issue - oauth_verifier Having some problems trying to exchange my JSAPI tokens for REST Oauth Tokens (https://developer.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens)
I'm using this library - http://code.google.com/p/oauth-php/ - As opposed to the PECL extension as I'm unable to install extensions onto the server.
There seem to be plenty of similar questions, but none which actually answer the question - How to use the above library to authenticate with Linkedin.
My code is as follows:
    $cookie_name        = "linkedin_oauth_" . $this->_c->linkedin_api_key;
    $credentials_json   = stripslashes($_COOKIE[$cookie_name]);
    $credentials        = json_decode($credentials_json);

    // Get the Access Token + Secret
    $access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';

    OAuthStore::instance("2Leg", array(
        'consumer_key'      => $this->_c->linkedin_api_key,
        'consumer_secret'   => $this->_c->linkedin_api_secret
    ));

    try {

        $request = new OAuthRequester($access_token_url, 'POST', array(
            'xoauth_oauth2_access_token' => $credentials->access_token
        ));

        $result = $request->doRequest();

    } catch(OAuthException2 $e) {

        print_r($e->getMessage());

    }

The catch statement outputs:
Request failed with code 400: oauth_problem=parameter_absent&oauth_parameters_absent=oauth_verifier
How do I get this oauth_verifier? It was my understanding that I shouldn't need it if I was passing the xoauth_oauth2_access_token already?
I've checked all of the variables I.E. $credentials and $this->_c and all of the variables are passing through correctly.

A: This is actually a bug in the oauth-php library. The library is incorrectly handling parameters which are prefixed with xoauth_* and treating them the same way it handles oauth_* parameters. This is in violation of the OAuth spec and most (all?) other OAuth libraries don't have this issue. The fix is to do the following:
Inside the file OAuthRequestSigner.php, find the following:
1) inside the getAuthorizationHeader function, find the line which reads:
if (strncmp($name, 'oauth_', 6) == 0 || strncmp($name, 'xoauth_', 7) == 0)

and change it to be:
if (strncmp($name, 'oauth_', 6) == 0)

2) Inside the function getQueryString, find the line which reads:
||  (strncmp($name, 'oauth_', 6) != 0 && strncmp($name, 'xoauth_', 7) != 0))

and change it to be:
||  (strncmp($name, 'oauth_', 6) != 0)

After that, all you need to do is essentially the same as you were already doing, which is the following:
try {

    $request = new OAuthRequester($access_token_url, "POST", array('xoauth_oauth2_access_token' => $access_token));

    $result = $request->doRequest();

    var_dump($result);

} catch(OAuthException2 $e) {

    print_r($e->getMessage());

}

And you should be all set. If you have any further issues, please do not hesitate to reach out on our developer forums and either myself or someone else on the team would be happy to help.
Enjoy!
-Jeremy


text:
Q: How to access a DB2 database with ODBC from a separate thread? I have a DB2 database in my CentOS 6.5 64 bit machine and have installed ODBC drivers to access the database from my C++ application.
I am using SQL CLI APIs to fetch the data from the database.
If I fetch the data from my main() function of the C++ application, SQL CLI APIs work fine (e.g. SQLAllocHandle) and I am able to read/write data from the database.
If I try to do the same operation on my POSIX thread, SQL CLI APIs fail to initialize the handle and eventually read/write fails.
SQLRETURN   sqlrc = SQL_SUCCESS;
SQLCHAR     pszSqlState[100];
SQLINTEGER  pfNativeError[100];
SQLCHAR     pszErrorMsg[100];
SQLSMALLINT cbErrorMsgMax;
SQLSMALLINT pcbErrorMsg;

/* allocate an environment handle */
sqlrc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnv);
if (sqlrc != SQL_SUCCESS)
{
    return 1;
}

sqlrc = SQLGetDiagRec(SQL_HANDLE_ENV, m_hEnv, 1, pszSqlState, pfNativeError, pszErrorMsg, 100, &pcbErrorMsg);

/* set attribute to enable application to run as ODBC 3.0 application */
sqlrc = SQLSetEnvAttr(m_hEnv,
                      SQL_ATTR_ODBC_VERSION,
                      (void*)SQL_OV_ODBC3,
                      0);

/* allocate a database connection handle */
sqlrc = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnv, &m_hDBconn);

sqlrc = SQLGetDiagRec(SQL_HANDLE_DBC, m_hEnv, 1, pszSqlState, pfNativeError, pszErrorMsg, 100, &pcbErrorMsg);

/* connect to the database */
sqlrc = SQLConnect(m_hDBconn,
                   (SQLCHAR *)db1Alias, SQL_NTS,
                   (SQLCHAR *)user, SQL_NTS,
                   (SQLCHAR *)pswd, SQL_NTS);

//sqlrc =  SQLGetDiagRec(SQL_HANDLE_DBC, m_hDBconn, 1, pszSqlState, pfNativeError, pszErrorMsg, 100, &pcbErrorMsg);

return sqlrc;

I am using Eclipse / IBM Data Studio for development.
I googled for known issues without any luck.
How to access a DB2 database with ODBC from a separate thread?
Info :
The first APi
 SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnv )

returns SUCCESS but the value of m_hEnv is invalid (-ve value).
So the subsequent APIs return -2 which is SQL_INVALID_HANDLE .
Call to
    SQLSetEnvAttr(m_hEnv,SQL_ATTR_ODBC_VERSION,(void *)SQL_OV_ODBC3, 0);
returns -2 SQL_INVALID_HANDLE .

A: The problem was, my application which uses SQL CLI code was not compiled using -D_REENTRANT flag.
Now I am able to use the SQL APIs inside my threads. Thanks all for your inputs.


text:
Q: Converting from lower to upper case in Sql Editor in Data Studio What keyboard shortcut can I use to switch from lower to upper case and upper to lower case in Sql Editor in Data Studio LUW ?

A: You can discover all the keybaord-shortcuts in Data Studio by using menu Help > Active Key Bindings.  This is valid for Data Studio version 4.1.3 and maybe some older versions. You can also use CTRL+SHIFT+L to open the same list of active key bindings.  The active key bindings is a long list, and can depend on which tool you are using in Data Studio.
The shortcut keys depend on your operating-system (e.g. Mac Os, Linux, Windows).
For Linux X64, in the SQL-editor, to convert selected text to uppercase is Shift+Ctrl+X - works for me.

A: Maybe, you wanted it.
If you apply the format to your code, all keywords will be in lowercase.
enter image description here


text:
Q: swift throws python errors from terminal I'm getting an error whenever I try to start swift related to python.  How do I fix this?

bash-3.2$ swift --version
  Apple Swift version 4.1 (swiftlang-902.0.48 clang-902.0.37.1)
  Target: x86_64-apple-darwin17.5.0
  bash-3.2$ swift
  Traceback (most recent call last):
    File "", line 1, in
    File "/usr/local/Cellar/python@2/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 52, in
      import weakref
    File "/usr/local/Cellar/python@2/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/weakref.py", line 14, in
      from _weakref import (
  ImportError: cannot import name _remove_dead_weakref

A: I get the same error, because the swift REPL uses the python interpreter which homebrew installed at /usr/local/bin/python.
To avoid this you can
export PATH=/usr/bin:$PATH
swift

or
PATH=/usr/bin:$PATH swift


text:
Q: Is this method to check the continuity of multivariable functions correct? Consider
$$f(x,y) =\begin{cases} \frac{\cos y\sin x}{x} & x\neq 0 \\
\cos y & x=0 .
\end{cases}$$
Is $f$ continuous at $(0,0)$?
Method 1
$f(0,0) = 1.$
Also, $\lim_{(x,y)\to(0,0)} f({x,y})=1 = f(0,0).$ (Easy to calculate.)
Therefore, $f$ is continuous at $(0,0)$.
The problem I find with this method is that it didn't verify whether the limit exists or not at $(0,0)$. I did check $y=mx$ path to the point $(0,0)$, and it did give $1$ as the value of the limit. But obviously, I cannot verify all the existing paths to $(0,0)$, so the only way to check the existence of the limit is (I think) to use the epsilon-delta definition of limit. But if I have to use the epsilon-delta definition of limit to check the existence of the given limit, then I could very well use the epsilon-delta definition of continuity to check whether the given function is continuous at $(0,0)$. Then there is no need to find the limit or check its existence. If that's the case, then isn't Method 1 incomplete and in a way redundant as well?

A: I think that it is much easier to do it as follows. Consider the function$$\begin{array}{rccc}\varphi\colon&\Bbb R&\longrightarrow&\Bbb R\\&x&\mapsto&\begin{cases}\frac{\sin x}x&\text{ if }x\ne0\\1&\text{ if }x=0.\end{cases}\end{array}$$Then $\varphi$ is continuous. It is clear that it is continuous at every point other than $0$, and it is also continuous at $0$, since $\lim_{x\to0}\frac{\sin x}x=1$. But then $f(x,y)=\varphi(x)\cos(y)$. Then $f$ is continuous, since it is the product of two continuous functions.If you really want to use the $\varepsilon-\delta$ definition, it can be used indeed. Note that, if $x\ne0$,$$f(x,y)-1=\frac{\sin x}x-1+\cos(y)-1-\left(\frac{\sin x}x-1\right)\bigl(\cos(y)-1\bigr).\tag1$$Given $\varepsilon>0$, take $\delta>0$ such that$$|x|<\delta\implies\left|\frac{\sin x}x-1\right|<\min\left\{\frac\varepsilon3,\sqrt{\frac\varepsilon3}\right\}\tag2$$and that$$|x|<\delta\implies\bigl|\cos(y)-1\bigr|<\min\left\{\frac\varepsilon3,\sqrt{\frac\varepsilon3}\right\}.\tag3$$So, if $\|(x,y)\|<\delta$, then $|x|,|y|<\delta$ and it follows nor from $(1)$, $(2)$, and $(3)$ that$$\left|f(x,y)-1\right|<\frac\varepsilon3+\frac\varepsilon3+\sqrt{\frac\varepsilon3}^2=\varepsilon.$$And it is clear that, if $x=0$, it is still true that $|f(x,y)-1|<\delta$.

A: HINT:
The idea is to start from the $\epsilon-\delta$ definition of continuity. So you write $$f(x+\delta_1,y+\delta_2)-f(x,y)=[f(x+\delta_1,y+\delta_2)-f(x,y+\delta_2)]+[f(x,y+\delta_2)-f(x,y)]$$


text:
Q: R.prop('parentNode', R.__) returns a function I had write a function init which should to get a className relative to align property and set this className to a parentNode. But I receive a function instead of parentNode.

const addClass = R.curry((className, el) => {
    console.log(className) //=> String
    console.log(el) //=> Function ???

    R.forEach(
        R.call(R.invoker(1, 'add'), R.__, el.classList),
        R.split(', ', className)
    )
})

const getAlignClassName = R.compose(
    R.cond([
        [R.equals('left'), R.always('video--align-left')],
        [R.equals('right'), R.always('video--align-right')],
        [R.T, R.always('video--align-center')]
    ]),
    R.prop('align')
)

const init = R.call(
    addClass,
    getAlignClassName(R.__),
    R.prop('parentNode', R.__)
    //R.prop('parentNode') // this one also returns a function
)

const tmp = { align: 'left', parentNode: 'some parent node' }

console.log(init(tmp))
<script src="https://cdn.jsdelivr.net/ramda/latest/ramda.min.js"></script>

A: I've just replaced R.call with R.converge. So, it's working now)


text:
Q: Enable HTTP Method POST for a specific script on a shared hosting Hello everybody I need to update some datas on a script placed on a shared hosting.
both scripts, access and destination are PHP files.
I need to access the external file trough a post operation, but server is responding me "501 Method not implemented "
I have tried also to put on top of the receiving file
header('Access-Control-Allow-Origin: *');

But I don't solve it as probably is nginx the same stopping it before the php file is executed.
How could I tell nginx or apache to enable post only for this file ?
Thanks everybuddy

A: Nginx limit_except directive can restrict your script to only post requests -
http://wiki.nginx.org/HttpCoreModule#limit_except
location /postzone {
  limit_except POST {
    deny   all;
  }
}

This would give a 403 for anything other than POST, not a 501. So they must be doing something else.
As you say, PHP can do nothing about this. If your host is blocking post requests they probably have a good reason, so I'd ask them.


text:
Q: Appending multiple times to same File using "a" mode I'm trying to update an invoice file, i wrote 2 functions, first one is called multiple times to fill in the names and prices. second one is called once to write the final taxes/discounts..etcProblem is, the second function outputs text before the first function.i'm sure the functions are called in the correct order.
code:
 int Update_Invoice(int No, int feeType) //update invoice file
{
    char type[2][8] = { {"Normal"},{"Urgent"} };
    int Fee = fees[No][feeType - 1]; //temporary variable to store fee of specific service type

    FILE* fptr = fopen(InvoiceName, "a");
    if (fptr == NULL)
        exit(1);
    else
    {
        fprintf(fptr, "%-30s\t\t%s\t\t%d\n", serviceType[No],type[feeType-1], fees[No][feeType-1]);
        return Fee;
    }
    fclose(fptr);
}
void Calculate_Final_Price(double total, double discount, double tax)
{
    FILE* fptr = fopen(InvoiceName, "a");
    if (fptr == NULL)
        exit(1);
    else
    {
        fprintf(fptr, "-----------------------------------------------------------------------\n");
        fprintf(fptr,"\t\t\t\t\tSubTotal\t%.2lf\n",total);
        fprintf(fptr, "\t\t\t\t\tDiscount\t%.2lf\n", discount);
        fprintf(fptr, "\t\t\t\t\tTax\t\t%.2lf\n", tax);
        total -= ((total * discount) / 100); // apply discount
        total += tax; // apply taxes
        fprintf(fptr, "\t\t\t\t\tTotal\t\t%.2lf\n",total); //final price
    }
    fclose(fptr);
}

actuall txt file:
Invoice Number: 200052

Service                 Type        Price
-----------------------------------------------------------------------
-------------------------------------------------------------------------
-->this should be in the end        SubTotal    876.00
-->this should be in the end        Discount    0.00
-->this should be in the end        Tax         0.00
-->this should be in the end        Total       876.00

Full Car Checkup                    Normal      300
Repair punctured car tyre/piece     Urgent      6
Battery change                      Urgent      210
Synthetic oil change                Normal      130
Mineral oil change                  Normal      80
Car tyre change/piece               Normal      150

A: the problem is probably here:
else
{
        fprintf(fptr, "%-30s\t\t%s\t\t%d\n", serviceType[No],type[feeType-1], fees[No][feeType-1]);
        return Fee;
}
fclose(fptr);

that code returns without closing the file. So the line isn't flushed at once and it conflicts with the other file object. Fix:
else
{
    fprintf(fptr, "%-30s\t\t%s\t\t%d\n", serviceType[No],type[feeType-1], fees[No][feeType-1]);
    fclose(fptr);
    return Fee;
}

(as a bonus you're no longer invoking undefined behaviour by trying to close a NULL file object)


text:
Q: Including input statements and conditions in the make file I am trying to create a makefile, for the first time. I went through some tutorials and I managed to create one, but I am having trouble with a couple of things. Below are the details.
Below are the files in the order of execution:

*

*CSV_to_txt.c - no dependency on any other files.

I want to include CSV_files/Equilibrium_trajectories.csv, which is my input, in the make file. Further, I run the command  tac Chemical_Equilibrium.txt in the terminal. Can I include this in the make file as well?

*fluid_profile.c - depends on pdfutil.h and beta_util.h.

I have the same problem of reading the inputs, for ex:
Enter the number of points
1000 --> to be included in the make file.
This file creates a text file called fluid_points.txt. What I want to include in the makefile is if this file already exists don't execute the command gcc fluid_points.c -o fluid_points.o -lm.
Structure of the make file:
all:
     gcc CSV_to_txt.c -o CSV_to_txt.o -lm
     ./CSV_to_txt.o
     #Include the file path and name when asked for it

     #ubuntu terminal command --> tac filename.txt > filename_changed.txt

     gcc fluid_profile.c -o fluid_profile.o -lm
     ./fluid_profile.o
     #Enter the number of points when prompted to do so

     #If fluid_points.txt file is already existing don't execute the above command, instead execute the below one

     gcc blah.c -o blah.o -lm
     ./blah.o

clean:
     $(RM) *.o *~

Any sort of help or even a link to a tutorial would be helpful.

A: A suggested makefile:
run:

.PHONY: run

CSV_to_txt: CSV_to_txt.c
     gcc CSV_to_txt.c -o CSV_to_txt -lm

fluid_profile: fluid_profile.c
     gcc fluid_profile.c -o fluid_profile -lm

blah: blah.c
     gcc blah -o blah.c -lm

run: CSV_to_txt fluid_profile blah
     echo "CSV_files/Equilibrium_trajectories.csv" | ./CSV_to_txt.o
     tac Chemical_Equilibrium.txt
     echo "1000" | ./fluid_profile.o
     ./blah.o

clean:
     $(RM) *.o *~

So, a break down -- first line, predeclare target run, such that it becomes the default target (if you do make, it will run the first target ).   Declare this as a phony target (This means there's no actual file called run being produced.   You can look up .PHONY for more details)
Then create some rules to generate the executables.  Each executable has its own rule to generate it.   Typically you would use automatic variables for these like $@ and $<, but I wanted to keep it simple for now.
Then the rule for run.   This is dependent on the executables (so executables will finish building before this rule runs).
Then, to pass the filename into the executable, you can simply echo the filename, and then pipe that into the executable.

A: You have a common newbie error... this is to think that a source file depends on other source files (a .c file depends on some .h files)  This is an error and probably the cause you are not getting your result.
The objective of a Makefile is to describe file dependencies in order to do the minimum set of commands to build the final target you specify.  For this you need to think that a target is something you are goint to create.
Is a source .c file something you create during the build proces? Not, so it cannot be a target of a rule.  The target, indeed is the result of the compilation.  The source file doesn't depend on a header file... it just includes it to make the compilation of the .o target (this is, actually the target).
Let's say you have a program hello.c that includes modA.h and modB.h.  (and even modB.h includes modB2.h)  If you modify any of them, you need to recompile hello.c, so your rule will be:
# (1)
hello.o: hello.c modA.h modB.h modB2.h
    cc -c hello.c                 # (2) see below.

*

*(1) a rule line starts at column 1 and has a left hand side (the target file) and a list of sources (dependencies).  Each time make sees that the target doesn't exist or has a last change date earlier than the change dates of any of the dependencies, the command lines below are executed, one after the other.

*(2) a command rule starts with a <tab> char in the first column of the line.  It represents a command (or a list of commands, each in it's command line) that are required to generate the target file from the sources.

*a line starting with # is a comment line (also valid to start in the middle of a rule or a command line)

*There is anothe type of line (a macro definition) but you need to learn first how to create dependencies and get used to them, before starting learning how to create macros.  Read the make(1) doc first.
you see that we only compile hello.c, but we have to do it every time we change any of the other files above.  There are two modules, modA.o and modB.o, each of them with their .c file and the includes needed in hello.c.  So:

modA.o: modA.c modA.h
    cc -c modA.c
modB.o: modB.c modB.h modB2.h
    cc -c modB.c

so when we change any of modA.c or modA.h then modA.o will be created.  And as modB.h we said above that included modB2.h, then if we modify it, it should be compiled.
Now the dependency of the program to be linked:  As the program is compiled, it has just three modules: hello.o, modA.o and modB.o.  To create hello all these three modules must be given to the linker.... so the Makefile needs also:
hello: hello.o modA.o modB.o
    cc -o hello hello.o modA.o modB.o

and so, the complete Makefile is:
# this rule is put first to become the default target.
# the default target is the final program.
hello: hello.o modA.o modB.o
    cc -o hello hello.o modA.o modB.o

# this rule is for the hello.o target only.
hello.o: hello.c modA.h modB.h modB2.h
    cc -c hello.c

# this rule is for modA.o
modA.o: modA.c modA.h
    cc -c modA.c

# and this one for modB.o
modB.o: modB.c modB.h modB2.h
    cc -c modB.c

and with this Makefile you'll enjoy, because you can touch any file, but the compiler will compile only the correct dependencies to generate the final executable program.
Make has a lot of more functionality, but that requires you to know at least the most basic of it.  Once after you have succeeded on the creation of the correct dependencies, you can start to study the other facilities of make, that are only there to abbreviate/avoid rewritting the same thing several times.  But read at least the make manual page.


text:
Q: Do NoSQL databases use or need indexes? I am a newbie in NoSQL databases and this may sound a bit stupid but I was wondering if  NoSQL databases use or need indexes?
If yes, how to make or manage them? any links?
Thanks

A: CouchDB and MongoDB definitely yes. I mentioned that in my book:

*

*http://use-the-index-luke.com/sql/testing-scalability/response-time-throughput-scaling-horizontal
Here are the respective docs:

*

*http://guide.couchdb.org/draft/btree.html

*http://www.mongodb.org/display/DOCS/Indexes
NoSQL is, however, too fragmented to give a definite "yes, all NoSQL systems need indexes", I believe. Most systems require and provide indexes but not at level most SQL databases do. Recently, the Cassandra people were proudly introducing secondary indexes, i.e., more than a single clustered index.

*

*http://www.datastax.com/dev/blog/whats-new-cassandra-07-secondary-indexes (well, not so recently as I remember)

A: Definitely nosql databases need index,
i.e. but in most popular databases you need not to maintain index by yourself because as per current needs of nosql databases communities of nosql databases is developing with new features and with "Code Less, Get More"


text:
Q: Implement Markov's algorithm using random letters till letters makeup one word in the string? I am trying to use the Markov chain to display random letters till the letters make up one of the words found in the string. I think I'm on the right track, but instead of stopping when it reaches one word it just prints the whole string of random.
I believe there will be a check to see if characters match with the print out, but not sure…
What am I doing wrong here?
public class Main {

    public static void main(String[] args) {

        final int NUMBER_OF_CHARS = 100000;
        String[] words = { "at", "is", "he", "we", "up", "on" };

        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = main.getRandomLowerCaseLetter();
            if ((i + 1) % 40 == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }
}

A: I don't see any if statements checking whether the characters have formed a word yet. In other words, the loop will never exit, because you haven't written logic for it to do so.
You probably want to store each character you generate in a String as you go, like this:
String chars = "";
...
for(...){
    ...
    chars.append(ch);
    ...
}

You should also write something like this to break out of the loop:
for(String word : words){
    if(chars.contains(word){
        break outerLoop;
    }
}

Label the outer for loop like this so the break statement breaks out of both loops, not just the inner for loop:
outerLoop: while(...){}

A: There are probably better methods out there for doing this but here is something quick that solves your problem, as suggested by Keara you need to store each character as you go, then loop through and check if you have found something that you are looking for. As (in the example you gave anyway) the words you are looking for are a maximum of 2 characters long it makes it simple to reset the string every time you have found an invalid combination.
import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

    final int NUMBER_OF_CHARS = 100000;
    String[] words = {"at", "is", "he", "we", "up", "on"};
    List<Character> characters = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_CHARS; i++) {
        char ch = getRandomLowerCaseLetter();
        characters.add(ch);

        if ((i + 1) % 40 == 0) {
            System.out.println(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        } else {
            System.out.print(ch);
            if (contains(characters, words)) {
                System.exit(0);
            }
        }
    }
}

public static boolean contains(List<Character> characters, String[] words) {
    String st = "";
    int count = 0;
    for (Character c : characters) {
        st += c;
        count++;
        if (count == 2) {
            for (String s : words) {
                if (st.equals(s)) {
                    System.out.println(" Found: " + s);
                    return true;
                }
            }
            count = 0;
            st = "";
        }
    }
    return false;
}

public static char getRandomCharacter(char ch1, char ch2) {
    return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}

public static char getRandomLowerCaseLetter() {
    return getRandomCharacter('a', 'z');
}
}

Kind Regards and happy programming!


text:
Q: Sharepoint lockout Recently a guy from our 3rd line team thought it would be funny to delete my account from AD. This has now been re-added. Everything is back to normal apart from my Access to Sharepoint sites.
I am getting The file exists. (Exception from HRESULT: 0x80070050) Error on all sites.
After some googleing I came across a guy with the same issue and it was an issue with the SID being different from my old account. Since this I deleted my account from Site Administrators and re-added. This would refresh the SID with the new one. I also check on the Content database that the site ID matched using the following transactions and the SIDs match.
select s.Id, w.FullUrl from Sites s inner join Webs w on
s.RootWebId = w.Id

select * from UserInfo where tp_Login='domain\username' and
tp_SiteID='<ID Code>'

I am now a bit clueless.

A: I have now deleted the user account from Site Colection from Central Admin and also deleted from Site Collection from all the seperate sites. Performed a IISreset and then re-added the user account to Site Colection in Cental Admin and onto all sites. I have now got all my access rights back.

A: You could have used the command:
stsadm -o migrateuser ...
To copy your old rights into your new account.