Q: Map in Fragment: incompatible types cannot be converted to Fragment I checked several solutions on StackOverflow but nothing fitted my special problem.
I have several Fragments and I want a google map activity in one of those.
So I prepared the layout and created a new google map Activity with the necessary name.
When I try to run it it says:
Error:(20, 42) error: incompatible types: FragmentScreenD cannot be converted to Fragment

Furthermore it is written
"Wrong 2nd argument type. Found "com.example.name.yapplication.FragmentScreenD", required "android.support.v4.app.Fragment".

After doing this the message did not disappear.
package com.example.name.myapplication;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment1, new FragmentScreenA()).commit();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment2, new FragmentScreenB()).commit();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment3, new FragmentScreenC()).commit();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment4, new FragmentScreenD()).commit();
    }
}

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="2"
    android:orientation="horizontal"
    android:paddingBottom="10dp"
    android:weightSum="2" >

    <FrameLayout
        android:id="@+id/fragment3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="0dp"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/fragment4"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1" />
</LinearLayout>

package com.example.name.myapplication;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class FragmentScreenD extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_screen_d);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

A: FragmentScreenD which is extended From FragmentActivity does not Fragment and the second arguement of FragmentManager's replace method needs a Fragment , FragmentScreenD can be started via intent and its behavior is like an Activity, change FragmentActivity to Fragment and implement the methods in FragmentScreenA,B,C,...

A:
I have several fragments and I want a google map activity in one of those.

You don't want an Activity, you want a Fragment, as the error is trying to tell you.
You can add a new SupportMapFragment() directly to the FrameLayout, or you need to instead extend that rather than FragmentActivity

A: Just take a map fragment in fragment XML and check this link it will helpful to solve problem
android MapView in Fragment


Q: Nodejs application healthcheck best practice I'm looking into setting up a healthcheck mechanism for nodejs microservices running via container orchestrations. From a nodejs/express point of view, what is considered best practice to ensure that the service is indeed running on a given port on a given container? Eg. A healthcheck middleware or particular nodejs library, using a separate service port etc.

A: In order to implement healthcheck in nodejs, use the following
use express-healthcheck as a dependency in your nodejs project
in your app.js or equivalent code, use the following line
app.use('/healthcheck', require('express-healthcheck')());
if your app is up your response will be like
{
  "uptime":23.09
}
also it returns a status code of 200
Hope this helps


Q: Next.js refreshes indefinitely when query params are present I'm running a pretty basic Next.js app on local (next dev) and whenever a route has query parameters, it loads an reloads in an infinite loop. I've removed all calls to router.push, router.replace, and window.location but to no avail. When there are no query params present, this doesn't happen, and when I deploy the app for production (next export) I see no such behavior. Any idea what could be going on?


Q: Why does read_edgelist from networkx not accept arrays/lists as weights? I am using Python and the networkx package to read an edgelist from file in order to build a graph.
My edgelist looks something like this:
[(0, 114, {'pts': array([[  1, 822],
       [  1, 821],
       [  2, 820],
       [  3, 819]], dtype=int16), 'weight': 23.38477631085024}),
(1, 110, {'pts': array([[ 1,  3],
       [ 1,  2],
       [ 2,  1]], dtype=int16), 'weight': 18.414213562373096})]

I wrote this edgelist with:
nx.write_edgelist(G, 'my_el.edgelist', data=True)

My edges are defined by the start and the end node, and following that, I have my weights. Each edge has two weights. The first weight is a array of pixel-coordinates, and the second is a float.
The graph was constructed from a skeleton with the ´sknw´ library using the build_sknw function:
def build_sknw(ske, multi=False):
    buf = buffer(ske)
    nbs = neighbors(buf.shape)
    acc = np.cumprod((1,)+buf.shape[::-1][:-1])[::-1]
    mark(buf, nbs)
    pts = np.array(np.where(buf.ravel()==2))[0]
    nodes, edges = parse_struc(buf, pts, nbs, acc)
    return build_graph(nodes, edges, multi)

Now I want to read in this edgelist to build a graph. However, Python does not recognize my array of pixel-coords as a single weight-element.
I've tried nx.read_edgelist('my_el.edgelist', data=True), which gives me the following error:
TypeError: Failed to convert edge data (["{'pts':", 'array([[', '1,', '822],']) to dictionary.

nx.read_edgelist('my_el.edgelist', data=['pts', 'weight'] gives me:
IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys ['pts', 'weight'] are not the same length

and nx.read_edgelist('my_el.edgelist', data=(('pts', int), ('weight', float'))) gives me
IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys (('pts', <class 'int'>), ('weight', <class 'float'>)) are not the same length

I assume that the function is having a problem with either the array as a weight, or with the formatting of the my_el.edgelist file, but I do not really know, how to properly solve this issue without any workarounds via conversion to string, or similar.
I'd be thankful if someone can point me in the right direction and help me out with this!

A: Dealing with numpy arrays seems to be a major problem for networkx. The function that converts my image skeleton to the graph G however seems to be using numpy arrays.
Since I prefer not to alter the imported function, a possible workaround that seemed to mitigate the problem when writing the edgelist to file was to change the array type thus:
for (s, e) in G.edges():
    G[s][e]['pts'] = G[s][e]['pts'].tolist()

It might not be the most computationally efficient, and doesn't deal with the root of the problem, but will get the job done, in case anybody encounters a similar issue.


Q: Noda Time Date Comparison I am new to Noda Time and I basically want to compare if a date has expired or not. In my case I have an object with the date it was created, represented by a LocalDate and the amount of months it's valid as an int, so I wanted to do a simple:
if ( Now > (dateCreated + validMonths) ) expired = true;

But I can't find in the Noda Time documentation the proper way to get the Now Date (they only show how to get the Now Time as SystemClock.Instance.Now) and the proper way to handle time comparisons.
For example if today is January 1st 2015 and the document was created in December 1st 2014, and it was valid for one month, today it expires its one month validity.
I miss methods such as isBefore() and isAfter() to compare dates and times. Simple overloads of the < > operators could also be very helpful.

EDIT:
1 - Sorry, there are < > operators to compare dates.
2 - I solve my problem using this code (not tested yet!):
...
LocalDate dateNow = this.clock.Now.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).LocalDateTime.Date;
LocalDate dateExpiration = DataASO.PlusMonths(validity);
return (dateNow < dateExpiration);

A: To get the current date, you need to specify which time zone you're in. So given a clock and a time zone, you'd use:
LocalDate today = clock.Now.InZone(zone).Date;

While you can use SystemClock.Instance, it's generally better to inject an IClock into your code, so you can test it easily.
Note that in Noda Time 2.0 this will be simpler, using ZonedClock, where it will just be:
LocalDate today = zonedClock.GetCurrentDate();

... but of course you'll need to create a ZonedClock by combining an IClock and a DateTimeZone. The fundamentals are still the same, it's just a bit more convenient if you're using the same zone in multiple places. For example:
// These are IClock extension methods...
ZonedClock zonedClock = SystemClock.Instance.InTzdbSystemDefaultZone();

// Or...
ZonedClock zonedClock = SystemClock.Instance.InZone(specificZone);


Q: DataFrame column data to series I have the following DataFrame that contains some rainfall data. I want to reformat this so that I get a Series with 24 entries indexed with 'Month-Year' so that it will be easier to plot this as a line.
    JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
Year
2015    96.6    58.9    23.5    18.6    62.9    26.7    60.0    108.6   67.9    58.1    78.0    80.4
2016    131.8   54.2    80.2    51.2    64.1    91.3    17.4    38.8    50.9    29.8    100.6   17.4

I was thinking I could iterate through each row and pull out each month individually and add it to a series. I was wondering if there was a better way.

A: Use unstack with to_frame i.e
ndf = df.unstack().to_frame().sort_index(level=1)

             0
    Year
JAN 2015   96.6
FEB 2015   58.9
MAR 2015   23.5
APR 2015   18.6
MAY 2015   62.9
JUN 2015   26.7
JUL 2015   60.0
AUG 2015  108.6
SEP 2015   67.9
OCT 2015   58.1
NOV 2015   78.0
DEC 2015   80.4
JAN 2016  131.8
FEB 2016   54.2
MAR 2016   80.2
APR 2016   51.2
MAY 2016   64.1
JUN 2016   91.3
JUL 2016   17.4
AUG 2016   38.8
SEP 2016   50.9
OCT 2016   29.8
NOV 2016  100.6
DEC 2016   17.4

If you need index as a string then
ndf.index = ['{} {}'.format(i,j) for i,j in ndf.index.values]

If you need it as a datetime then
ndf.index = pd.to_datetime(['{} {}'.format(i,j) for i,j in ndf.index.values])


Q: How recursively find files with Unicode names in C++? I found and modify solution from here:
#include <iostream>
#include <windows.h>
#include <vector>
#include <fstream>

using namespace std;

//wofstream out;

void FindFile(const std::wstring &directory)
{
    std::wcout << endl << endl << endl << "FindFile(" << directory << ")" << std::endl;

    std::wstring tmp = directory + L"\\*";
    WIN32_FIND_DATAW file;
    HANDLE search_handle = FindFirstFileW(tmp.c_str(), &file);
    if (search_handle != INVALID_HANDLE_VALUE)
    {
        std::vector<std::wstring> directories;

        do
        {
            std::wcout << std::endl;
            std::wcout << "    [" << file.cFileName << "]" << std::endl;
            tmp = directory + L"\\" + std::wstring(file.cFileName);

            if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((!lstrcmpW(file.cFileName, L".")) || (!lstrcmpW(file.cFileName, L".."))) {
                    std::wcout << "continuing..." << std::endl;
                }
                else {
                    std::wcout << "saving path to this directory" << std::endl;
                    directories.push_back(tmp);
                }
            } else {
                std::wcout << "save [" << tmp << "] as file" << std::endl;
            }

            //std::wcout << tmp << std::endl;
            //out << tmp << std::endl;
        }
        while (FindNextFileW(search_handle, &file));

        std::wcout << "all items inside current directory was worked out. close it's handle." << std::endl;
        FindClose(search_handle);

        for(std::vector<std::wstring>::iterator iter = directories.begin(), end = directories.end(); iter != end; ++iter) {
            std::wcout << "recursively find in next directory: [" << *iter << "]" << std::endl;
            FindFile(*iter);
        }
    } else {
        std::wcout << "invalid handle value" << std::endl;
    }
}

int main()
{
    //out.open("C:\\temp\\found.txt");

    FindFile(L"C:\\test");

    //out.close();

    cout << "The end" << endl;
    string str;
    cin >> str;

    return 0;
}

but this code isn't working with folders or files with cyrillic names (but I use Unicode versions of all types and functions!)
Update: Application just finish, without any exceptions, as if all commands was executed.
Update-2 (print-screen):
Who had the same problem? Thanks for any help.
SOLVED
Thanks a lot to @zett42 !
After some refactoring working code looks like:
#include <iostream>
#include <windows.h>
#include <vector>
#include <fstream>
#include <io.h>
#include <fcntl.h>

using namespace std;

vector<wstring> FindFiles(const std::wstring &directory) {
    vector<wstring> files;
    std::vector<std::wstring> directories;

    std::wstring fullPath = directory + L"\\*";
    WIN32_FIND_DATAW file;
    HANDLE search_handle = FindFirstFileW(fullPath.c_str(), &file);

    if (search_handle == INVALID_HANDLE_VALUE)
        return files;

    do
    {
        fullPath = directory + L"\\" + std::wstring(file.cFileName);

        if (!(file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
            files.push_back(fullPath);
        else {
            if ((lstrcmpW(file.cFileName, L".")) && (lstrcmpW(file.cFileName, L"..")))
                directories.push_back(fullPath);
        }
    }
    while (FindNextFileW(search_handle, &file));

    FindClose(search_handle);

    for(std::vector<std::wstring>::iterator iter = directories.begin(), end = directories.end(); iter != end; ++iter) {
        vector<wstring> newFiles = FindFiles(*iter);
        files.insert(files.begin(), newFiles.begin(), newFiles.end());
    }

    return files;
}

int main()
{
    _setmode( _fileno(stdout), _O_U16TEXT );

    vector<wstring> files = FindFiles(L"E:\\test");

    wcout << L"All found files: " << endl;
    for (int i = 0; i < files.size(); ++i)
        wcout << files[i] << endl;

    cout << "The end" << endl;
    string str;
    cin >> str;

    return 0;
}

A: On Windows, Unicode output to console doesn't work by default, even if you use std::wcout.
To make it work, insert the following line at the beginning of your program:
_setmode( _fileno(stdout), _O_U16TEXT );

_setmode and _fileno are Microsoft specific function.
You may also have to change console font. I'm using Lucida Console which works fine for cyrillic letters.
Complete example:
#include <iostream>
#include <io.h>      // _setmode()
#include <fcntl.h>   // _O_U16TEXT

int main()
{
    // Windows needs a little non-standard magic for Unicode console output.
    _setmode( _fileno(stdout), _O_U16TEXT );

    std::wcout << L"по русски\n";
}

Example should be saved as UTF-8 encoded file because of the Unicode string literal, but this is not relevant in your case because you don't have Unicode string literals.
I have successfully tested this code under MSVC2015 and MSVC2017 on Win10.


Q: Is it possible to use angular lazy loading without a routes file I am using angular lazy loading for my modules.
For example I load the modules like this as recommended by AG8
const routes: Routes = [
  {path: 'home', component: HomeComponent, data: {title: 'Home', animation: 'Home'}},
  {path: 'services', loadChildren: () => import('./modules/services.module').then(module => module.ServicesModule), data: {title: 'Services', animation: 'Services'}},
  // {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'login', loadChildren: () => import('./modules/login.module').then(module => module.LoginModule), data: {title: 'Login', animation: 'Login'}},
  {path: 'dashboard', loadChildren: () => import('./modules/dashboard.module').then(module => module.DashboardModule ), data: {title: 'Dashboard', animation: 'Dashboard'}, canActivate: [AppAuthGuard]},
  {path: 'user/:userID/event/:eventID', loadChildren: () => import('./modules/event.module').then(module => module.EventModule ), data: {title: 'Event Details', animation: 'Event'}},
  {path: 'user/:userID', loadChildren: () => import('./modules/user.module').then(module => module.UserModule), data: {title: 'Profile', animation: 'User'}},
  {path: '**', redirectTo: 'home', pathMatch: 'full' },
];

The for each of those modules I have their corresponding files eg:
@NgModule({
  imports: [
    CommonModule,
    SomeRoutingModule
  ],
  declarations: [SomeComponent]
})
export class SomeModule { }

But for all those modules I have to create their corresponding router files eg:
const routes: Routes = [
  {
    path: '',
    component: SomeComponent
  }
];

Is there a way to just guide from the parent module the route to load the lazy module's declared component without having to create a router file?
Something like:
loadChildren: () => import('./modules/services.module').then(module => module.ServicesModule.SomeComponent)


Q: Jquery menu breaking on fast clicking/ scrolling over I have this jquery code below, but the problem is that if I scroll over and out of the trigger element quickly and through the menu, then it breaks, progressively showing less elements each time until nothing is shown. Can I add a timer or easing to stop this breaking?

Read the blog

paperback

Signed edition

kindle edition

hardback edition

postcard edition

(function ($) {
Drupal.behaviors.weaveoftheride = {
attach: function(context, settings) {

 console.log('called');
$('.buying-dropdown li').hover(
        function () {
            //show its submenu
            $('ul', this).stop().slideDown(100);

        },
        function () {
            //hide its submenu
            $('ul', this).stop().slideUp(100);
        }
    );
}

};
})(jQuery);

A: You should force jQuery to clear the animation queue and jump to the end of the animation when using the .stop() method, i.e. .stop(true, true).


Q: Python, simple calculation User types an integer number (smaller than 100, bigger than 0)
If user types 0, the program ends. In case of numbers that are 100 or bigger, or that are -1 or smaller, it shows INVALID, and prompts user to keep entering number.
a = int(input('Enter a number: '))

total =0
keep = True

while keep:

    if a ==0:
        print('Thanks for playing.. goodbye')
        break;
    else:
        while a>99 or a <0:
            print('INVALID')
            a = int(input('Enter a number: '))

    total = total + a
    print(total)
    a = int(input('Enter a number: '))

Just putting normal numbers and getting the sum, I enter 0, then it stops, but when I enter 100, INVALID shows up, then I enter 0, the program doesn't end and it keeps showing me INVALID.
Any suggestions will be appreciated. Thanks!

A: At your code, the else never breaks the loop so it only sums the total after it has exitted that 2nd loop, but that 2nd one doesn't have a behaviour for 0. You should try to keep it simple with just one loop.
total =0
while True:
    a = int(input('Enter a number: '))
    if a == 0:
        print('Thanks for playing.. goodbye')
        break
    else:
        if a > 99 or a < 0: # You don't need a second while, just an if.
            print('INVALID')
        else:
            total = total + a
            print(total)

Identation is key at python, be careful with it.
Also cleaned a bit your code. As example: Since you get into a loop with the while there is no need to use 2-3 different inputs in and out of the loop, just add it once at the beginning inside of the loop.

A: I think this is a more pythonic approach
total =0

while True:
    a = int(input('Enter a number: '))
    if a == 0:
        break
    if a>99 or a <0:
            print('INVALID')
    else:
        total = total + a

print(total)
print('Thanks for playing.. goodbye')

A: When using your code, the result is :
Enter a number: 100
INVALID

Enter a number: 0
0

Enter a number: 0
Thanks for playing.. goodbye

And I think your code may should be:
a = int(input('Enter a number: '))

total =0
keep = True

while keep:

    if a ==0:
        print('Thanks for playing.. goodbye')
        break;
    else:
        while a>99 or a <0:
            print('INVALID')
            a = int(input('Enter a number: '))
            if a ==0:
                print('Thanks for playing.. goodbye')
                break;

    total = total + a
    print(total)
    a = int(input('Enter a number: '))

You may procide your requirement more detail.

A: You are in while loop of else conditional since you entered 100 at first and you can't get out of there unless you enter a number satisfies 0 <= a <= 99. You can make another if statement for a == 0 to exit the while loop just below a = int(input('Enter a number')) of else conditional.
I think it is good to check where you are in while loop using just one print(a). For example, just before if-else conditional or just before while of else conditional. Then, you can check where it gets wrong.
a = int(input('Enter a number: '))

total = 0
keep = True

while keep:
    \\ print(a) here to make sure if you are passing here or not.
    if a == 0:
        print('Thanks for playing.. goodbye')
        break;
    else:
        \\ print(a) here to make sure if you are passing here or not.
        while a > 99 or a < 0:   \\You are in while loop since you entered 100 at first and you can't get out from here unless you enter a: 0 <= a <= 99.
            print('INVALID')
            a = int(input('Enter a number: '))
            if a == 0:
                print('Thanks for playing.. goodbye')
                break;
    total = total + a
    print(total)
    a = int(input('Enter a number: '))


Q: Zend Framework - Issue with delete from database code In my Application_Model_DbTable_User, I have the following function:
public function deleteUser($username)
{
    $this->delete('username = ' . (string) $username);
}

This function is being called from my AdminController, with this three lines of code.
$uname = $this->getRequest()->getParam('username');
$user = new Application_Model_DbTable_User();
$user->deleteUser($uname);

This error however, turns up.

Column not found: 1054 Unknown column 'test' in 'where clause'

With test being the user I am trying to delete.
This code is adapted from a previous code which deletes based on id, a INT field, which works perfectly fine. What am I doing wrong? I would be happy to give more detailed codes if needed. Thanks.

A: Your query isn't quoted:
$this->delete('username = ' . (string) $username);

This equates to:
WHERE username = test

If you use the where() method, it will do this for you:
$table->where('username = ?', $username);

Or (like the example in the docs):
$where = $table->getAdapter()->quoteInto('bug_id = ?', 1235);
$table->delete($where);


Q: Winapi detect button hovering I've got a C++ project in which I'm using the Winapi to develop a window with a button and I want to change the text of the button when it's being hovered. For example, changing "Click me" to "Click me NOW!", when hovered. I've tried searching but I've not found any good ways to do this.
I noticed that when user hovers, the WM_NOTIFY message is received, but I don't know how to ensure that it has been called by the mouse hover. I've found that I can use TrackMouseEvent to detect hovering, but it's limited to a period of time and I want to execute an action every time the user hovers the button.
Here is how I create a button:
HWND Button = CreateWindow("BUTTON", "Click me",
        WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
        20, 240, 120, 20,
        hwnd, (HMENU)101, NULL, NULL);

And this my window procedure:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    switch (msg)
    {
    case WM_NOTIFY:
    {
        //??? Here is where I get a message everytime I hover the button, But I don't know any proper way to see if it has been executed by the button.
    }
    case WM_CREATE: //On Window Create
    {
        //...
    }
    case WM_COMMAND: //Command execution
    {
        //...
        break;
    }
    case WM_DESTROY: //Form Destroyed
    {
        PostQuitMessage(0);
        break;
    }
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

A: Assuming you're using the common controls there is the BCN_HOTITEMCHANGE notification code for the WM_NOTIFY message. The message includes the NMBCHOTITEM structure, which includes information for whether the mouse is entering or leaving the hover area.
Here's an example:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_NOTIFY:
        {
            LPNMHDR header = *reinterpret_cast<LPNMHDR>(lParam);

            switch (header->code)
            {
                case BCN_HOTITEMCHANGE:
                {
                    NMBCHOTITEM* hot_item = reinterpret_cast<NMBCHOTITEM*>(lParam);

                    // Handle to the button
                    HWND button_handle = header->hwndFrom;

                    // ID of the button, if you're using resources
                    UINT_PTR button_id = header->idFrom;

                    // You can check if the mouse is entering or leaving the hover area
                    bool entering = hot_item->dwFlags & HICF_ENTERING;

                    return 0;
                }
            }

            return 0;
        }
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

A: You can check the code of the WM_NOTIFY message to see if it is a NM_HOVER message.
switch(msg)
{
case WM_NOTIFY:
    if(((LPNMHDR)lParam)->code == NM_HOVER)
    {
       // Process the hover message
    }
    else if (...) // any other WM_NOTIFY messages you care about
    {}
}

A: You can use simply SFML to do this.
Code:
RectangleShape button;
button.setPosition(Vector2f(50, 50));
button.setSize(Vector2f(100, 40));
button.setFillColor(Color::Green);
if(button.getGlobalBounds().contains(static_cast<Vector2f>(Mouse::getPosition(/*your
window name*/window)
{
    button.setFillColor(Color::Red);
}


Q: Can angular be exposed as webservice API? I want to expose angular as web service, is that possible?
In other words, can a backend calls angular, using typescript language?

A: NO, it's not possible. Angular is a FRONT-END framework

A: Strictly speaking, It is not recommended but I would say it is possible.
Basically, everyone will say that it is just "FrontEnd" web framwork.
But I see that it also can be a multi-platform framework for frontend and  backend as well. The main Angular core team didn't define this framework as one "Frontend" framework. Rather, it says one framework across all platform. It means it can be transformed anything. They think bigger than  non-angular developers. I see the bigger picture and future with Angular. Of course, this is just mainly used for the mobile and desktop for now. Many developers have a skeptical idea of this. I would agree.
For example, Ionic/Nativescript. They adopted Angular as a core framework. Yes, this is for mobile(Frontend right?).
However, What about Nest.js. Cool right?
This is totally server-side web framework for "Backend".
The fact is that this framework heavily referenced "Angular framework" such as Angular-like Dependency Injection system.
They even mentioned "The architecture is heavily inspired by Angular."
Let's say you are a pioneer and you can make it possible.
I highly recommend to play with the Angular platform source codebase.
Git clone and modify something and build it(it takes some time but it should work at your local computer). If you see the github codebase, this is huge and actually have capability or "potential" to serve as a backend.
Of course, it depends on a situation. So ask yourself What kind of your expectation from it and what the purpose is.
Angular is just javascript(transpiled by Typscript) program.
After having transpiled javascript static files, it requires a http server to serve the files.
Luckily, Angular Frmaework has its own local server( called ng serve  yes we know this one which is a cute http/https server.
Thus, technically speaking, Angular is "Framework" not library. Framework includes many tools and even app servers in it. I would say that it's possible and it can even directly communicate with other Angular applications with websocket and webRTC as well.
Don't make me wrong. Once again, It is only possible with the embedded Angular Serve module(ng serve) if you don't want to install other 3rd party http server.
These days, What a Javascript/Typescript world. Javascript/Typescript can do everything. Angular is a part of it and it is the most advanced web framework among others.
Check out the following github codes. Hope you like my answer. Take care.
angular-cli/packages/angular_devkit/core/node/
architect-command.ts
angular devkit dev-server

Anything is possible


Q: Replacting XML node text using PowerShell I am having my XML document as follows
  <Batch>
  <Alter>
    <ObjectDefinition>
      <DataSources>
        <DataSource>
          <ConnectionString>Provider=SQLNCLI11.1;Data Source=ABC;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString>
          <ConnectionString>Provider=SQLNCLI11.1;Data Source=XYZ;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString>
        </DataSource>
      </DataSources>
    </ObjectDefinition>
  </Alter>
</Batch>

I would like to replace the entire connection-string nodes as follows
$ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"
Here is what I tried but this is replacing only one node content
$XMLA = "D:\employee.xml"
$SqlDataBase = [xml](Get-Content $XMLA)
$data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString")
#$data
$DataSource = "localhost"
foreach($xn in $data)
{

   $DataBase = $xn.'#text'.Split(";").Split("=")
   $DataBase[$DataBase.Length - 1]
   $DataBase = $DataBase[$DataBase.Length - 1]

   $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"

   $SqlDataBase.SelectSingleNode("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString").InnerText = "$ConnectionString";
}
$SqlDataBase.Save($XMLA)

So any better way to replace multiple nodes please let me know

A: This is best way where I have taken the source from here
Selecet XML Nodes by similar names in Powershell
$XMLA = "D:\employee.xml"
$SqlDataBase = [xml](Get-Content $XMLA)
$data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString")
#$data
$DataSource = "localhost"

$SqlDataBase.Batch.Alter.ObjectDefinition.DataSources.DataSource.ChildNodes | Where-Object Name -Match 'ConnectionString' | ForEach-Object {

    $DataBase = $_.'#text'.Split(";").Split("=")
    $DataBase = $DataBase[$DataBase.Length - 1]

    $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"

    $_.'#text' = "$ConnectionString"
}

$SqlDataBase.Save($XMLA)


Q: Access VBA Return 0 in grouping even if there is no match I have employees table in access db with days on which they have worked on:
Table A
employee_id | date_wrk | Project | Worked
-----------------------------------------
1   10      |01.01.2015|Project1 | 1
2   10      |12.01.2015|Project1 | 0,5
3   10      |01.02.2015|Project1 | 1
4   10      |01.02.2015|Project2 | 1
5   10      |04.02.2015|Project2 | 1
6   12      |05.02.2015|Project2 | 1

What i need is Final table with sum of days done by month by projects:
employee_id | Month   | Project   | Worked
-----------------------------------------
    10      |January  | Project 1  | 1,5
    10      |February | Project 1  | 1
    10      |February | Project 2  | 2
    10      |March    | Project 1  | 0

I group by month(date) with sum of days worked - The problem is I want to display all months jan-dec - the month and 0 if employee doesn't have any day worked in given month for given project..
I tried to build months table with all months listed and right join it but it doesnt help..
Any ideas would be appriciated.
Cheers!
    .....

A: I try to avoid right join because it's needlessly confusing.
Here's an example left join approach:
select  e.employee_id
,       m.month
,       a.project
,       sum(a.worked)
from    (
        select  distinct employee_id
        from    TableA
        ) e
,       MonthsTable m
left join
        TableA a
on      a.employee_id = m.employee_id
        and month(a.date_wrk) = m.month
group by
        e.employee_id
,       m.month
,       a.project

The cross join creates a matrix of each employee and each month.  For each employee-month combination in the matrix, it optionally looks up the project hours.

A: Ok I did it basing on Andomar suggestion - but as  Access is not fond of sub-queries and cross join I created additional table based on :
select  distinct employee_id,months.month
from TableA,months

which give me a cross join table which then I linked to tableA.
Cheers!


Q: AWS CodePipeline: source action has insufficient permissions for CodeStar connection I'm setting up a CodePipeline, and I created an action to fetch the source from GitHub.
This requires to set up a connection, which I did, and things look fine also on GitHub's side.
However, if I release a change to the pipeline, I see the following error at the source stage:
Insufficient permissions
Unable to use Connection: arn:aws:codestar-connections:us-east-1:REDACTED:connection/REDACTED. The provided role does not have sufficient permissions.

I added full CodeStar access to the pipeline's service role (which I found in the pipeline settings) and looks like this:
arn:aws:iam::REDACTED:role/service-role/AWSCodePipelineServiceRole-us-east-1-REDACTED

Does anybody have any idea of what might be missing? Thanks!

A: The solution was to add this bit to the policy of the service role:
{
        "Effect": "Allow",
        "Action": "codestar-connections:UseConnection",
        "Resource": "insert ARN of the CodeStar connection here"
}


Q: How to parse cell format data from a .xlsx file using xlrd I am relatively new to python and I am trying to read information from an excel sheet to generate a graph. So far I am using the most current version of the xlrd library (0.9.4) in a nested for loop to grab the value from each cell. However, I am unsure how to access the formatting information for each cell
For example, if a cell were formatted to display as currency in the excel file, using the standard sheet.cell(row, column).value from xlrd would only return 5.0 instead of $5.00
I found here that you can set the formatting_info parameter to true when opening the workbook in order to see some of the format information, however I am primarily using excel 2013 and my excel sheets are being saved by default as .xlsx files. According to this issue on GitHub, support for formatting_info has not yet been implemented for .xlsx files.
Is there any way around using the formatting_info flag, or any other way that I can detect when a format, currency specifically, has been used in order to reflect that in my graphs? I am aware that it is possible to convert .xlsx files to .xls files such as shown here, but I am concerned about information/formatting loss.


Q: How to bulk insert data in Djnago without providing fields to model How to bulk insert data with only providing dictionary key and not worry about manually providing fields and type of fields in models.py
What I have to do right now:
models.py
from django.db import models

# Create your models here.

class Info(models.Model):
    name = models.CharField(max_length=70)
    email = models.CharField(max_length=70)

Outout:
name | email
Jon  | j@g.com

mongodb collection
what I want without using fields and assigning more than 20-30 fields:
name | email | fname | lname | cellNum | add | age | height | etc...

for example using mongoClient to bulk insert data without providing fields
data = {x:x, y:y, z:z}
collection.insert_one(data)
collection.insert_many([data,...])


Q: gcm canonical id should be updated or not I am working on an android project which uses gcm. I came to know that if we uninstall the appfrom device and reinstalled most of the time the device gets new registration id.Then if we do not delete the old one from application server and update, The messages will be sending to both ids and in the response it will be showing canonical id is present.My question is, at this point message will be successfully send to that device or not?

A: When you receive a canonical registration ID in the response from Google, the message was accepted by the GCM server and the GCM server would attempt to deliver it to the device. Whether it is actually sent to the device depends on whether the device is available (i.e. connected to the internet).
So if your server sends a GCM message to both the old ID and the new ID, the device will probably get two messages.

Canonical IDs
On the server side, as long as the application is behaving well,
  everything should work normally. However, if a bug in the application
  triggers multiple registrations for the same device, it can be hard to
  reconcile state and you might end up with duplicate messages.
GCM provides a facility called "canonical registration IDs" to easily
  recover from these situations. A canonical registration ID is defined
  to be the ID of the last registration requested by your application.
  This is the ID that the server should use when sending messages to the
  device.
If later on you try to send a message using a different registration
  ID, GCM will process the request as usual, but it will include the
  canonical registration ID in the registration_id field of the
  response. Make sure to replace the registration ID stored in your
  server with this canonical ID, as eventually the ID you're using will
  stop working.

(Source)
You can overcome this problem by assigning a unique identifier to each instance of your application. If you store that identifier in the device's external storage, it won't be deleted when the app is uninstalled. Then you can recover it when the app is installed again. If you send this identifier to your server along with the registration ID, you can check if your server has an old registration ID for this identifier, and delete it.

A: @Eran We have two option either to remove older registration ids or update with Key and position of canonical id. I prefer to update... You can view working code of mine i have answered here Steps to Update Canonical Ids


Q: I am making a paint application using kotlin. I wanted to erase my last path using an undo button. How can I do that? I was trying to make a paint app through which users can paint and draw for fun.
I wanted to erase a drawing partially by using the undo button in my app. The floating action button I have used erases the whole drawing, but I want only that last part of the drawing to get erased. Kindly help me how can I do that ?
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".MainActivity">

<LinearLayout
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    android:background="@drawable/toolbar_background"
    android:gravity="center"
    app:layout_constraintRight_toRightOf="parent">

    <ImageButton
        android:id="@+id/redColor"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:background="@drawable/red_background"/>

    <ImageButton
        android:id="@+id/blueColor"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:background="@drawable/blue_background"/>

    <ImageButton
        android:id="@+id/blackColor"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:background="@drawable/black_background"/>

    <ImageButton
        android:id="@+id/whiteColor"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:background="@drawable/white_background"/>

</LinearLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toBottomOf="@id/toolbar"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintBottom_toBottomOf="parent">

    <include
        android:id="@+id/include"
        layout="@layout/paint_view" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/resetButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="RESET"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.954"
        app:layout_constraintStart_toStartOf="parent"
        android:src="@drawable/ic_baseline_delete_24"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt
package com.example.dapple

import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.dapple.PaintView.Companion.colorList
import com.example.dapple.PaintView.Companion.currentBrush
import com.example.dapple.PaintView.Companion.pathList
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

companion object{
    var path = Path()
    var paintBrush = Paint()
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    supportActionBar?.hide()

    redColor.setOnClickListener{
        paintBrush.color = Color.RED
        currentColor(paintBrush.color)
    }

    blueColor.setOnClickListener{
        paintBrush.color = Color.BLUE
        currentColor(paintBrush.color)
    }

    blackColor.setOnClickListener{
        paintBrush.color = Color.BLACK
        currentColor(paintBrush.color)
    }

    whiteColor.setOnClickListener{
        paintBrush.color = Color.WHITE
        currentColor(paintBrush.color)
    }

    resetButton.setOnClickListener{
        pathList.clear()
        colorList.clear()
        path.reset()
    }
}

private  fun currentColor(color: Int){
    currentBrush = color
    path = Path()
}
}

PaintView.kt
package com.example.dapple

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintSet
import com.example.dapple.MainActivity.Companion.paintBrush
import com.example.dapple.MainActivity.Companion.path

class PaintView : View {

var params:ViewGroup.LayoutParams? = null

companion object{
    var pathList = ArrayList<Path>()
    var colorList = ArrayList<Int>()
    var currentBrush = Color.WHITE
}

constructor(context: Context) : this(context, null){
    init()
}
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
{
    init()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init()
}

private fun init(){
    paintBrush.isAntiAlias = true
    paintBrush.color = currentBrush
    paintBrush.style = Paint.Style.STROKE
    paintBrush.strokeJoin = Paint.Join.ROUND
    paintBrush.strokeWidth = 8f

    params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}

override fun onTouchEvent(event: MotionEvent): Boolean {
    var x = event.x
    var y = event.y

    when(event.action){
        MotionEvent.ACTION_DOWN->{
            path.moveTo(x,y)
            return true
        }
        MotionEvent.ACTION_MOVE->{
            path.lineTo(x,y)
            pathList.add(path)
            colorList.add(currentBrush)
        }
        else -> return false
    }
    postInvalidate()
    return false
}

override fun onDraw(canvas: Canvas) {
    for(i in pathList.indices){
        paintBrush.setColor(colorList[i])
        canvas.drawPath(pathList[i],paintBrush)
        invalidate()
    }
}
}


Q: Pythonic Way To Warn Developers For Broken Code Is there a pythonic way to throw an exception to other developers to warn them about using a piece of code with bugs in it?
For example:
def times_two(x):
    raise BrokenException("Attn.This code is unreliable. Only works on positive numbers")
     x = abs(x) * 2
     return x

I understand that I can raise a generic exception with a message, or even derive my own exception classes, but i just want to know if there is a built-in, pythonic way to do something like this.
And also, I understand that why the actual times_two function doesn't work. That was just an example function.
This is not something to validate input parameters, or even returned values.
This is simply to mark a function as potentially unreliable.
The code must be used in some areas under very specific circumstances, but when devs are writing code and run across this function should be warned of the limitations.

A: Your example is pretty flawed for any use case in which alerting the developers would be needed. This would need to alert the user not to input a negative number.
def times_two(x):
    if x < 0:
        raise BrokenException("Attn user. Don't give me negitive numbers.")
    return x * 2

Although, I think if your example more accurately described an actual error needing developer attention then you should just fix that and not put it into production knowing there is an error in it.
sentry.io on the other hand can help find errors and help developers fix errors while in production. You may want to look into that if warnings isn't for you. From their README.me:

Sentry fundamentally is a service that helps you monitor and fix
  crashes in realtime. The server is in Python, but it contains a full
  API for sending events from any language, in any application.

A: Builtin Exception 'ValueError' is the one that should be used.
def times_two(x):
    if x < 0:
        raise ValueError('{} is not a positive number.'.format(x))
    return x * 2

A: This seems like an XY problem. The original problem is that you have some code which is incomplete or otherwise known to not work. If it is something you are currently working on, then the correct tool to use here is your version control. With Git, you would create a new branch which only be merged into master and prepared for release to production after you have completed the work. You shouldn't release a partial implementation.

A: Do you want to stop execution when the function is called? If so, then some sort of exception, like the BrokenException in your example is a good way of doing this.
But if you want to warn the caller, and then continue on anyway, then you want a Warning instead of an exception. You can still create your own:
class BrokenCodeWarning(Warning)
    pass

When you raise BrokenCodeWarning, execution will not be halted by default, but a warning will be printed to stderr.

The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).

https://docs.python.org/3.7/library/warnings.html#the-warnings-filter


Q: NHibernate - counters with concurrency and second-level-caching I'm new to NHibernate and am having difficulties setting it up for my current website. This website will run on multiple webservers with one database server, and this leaves me facing some concurrency issues.
The website will have an estimated 50.000 users or so registered, and each user will have a profile page. On this page, other users can 'like' another user, much like Facebook. This is were the concurrency problem kicks in.
I was thinking of using second-level cache, most likely using the MemChached provider since I'll have multiple webservers. What is the best way to implement such a 'Like' feature using NHibernate? I was thinking of three options:

*

*Use a simple Count() query. There will be a table 'User_Likes' where each row would represent a like from one user to another. To display the number the number of likes, I would simply ask the number of Likes for a user, which would be translated to the database as a simple SELECT COUNT(*) FROM USER_LIKES WHERE ID = x or something. However, I gather this would be come with a great performance penalty as everytime a user would visit a profile page and like another user, the number of likes would have to be recalculated, second-level cache or not.

*Use an additional NumberOfLikes column in the User table and increment / decrement this value when a user likes or dislikes another user. This however gives me concurrency issues. Using a simple for-loop, I tested it by liking a user 1000 times on two servers and the result in the db was around 1100 likes total. That's a difference of 900. Whether a realistic test or not, this is of course not an option. Now, I looked at optimistic and pessimistic locking as a solution (is it?) but my current Repository pattern is, at the moment, not suited to use this I'm afraid, so before I fix that, I'd like to know if this is the right way to go.

*Like 2, but using custom HQL and write the update statement myself, something along the lines of UPDATE User SET NumberOfLikes = NumberOfLikes + 1 WHERE id = x. This won't give me any concurrency issues in the database right? However, I'm not sure if I'll have any datamismatch on my multiple servers due to the second level caching.

So... I really need some advice here. Is there another option? This feels like a common situation and surely NHibernate must support this in an elegant manner.
I'm new to NHIbernate so a clear, detailed reply is both necessary and appreciated :-) Thanks!

A: I suspect you will see this issue in more locations. You could solve this specific issue with 3., but that leaves other locations where you're going to encounter concurrency issues.
What I would advise is to implement pessimistic locking. The usual way to do this is to just apply a transaction to the entire HTTP request. With the BeginRequest in your Global.asax, you start a session and transaction. Then, in the EndRequest you commit it. With the Error event, you go the alternative path of doing a rollback and discarding the session.
This is quite an accepted manner of applying NHibernate. See for example http://dotnetslackers.com/articles/aspnet/Configuring-NHibernate-with-ASP-NET.aspx.

A: I'd go with 3. I believe this in this kind of application it's not so critical if some pages show a slightly outdated value for a while.
IIRC, HQL updates do not invalidate the entity cache entry, so you might have to do it manually.


Q: delete specific rows from a flat file How to delete specific rows from a flat file on the basis of first 4 characters of a row?  For example; delete the rows starting with '1000'.  (After deleting these rows, the file will remain there with other rows that start with '2000', '3000', and so on.
Or, how to write the rows starting with '1000', '2000', and '3000' into different flat files?  (Each row has varying number of columns and columns have different width).


Q: Deleting top 100 records from database via NHibernate using linq Is there a way to delete top 1000 records from database via NHibernate using ling , something similar like Take(100) when u are fetching data?


Q: Access VBA Checkbox error 2447 Ok, I'm getting the error 2447 when trying to create a new record in my database.  Here is the code that is have.
'This checks the record each time a record is changed to see if it needs to display the text boxes
Private Sub Form_Current()
If Me.SigCheck = 1 then <--This is where I'm getting the error.
SigSerialtxt.Visible = True
SigSeriallbl.Visible = True
SigAssettxt.Visible = True
SigAssetlbl.Visible = True
Else
SigSerialtxt.Visible = False
SigSeriallbl.Visible = False
SigAssettxt.Visible = False
SigAssetlbl.Visible = False
End if
End Sub

I've tried to change the variable to True, as well as -1, but neither of the work.  I'm lost as to what to use.

A: fixed the issue, I set the default to 0, now there is no error and it works properly.


Q: How to get reference to commits in git Lets have a git master branch and at some moment lets fork branch for release (release branch will be called R1). Sometimes I need to push commit to both of them(master and R1). Usually I work on master branch, when I'm done I test it, cherry-pick to R1, test it there and push to both of them.
I would like to have in R1 commit reference to master branch. This is done by cherry-pick -x. However, this approach works ONLY when I push to master branch and then cherry-pick from master to R1. Let say that testing take too much time and I want to have master and R1 in sync as much as I can ( I want to minimize time gap between pushes), so I would like to push simultaneously. In this way I can not get reference (-x in cherry-pick), because hash will change while doing rebase in R1 (can not use merge).
Is there any way how to automatize this, so I will have correct hash in R1 description? Something like hash predicting?

A:
Is there any way how to automatize this, so I will have correct hash in R1 description? Something like hash predicting?

The short answer is no.
The longer answer is still no, but you might not need to predict the hash.  The issue here is that you are copying some fix commit—let's call this F—from master to another branch.  Let's call this -x cherry-picked copy commit Fx.  You may also end up copying the fix commit to a new fix commit because you are avoiding using git merge in this work-flow, so if master has acquired new commits, you use rebase to cherry-pick F into a new commit F' that you will add to master, and now you want to replace your Fx—your cherry-picked copy of F—with a cherry-picked copy of F'.
So, you can just do that.  If you rebase commit F to make F', strip Fx from the other branch and re-run git cherry-pick -x to copy F' to Fx'.  You already know which commits these are, because you have the original hash ID of F and cherry-picking it (via rebase) produces F'; and you have F's hash ID in Fx.  The drawback is that this re-copies any commits after Fx on the other branch, since "strip Fx from the other branch" can be nontrivial.
(An alterative approach, one that avoids all this fussing-about, is to merge the fix into both branches.  See How to do a partial merge in git? and the linked blog articles.)


Q: C implicit conversion? Can someone explain to me how
printf("%d", -2<2u?1:-1);

prints out '-1'. I assume there is some kind of implicit conversion going on but I can't seem to grasp it.

A: -2 is getting converted to unsigned integer. This will be equal to UINT_MAX - 1, which is definitely greater than 2. Hence, the condition fails and -1 is printed.


Q: Simple loop on windows7 creates memory leak? I am unsure about this, but this question might be related to Memory leak in batch for loop?.
I have the following trivial batch script:
@echo off
:label
cmd.exe /c cls
echo hello
goto label

When this script runs on a Windows7 32-bit installation, it behaves well. But when I run it on the few Windows7 64-bit machines that I have access to, it slowly and apparently irrevocably eats up all system memory - as seen in the Windows task manager. The memory stays in use after closing the window that executes the above batch lines.
Is this happening to other people? If not, do you know what could cause this? Other installed software on the system?
I have the same behavior if I do a
while True: os.system('cls')

loop in a Python-X/Y shell. It seems to be linked to the creation of a sub process. If I change the above from cmd.exe /c cls to just cls, I do not get a memory leak. I ran into this problem because I ported a Python script from Linux that repeatedly does a clear screen for a statistics display, implemented for Windows as shown in Clear the screen in python.

A: I ran it on my x64 machine and it works ok, it does start to struggle as time goes but I wouldn't call it a memory leak, if anything it just hammers the CPU when it spikes.
It could just be struggling to keep up with the commands depending on the performance of the computer. I added in a timeout for a second, now cmd is much happier and showing less than 1MB RAM consumption.
Try just adjusting this to your needs, or find middle ground where you get the speed and the performance, just give cmd a break :)
@echo off
:label
cmd.exe /c cls
echo hello
timeout /t 1 >nul
goto label


Q: Coping text from textarea to div in jQuery I'd like to copy text from textarea to div using this code but there are line breaks missing.
$("#some-div").text($("#some-textarea").val().replace('/\n/g', '
'));

What's going wrong?
Thanks

A: The text function will set text, not HTML.
You need replace the newlines in the generated HTML:
$("#some-div").text($("#some-textarea").val())
              .html(function(index, old) { return old.replace(/\n/g, '
') });

Note that you cannot set the HTML directly from the textarea, because that won't escape HTML tags.
Also, unlike PHP, Javascript uses regex literals, so you cannot put a regex in a string.

A: Rather than treating HTML as a string, I would suggest creating DOM nodes. Normalize the textarea value (IE uses \r\n rather than \n), split the textarea value on line breaks and create text nodes separated by
 elements:
var div = $("#some-div")[0];
var lines = $("#some-textarea").val().replace(/\r\n/g, "\n").split("\n");
for (var i = 0, len = lines.length; i < len; ++i) {
    if (i) div.appendChild(document.createElement("br"));
    div.appendChild(document.createTextNode(lines[i]));
}


Q: CRC16 modbus calculation returns wrong value for long data packets I'm connecting to a device through a serial port. The device appends a CRC16 tag to the end of the data packet in big-endian mode. In software side, the code to check CRC is something like this:
bool Protocol::checkCRC(const QByteArray &buf) {
    if(buf.size()<3){
        return false;
    }
    int len = buf.size()-2; // Exclude CRC token
    quint16 crc = 0xFFFF;
    quint16 claim = static_cast<uchar>(buf.at(buf.size()-1));
    claim*=0x100;
    claim+=static_cast<uchar>(buf.at(buf.size()-2));

    for (int pos = 0; pos < len; pos++)
    {
        crc ^= (quint16)buf[pos];         // XOR byte into LSB of crc
        for (int i = 8; i != 0; i--) {    // Loop over each bit
            if ((crc & 0x0001) != 0) {    // If the LSB is set
                crc >>= 1;                // Shift right and XOR 0xA001
                crc ^= 0xA001;
            }
            else                          // Else LSB is not set
                crc >>= 1;                // Just shift right
        }
    }
    return crc==claim;
}

I copied the code from this question.
It works fine for small packets. For example following data packet is passed in CRC16 check using this function:
0x04, 0x10, 0x00, 0x3d, 0xc1

Reported CRC is 0xC13D and function calculates 0xC13D as well. But for big data packets (in my case 53 bytes) the function fails to calculate correct CRC:
0x34, 0x02, 0x02, 0x08, 0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x0a, 0xdf, 0x07, 0x0a, 0x39,
0x1b, 0x02, 0x02, 0x79, 0x61, 0xbf, 0x34, 0xdd,
0x0b, 0x83, 0x0f, 0x10, 0x03, 0x1b, 0x11, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfc, 0x98

Reported CRC is 0x98FC but calculated value is 0xDFC4.

A: I don't know what the QByteArray type is, but I'll wager that it is an array of signed characters. As a result, when the high bit of a byte is a one, that sign bit is extended when converted to an integer which all gets exclusive-or'ed into your CRC at crc ^= (quint16)buf[pos];. So when you got to the 0xdf, crc was exclusive-or'ed with 0xffdf instead of the intended 0xdf.
So the issue is not the length, but rather the likelihood of having a byte with the high bit set.
You need to provide unsigned bytes, or fix the conversion, or do an & 0xff to the resulting byte before exclusive-or'ing with the CRC.


Q: Echart vs 5: I cannot get Sliders in three containers combined to work as one I have succeeded in making three charts (containers) above each other in ECHARTS v5 and all works fine. However, I need all three sliders to work as one. Meaning that if I change one slider the other two must do exactly the same so the x-Axis data remains the same to make comparison easier.
Is this possible and if yes how? <Remark: Has been answered by 'A mere dev' and the solution is in the code below >.
Now need to add an additional candle chart in myChart1 part to show Heikin Ashi candles with on off toggle just like the lines in myChart1.
< made a new question if this: Link to this question>
<!DOCTYPE html>

        <meta charset="utf-8">

A: Use echarts.connect to connect your charts as follow :
echarts.connect([myChart1, myChart2, myChart3])

For this to work on your example, you'll have to remove the ids from the 3 'slider' type  dataZoom.
dataZoom: [
  {
    type: 'inside',
    start: 50,
    end: 100
  },
  {
    show: true,
    //id: 'S3',
    type: 'slider',
    top: '8%',
    start: 50,
    end: 100,
    height: 20,
    handleSize: '100%'
  }
],


Q: on session end event I have a Symfony2 project, where at the beginning of each session, I create a folder on the server where the user can manipulate and place his files.
I want to be able to delete the user's folder, when he closes his browser
(or any other related event, maybe check for a session timeout?).
How can I achieve this?
PS: I have read somewhere that java has a sessionHandler where you can code your function.
Is there anything similar in php (Symfony2 specifically)?

A: First of all, you cannot recongnize if a browser is closed by HTML and PHP. You would need ajax and constant polling or some kind of thing to know the browser is still there. Possible, but a bt complicated, mainly because you might run into troubles if a browser is still there (session is valid) but has no internet connection for a few minutes (laptop, crappy wlan, whatever).
You cannot have a sessionHandler which does this for you in PHP because PHP is executed when a script is retrieved from your server. After the last line is executed, it stops. If no one ever retrieves the script again, how should it do something? There is no magic that restarts the script to check if the session is still there.
So, what to do? First of all you want to make the session visible by using database session storage or something like that. Then you need a cronjob starting a script, looking up all sessions and deciding which one is invalid by now and then does something with it (like deleting the folder). Symfony can help as it allows you to configure session management in a way that it stores sessions in the database (see here) as well as creating a task which can be executed via crontab (see here).
The logical part, which contains deciding which session is invalid and what to do with this sessions) is your part. But it shouldn't be very hard as you got the session time and value in the database.


Q: Find the name of the employees with a particular letter I'm having the schemas like:
Employee (Empno, Empname, City)
Project (Pno, Pname)
Part (Partno, Partname, Color)
Use (Pno, Partno)
Works (Empno, Pno)

From these schemas I had created a sample tables:
The goal is to find the names of the projects where no employees are working whose name starts with 'S'
I'm using ORACLE 11g Express Edition.
Here I used this query :
For Names:
Select DISTINCT Pname FROM
(
SELECT w.Empno, p.Pno, p.Pname, e.Empname
FROM Works w
LEFT JOIN Project p ON w.Pno=p.Pno
LEFT JOIN Employee e ON e.Empno=w.Empno
)
WHERE Empname not like 'S%';

A: If you think about how to explain the process. There are several methods to solve this including:

*

*You would start with each of the Projects and find out if there does not exist anybody who Works on the project where the Employees name starts with S. You can do this using NOT EXISTS.

or

*Again, start with a Project and find, if any, who Works on the project and their corresponding Employees details using LEFT OUTER JOINs (but starting from the Project) and filtering for employee names starting with S in the JOIN condition. Then GROUP BY the primary key for the project and find those projects HAVING a COUNT of zero matched employees.

Since this appears to be a homework question, I'll leave the rest for you to complete.


Q: Appinvite_styles.xml:5: error When including Google Play Services library to eclipse I need to add an ad to my application. So I need to include Google Play Services library to my project. I have installed lastest version of Google Play Services (r29) and added to my projects as libProject. But when I add this service lib I'm getting error below:
workspace\Google_Play_Services_Lib\res\values-v21\appinvite_styles.xml:5: error: Error retrieving parent for item: No resource found that matches the given name '@android:style/Theme.Material.Light.DialogWhenLarge.NoActionBar'.

How can I solve this problem ? Thanks for help..

A: just changed Project SDK to 20 (from 21) and all compiled.

A: I have solved the problem by checking the Is Library option and I referenced appcompat_v7

A: I was also facing same problem, but now it's been resolved. Below are the steps I followed
- Go to project properties->Android
- Under 'Project Build Target', select Android 5.0.1. Press and clean the library project.


Q: A global nextjs middleware without need for import in all the routes TLDR;
a middleware to nextjs like express where I only define it once and it'll automatically applies to all of my routes
I want a middleware style like we have in express I'll define a middleware inside the server.js(entry file) and the middleware will apply to all the routes without any other work needed. well I need similar thing to NextJs
these what I've been tried and used for a while
1: Using High Order Component (HOC):
I don't like this approach because of these drawbacks

*

*Using HOC will disable fast-refresh functionality which's is really nice future to have More Info Here

*I have to import my middleware in every api route file which is really not fun to do and wrapping your api files in a function is not a thing to remember all the time
2: using next-connect
I don't like to use this package due to these drawbacks

*

*The nextjs ways to handle api routes seem more natural since i use nextjs i want to still use the nextjs way to handle my routes. not totally different style just for sake of a middleware

*same as the HOC I don't like to import nc and my-middleware in every api file

well why not just using a custom server like express? the thing is when i use nextjs I want to only use nextjs also using a custom server will lose so many cool future of nextjs which's is partially why I use nextjs

A: You can implement _app.tsx, which will run for all pages, though it has some drawbacks too like disabling automatic static generation.
Another option is to implement a custom server using express itself, as shown in this example


Q: Calling LUIS speech recognition service I'm trying to build simple app using LUIS service. I use project oxford version 1.0.0.6 SpeechRecognitionServiceFactory.CreateDataClientWithIntent to create a data client, but confused with it's interface. My understanding is that LUIS accepts only text queries, but above client only has method SendAudio which accepts only byte array (works perfectly with CRIS when sending audio files). So, should this method be used to for text query as well or is there some other way to make this call?

A: I think that you are missing things. One thing is to call CRIS (and watch out I think that you are using an outdated SDK, take a look at the new one and also to the docs), and another thing is to call LUIS, which is another SDK (this one).
Once you get the output of CRIS, you can just call the LUIS SDK to send the query text.


Q: force input element's width to size to its content/value I'm trying to unstyle an input element so that its text looks like plain/inline-text, and I've reset pretty much every css property it can have, but I can't get the input's width to adjust/shrink to its content (input { width:auto; min-width:0; } does not work). It obeys an arbitrary width like input { width: 10px; }, so obviously its width is adjustable.
I see people trying to do it with javascript (the fiddle from the answer doesn't work anymore), so I'm wondering if what I want is even possible.
Here's a fiddle.

A: Played with this. Couldn't do it. What are you trying to achieve? Are you aware of the contenteditable attribute?
This might get you what you need.
https://developer.mozilla.org/en-US/docs/HTML/Content_Editable

A: What if you just avoid the whole style snafu and do a little text shuffling? You already have everything you need with jQuery.
http://jsfiddle.net/2fQgY/8/
The date is <input class="myDate" type="hidden" value="foo" />.
Thanks for coming.

$('.myDate').datepicker({
    showOn: 'button',
    buttonText: 'select...',
    onClose: function () {
        var dateText = $(this).val();
        $('.dateSpoof').html(dateText);
        $('.ui-datepicker-trigger').hide();
    },
    dateFormat: 'd M yy'
});

Here's an example that's resettable: http://jsfiddle.net/2fQgY/11
And here's one that's all text and nothing but text: http://jsfiddle.net/2fQgY/14


Q: RegEx expression not alerting properly in JS Okay, so when the user enters his/her full name in the field, I want a greeting to say, "Nice to meet you, (split name).  I want to take the value of the input, take the innerHTML, split it, then take the first part ([0]), and alert it!
Ignore the if/else stuff :P
HTML
 <form onsubmit="return formValidate(this);">

        Full name

        <input type="text" id="name"/>
</form>

JS
function formValidate(form){

// set initial status
var status = true;

    var name = document.getElementById("name"),
   full_name = name.innerHTML,
   full_name_split = full_name.split(" ")[0];

    if(name.value == "") {
        document.getElementById("name-alert").innerHTML = alerts[0];
        status = false;
    } else if(namePatt.test(name.value) == false){
        document.getElementById("name-alert").innerHTML = alerts[1];
        status = false;
    } else if(name.value.indexOf(charSpace) == 0 || name.value.indexOf(charSpace) == -1){
        document.getElementById("name-alert").innerHTML = alerts[2];
        status = false;
    }

    alert(full_name_split);

// return the initial status
return status;

  }

A: input elements do not have .innerHTML. Use .value instead:
var name = document.getElementById("name"),
    full_name = name.value,
    full_name_split = full_name.split(" ")[0];


Q: phpStorm remote debug goes to server_ip/index page all the time, what is wrong? I am trying to setup remote debug in a remote project under phpStorm 10.0.2 and I can't. Any time I set a breakpoints and hit Shift+F9 or Alt+Shift+F9 browser opens this URL: http://remote_host_ip/index.php and I don't know why. xDebug is installed and enabled, see the pic below for further info:

Debugger config seems to be fine, see the pic below:

What I am missing here?

The issue was "fixed" with @lazyone suggestion. Now I didn't get redirect to http://remote_host_ip/index.php but I am running in a second issue since breakpoints aren't respected. In the pic below I show my setup for index.php debug:

As soon as I start debug I can step into or step over but in none I get redirected to web page where I enter for example login and password. I am still missing something here just don't know what, any advice?
Note: Yes I know you will ask for all the configs I had made but are a bunch, so ask for them and I will edit the post to add them.


Q: Android : getting only the last item in the listview multiple times i am trying to get the items in the listview using json from server, for this i have made my custom adapter. but if there are 6 items on the server it displays the last item 6 times in the list view and i have given a checkbox infront of every item in the list to get the id of the checked item. here is my code:
btnclub.setOnClickListener(new OnClickListener() {

        ArrayList<Integer> checkedList = new ArrayList<Integer>();

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Dialog d = new Dialog(TennerTextActivity.this);
            d.setContentView(R.layout.slctevnt);

            ListView list = (ListView) d.findViewById(R.id.list_mulitple);
            HashMap<String, String> list_map = new HashMap<String, String>();

            // Initialize CATEGORY_LIST HERE
            try {
                client = new DefaultHttpClient();
                HttpGet get = new HttpGet(
                        "http://dhklashfgsdhgsdg");
                HttpResponse rp = client.execute(get);
                String result = EntityUtils.toString(rp.getEntity());
                System.out.println("----------------------- result: "
                        + result);

                result = "{\"root\": " + result + "}";
                JSONObject root = new JSONObject(result);
                JSONArray sessions = root.getJSONArray("root");

                for (int i = 0; i < sessions.length(); i++) {
                    HashMap<String, String> map2 = new HashMap<String, String>();
                    JSONObject e = sessions.getJSONObject(i);
                    list_map.put("category_name", e.getString("name"));
                    list_map.put("category_id", e.getString("id"));
                    list_category.add(list_map);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            list.setAdapter(new MyAdapter());
            d.show();
            Button btndone = (Button) d.findViewById(R.id.button_multiple);
            btndone.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    for(int i = 0 ; i < checkedList.size() ; i++) {
                        clubs = "," + String.valueOf(checkedList.get(i));
                    }
                    clubs = clubs.substring(1);
                    System.out.print(clubs);
                    Log.e("club", clubs);
                }
            });

and my adapter is:
class MyAdapter extends BaseAdapter {

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return list_category.size();
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {

                if (convertView == null) {
                    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.dialoglist,
                            null);
                    TextView item = (TextView) convertView
                            .findViewById(R.id.dialogitem);
                    item.setText(list_category.get(position).get(
                            "category_name"));

                }
                CheckBox check = (CheckBox)convertView.findViewById(R.id.checkBox_list);
                check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // TODO Auto-generated method stub
                        if(isChecked) {
                            int temp = Integer.parseInt(list_category.get(position).get("category_id"));
                            checkedList.add(temp);
                            Object[] tempArray = checkedList.toArray();
                            Arrays.sort(tempArray);
                            checkedList.clear();
                            for(int i = 0 ; i < tempArray.length ; i++) {
                                checkedList.add((Integer) tempArray[i]);
                            }
                        }
                    }
                });

                return convertView;
            }

        }

please tell where i am doing wrong ...

A: i think you have to change for loop like this
 for (int i = 0; i < sessions.length(); i++) {
                        HashMap<String, String> map2 = new HashMap<String, String>();
 HashMap<String, String> list_map = new HashMap<String, String>();

                        JSONObject e = sessions.getJSONObject(i);
                        list_map.put("category_name", e.getString("name"));
                        list_map.put("category_id", e.getString("id"));
                        list_category.add(list_map);

                    }

A: problem is in below line
                   list_map.put("category_name", e.getString("name"));
                    list_map.put("category_id", e.getString("id"));
                    list_category.add(list_map);

you are putting category_name and id into list_map and adding same into list_category. here you are adding list_map instance in list_category. and becuse of the key for map(which is category_name and id ) is same,
it can store only one value corresponding to one key, hence it is storing last inserting value of these keys.
when you are updating list_map with new data the instance itself getting change), That is why it is showing 6 times of last list_map data.
Solution : what you can do here, initialize list_map in loop only with new keyword, so it will insert new instance every-time you insert into list_category. or you can use two d array. instead of hashmap.
HashMap<String, String> list_map = new HashMap<String, String>();

P.S: I pointed out one problem in your code, which is causing duplicacy of data, there can be other problem also as suggested by other SO members.
Edit:
replace your below code
for(int i = 0 ; i < checkedList.size() ; i++) {
                        clubs = "," + String.valueOf(checkedList.get(i));
                    }
                    clubs = clubs.substring(1);

with something like below
   StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < checkedList.size() ; i++) {
                       sb.add(String.valueOf(checkedList.get(i))+",");
                    }
                 sb.deleteCharAt(sb.lastIndexOf(","));

A: change getView methode like this
if (convertView == null)
{
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.dialoglist,null);
}

TextView item = (TextView) convertView.findViewById(R.id.dialogitem);
item.setText(list_category.get(position).get("category_name"));


Q: multiplying modified colums to form new column I want a query like:
select tp.package_rate, sum(sell) as sold_quantity , select(tp.package_rate * sold_quantity ) as sell_amount from tbl_ticket_package tp where tp.event_id=1001

here the system firing error  while doing the multiplication as
sold_quantity is invalid column

another problem is that in multiplication I want to use package_rate which got by select query from tp.package_rate but it multiplying with all package_rate of the table but I want only specific package_rate  which was output of select query
What would you suggest? I want to bind this query in gridview . is there any way to do it using ASP.net gridview?

A: Your problem is that you are referring to sold_quantity here :
select(tp.package_rate * sold_quantity )

The alias is not recognized at this point.You will have to replace it with sum(sales). You will also have to group by tp.package_rate.
Your query should ideally be like :
    select tp.package_rate, sum(sell) as sold_quantity ,
(tp.package_rate * sum(sell) ) as sell_amount from tbl_ticket_package tp
where tp.event_id=1001 group by tp.package_rate;

I am guessing that tp.package_rate is unique for a given event_id, from latter part of your question. If that's not the case, the sql you have written makes no sense.


Q: Text-decoration: none not working Totally baffled! I've tried rewriting the text-decoration: none line several different ways. I also managed to re-size the text by targeting it but the text-decoration: none code will not take.
Help much appreciated.
Code

.widget
{
     height: 320px;
     width: 220px;
     background-color: #e6e6e6;
     position: relative;
     overflow: hidden;
}

.title
{
     font-family: Georgia, Times New Roman, serif;
     font-size: 12px;
     color: #E6E6E6;
     text-align: center;
     letter-spacing: 1px;
     text-transform: uppercase;
     background-color: #4D4D4D;
     position: absolute;
     top: 0;
     padding: 5px;
     width: 100%;
     margin-bottom: 1px;
     height: 28px;
     text-decoration: none;
}

a .title
{
     text-decoration: none;
}

Underlined. Why?

A: Add this statement on your header tag:

A: a:link{
  text-decoration: none!important;
}

=> Working with me :) , good luck

A: You have a block element (div) inside an inline element (a). This works in HTML 5, but not HTML 4. Thus also only browsers that actually support HTML 5.
When browsers encounter invalid markup, they will try to fix it, but different browsers will do that in different ways, so the result varies. Some browsers will move the block element outside the inline element, some will ignore it.

A: Try placing your text-decoration: none; on your a:hover css.

A: if you want a nav bar do
ul{ list-style-type: none; } li{text-decoration: none;

*

*This will make it want to make the style of the list type to None or nothing

with the  tag:
a:link {text-decoration: none}

A: I have an answer:

Underlined. Why?

It works.

A: Add a specific class for all the links :
html :
 text

in css :
.noDecoration {
  text-decoration: none;
}

A: Use CSS Pseudo-classes and give your  tag a class, for example:

and add this to your stylesheet:
.noDecoration, a:link, a:visited {
    text-decoration: none;
}

A: There are no underline even I deleted 'text-decoration: none;' from your code.
But I had a similar experience.
Then I added a Code
a{
 text-decoration: none;
}

and
a:hover{
 text-decoration: none;
}

So, try your code with :hover.

A: As a sidenote, have in mind that in other cases a codebase might use a border-bottom css attribute, for example border-bottom: 1px;, that creates an effect very similar to the text-decoration: underline. In that case make sure that you set it to none, border-bottom: none;

A: I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me.
In my case I had to remove the box-shadow as well.
a:hover {
    text-decoration: none;
    box-shadow: none;
}

A: An old question and still no explanation. The underline is drawn not on your
 element but on its parent a, since all browsers set this style for links by default.
If you provide custom decoration style for the inner div - it will be visible instead of the parent style. But if you set none (and it is already set on divs by default), your div will not be decorated, but its parent decoration will become visible instead.
So, as people suggested, in this case to remove all the decoration text-decoration: none; should be set on the parent a element.


Q: How to fix CA Dispose objects before losing scope? CA throw the following message:
CA2000 Dispose objects before losing scope.
In method 'GetMatchingJobsDeferred(BackgroundJobSearchParameters)',
object '<>g__initLocal0' is not disposed along all exception paths.
Call System.IDisposable.Dispose on object '<>g__initLocal0' before
all references to it are out of scope.

I have disposable type CompositeCollection.
public sealed class CompositeCollection<T> : IEnumerable<T>, IDisposable
{
    private readonly List<IEnumerable<T>> _enumerables = new List<IEnumerable<T>>();
    private readonly List<IDisposable> _disposables = new List<IDisposable>();

    public void Add(IEnumerable<T> enumerable)
    {
        _enumerables.Add(enumerable);
    }

    public void Add(IDeferredResultCollection<T> deferredResultCollection)
    {
        _enumerables.Add(deferredResultCollection);
        _disposables.Add(deferredResultCollection);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _enumerables.Aggregate((results, enumerable) => results.Concat(enumerable)).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Dispose()
    {
        foreach (var item in _disposables)
        {
            item.Dispose();
        }
    }
}

And that how I used it:
public IDeferredResultCollection<BackgroundJobInfoLight> GetMatchingJobsDeferred(BackgroundJobSearchParameters jobSearchParameters)
{
    var memoryLocatedJobs = GetInMemoryJobs(jobSearchParameters);
    var databaseLocatedJobs = GetInDatabaseJobsDeferred(jobSearchParameters, memoryLocatedJobs);

    return new CompositeCollection<BackgroundJobInfoLight>
    {
        memoryLocatedJobs,
        databaseLocatedJobs
    };
}

I have exception when return statement called.
How to fix that?
I add try catch and it doesn't help
 public IDeferredResultCollection<BackgroundJobInfoLight> GetMatchingJobsDeferred(BackgroundJobSearchParameters jobSearchParameters)
    {
        CompositeCollection<BackgroundJobInfoLight> deferredJobs = null;
        DeferredResultCollection<BackgroundJobInfoLight> databaseLocatedJobs = null;
        try
        {
            var memoryLocatedJobs = GetInMemoryJobs(jobSearchParameters);
            databaseLocatedJobs = GetInDatabaseJobsDeferred(jobSearchParameters, memoryLocatedJobs);

            deferredJobs = new CompositeCollection<BackgroundJobInfoLight> { memoryLocatedJobs, databaseLocatedJobs };
            return deferredJobs;
        }
        catch
        {
            if (databaseLocatedJobs != null)
            {
                databaseLocatedJobs.Dispose();
            }

            if (deferredJobs != null)
            {
                deferredJobs.Dispose();
            }

            throw;
        }
    }

A: When returning the disposable objects, it should be the responsibility of the caller code to Dispose the object. Had the Disposed been called inside the method itself, the disposed object will return to the caller method, (wont be of any use).
In that case it is safe to supress the warning.
BUT what if the exception occurred in this method?

If a disposable object is not explicitly disposed before all
  references to it are out of scope, the object will be disposed at some
  indeterminate time when the garbage collector runs the finalizer of
  the object. Because an exceptional event might occur that will prevent
  the finalizer of the object from running, the object should be
  explicitly disposed instead. MSDN

So, if you anticipate any exception in the method, you should have this code in try...catch block and in catch block you should call Dispose() checking if the object is not null.
And when you are not returning IDisposable you can use using statement or try...finally and call dispose in finally

A: Why are you keeping items in to different list variables? It may have something to do with your issue.  Keep it DRY Store them in one list and safely cast to what you are looking for.
IDisposable myDispType = myEnumarableType as IDisposable;
If (myDispType != null)
    {//your logic here}


Q: can't get web page source from url in Swift I'm currently using SwiftHTTP for getting source of url address. I am using 'get method' for getting source code of url address which is
 do {
            let opt = try HTTP.GET(self.my_url_address!)
            opt.start { response in
                if let err = response.error {
                    print("error: \(err.localizedDescription)")
                    return
                }
                print(response.description)
            }
        } catch let error {
            print("got an error creating the request: \(error)")
        }

after this code run I got this output in Xcode output screen
URL: http://myweburl.com/detay/swat-under-siege.html

Status Code: 200

Headers: Content-Type: text/html
Connection: keep-alive
CF-RAY: 38391215a60e2726-FRA
Set-Cookie: ASPSESSIONIDSABBBSDT=HPKKPJGCDLKMDMILNGHPCAGD; path=/
Date: Mon, 24 Jul 2017 18:51:24 GMT
Vary: Accept-Encoding
X-Powered-By: ASP.NET Transfer-Encoding: Identity
Server: cloudflare-nginx
Content-Encoding: gzip
Cache-Control: private

The status code is 200 but the output is not the source code of url. How can I fix this?

A: Response is correct. I've tried requesting the website (the real one) and it works:
print(response.data.base64EncodedString())

If you decode the BASE64 data, it will render valid HTML code.
The issue seems related to encoding. After checking the website's head tag, it states that the charset is windows-1254
String(data: response.data, encoding: .windowsCP1254) // works. latin1, etc.

Your issue is similar to SWIFT: NSURLSession convert data to String


Q: How to set control (windows control) position to some other control relative postion I want to set control position relative to other control so when i make one control hide then other control move up like this.
Ex.
Label1
Label2
Label3
When i hide Label2 so output will be
Label1
Label3

A: You can use FlowLayoutPanel
Though, you might need to set the FlowDirection to TopDown
Just put those labels into the panel


Q: Keeping variable names when exporting Pyomo into a .mps file So, i'm currently working with a pyomo model with multiple instances that are being solved in parallel. Issue is, solving them takes pyomo quite a long time (like 2 to 3 secs, even though the solving part by gurobi takes about 0.08s). I've found out that, by exporting a pyomo instance into an .mps file and then giving it to gurobipy i can get like an increase of 30% in overall speed.
The problem comes later, when i want to work with the variables of the solved model, because ive noticed that, when exporting the original instance from pyomo into a .mps file, variable names get lost; they all get named "x" (so, for example, model.Delta, model.Pg, model.Alpha, etc get turned into x1, x2, ... ,x9999 instead of Delta[0], Delta[1], ... Alpha[99,99]).
Is there a way to keep the original variable name when exporting the model?

A: Managed to solve it!
To anyone who might find this useful, i passed a dictionary with "symbolic_solver_labels" as an io_options argument for the method, like this:
instance.write(filename = str(es_) + ".mps", io_options = {"symbolic_solver_labels":True})

Now my variables are correctly labeled in the .mps file!


Q: Operator overloading From language design point of view , What type of practice is supporting operator overloading?
What are the pros & cons (if any) ?

A: Pros: you can end up with code which is simpler to read. Few people would argue that:
BigDecimal a = x.add(y).divide(z).plus(m.times(n));

is as easy to read as
BigDecimal a = ((x + y) / z) + (m * n); // Brackets added for clarity

Cons: it's harder to tell what's being called. I seem to remember that in C++, a statement of the form
a = b[i];

can end up performing 7 custom operations, although I can't remember what they all are. I may be slightly "off" on the example, but the principle is right - operator overloading and custom conversions can "hide" code.

A: EDIT: it has been mentioned that std::complex is a much better example than std::string for "good use" of operator overloading, so I am including an example of that as well:
std::complex<double> c;
c = 10.0;
c += 2.0;
c = std::complex<double>(10.0, 1.0);
c = c + 10.0;

Aside from the constructor syntax, it looks and acts just like any other built in type.

The primary pro is that you can create new types which act like the built in types. A good example of this is std::string (see above for a better example) in c++. Which is implemented in the library and is not a basic type. Yet you can write things like:
std::string s = "hello"
s += " world";
if(s == "hello world") {
    //....
}

The downside is that it is easy to abuse. Poor choices in operator overloading can lead to accidentally inefficient or unclear code. Imagine if std::list had an operator[]. You may be tempted to write:
for(int i = 0; i < l.size(); ++i) {
    l[i] += 10;
}

that's an O(n^2) algorithm! Ouch. Fortunately, std::list does not have operator[] since it is assumed to be an efficient operation.

A: The initial driver is usually maths. Programmers want to add vectors and quaternions by writing a + b and multiply matrices by vectors with M * v.
It has much broader scope than that. For instance, smart pointers look syntactically like normal pointers, streams can look a bit like Unix pipes and various custom data structures can be used as if they were arrays (with strings as indexes, even!).
The general principle behind overloading is to allow library implementors to enhance the language in a seamless way. This is both a strength and a curse. It provides a very powerful way to make the language seem richer than it is out of the box, but it is also highly vulnerable to abuse (more so than many other C++ features).

A: You can do some interesting tricks with syntax (i.e. streams in C++) and you can make some code very concise. However, you can have the effect of making code very difficult to debug and understand. You sort of have to constantly be on your guard about the effects of various operators of different kinds of objects.

A: You might deem operator overloading as a kind of method/function overloading. It is part of polymorphism in object oriented language.
With overloading, each class of objects work like primitive types, which make classes more natural to use, just as easy as 1 + 2.
Say a complex number class, Complex.
Complex(1,2i) +  Complex(2,3i) yields Complex(3,5i).
5 + Complex(3, 2i) yields Complex(8, 2i).
Complex(2, 4i) + -1.8 yields Complex(0.2, 4i).
It is much easier to use class this way.  If there is no operator overloading, you have to use a bunch of class methods to denote 'add' and make the notation clumsy.
The operator overloading ought to be defined carefully; otherwise, comes confusion. For example, '+' operator is natural to adding numbers, time, date, or concatenation of array or text. Adding '+' operator to a class of Mouse or Car might not make any sense.  Sometimes some overloading might not be seem natural to some people. For example, Array(1,2,3) + Array(3,4,5).  Some might expect Array(4,6,8) but some expect Array(1,2,3,3,4,5).


Q: Would 2 consecutive .load calls in jquery execute async? In a script like the following, would the load functions be called in asynchronously or one after another?
<script language="javascript" type="text/javascript">

    $(document).ready(function () {

          $("#TheLink").click(){
                $("#PlaceToUpdate1").load("/Controller/Method/View1");
                $("#PlaceToUpdat2").load("/Controller/Method/View2");

          }

        });
    });
</script>

A: Asynchronously, by default. If you need them to be one-after-the-other, you can do a few things:

*

*Place the second in the callback of the first.

*Set $.ajax({async:false})

*You could possibly even set these up in a queue.

The cleanest way is probably option 2.

A: Yes, the full call for load is:
load( url, [data], [callback] )

the third optional parameter is a callback method that will be called when the asynchronous load method completes.


Q: The syntax of my rename command is incorrect When trying to rename a file in a command prompt, I am getting the error:

The syntax of the command is incorrect.

Here's my command:
rename "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs.old"

A: rename does not support a path for the destination (just the new filename):
rename "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" "trusted.certs.old"