text:
Q: How can I display the list of available Wi-Fi networks? My Ubuntu laptop's Wi-Fi works fine on various Wi-Fi networks. But the list of available networks accessed from the toolbar icon of nm-applet no longer appears. I just see the known networks. The list of hidden networks also doesn't show any new networks.
sudo iwlist scan likewise only shows known networks.
How do I get a list of all available networks so I can connect to one?
I am using Xubuntu 14.04.

A: To scan all networks try using the command sudo iw dev wlan0 scan | grep SSID.
You can find more info here: https://askubuntu.com/a/16588/362944

A: Further to what has been already answered here, I've merged a few of them and added a little flavor of my own.
As for the nmcli answer, sure, do that if you want to install more software. But if you're looking for Access Points, maybe you don't have an internet connection yet and are unable to connect to install said software. With all that said, here's my solution:
for i in $(ls /sys/class/net/ | egrep -v ^lo$); do sudo iw dev $i scan | grep SSID | awk '{print substr($0, index($0,$2)) }'; done 2>/dev/null | sort -u

Breaking it down:
for i in $(ls /sys/class/net/ | egrep -v ^lo$);

Lets have a look at all the contents of the location /sys/class/net. This will list all the network devices, but we're not really interested in the loopback interface. so we'll ignore that one
do sudo iw dev $i scan | grep SSID | awk '{print substr($0, index($0,$2)) }';done

For each of the network interfaces we found above, lets do the scan to list all the SSIDs (and only the SSIDs)
2>/dev/null

And ignore all the errors (like searching for SSIDs with ethernet interfaces).
| sort -u

And finally, If you have multiple wi-fi adapters on the system, only list each SSID once.

A: Use the nmcli dev wifi command. It shows transfer rate, signal strength, and security (e.g. WPA) as well:

For more, see nmcli's manual and this for usage examples of nmcli.

A: In Ubuntu 16.04:

*

*Go to /sys/class/net you can see list of directories here.

*Find the wireless interface. It has wireless directories, for example in my case it's wlp10. You can check it using ls wlp10. If the directory's name different, use that directory's name.

*sudo iwlist wlp1s0 scan | grep ESSID
From here you can list all available Wi-Fi access points.
Source here.


text:
Q: PYTHON recursive sum of numbers in a list def recSum(list):
    if len(list)==0:
         return 0
    else:
         return list[0] + recSum(list[1:])

getSum([1,2,3,4,5])

How do I add an extra argument(p) which stops the recursion in index p?
for example having the list [1,2,3,4,5] and I want to have the sum till index[3]?

A: If you need to do it recursively, create a helper with a parameter to keep track of what index you're on:
def recSum(list, p):
    recSumHelper(list, p, 0)

def recSumHelper(list, p, idx):
    if len(list)==0 or idx > p:
         return 0
    else:
         return list[0] + recSumHelper(list[1:], p, idx + 1)

getSum([1,2,3,4,5])

A: If you want a function that can operate over all generators and not only arrays, itertools helps:
import itertools

def recSum(data, cutoff):
    return sum( itertools.islice(data, cutoff))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to scale down a HD image to SD images? I'm a newbie here. I have searched up a little but couldn't find any solution.
I have a big image (HD Image) which I will ask the user to upload.
I want to show the image on Mobile/Tablet/Desktop.
Question:
Given a HD image, How do I scale down my image to 480p(mobile) or 720p(Tablet) or 1080p(desktop).
How can I reduce the size of the image?
Server side is fine too. Any java open source libraries available would really help!
Thanks,
R

A: max-width:100%; height:auto;
example: <img src="..." style="max-width:100%; height:auto;" >

I normally create css classes like that to scale images with different screen sizes and devices. You can also use "width" to fill whole content block. That is if you want to do it without changing/resizing image file itself.

A: JavaScript itself cannot compress file for you, therefor the size and resolution of the image that you serve will always be the source resolution.
I have actually just encountered this issue, and the solution was to user a Server-Side language such as PHP to do this for you. If you are interested I used Image Intervention


text:
Q: Magento 2 - Disable cache invalidation temporarily during processing, then invalidate appropriate caches? I'm in the process of developing a bespoke product import/sync module for Magento 2 and I'm trying to find ways to speed the process up as much as possible.
The full set of products contains over 800k entries, and that data will be processed at least once a day (more likely to be 2-3 times per day).
I've significantly improved the creating/updating of product entities and attributes by using ResourceConnection::insertMultiple/insertOnDuplicate, but using StockRegistry::updateStockItemBySku seems to be taking up a huge portion of the overall time.
According to \Magento\Framework\Profiler the majority of the time taken while setting quantities is taken up with EVENT:clean_cache_by_tags, specifically Magento\Framework\Cache\Frontend\Decorator\Profiler::clean
Is there a practical way to disable cache invalidation/events for the duration of data processing, then invalidate the relevant caches in one batch afterward?
I suppose I could go the same route I have with product entities/attributes and just update/insert records, but without more investigation I'm not sure what other events/handling is taken into account when it comes to stock and availability of products.
Anyone have any ideas/tips or direction that might be helpful?


text:
Q: Коррекция даты с учетом года Здравствуйте, подскажите есть ли в PHP какая нибудь умная функция, которая принимала бы в качестве базовой даты строку "29 dec 2016" и определяла что строка "18 jan" уже 2017 год?
Это работает не так как мне нужно:
$date1 = strtotime('29 dec 2016');
$date2 = strtotime('18 jan', $date1);
echo date("Y-m-d H:i:s", $date2);
// 2016-01-18 00:00:00

A: Просто проверить не меньше ли текущей даты 18 января и прибавить год.
$date1 = strtotime('29 dec 2016');
$date2 = strtotime('18 jan', $date1);
if ($date1 > $date2) {
    $date2 = strtotime('+1 year', $date2);
}
echo date("Y-m-d H:i:s", $date2);
// 2017-01-18 00:00:00


text:
Q: How to get a UIViewController that added a subview from subview? I have a UIView which is added to UIViewController.
UIView is a separate class and separate .h and .m files.
I want to present another UIViewController or something. How to access the UIViewController that added this UIView from UIView ?

A: Short answer: No, you can't know which exactly is the view's view controller, because that would break MVC principles.

I don't think you understood what MVC means and stands for. It wouldn't be a good approach to present a view controller from a view object of another view controller. It is the view controller who should provide any information view needs from the outside world.
UIView objects are meant to just display UI components to screen and are responsible for drawing and laying out their child views correctly.
As I said above, you should handle those kind of interactions between the views  (or communication channels, whatever you call it) always in controllers to where they actually belong. In this context, you should present any view controller from another view controller, not another view. If you need to send messages from a view to its view controller, you can make use of the delegate approach or NSNotificationCenter class.
If it were up to me, I would personally prefer using delegate when view needs some information from its view controller. It is more understandable than using notification center as it makes it much easier to keep track of information flow. However in your case, in other words  where view controller needs information from view (reverse communication), I'd go with the notification center.
So let's enrich this conversation with an example:
@implementation SomeView

- (IBAction)buttonClicked:(id)sender
{
    NSDictionary *userInfo = @{@"value": [self someCalculatedValue]};

    [[NSNotificationCenter defaultCenter] postNotificationName:ViewButtonClickedNotification object:self userInfo:userInfo];
}
@end

Note that, you should never leave the object: argument of [NSNotificationCenter:postNotificationName:object] method as nil since it will help the controller distinguish the notification sent by its view from other notifications.
@implementation SomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewButtonClicked:) name:ViewButtonClickedNotification object:self.view];
}

- (void)viewButtonClicked:(NSNotification *)
{
    NSNumber *someCalculatedValue = notification.userInfo[@"value"];

    [self presentViewController:[[UIViewController alloc] initWithCalculatedValue:someCalculatedValue] animated:YES completion:nil];
}
@end

For more information about communication patterns in iOS, you might want to take a look at this great article in order to comprehend how they work.


text:
Q: Login function, won't login if code is wrong on first attempt I have made this function to have a simple login using a password. When I press the right password on first attempt it works, and then it also works as expected, when I use all my attempts. But if I make the password wrong in the first attempt, it won't accept the right password on second and third attempt.
Here's the code:
void login(string password)
{
    string input;
    int loginAttempt = 0;
    int RightPassword = 0;

    cout << "Hello! To use the Home Automation System, please login." << endl;

    while (RightPassword == 0)
    {
        cout << "\nEnter your user password: ";
        char temp;
        while(true) /* Infinite loop, exited when RETURN is pressed */
        {
            temp = getch(); /* Get the current character of the password */
            if (GetAsyncKeyState(VK_RETURN))
            {
                break;
            }
            input += temp;
            cout << '\01'; /* Print a smiley */
        }
        for (int i = 0; i <= input.length(); i++)
        {
            if (input[i] != password[i])
            {
                ++loginAttempt;
                cout << "\nWrong password, " << 3 - loginAttempt << " attempts left." << endl;
                break;
            }
            RightPassword = 1;

        }
        if (loginAttempt == 3)
        {
            cout << "Too many login attempts! The program will now terminate.";
            exit(1);
        }
        cin.clear();
    }
    system("CLS");
    cout << "Welcome user! Thank you for logging in.\n";
}

I also want to have a way to use backspace to delete the previous char, instead of counting as a char, when I type in the password. Could you help with this too?
Thanks a lot in advance!

A: string input is never cleared and therefore is constantly being added to
so input is ending up being something like: badpasswordcorrectpasswordreallycorrectpassword
To fix simply clear input on every attempt
http://www.cplusplus.com/reference/string/string/clear/

A: It doesn't appear that you're resetting your "input" variable after a failed attempt. This means all your previous attempts are being stored in "input" and affecting your password checks in the future. Add something like
input = "";

after you detect a failed password.

A: write input=""; right after you cout<<"Please enter a password";


text:
Q: How to access vertx HttpClientRequest fields? I am writing a web server in java using vertx.
I use the server as a proxy to other services, and I'm the the testing stage. I want to know that I have created the request correctly with custom tokens and headers.
But, I cant manage to find a way to receive the properties upon creation.
HttpClientRequest clientRequest = vertx.createHttpClient().request(HttpMethod.GET,80,"host","/path?query=value");

When I try to read the host clientRequest.getHost() I receive a null, but in debug, reading its values, I can see a property named delegate which contains all of its data.
How can I access those values from clientRequest?

A: What you see in debug is:
((HttpClientRequestImpl) req).host

While getHost() method actually returns you hostHeader
For testing purposes I suggest to cast your HttpClientRequest to HttpClientRequestImpl, as it will expose more data.
If everything else fails, you can also fall back to reflection, of course.


text:
Q: keycloak-angular: Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource I am developing an web app and I am using angular for front-end and keycloak for security.
I am using the following packages on angular side:
keycloak-js@10.0.1
keycloak-angular@8.0.1
On front-end (angular app) I am trying to retrieve the user details using the following service:
import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';

@Injectable({
  providedIn: 'root'
})
export class JwtDecoderService {

  public profile;

  getUserProfile(){

   this.keycloakService.loadUserProfile().then(x => this.profile = x)

  }
  constructor(public keycloakService: KeycloakService) {}
}

As I think, the call to the loadUserProfile() initiates a GET request to a client (account) of the keycloak server.
I get a CORS error message as a response, see below:

I have tried to add localhost:4200 as Web Origins for the clients used, the client configured as mine on angular part is newClient, nevertheless the above request is targeting the account client.
In the end I put * as web origin for all clients involved both newClient and account.
Here are my list of clients:

As I mentioned this is the client I have indicated in angular:
export const environment = {
  production: false,
  keycloakConfig: {
    clientId: 'newClient',
    realm: 'SportEmploy',
    url: 'http://localhost:8083/auth'
  }
};

newClient configuration:
1.

2.

account client configuration:
1.

2.

I have tried to put into WebOrigins of the both clients variations of
http://localhost:4200/  http://localhost:4200  http://localhost:4200/* +  and * , anything of this did not work.
This is how I start keycloak on angular side:
import {KeycloakService, KeycloakOptions} from 'keycloak-angular'
import { environment } from './environments/environment'

export function initializer(keycloak: KeycloakService): () => Promise<any> {

    const options: KeycloakOptions = {

        config: environment.keycloakConfig
    };

    return (): Promise<any> => keycloak.init(options);

}

Any ideas what could be wrong in my keycloak config ?

A: I know this is an old question but given that I had the same issue and I found the fix, I'd like to share it here for the ages.
If you set the role account/viewProfile to your users
like this the cors error will fade away.
I've opened a JIRA https://issues.redhat.com/browse/KEYCLOAK-18523 for this fyi

A: Use the implicit flow for Keycloak instead of default authorization-code
keycloak.init({
...
initOptions: {
      flow: 'implicit',
}
}

and Access Type option to Public


text:
Q: Iterating Through A List I'm trying to iterate through this list and get the value for one doctor at a time.
There are multiples per each doctor in the excel document, but I want the output to be the doctors one at  time.
In the excel document, it goes HILL CANN CANN HILL and that's currently what I'm getting back.
But I want to iterate per doctor so it would go HILL HILL CANN CANN
        Dim physname As New List(Of String)()

    'Get all of the data from tblPhysician that you will use and put into a list for searching the excel file
    Sql = "select * from tblPhysician "
    conn = New OdbcConnection(connectionString)
    conn.Open()
    comm = New OdbcCommand(Sql, conn)
    dr = comm.ExecuteReader()

    'Populate the physname list with the doctors names
    While (dr.Read())
        physname.Add(dr("PhysicianName").ToString())
    End While

range = oxlsheet.UsedRange
    For rcnt = 1 To range.Rows.Count
        For ccnt = 2 To 6
            varray = CType(range.Cells(rcnt, ccnt), Excel.Range)
            If (IsNumeric(varray.value)) Then
                temp = varray.value.ToString
            Else
                temp = varray.value
            End If

            'Iterate through physname list for each doctor in the list
            For Each doctor As String In physname

                If (rcnt > 8) Then
                    If (IsNumeric(varray.Columns(4).value)) Then
                        temp2 = varray.Columns(4).value.ToString
                    Else
                        temp2 = varray.Columns(4).value
                    End If

                    'If the name in the excel column matches, write out the name and value
                    If (temp2 = doctor) Then
                        Console.WriteLine(varray.Columns(4).value)
                        Console.WriteLine(varray.Columns(5).value)
                        Console.ReadLine()
                    End If

                End If

            Next

        Next
    Next

A: Here's some examples using LINQ. I highly suggest you read up on it, as there's some powerful stuff in there. Learning LINQ as well as lambda expressions and anonymous methods/functions can be extremely helpful!
Imports System
IMports System.Collections.Generic
Imports System.Linq

Public Module Module1

    Public Sub Main()
        Dim physname as new List(Of String) From {"HILL", "CANN", "CANN", "HILL"}

        ' Output the raw list as a baseline...
        Console.WriteLine("Raw list of physicians:")
        For Each physician as string in physname
            Console.WriteLine(physician)
        next

        ' Using Distinct will select each physician once...
        Console.WriteLine()
        Console.WriteLine("Distinct physicians:")
        For Each physician as String in physname.Distinct()
            Console.WriteLine(physician)
        next

        ' Sort the list in place and then display...
        Console.WriteLine()
        Console.WriteLine("Raw physicians list ordered:")
        physname.Sort()
        For Each physician as String in physname
            Console.WriteLine(physician)
        next
    End Sub
End Module

This example doesn't directly fix your problem in a sort of copy-and-paste-into-your-project fashion, but it illustrates a couple ways to iterate through a generic List.


text:
Q: How to post photos in foursquare using api in iphone I would like to post photos to Foursquare. I already have Foursquare integration and I'm able to access user's information, but  I don't know how to post images other than the profile picture. Please help.

A: See foursquare's photos/add endpoint documentation: https://developer.foursquare.com/docs/photos/add


text:
Q: Is it possible to generate db.changelog-master.yaml on the basis of exsisting database? I would like to use db.changelog-master.yaml file to specify a database on Heroku. I created a relational database thanks to Spring Data JPA and I want to create db.changelog-master.yaml with the same structure as the relational database.
Is there any way to generate the inside of db.changelog-master.yaml (liquidbase) on the basis of exsisting database?
(Update) Example solution for Postgres:
liquibase --driver=org.postgresql.Driver --classpath=C:\Users\admin\postgresql-42.2.4.jar --changeLogFile=C:\Users\admin\db.changelog-master.yaml --url="jdbc:postgresql://localhost:5432/database" --username=postgres --password=postgres generateChangeLog

A: You can generate the change log to create the existing database schema.
liquibase --driver=oracle.jdbc.OracleDriver \
      --classpath=\path\to\classes:jdbcdriver.jar \
      --changeLogFile=com/example/db.changelog.xml \
      --url="jdbc:oracle:thin:@localhost:1521:XE" \
      --username=scott \
      --password=tiger \
      generateChangeLog

insert your values
Look in official documentation:
https://www.liquibase.org/documentation/generating_changelogs.html


text:
Q: How to use preferencesResId instead addPreferencesFromResource I just start to study android, so have some problem
i have a file res/xml/settings.xml - settings from menu
create class Prefs and try to use settings from file above
package org.example.sudoku;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Prefs extends PreferenceActivity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          addPreferencesFromResource(R.xml.settings);
       }
    }

Problem, that addPreferencesFromResource cant be used and i need to use preferencesResId (according to comments), but if i write something like this
     preferencesResId(R.xml.settings);

its not good.
Where is error in code? Could any1 help?
Also i try to learn android by using book - Hello Android.

A: preferencesResId() is not a method, it is a placeholder in conversation for your resource id (R.xml.settings).
So although
addPreferencesFromResource(R.xml.settings);

Is deprecated, if you're using this approach, this is still the most correct way - there isn't another way using the deprecated approach.
I suggest you look at this SO question - it tells you what you should be using instead (PreferenceFragments). If you need a code sample, fire up Eclipse and the ADT plugin and make a SettingsActivity via the new Activity Wizard.
And as usual, here is the full JavaDoc for PreferenceActivity.


text:
Q: Which software is available to connect to and manage cell phones? Is there any application that can connect to my Nokia 2700c phone and check my messages, applications, files, etc?
Is there some application available in Ubuntu like the Nokia PC Suite, for Windows?
I saw some applications like kmobiletools in software center but nothing is working.

A: Wammu (Click To install)

It works with any phone that Gammu supports, including many models from Nokia, Siemens, and Alcatel. It has complete support (read, edit, delete, copy) for contacts, todo, and calendar. It can read, save, and send SMS. It includes an SMS composer for multi-part SMS messages, and it can display SMS messages that include pictures. Currently, only text and predefined bitmaps or sounds can be edited in the SMS composer. It can export messages to an IMAP4 server (or other email storage).

It cannot browse the files on a phone.For that you can use gMobileMedia.
gMobileMedia (Click To Install)

A short description this application let's you easily upload and download images, ringtones, photos and applications to your mobile phone, all that you need is a data cable or any other connection method supported by gammu.
This application has been targeted mainly for Nokia cell phones (I only have those to test), but theoretically it can handle all the phones that gammu has support for.  This is also because I never could found an easy to use alternative in Linux for Nokia's PC Suite.


text:
Q: Max retries exceeded while using rotating proxy with Python requests I'm currently working with an Imgur Bot using Python and requests lib with a rotating proxy. I run multiple instances of this bot, but sometimes, some of them got this error:
HTTPSConnectionPool(host='api.imgur.com', port=443): Max retries exceeded with url: /3/credits (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response')))

Here is how the session is defined:
session = requests.Session()
session.proxies = {"http": cre["Proxy"]}

I have no idea why it crashes since only a part instances I run got this error. The others work well.
Thanks, mates!

A: Maybe your proxies are wrong configurated?
I think you run into some form of "requesting too much too fast".
Try to delay some requests (like 3 seconds).


text: Q: IIS Access another file of another server denied I use C# to have a IIS on server A. And the part of code is to get data from another server B (get fiel from \serverB\C$\folder\file.txt). I have already granted the full controll to everyone and serverA$. However the IIS write a log that "Exception: Access to the path '\serverB\C$\folder\file.txt' is denied. ".


text:
Q: Find $r$, given that $F_r= 2F_{101}+F_{100}$
Find $r$, given that $F_r= 2F_{101}+F_{100}$.

We know that the recurrence relation for the Fibonacci sequence is $F_n= F_{n-1}+F_{n-2}$ and that $F_0 = F_1 = 1$, but how to proceed further?

A: $$F_{103}=F_{102}+F_{101},\quad F_{102}=F_{101}+F_{100}\quad \implies \quad F_{103}=2F_{101}+F_{100}$$

A: You can repeat the relation,
$$ F_{n} = F_{n-1} + F_{n-2} $$
$$ F_{n+1} = F_{n} + F_{n-1} $$
$$ \rightarrow F_{n+1} = [F_{n-1} + F_{n-2}] + F_{n-1} $$
$$ F_{n+1} = 2 \cdot F_{n-1} + F_{n-2} $$
You could do this as many times as you like and get to the expression of any number in the sequence in terms of the 2 first ones.


text:
Q: Move Attachment Script I have a VBA Script that I have used to move attachments from emails into a folder for consumption by an SSIS package. However, what I want to do it alter the script so that it renames the Attachment as it saves it to the folder.
Here is the current Script.
Public Sub saveAttachmenttoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String

    saveFolder = "\\vswi-sql\DATABASES\DATAWAREHOUSE\UNIVERSAL_DW\CS\CS_IMPORTS"
        For Each objAtt In itm.Attachments

            objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

            Set objAtt = Nothing
    Next

End Sub

I am not familiar with VBA enough to comfortably make the correction, but I have a feeling it's an alteration to the last few lines.
The attachment that is received is named "WORKBOOK_4X5OFXQG7.XLS", it is a broadcasted report from our Netweaver system. I want to save it as "HRIS_CS_Complaints.xls".

A: You have to change the line
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

In your particular case:
objAtt.SaveAsFile saveFolder & "\" & "HRIS_CS_Complaints.xls"

Please note that this will save ALL your attachments under this file name, so I think you should at least add another variable suffix to this file name like the current timestamp, attachment index etc.


text:
Q: How to change permalinks for custom post types only I added a custom post type in functions.php.
And And I only changed the custom post type permalink in functions.php, but I get 404 Not Found page.
What should I do?
functions.php
function add_custom_post_type(){
  register_post_type(
      'carrot',
      [
          'label' => 'Carrot',
          'public'        => true,
          'has_archive'   => true,
          'menu_position' => 5,
          'menu_icon'     => 'dashicons-carrot',
          'hierarchical' => true,
          'supports' => [
              'title',
              'editor',
              'page-attributes'
          ]
      ]
  );
}
add_action('init', 'add_custom_post_type');

add_filter('post_type_link', 'my_post_type_link', 1, 2);
add_filter('rewrite_rules_array', 'my_rewrite_rules_array');

function my_post_type_link($link, $post){
  if($post->post_type === 'carrot'){
    return home_url('/carrot/'.$post->ID);
  } else {
    return $link;
  }
}
function my_rewrite_rules_array($rules){
  $new_rule = array(
    'carrot/([0-9]+)/?$' => 'index.php?post_type=carrot&p=$matches[1]'
  );
  return $new_rule + $rules;
}


text:
Q: How to find OpenCV installed in /usr/local when building ROS node I am using ROS Kinetic with OpenCV. I created a node that uses CUDA implemented algorithms of OpenCV (which are not available in the ros-kinetic-opencv3 package) so I compiled OpenCV from source with CUDA enabled and installed it in /usr/local.
To test if my /usr/local installation was working as expected (and if my code was correct) I created a program, outside of ROS, with the following CMakeList.txt:
cmake_minimum_required(VERSION 2.8.3)
project(stereo_algorithms_testing)
set(ENV{OpenCV_DIR} "/usr/local")
find_package(OpenCV REQUIRED)
include_directories(include ${OpenCV_INCLUDE_DIRS})
add_executable(stereo_algorithms main.cpp)
target_link_libraries(stereo_algorithms ${OpenCV_LIBS})

When I run cmake ., I get the following output:
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/g++
-- Check for working CXX compiler: /usr/bin/g++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Found CUDA: /usr/local/cuda (found suitable exact version "8.0")
-- Found OpenCV: /usr/local (found version "3.2.0")
-- Configuring done
-- Generating done
-- Build files have been written to: /home/degraw/Opencv_testing/stereo_algorithms/test

All is well, and the code runs as expected with no runtime errors.
Now when I use the same code in a ROS node I have the following CMakeList.txt:
cmake_minimum_required(VERSION 2.8.3)
project(depth_calculator)
set(ENV{OpenCV_DIR} "/usr/local")
find_package(OpenCV REQUIRED core highgui calib3d PATHS /usr/local NO_DEFAULT_PATH)
find_package(catkin REQUIRED COMPONENTS cv_bridge image_transport)
catkin_package()
include_directories(include ${OpenCV_INCLUDE_DIRS} ${catkin_INCLUDE_DIRS})
add_executable(double_image_acq src/double_image_acquisition.cpp)
target_link_libraries(double_image_acq ${OpenCV_LIBS} ${catkin_LIBRARIES})

Notice that I explicitly tell cmake to only look for OpenCV in /usr/local.
The output of catkin_make is:
-- Using CATKIN_DEVEL_PREFIX: /home/degraw/catkin_ws/devel
-- Using CMAKE_PREFIX_PATH: /home/degraw/catkin_ws/devel;/usr/local;/opt/ros/kinetic
-- This workspace overlays: /home/degraw/catkin_ws/devel;/opt/ros/kinetic
-- Using PYTHON_EXECUTABLE: /usr/bin/python
-- Using Debian Python package layout
-- Using empy: /usr/bin/empy
-- Using CATKIN_ENABLE_TESTING: ON
-- Call enable_testing()
-- Using CATKIN_TEST_RESULTS_DIR: /home/degraw/catkin_ws/build/test_results
-- Found gtest sources under '/usr/src/gtest': gtests will be built
-- Using Python nosetests: /usr/bin/nosetests-2.7
-- catkin 0.7.6
-- BUILD_SHARED_LIBS is on
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~  traversing 2 packages in topological order:
-- ~~  - depth_calculator
-- ~~  - zed_wrapper
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- +++ processing catkin package: 'depth_calculator'
-- ==> add_subdirectory(depth_calculator)
-- Found OpenCV: /opt/ros/kinetic (found version "3.2.0") found components:  core highgui calib3d
...
...
...
Running command: "make -j4 -l4" in "/home/degraw/catkin_ws/build"
[ 14%] Built target zed_wrapper_gencfg
[ 28%] Linking CXX executable /home/degraw/catkin_ws/devel/lib/depth_calculator/double_image_acq
[ 57%] Built target ZEDWrapper
[ 85%] Built target zed_wrapper_node
CMakeFiles/double_image_acq.dir/src/double_image_acquisition.cpp.o: In function `OpencvDisparityCalculator::callback(boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&, boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&)':
double_image_acquisition.cpp:(.text._ZN25OpencvDisparityCalculator8callbackERKN5boost10shared_ptrIKN11sensor_msgs6Image_ISaIvEEEEES9_[_ZN25OpencvDisparityCalculator8callbackERKN5boost10shared_ptrIKN11sensor_msgs6Image_ISaIvEEEEES9_]+0x1ad): undefined reference to `cv::cuda::createStereoBM(int, int)'
collect2: error: ld returned 1 exit status
depth_calculator/CMakeFiles/double_image_acq.dir/build.make:175: recipe for target '/home/degraw/catkin_ws/devel/lib/depth_calculator/double_image_acq' failed
make[2]: *** [/home/degraw/catkin_ws/devel/lib/depth_calculator/double_image_acq] Error 1
CMakeFiles/Makefile2:353: recipe for target 'depth_calculator/CMakeFiles/double_image_acq.dir/all' failed
make[1]: *** [depth_calculator/CMakeFiles/double_image_acq.dir/all] Error 2
Makefile:138: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make -j4 -l4" failed

Obviously it's a linker issue. It finds the wrong OpenCV (the ROS OpenCV) which does not include the libraries for CUDA.
How can I tell catkin_make to find the OpenCV in /usr/local?


text:
Q: How to resolve "_this is undefined" in angular 2 i am trying to populate a list by getting items from a firebase database and pushing them to a list. After a lot of searching around i reached this point in my code:
this.angFire.database.list('/SpareParts', {
  query: {
    orderByChild: '',
    limitToFirst: this.limit  // this is a BehaviorSubject<number>(3)
  }
}).subscribe(items => items.forEach(item => function f(j) {
  setTimeout(() => {
    console.log('timeout');
    this.items.push(item);
    if (--j) f(j);
  }, 3000)
}.bind(this)(3) ));

Here i am grabbing only 3 items from firebase. The code does work in a way. It goes through the setTimeout, pushes the three items at the same time in the list and after it's done, it crashes with the error:

_this is undefined

Before this, i was getting the error

this is undefined

so i used the .bind function which still didn't work.
Any advise on this would be much appreciated. Thank you.

A: Store this as a variable outside of your function and use that reference to refer to your component.
var self = this; // <-- store here
this.angFire.database.list('/SpareParts', {
  query: {
    orderByChild: '',
    limitToFirst: this.limit  // this is a BehaviorSubject<number>(3)
  }
}).subscribe(items => items.forEach(item => function f(j) {
  setTimeout(() => {
    console.log('timeout');
    self.items.push(item); // <-- use here
    if (--j) f(j);
  }, 3000)
}.bind(this)(3) ));


text:
Q: How to map a for-loop with nested ifs into Java 8 stream when there is assignment of global variable I've been attempting to learn Java 8 .stream() and as part of that to convert this for-loop. I can't come across the proper way to go about it. .map, and .forEach don't seem to help here.
My main issue comes when I'm trying to assign a DateFormat releaseDate to a parsed records.getReleaseDate() object and then compare it to a set beforeDate object. Any thoughts?
DateFormat sourceFormat = new SimpleDateFormat("yyyy.MM.dd");
Date releaseDate = new Date();
Date beforeDate;

beforeDate = sourceFormat.parse("2001.01.01");

Records records = (Records) obj;

for (Record recs : records.getRecordsList()) {
    try {
        releaseDate = sourceFormat.parse(((Record) recs).getReleaseDate());
    } catch (ParseException e) {
        System.err.println("PARSE EXCEPTION. Unable to parse record.getReleaseDate()");
        e.printStackTrace();
    }

    if (((Record) recs).getTrackListing().size() > 10) {
        if (releaseDate.before(beforeDate)) {
            Release release = new Release();
            release.setName(((Record) recs).getName());
            release.setTrackCount(((Record) recs).getTrackListing().size());
            data.add(release);
        }
    }
}

And this is my initial approach to .stream():
records.getRecordsList().stream()
    .filter(r->r.getTrackListing().size()>10)
    .filter(r >sourceFormat.parse(r.getReleaseDate()).before(beforeDate)))
    .collect(Collectors.toList()));

A: Haven't really tested the code, I hope the idea is clear. I would do something like this:
final DateFormat sourceFormat = new SimpleDateFormat("yyyy.MM.dd");
final Date beforeDate = sourceFormat.parse("2001.01.01");

((Records) obj).getRecordsList()
        .stream()
        .filter(rec -> rec.getTrackListing().size() > 10)
        .filter(rec -> {
            try {
                return sourceFormat.parse(rec.getReleaseDate()).before(beforeDate));
            } catch (ParseException e) {
                System.err.println("PARSE EXCEPTION. Unable to parse record.getReleaseDate()");
                e.printStackTrace();
                return null;
            }
        })
        .filter(Objects::nonNull)
        .map(rec -> {
            Release release = new Release();
            release.setName(rec.getName());
            release.setTrackCount(rec.getTrackListing().size());
            return release;
        })
        .collect(Collectors.toList());

And by the way, if you use Java 8 I would recommend you to use new date/time api to avoid ParseException and null checks, this would be a way cleaner.

A: I understand your question, that you don't know how to use the .map or .forEach streaming functions. .map is used to keep the "stream" alive and map the actual objects/values going through the streams (in your case from instances of Record to instances of Release). .forEach is a sink, so that the stream always ends at an forEach. Thus, you want to use .map (see http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/).
Your source code already has some problems:

*

*What if releaseDate is parsed and an exception is thrown? The value of releaseDate will not change (and may be new Date() or the value of the previous record.

*Why even parsing the releaseDate if it's only used if the getTrackListing().size() > 10? I'd parse it only after the condition was checked true.

*To use lambdas your "outer variables" must be final to be used within the stream.

That said, to get your things working you are on the right track, but you still have to map your recs to an release:
// see 3.
final Date beforeDate = sourceFormat.parse("2001.01.01");

records.getRecordsList().stream()
    .filter(r -> r.getTrackListing().size() > 10)
    .filter(r - {
       // if the parsedDate is invalid we don't want to process, see 1. and 2.
       Date parsedDate;
       try {
          parsedDate = sourceFormat.parse(r.getReleaseDate());
       } catch (ParseException e) {
          System.err.println("...");
          e.printStackTrace();
          parsedDate = null;
       }

       return parsedDate != null && parsedDate.before(beforeDate);
    })
    .map(r -> {
       // map the records to an release
       Release release = new Release();
       release.setName(r.getName());
       release.setTrackCount(r.getTrackListing().size());
       return release;
    })
    .collect(Collectors.toList()));

I just copy and pasted your code (and fixed obvious syntax errors), so have a close look!


text:
Q: How to pass parameter from child model window to parent viewModel Use-Case
Open a pop-up window on an click event in a viewModel with some param so that related data could be loaded in the pop-up. Now get the selected data-models from the pop-up window and return those params back to the parent view mode.
Issue

*

*I am not able to get the params from that model window but can pass params to model window.

*Correct me if I am wrong, model window would have it's on View-Model/composer associated with it and it will handle all the actions locally.

In short, when I close the window, I want to have selected/data, or ListModel in my parent viewmodel, without creating it again using following line of code, because it doesn' go with my use case, I have to keep the layout as it is after closing the model pop-up window
Executions.createComponents(MODEL_WINDOW_PAGE, null, map);

A: Here you can see example how can we do this ..Let us suppose
    public void createReorderModal(Component comp) {
    Map args = new HashMap();
    List list = new ArrayList();
    list.add("test");
    args.put("availableList", list );
    Executions.getCurrent().createComponents("/core/component/model_window.zul",comp, args);

        }

Now in model_window.zul have a own ViewModel ,now in this viewmodel's afterCompose method write below code,to get argument passed in previous step.
@AfterCompose
public void doAfterCompose(@ContextParam(ContextType.VIEW) Component view,
            @ExecutionArgParam("availableList")   List list) {
//Your Business logic
}

Now how you will pass the data from child modal Window to main Window , for that you have create a button in your child Window like this.
<button onClick="@command('doSort')" type="button" label="Sort" />

Now in this doSort() method do this logic..
    @Command
    public void doSort(@ContextParam(ContextType.VIEW) Component view) {
        Map<String, Object> params = new HashMap<String, Object>();
            List someData = new ArrayList();
            someData.add(Add some Data which you send back);
            params.put("orderBySelection", someData);

            Binder bind = (Binder) view.getParent().getAttribute("binder");
            if (bind == null)
                return;
            bind.postCommand("doColumnSorting", params);

            view.detach();
    }

Now you will check this line of code..
bind.postCommand("doColumnSorting", params);

this line will do magic for you .this line will call Parent View Modal Method and now you are in parent viewmodel class and change the respected value and NotifyChange it. May be this will help you


text:
Q: Consulta con AND usando python a Mongodb Atlas Espero que me podáis ayudar. Estoy tratando de hacer una consulta usando operadores, esta vez $and. La idea es que mediante un script de python me saque los datos que tengo alojados en una base de datos en MongoDB Atlas.
El caso es que tengo problemas al escribir el código de consulta en el script de python.
La parte del codigo que uso para hacer la consulta es:
else:
        if Sel_user_ini == '3':
            id_usuario_change = input('Introduce el usuario a borrar: ')
            records.delete_one('Nombre',':', id_usuario_change)
        elif Sel_user_ini == '4':
            TipRes = input('Elige el tipo de respuesta(true/false')
            nSeg = input('Numero de Seguidores')
            id_usuario_change = db.Entradas_chicas_IG.find({ $and: [{Seguidores: { $gte: 250}},{"Respuesta" : "true"}]})
            for documento in records.find({'Nombre': id_usuario_change}):
                print(documento)

El problema es que me da un error de sintaxis en el $and de la consulta:
db.Entradas_chicas_IG.find({ $and: [{Seguidores: { $gte: 250}},{"Respuesta" : "true"}]})

supongo que python lo esta pillando como un variable o carácter especial.
Como evito este problema?

A: Lo que sucede es que Python interpreta que intentas llamar una variable que no existe, además en Python no se pueden crear variables que inicien por $. Simplemente ponlo entre comillas y se resolverá el problema.
db.Entradas_chicas_IG.find({ "$and": [{Seguidores: { "$gte": 250}},{"Respuesta" : "true"}]})

Haz lo mismo también con $gte

A: PROBLEMA
El problema es sencillo, estás tratando de hacer una consulta desde lenguaje Python y el mismo tiene ciertas reglas de sintaxis que no puedes obviar. El método find() del Driver PyMongo (Driver Oficial de MongoDB para Python), recibe como argumentos diferentes parámetros, entre ellos ellos un filtro, que según la documentación es un Objeto tipo SON:

filter (opcional): un objeto SON especificando los elementos que deben estar presentes para que un documento sea incluido en el resultado.

Sucede que los objetos SON, son estructuras de tipo diccionario de Python, las cuales tienen un sintaxis particular.
SOLUCIÓN
La solución es sencilla, tal como te han sugerido en la primera respuesta, debes escribir los nombres de clave de los filtros y opciones tal como se escriben los nombres de clave en los diccionarios: usando doble comilla o comilla simple (según tu preferencia).
Tu consulta debería escribirse así:
db.Entradas_chicas_IG.find({ "$and": [{"Seguidores": { "$gte": 250}},{"Respuesta" : "true"}]})

Si necesitas saber la equivalencia entre un tipo de MongoDB y Python puedes consultar la tabla de equivalencias
Espero que esto te ayude a entender el problema y cómo solucionarlo.


text:
Q: RMI Threadfactory Is it possible to assign a Custom Thread Factory to the RMI server.  I currently use the following code:
    try {
        String sName = InetAddress.getLocalHost().getHostName();
        thisAddress = (InetAddress.getLocalHost().toString());
    } catch (UnknownHostException ex) {
    shutdown();
    }
    thisport = 8081;

    registry = LocateRegistry.createRegistry(thisport);
    registry.rebind("rmiserver", this);
    System.out.println("Listening on " + thisAddress + " at port " + thisport);

However, I would like to set that the threads created are not standard Threads but a sub-class of the same.
Regards,
KT

A: No, you can't control the threads created by the RMI runtime system. It doesn't use a thread factory at all actually, just new Thread(...).
EDIT: I should clarify that I am speaking of the Sun implementation of RMI/JRMP. I have heard that the IBM implementation uses a thread pool, and I can't speak for what happens in RMI/IIOP at all, there being so many possible providers.


text:
Q: Why won't my divs line up? Here is my HTML
<!DOCTYPE html>

    <title>
        Oaki Softworks
    </title>
    <link href='style.css' rel='stylesheet' type='text/css'>
    <link rel="icon" href="favicon.png">

Contact Us

Careers

Products

About Us

Video games as art.

Even before the conception of our company, we have always embraced video games as the newest, emerging art form. Video games engage an audience like no other medium: allowing them to digest the material at their own pace, to identify themselves within their avatar as they see fit, and to interact with the world around them. Oaki Software aims to underline these elements of art even further with our own game design.

            Oaki Softworks™

Fort Collins, CO 80521

benkulka@oakisoftworks.com

Here is my CSS
body {
    background-color: #021034;
    padding: 0px;
    margin: 0px;
}

#navigation {
    position: fixed;
    background-color: black;
    height: 40px;
    width: 100%;
    color: white;
    color: #adb7bd;
    font-family: 'Lucida Sans', Arial, sans-serif;
    font-size: 16px;
    line-height: 26px;
}

div.navigation_tile {
    height: 30px;
    width: 15%;
    align-content: center;
    text-align: center;
    float: right;
    margin: 5px;
}

div.navigation_tile:hover {
    background-color: #092466;
}

div.navigation_tile:active {
    background-color: white;
    color: black;
}

#content {
    margin-top: 30px;
    display: inline-block;
    text-align: justify;
}

#blurb{
    padding: 40px 0 0 25px;
    width: 28%;
    height: 250px;
}

#main_pic {
    float: right;
    width: 66%;
    height: 250px;
    border: 10px #092466 solid;
    overflow: hidden;
}

h1{
    color: #A5B7E3;
    font-family: 'Lato', sans-serif;
    font-size: 54px;
    font-weight: 300;
    line-height: 58px;
    margin: 0 0 20px;
}

h2 {
    color: #6681C4;
    font-family: 'Lato', sans-serif;
    font-size: 34px;
    margin: 0 0 10px;
}

p{
    text-indent: 20px;
    color: white;
    font-size: 12px;
    font-weight: 100;
    font-family: 'Lucida Sans', Arial, serif;
    line-height: 20px;
}

img.social_media_icon{
    height: 15px;
    width: 15px;
    padding: 5px;
}

#footer {
    height: auto;
    width: 100%;
    background-color: black;
    text-align: center;
    padding: 5px;
}

I'm trying to get my #blurb div to line up with my #main_pic div within my parent #content div, but I'm having trouble doing so. Can someone point me in the right direction?

A: #blurb {
    [...]
    float: left;
}
#content {
    [..]
    overflow: hidden;
}

Also consider removing  height: 250px; from #blurb ... hard to say is it required for some reason.


text:
Q: Javascript - time difference in seconds between two dates I have to create a function that calculates the time in seconds from now to July 4th.
This is what I have so far:

function getTimeDiff(fdate, pdate) {
  var fSeconds = fdate.getTime();
  var pSeconds = pdate.getTime();
  var secondsLeft = (fSeconds - pSeconds) / 1000
  return secondsLeft;
}

var x = getTimeDiff(new Date(2019, 6, 4, 0, 0), new Date());
console.log(x);

When I run the code in my browser it states that

"fdate.getTime() is not a function"

How do I fix this?

A:
How do I enter dates so that my function recognizes that I am entering a "new Date()"?

Perhaps you mean to do this:
var x = getTimeDiff(new Date(2019, 7, 4, 24, 0, 0), new Date(2019, 6, 7, 24, 11, 0));

A: If you want to compare a date to today, there is no need to pass today as a variable to the function (the code will get a little bit simple).
function getTimeDiff(year, month, day) {
  var today = new Date();
  var targetDate = new Date(year, month, day);
  return Math.round( (targetDate.getTime() - today.getTime()) / 1000);
}

console.log(getTimeDiff(2019,6,6));

Because getTime outputs the value in miliseconds, I have divided by 1000 and rounded the value, so you get an integer.
The code outputs somethink like 2293103 (tested in Chrome and Firefox)


text:
Q: C++: Infinite loop with a simple menu selection The script I am working on is over a page long, so I am going to link it (one simple file):
http://pastebin.com/7BVHmQGp
I apologize for that. My problem is I get into an infinite loop in my code, for example after I select 1 or 2 for encrypting/unencrypting it lets me enter the word, and when I next enter the "shift" for the cipher it runs an infinite loop of the menu.
I had tried for so many hours to debug this, I thought it was a problem with cin, for example when you enter an invalid choice it just throws an infinite loop/
What seems to cause the infininte loops?

A: I think you should be ignoring the newline character instead of a space
I tried with the following and it works on VS2010
    cin.ignore(1, '\n');
    getline(cin, input);

A: Try cin.clear, I believe you are constantly reading your initial input character.
    cin >> selection;
    cin.clear();

A: This page should explain all you need to know.


text:
Q: jQuery pesquisa em uma tabela Estou renderizando valores em uma tabela e tenho que filtrar por um campo que chama razao, para isso utilizo um script, a consulta funciona mas ao deletar a consulta feita os valores anteriores não voltam, ou seja ao apagar o campo pesquisa a pesquisa ainda persiste.
HTML pesquisa:

<input type="text" value="" class="form-control pesquisa" style="max-width:200px" />

Js:
 $(".pesquisa").keyup(function () {
                var texto = $(this).val();
                $(".lista").css("display", "grid");
                $(".lista").each(function () {
                    if ($(this).find(".razao").text().toUpperCase().indexOf(texto.toUpperCase()) < 0) {
                        $(this).css("display", "none");
                    }
                })
            })

HTML lista:
 @if (Model != null)
                {
                    foreach (var item in Model)
                    {

                                @Html.DisplayFor(modelItem => item.codigo)

                                @Html.DisplayFor(modelItem => item.razao)

                                @Html.DisplayFor(modelItem => item.cidade)

                                @Html.DisplayFor(modelItem => item.estado)

                                @Html.DisplayFor(modelItem => item.telefone)

                    }
                }

Alguém pode me ajudar?

A: Ao apagar o valor do campo de pesquisa, você deve retirar o estilo display: none, assim todos os itens irão voltar para o seu estado original, ou seja, irão aparecer novamente.
Do jeito que está sua função, ele apenas esconde os resultados que não são compatíveis com o valor do campo de pesquisa e não faz o contrário, que é mostrar.

A: Tenho esse script que pode servir ao seu caso.
 $('#tblSegundoNivel_linha1 tbody').find('tr').each(function (indexTr, valueTr) {
            $(this).find('td').each(function (indexTd, valueTd) {
                if (indexTd === 5) {
                    if ($(valueTd).html().indexOf(b) === -1) {
                        $(valueTd).parent().hide();
                    } else {
                        $(valueTd).parent().show();
                    }
                }
            });
        });

A pesquisa é feita pelo número da coluna, também preferi esconder os resultados com $().hide() ao meu ver fica mais limpo o código.


text:
Q: How pass numpy array from Python to Golang function I'm trying  create library using with Golang for working in Python. But I have one problem: I can't pass numpy array to go function. Please, help me solve problem.
My code:
main.go:
package main

import "C"
import "fmt"

type Matrix [][] int

//export Mass
func Mass(data Matrix) int {
  var sum int=0
  for i, x:= range data {
    for j, _ := range x {
        sum+=data[i][j]
    }
  }
  return sum
}

func main() {
}

ex.py:
from ctypes import *
import numpy as np

mysum = cdll.LoadLibrary(r'D:\tests\go\sum.dll')

array_2d_int = np.ctypeslib.ndpointer(dtype=c_int32, ndim=2,
                                      flags='CONTIGUOUS')

def mass(a):
    mysum.Mass.argtypes = [array_2d_int]
    mysum.Mass.restype = c_int32
    return mysum.Mass(a)

Compiling cmd-line:
go build -buildmode=c-shared -o sum.dll main.go

When I call function from dll-library:
from ex import mass
import numpy as np

a=np.array([[1,2],[3,4]])

print(mass(a))

I have errors:
unexpected fault address 0x1b216000
fatal error: fault
[signal 0xc0000005 code=0x0 addr=0x1b216000 pc=0x6ac92c1f]

goroutine 17 [running, locked to thread]:
....

A: I dont know if this is what you are looking for.

*

*Write the resulting numpy array to a file

*Read the file in your go code

Execute the relevant commands in batch


text:
Q: SQL: Joining 3 tables to generate report dashboard I am trying to join 3 different tables that holds my test execution results as "PASS", "FAIL" and "SKIP". There are 2 common properties in these 3 tables on the basis of which I need to club my result i.e. "BUILD_NUMBER" and "COMPONENT".
Tried several approach but does not get the desired result.
Best result reached so far.

Sample query:
select test_execution.COMPONENT, test_execution.BUILD_NUMBER,
count(test_execution.TEST_STATUS) as PASS from (test_execution
INNER JOIN test_execution_fail ON
test_execution.BUILD_NUMBER = test_execution_fail.BUILD_NUMBER) group by
COMPONENT,BUILD_NUMBER;

My tables look like below:
CREATE TABLE test_execution_skip (
BUILD_NUMBER int,
TEST_NAME varchar(255),
TEST_CLASS varchar(255),
COMPONENT varchar(255),
TEST_STATUS varchar(255)

);
Other two tables are exactly same with test_execution and test_execution_fail as their names.
test_execution table holds 3 records(all pass values), test_execution_fail table holds 2 records (all fail values) and test_execution_skip table holds 1 record(skip value).
I want to populate data that will show me BUILD_NUMBER, COMPONENT, TOTAL, PASS, FAIL, SKIP as records where TOTAL, PASS, FAIL and SKIP will show the respectives counts.
Any help is appreciated here.

A: Not sure if this answers your question but you could try something like this
WITH cte AS (
SELECT * FROM test_execution
union
SELECT * FROM test_execution_fail
UNION
SELECT * FROM test_execution_skip
)

SELECT t.*,  (SKIP + FAIL + PASS) AS TOTAL  FROM (
select
      COMPONENT,
      BUILD_NUMBER,
      SUM(IF(TEST_STATUS = 'skip', 1, 0 )) as SKIP,
      SUM(IF(TEST_STATUS = 'fail', 1, 0 )) as FAIL,
      SUM(IF(TEST_STATUS = 'pass', 1, 0 )) as PASS
      FROM cte
group by COMPONENT,BUILD_NUMBER
)t

db fiddle


text:
Q: Deadlock behaviour having 3 threads with wait and notify I have 3 Threads, all 3 doing the same thing "[...]" (e.g. writing to a list, on which we synchronize):
public void run(){
  long time= System.currentTimeMillis();
  while(System.currentTimeMillis - time < 10000){
    synchronized(object){
      [...]
      object.notifyAll();
      object.wait();
    }
  }
  System.out.println(Thread.currentThread.getName() + " just finished");
}

What I found curious, is that when one thread exits the while-loop, a deadlock occurs. My problem is not that it happened, as it is exactly what I was testing, but when it occured. Shouldn't the deadlock happen after two threads are finished because there is one left that cannot be notified by any of the finished two?
Of course there is a chance that two threads call their "wait" at the same time, so we get a deadlock after just one finished thread because the two waiting ones cannot be woken up by the finished one, but I have run the test numerous times and the result is always the same: Deadlock after just one finished thread.
Am I missing something?

A: The wait function will wait whether there's something to wait for or not. Before you call wait, you must check whether the thing you want to wait for has already happened -- that's why you're in a synchronized block, so that you hold the lock that protects the shared state that you are waiting for.
You will never get wait/notifyAll to work without some shared state that you are waiting to reach some particular state. You must use the lock to protect that shared state, and you must check its state before calling wait. Otherwise, you will always have possible races including the one you are seeing where you wait for something to happen even though it has already happened, thus waiting forever.


text:
Q: Can I override DropLocation target to avoid network latency? In Team Build 2008, the Drop Location for a build is no longer specified in the .proj file, and instead is stored in the database and maintained in the GUI tool.
The GUI tool only accepts a network path as a drop location (i.e. \\server\share) and will not accept a local path.
Our build server also hosts the dropped files, so it seems that forcing a file copy operation to go through the network share introduces a lot of lag time when copying a large number of files. I would like to override this feature so that I can specify a local directory for drop location, but I can't figure out how.

A: I haven't worked with the 2008 version only the 2005 version, but it seems you could do this manually.  Set the SkipDropBuild property to true.  Then copy all the binaries manually in the BeforeDropBuild event using the Copy command built into Team Build.
Something like this:
<SourceDir>$(SolutionRoot)\..\Binaries\Release</SourceDir>
<SkipDropBuild>true</SkipDropBuild>
<CreateItem Include="$(SourceDir)\**\*.*">
        <Output TaskParameter="Include" ItemName="BuiltBinaries"/>
</CreateItem>
<Target Name ="BeforeDropBuild">
        <Copy SourceFiles="@(BuiltBinaries)" DestinationFiles="@(BuiltBinaries->'C:\droplocation\%(Filename)%(Extension)')"/>
</Target>

A: I've found an easier solution, and that is to just do a file system move on the Release folder. Since the drop location actually sits on the same  physical drive, I'm ok with that. I've added this to the TFSBuild.proj file:
<Target Name="CoreDropBuild"
        Condition=" '$(SkipDropBuild)'!='true' and '$(IsDesktopBuild)'!='true' "
        DependsOnTargets="$(CoreDropBuildDependsOn)" >
    <Exec Command="move $(BinariesRoot)\Release d:\BuildOutput\$(BuildNumber)\Release"/>
</Target>

A: The actual BuildDropLocation needs to be available on a network share.  The drop location is used by clients and the TFS Application Tier when you publish test results.  It also needs to be accessible to both clients and the TFS Application Tier machine when accessing build results.  As part of the datawarehouse step the TFS Application Tier machine will access the build results over the drop location to find the test results files to add to the warehouse.
That said, assuming that your build server is the same machine that is hosting your drop location share - and will always be the same machine then you can skip the drop step from the TFSBuild.proj.  One solution would probably be a combination of those outlined by Todd and Chad i.e. something like:
<SkipDropBuild>true</SkipDropBuild>
<Target Name ="AfterDropBuild">
        <Exec Command="move $(BinariesRoot)\Release d:\BuildOutput\$(BuildNumber)\Release"/>
</Target>

Note that you shouldn't actually have to hard-code the "Release" part but be able to get that from the configuration properties - however I don't have my TeamBuild targets file to hand so I cannot say exactly what that is at the moment so I'll look it up when I get back to my desk and edit this answer accordingly.
That said there are quite a few risks involved in doing this.

*

*You have to make sure that you have all the file paths lined up exactly right or things like viewing a build log or populating the TFS warehouse with test results might stop working

*You will have hard-coded your build and drop locations to always exist on the same machine. If someone attempts to build your TFSBuild.proj file on a different machine then things won't work as they expect

*If someone edits the drop location property in the build definition then they have to know to make a corresponding edit in the TFSBuild.proj file

Therefore because of the maintainability issues involved in this approach - I wouldn't recommend it in the vast majority of cases.  It would be worth doing a test and seeing how much time this actually saves to to determine if it is a worthwhile optimization in your circumstances.


text:
Q: Message error 'C:/Program' not found with glmmadmb() in R Using:

*

*Windows 7

*Emacs 24.3

*ESS

*R 3.1.1

The error from a glmmadmb() call:
Error in system(cmd, intern = intern, wait = wait | intern, show.output.on.console = wait,  :   'C:/Program' not found"
Prompted me to reinstall R in a pathname that had no spaces, as recommended from this post concerning the same error (with Rcpp).  I did such, and the error persisted.
The code ran without error in Rstudio with the standard/default R installation (pathname with spaces).  My problem occurred with EMACS/ESS/R 3.1.1 when trying to fit a glmmadmb(), which prompted me to run with debug=TRUE
>   gaFP0<-glmmadmb(count~tx,
                    random=~(1|Feed)+(1 | Pint),
                    data=dnoNM,family="nbinom",zeroInflation=TRUE,
                    debug=TRUE)

Which output:
platform: windows 64
executable name: glmmadmb.exe
bin_loc: C:/RLIB/glmmADMB/bin/windows64/glmmadmb.exe
using temp directory
C:\Users\user1\AppData\Local\Temp\Rtmpq2AddG\glmmADMB90e434c55ff2
creating temp directory changed working directory to
C:/Users/user1/AppData/Local/Temp/Rtmpq2AddG/glmmADMB90e434c55ff2
Command line: "C:/RLIB/glmmADMB/bin/windows64/glmmadmb.exe" -maxfn 500 -maxph 5 -noinit -shess
Error in system(cmd, intern = intern, wait = wait | intern, show.output.on.console = wait,  :
'C:/Program' not found
 changed working directory to h:/
removed temp directory
C:\Users\user1\AppData\Local\Temp\Rtmpq2AddG\glmmADMB90e434c55ff2

As a note -- I also reinstalled Emacs to have no spaces in the pathname and still had the error, although I did not uninstall the original version.

A: The hack I employed so that EMACS/ESS could run the code was the following Sys.setenv() statement before the function call.
>   Sys.setenv(R_SHELL = "C:\\Windows\\system32\\cmd.exe")
>   gaFP0<-glmmadmb(count~tx,
                    random=~(1|Feed)+(1 | Pint),
                    data=dnoNM,family="nbinom",zeroInflation=TRUE,
                    debug=TRUE)

Now glmmadmb() runs as expected.  See the reasons as explained by Ross Boylan (this Q&A stackoverflow post was written with his permission).


text:
Q: MYSQL get status topic for show static pages or normal page in this below sql commands i want to add option to choice which topics must be show normal posts or static pages ?
in setting table i have default_front_page to change this option. if this filed is not 0 sql commad must be fetch static page
default_front_page is static page id and i.id is topic id.
all posts such as normal or static pages seved into contents table and i can use with post_type filed to guess this post is normal or static.whats my problem in this code now?
SELECT
     SQL_CALC_FOUND_ROWS i.* ,
     c.title AS category_name,
     u.name,
     u.family,
     i.thumb_image,
     CONCAT( u.name, ' ', u.family ) AS author,
     tumbnail_image_width,
     tumbnail_image_height,
     CASE (s.sortable)
        WHEN 3 THEN 100000000 - i.id
        WHEN 2 THEN i.date_time
        WHEN 1 THEN i.order_display
     END  AS SortField
  FROM   contents i
  JOIN   categories c ON c.id = i.category
  JOIN   users u ON u.id = i.posted_by
  JOIN   settings s ON s.portal = i.portal
  WHERE
         i.portal = '{$portal_id}'
         AND CASE WHEN post_type = 4
              THEN date(NOW()) BETWEEN i.from_dateTime AND i.to_dateTime
         ELSE post_type = 1
         END
  AND i.t_status = 1 AND
         CASE WHEN s.default_front_page <> 0
              THEN i.id = s.default_front_page
         END
  ORDER BY SortField
  LIMIT {$portalSettings['display_post_count']};

A: There is no need to use CASE in the WHERE clause. AND and OR should do it:
WHERE
     i.portal = '{$portal_id}'
     AND (
           (post_type = 4
             AND date(NOW()) BETWEEN i.from_dateTime AND i.to_dateTime
           )
           OR post_type = 1
         )
     AND i.t_status = 1
     AND (s.default_front_page = 0 OR i.id = s.default_front_page)


text:
Q: Unable to detect wifi p2p group owner by legacy devices I am trying to create a wifi direct p2p Group owner using wpa_supplicant and wpa_cli. Once the group is create with p2p_group_add, how can we connect legacy wifi devices to the GO? I see the GO in Android mobile search, however I am not able to detect/find GO in legacy laptop with just wifi support. May I know if any configurations need to be done for supporting legacy devices like security type etc. Please suggest.

A: An autonomous GO should be detected by any legacy wifi device - no special configuration is necessary. The GO should be beaconing and responding to any probe requests, both of which allow a legacy wifi system to detect it (it will just ignore the special P2P IE).
I just tried the same scenario and both my Android phone and my Windows 7 laptop could see the GO running on my Linux laptop.
As your Android phone can see the GO then it is obviously responding to probe requests, so the fact your Windows machine cannot see it is likely to be an issue with the specific netcard used (either in your wpa_supplicant machine, or your Windows machine).
Some further debugging may be necessary to find the root cause, for example using wireshark, and if possible either upgrading the wifi netcard driver on your Windows machine, or swapping it out with a different vendor.


text:
Q: What distribution do you get from this broken random shuffle? The famous Fisher-Yates shuffle algorithm can be used to randomly permute an array A of length N:
For k = 1 to N
    Pick a random integer j from k to N
    Swap A[k] and A[j]

A common mistake that I've been told over and over again not to make is this:
For k = 1 to N
    Pick a random integer j from 1 to N
    Swap A[k] and A[j]

That is, instead of picking a random integer from k to N, you pick a random integer from 1 to N.
What happens if you make this mistake?  I know that the resulting permutation isn't uniformly distributed, but I don't know what guarantees there are on what the resulting distribution will be.  In particular, does anyone have an expression for the probability distributions over the final positions of the elements?

A: What a lovely question!  I wish I had a full answer.
Fisher-Yates is nice to analyze because once it decides on the first element, it leaves it alone.  The biased one can repeatedly swap an element in and out of any place.
We can analyze this the same way we would a Markov chain, by describing the actions as stochastic transition matrices acting linearly on probability distributions.  Most elements get left alone, the diagonal is usually (n-1)/n.  On pass k, when they don't get left alone, they get swapped with element k, (or a random element if they are element k).  This is 1/(n-1) in either row or column k.  The element in both row and column k is also 1/(n-1).  It's easy enough to multiply these matrices together for k going from 1 to n.
We do know that the element in last place will be equally likely to have originally been anywhere because the last pass swaps the last place equally likely with any other.  Similarly, the first element will be equally likely to be placed anywhere.  This symmetry is because the transpose reverses the order of matrix multiplication.  In fact, the matrix is symmetric in the sense that row i is the same as column (n+1 - i).  Beyond that, the numbers don't show much apparent pattern. These exact solutions do show agreement with the simulations run by belisarius: In slot i, The probability of getting j decreases as j raises to i, reaching its lowest value at i-1, and then jumping up to its highest value at i, and decreasing until j reaches n.
In Mathematica I generated each step with
 step[k_, n_] := Normal[SparseArray[{{k, i_} -> 1/n,
                      {j_, k} -> 1/n, {i_, i_} -> (n - 1)/n} , {n, n}]]

(I haven't found it documented anywhere, but the first matching rule is used.)
The final transition matrix can be calculated with:
Fold[Dot, IdentityMatrix[n], Table[step[m, n], {m, s}]]

ListDensityPlot is a useful visualization tool.
Edit (by belisarius)
Just a confirmation. The following code gives the same matrix as in @Eelvex's answer:
step[k_, n_] := Normal[SparseArray[{{k, i_} -> (1/n),
                      {j_, k} -> (1/n), {i_, i_} -> ((n - 1)/n)}, {n, n}]];
r[n_, s_] := Fold[Dot, IdentityMatrix[n], Table[step[m, n], {m, s}]];
Last@Table[r[4, i], {i, 1, 4}] // MatrixForm

A: An Empirical Approach.
Let's implement the erroneous algorithm in Mathematica:
p = 10; (* Range *)
s = {}
For[l = 1, l <= 30000, l++, (*Iterations*)
   a = Range[p];
   For[k = 1, k <= p, k++,
     i = RandomInteger[{1, p}];
     temp = a[[k]];
     a[[k]] = a[[i]];
     a[[i]] = temp
   ];
   AppendTo[s, a];
]

Now get the number of times each integer is in each position:
r = SortBy[#, #[[1]] &] & /@ Tally /@ Transpose[s]

Let's take three positions in the resulting arrays and plot the frequency distribution for each integer in that position:
For position 1 the freq distribution is:

For position 5 (middle)

And for position 10 (last):

and here you have the distribution for all positions plotted together:

Here you have a better statistics over 8 positions:

Some observations:

*

*For all positions the probability of
"1" is the same (1/n).

*The probability matrix is symmetrical
with respect to the big anti-diagonal

*So, the probability for any number in the last
position is also uniform (1/n)

You may visualize those properties looking at the starting of all lines from the same point (first property) and the last horizontal line (third property).
The second property can be seen from the following matrix representation example, where the rows are the positions, the columns are the occupant number, and the color represents the experimental probability:

For a 100x100 matrix:

Edit
Just for fun, I calculated the exact formula for the second diagonal element (the first is 1/n). The rest can be done, but it's a lot of work.
h[n_] := (n-1)/n^2 + (n-1)^(n-2) n^(-n)

Values verified from n=3 to 6 ( {8/27, 57/256, 564/3125, 7105/46656} )
Edit
Working out a little the general explicit calculation in @wnoise answer, we can get a little more info.
Replacing 1/n by p[n], so the calculations are hold unevaluated, we get for example for the first part of the matrix with n=7 (click to see a bigger image):

Which, after comparing with results for other values of n, let us identify some known integer sequences in the matrix:
{{  1/n,    1/n      , ...},
 {... .., A007318, ....},
 {... .., ... ..., ..},
 ... ....,
 {A129687, ... ... ... ... ... ... ..},
 {A131084, A028326 ... ... ... ... ..},
 {A028326, A131084 , A129687 ... ....}}

You may find those sequences (in some cases with different signs) in the wonderful http://oeis.org/
Solving the general problem is more difficult, but I hope this is a start

A: The "common mistake" you mention is shuffling by random transpositions. This problem was studied in full detail by Diaconis and Shahshahani in Generating a random permutation with random transpositions (1981). They do a complete analysis of stopping times and convergence to uniformity. If you cannot get a link to the paper, then please send me an e-mail and I can forward you a copy. It's actually a fun read (as are most of Persi Diaconis's papers).
If the array has repeated entries, then the problem is slightly different. As a shameless plug, this more general problem is addressed by myself, Diaconis and Soundararajan in Appendix B of A Rule of Thumb for Riffle Shuffling (2011).

A: Wikipedia's page on the Fisher-Yates shuffle has a description and example of exactly what will happen in that case.

A: You can compute the distribution using stochastic matrices. Let the matrix A(i,j) describe the probability of the card originally at position i ending up in position j. Then the kth swap has a matrix Ak given by Ak(i,j) = 1/N if i == k or j == k, (the card in position k can end up anywhere and any card can end up at position k with equal probability), Ak(i,i) = (N - 1)/N for all i != k (every other card will stay in the same place with probability (N-1)/N) and all other elements zero.
The result of the complete shuffle is then given by the product of the matrices AN ... A1.
I expect you're looking for an algebraic description of the probabilities; you can get one by expanding out the above matrix product, but it I imagine it will be fairly complex!
UPDATE: I just spotted wnoise's equivalent answer above! oops...

A: I've looked into this further, and it turns out that this distribution has been studied at length. The reason it's of interest is because this "broken" algorithm is (or was) used in the RSA chip system.
In Shuffling by semi-random transpositions, Elchanan Mossel, Yuval Peres, and Alistair Sinclair study this and a more general class of shuffles. The upshot of that paper appears to be that it takes log(n) broken shuffles to achieve near random distribution.
In The bias of three pseudorandom shuffles (Aequationes Mathematicae,  22, 1981, 268-292), Ethan Bolker and David Robbins analyze this shuffle and determine that the total variation distance to uniformity after a single pass is 1, indicating that it is not very random at all. They give asympotic analyses as well.
Finally, Laurent Saloff-Coste and Jessica Zuniga found a nice upper bound in their study of inhomogeneous Markov chains.

A: This question is begging for an interactive visual matrix diagram analysis of the broken shuffle mentioned. Such a tool is on the page Will It Shuffle? - Why random comparators are bad by Mike Bostock.
Bostock has put together an excellent tool that analyzes random comparators. In the dropdown on that page, choose naïve swap (random ↦ random) to see the broken algorithm and the pattern it produces.
His page is informative as it allows one to see the immediate effects a change in logic has on the shuffled data. For example:
This matrix diagram using a non-uniform and very-biased shuffle is produced using a naïve swap (we pick from "1 to N") with code like this:
function shuffle(array) {
    var n = array.length, i = -1, j;
    while (++i < n) {
        j = Math.floor(Math.random() * n);
        t = array[j];
        array[j] = array[i];
        array[i] = t;
    }
}

But if we implement a non-biased shuffle, where we pick from "k to N" we should see a diagram like this:

where the distribution is uniform, and is produced from code such as:
function FisherYatesDurstenfeldKnuthshuffle( array ) {
    var pickIndex, arrayPosition = array.length;
    while( --arrayPosition ) {
        pickIndex = Math.floor( Math.random() * ( arrayPosition + 1 ) );
        array[ pickIndex ] = [ array[ arrayPosition ], array[ arrayPosition ] = array[ pickIndex ] ][ 0 ];
    }
}

A: Let's say

*

*a = 1/N

*b = 1-a

*Bi(k) is the probability matrix after i swaps for the kth element. i.e the answer to the question "where is k after i swaps?". For example B0(3) = (0 0 1 0 ... 0) and B1(3) = (a 0 b 0 ... 0). What you want is BN(k) for every k.

*Ki is an NxN matrix with 1s in the i-th column and i-th row, zeroes everywhere else, e.g:

*

*Ii is the identity matrix but with the element x=y=i zeroed. E.g for i=2:

*

*Ai is

Then,

But because BN(k=1..N) forms the identity matrix, the probability that any given element i will at the end be at position j is given by the matrix element (i,j) of the matrix:

For example, for N=4:

As a diagram for N = 500 (color levels are 100*probability):

The pattern is the same for all N>2:

*

*The most probable ending position for k-th element is k-1.

*The least probable ending position is k for k < N*ln(2), position 1 otherwise

A: I knew I had seen this question before...
" why does this simple shuffle algorithm produce biased results? what is a simple reason? " has a lot of good stuff in the answers, especially a link to a blog by Jeff Atwood on Coding Horror.
As you may have already guessed, based on the answer by @belisarius, the exact distribution is highly dependent on the number of elements to be shuffled.  Here's Atwood's plot for a 6-element deck:

A: The excellent answers given so far are concentrating on the distribution, but you have asked also "What happens if you make this mistake?" - which is what I haven't seen answered yet, so I'll give an explanation on this:
The Knuth-Fisher-Yates shuffle algorithm picks 1 out of n elements, then 1 out of n-1 remaining elements and so forth.
You can implement it with two arrays a1 and a2 where you remove one element from a1 and insert it into a2, but the algorithm does it in place (which means, that it needs only one array), as is explained here (Google: "Shuffling Algorithms Fisher-Yates DataGenetics") very well.
If you don't remove the elements, they can be randomly chosen again which produces the biased randomness. This is exactly what the 2nd example your are describing does. The first example, the Knuth-Fisher-Yates algorithm, uses a cursor variable running from k to N, which remembers which elements have already been taken, hence avoiding to pick elements more than once.


text:
Q: Поблоковая прокрутка на jQuery Есть скрипт поблоковой прокрутки на jQuery. Как сделать так чтоб он не перекидывал тебя на первый блок после прокрутки до последнего? нашел ответ но я не знаю как этот ответ написать на jquery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var anchors = [];
var currentAnchor = -1;
var isAnimating  = false;
$(function(){
    function updateAnchors() {
        anchors = [];
        $('.anchor').each(function(i, element){
            anchors.push( $(element).offset().top );
        });
    }
    $('body').on('mousewheel', function(e){
        e.preventDefault();
        e.stopPropagation();
        if( isAnimating ) {
            return false;
        }
        isAnimating  = true;
        if( e.originalEvent.wheelDelta >= 0 ) {
            currentAnchor--;
        }else{
            currentAnchor++;
        }
        if( currentAnchor > (anchors.length - 1)
           || currentAnchor < 0 ) {
            currentAnchor = 0;
        }
        isAnimating  = true;
        $('html, body').animate({
            scrollTop: parseInt( anchors[currentAnchor] )
        }, 200, 'swing', function(){
            isAnimating  = false;
        });
    });
    updateAnchors();
});

A: Разделить условия довольно просто - здесь jquery не затрагивается.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var anchors = [];
var currentAnchor = -1;
var isAnimating  = false;
$(function(){
    function updateAnchors() {
        anchors = [];
        $('.anchor').each(function(i, element){
            anchors.push( $(element).offset().top );
        });
    }
    $('body').on('mousewheel', function(e){
        e.preventDefault();
        e.stopPropagation();
        if( isAnimating ) {
            return false;
        }
        isAnimating  = true;
        if( e.originalEvent.wheelDelta >= 0 ) {
            currentAnchor--;
        } else {
            currentAnchor++;
        }

        if( currentAnchor > (anchors.length - 1) ) {
            currentAnchor = anchors.length - 1;
        }

        if (currentAnchor < 0) currentAnchor = 0;

        isAnimating  = true;
        $('html, body').animate({
            scrollTop: parseInt( anchors[currentAnchor] )
        }, 200, 'swing', function(){
            isAnimating  = false;
        });
    });
    updateAnchors();
});


text:
Q: rails 3 auto complete (prototypejs) I'm looking for a good auto complete plugin for rails3, based on prototype.
The plugin of dhh should be the right one, but a bit old (last commit in 2007)
do you have any good experience with one of the 68 fork with rails 3? (rails/auto_complete/network)
thanks

A: First result on google and incredibly easy to get up and running. May require a bit of DIY and elbow grease but I found it to be minimally invasive...
http://www.devbridge.com/projects/autocomplete/

A: Rails3-jquery-autocomplete is the best plugin to date :
https://github.com/crowdint/rails3-jquery-autocomplete
It has a good documentation on github, it can get you up & running in a few minutes.


text:
Q: Can you put a NavigationPage inside a ContentPage? I'm trying to create a music player in Xamarin Forms. Now at the bottom of my page there always is a bar with the music player controls. Instead of always adding the  tag and creating a new PlayerBar in each view, I thought it would be useful to create a RootPage with the PlayerBar created once inside and above it a NavigationPage that spans the rest of the view.

In XAML it would look a bit like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:views="clr-namespace:PodBase.Views"
             xmlns:controls="clr-namespace:PodBase.Controls"
             x:Class="PodBase.Views.RootPage">
    <ContentPage.Content>
        <Grid>
            <NavigationPage>
                <x:Arguments>
                    <views:MainPage/>
                </x:Arguments>
            </NavigationPage>
            <controls:PlayerControl/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

However when I try it out I get an error saying NavigationPage cannot be added to IGridList. Are there any other options I can use to work this out?

A: This is not possible. A Page can only be at the root. Inside you can have one VisualElement and within that VisualElement you can nest as many things as you like.
To achieve this kind of behavior, either inherit from the NavigationPage and add the player control at the bottom. Or, you will have to mimic your own navigation page behavior.


text:
Q: mongodb select either both documents or none I am in situation where I have to update either two documents or none of them, how is it possible to implement such behavior with mongo?
// nodejs mongodb driver
Bus.update({
  "_id": { $in: [ObjectId("abc"), ObjectId("def")] },
  "seats": { $gt: 0 }
}, {
  $inc: { "seats": -1 }
}, { multi: true }, function(error, update) {
  assert(update.result.nModified === 2)
})

The problem with code above it will update even if only one bus matched. In my case I try to book ticket for bus in both directions and should fail if at least one of them already fully booked.
Thank you


text:
Q: AppRTC storing the audio locally I am using AppRTC which is a iOS wrapper of WebRTC,
I need to record the audio of the Video Call, so that we can play the audio later if needed.
I tried using AVAudioRecorder, but it only records the input of microphone (not the external speakers).
How to record the conversation to a audio file?


text:
Q: Html tags not working in new Gmail app (version-7.5.7.156101332.release) Just got a weird issue, same code was working fine with previous version but this recent gmail (version-7.5.7.156101332.release) update is not supporting Html tags.
Here is the code:
public static void sendMail(Activity activity){
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("text/html");
        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
        i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
        i.putExtra(Intent.EXTRA_TEXT   , Html.fromHtml("
Title
body of email
New line"));
        try {
            activity.startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(activity, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }
    }


text:
Q: Downlaod drawables from server to reduce APK file size To reduce the APK file size, I want to remove the drawables (images and XML files) from my project and download the proper ones from my server on the first app start.
The problem is how to load and use the downloaded drawables in my code?
This is what I found after some research:

*

*For normal images, I can use BitmapDrawable.

*For 9-patch images, I can use NinePatchDrawable.

But I still don't know how to load and use XML drawables that have references to other drawables, like this:
<layer-list>
  <item>
    <bitmap android:src="@drawable/other_drawable" />
  </item>
</layer-list>

Any thoughts on this or other effective ideas to reduce the APK file size would be appreciated.
Notes:

*

*The drawables make up most of the APK file size (20mb/25mb).

*I already compressed image files and I'm using ProGuard.

Update:
After some more research, it seems to me possible to load/use downloaded XML drawables after modifying them a little by using custom attributes for referenced drawables and a subclass of Drawable instead of native BitmapDrawable. So the above XML drawable example will become something like this:
<layer-list xmlns:custom="http://schemas.android.com/apk/res-auto">
  <item>
    <custom-bitmap custom:ref="other_drawable" />
  </item>
</layer-list>

Though, it's not a very easy solution and I'm not sure it's better than doing things manually.
References:

*

*https://groups.google.com/forum/#!topic/android-developers/glpdi0AdMzI

*https://code.google.com/p/adet/source/browse/trunk/AdetSample/res/drawable/svg_button.xml

A: XML Files and drawables are only to help developers, these are not the essential part of the programming in android. If you want to download from server you can do this.
what you have to do is Create Layouts and other things manually in Java files.
i-e
RelativeLayout rl =new Relativelayout(Context);// To create Layout
Button button = new Button(Context); // Create Components Like this
button.setText("abc");// Set Properties

Now add components to layout as a child.
rl.addView(button,new          Layoutparams(Layoutparams.WRAP_CONTENT,Layoutparams.WRAP_CONTENT));

In onCreate return this Layout!
For drawables include very important in your drawable and download others through HTTP Calls.
Hope it helps.

A: First of all, that size isn't too bad if your application have intense ui interaction. Also, in some moment the user will need download that drawables, why not in the installation from the google playstore?. Anyways, If you really want to do it, you can do the following:
For the reference in your layouts, you will need hook up from every widget that have a reference to a drawable and implement your own tag. For example, if you old layout looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ImageView
    android:id="@+id/someImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/somePicture" />

</RelativeLayout>

Now should look like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.custom"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.example.custom.RemoteImageView
    android:id="@+id/someImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    custom:remoteSrc="somePicture" />

</RelativeLayout>

Remember add the custom tag definition in your attrs.xml. In the implementation of the class you can get the image (if exist) from some cache like this:
public class RemoteImageView extends ImageView {

private String remoteSrc;
private DiskLruImageCache diskCache;

public RemoteImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public RemoteImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    diskCache = new DiskLruImageCache(this, "cache", 1024 * 1024 * 30, CompressFormat.PNG, 70);
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
            R.styleable.RemoteImageView, 0, 0);

    try {
        remoteSrc = a.getString(R.styleable.RemoteImageView_remoteSrc);
        Bitmap cachedImage;
        if (!diskCache.containsKey(remoteSrc)) {
            //Download it from Internet and save it into the cache
            //...
            diskCache.put(remoteSrc, bitmapThatYouDownload);
        }
        cachedImage = diskCache.getBitmap(remoteSrc);
        //Use the cachedImage as the bitmap for this view.
    } finally {
        a.recycle();
    }
}

public RemoteImageView(Context context) {
    super(context);
}

}

To see about DiskLruImageCache you can check this links:
DiskLruCache
You can do some tricks with this like have a two-levels cache, the first one with a memory cache and the second one with a disk cache. Already exist libraries that does stuff like this, but how you need your custom tags, you can either modify those libraries or use the cache library in your classes like I show you above.

For the AnimationDrawable's like animation-list you will need build the animation in runtime. For example like this:
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(new BitmapDrawable(getResources(),diskCache.get(myFirstFreame)), 100);
animation.addFrame(new BitmapDrawable(getResources(),diskCache.get(mySecondFrame)), 1000);
animation.addFrame(new BitmapDrawable(getResources(),diskCache.get(myThirdFrame)), 1000);
animation.setOneShot(false);

ImageView imageAnim =  (ImageView) findViewById(R.id.img);
imageAnim.setBackgroundDrawable(animation);

Remember check if myFirstFrame,mySecondFrame and myThirdFrame are already in the cache. If not then download them and add them.
Hope this help, but if I was you, I would keep that size, personally isn't so much, I've developed a tumblr client with a lot of animation and ui features, and the apk size was around 15 MiB.

A: I doubt if your drawable goes this much (20MB) here i mean to drawable is xml Files only.
Coz these can not be downloaded later, Have you properly optimize your code for Re-useability?
but you are free with the Images/raw's like audio files or something like this
My Suggestions
Note: If you are looking for downloadable xml drawables then answer is no it is not possible it must be withing apk and also you can follow the following to optimize

*

*You shall download All of your Audio/images and other files on installation cause this is the only solution to reduce the apk size

*You can't do anything with your xml Drawables you will have to have with apk so you shall optimize code as much as possible.

*For xml Drawable you can look for Re-useability

As your question says how to use Downloaded drawable to you code
so the answer is You can not go with xml drawable but yes you can do these things with images
and there is clear method of setting drawable from file or creating Bitmap from file

A: As per your requirement you can not change the xml drawables at runtime.
Other that if you still need this functionality you can download it on your application's splash screen and set it runtime as you have suggest using BitmapDrawable.
But as per my opinion this is not right way to use this, as when you create your activity that time your view already render on setContentView(layoutID). So when you call your activity it will display the blank views without images.
And from other resources i have read that you can not change the resources file like drawable, raw,strings at runtime as it's id's can't create on runtime.

A: You could use expansion files (see http://developer.android.com/google/play/expansion-files.html) and move your resources there using the jobb tool (http://developer.android.com/tools/help/jobb.html).
You would still have to handle unavailable resources as long as the expansion file has not been downloaded though.


text:
Q: How to solve java.lang.OutOfMemory exception in android? 02-22 23:37:03.349    1845-1845/com.vinay.vshotelapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.vinay.vshotelapplication, PID: 1845
    java.lang.OutOfMemoryError: Failed to allocate a 4801692 byte allocation with 1152928 free bytes and 1125KB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
            at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
            at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:973)
            at android.content.res.Resources.loadDrawableForCookie(Resources.java:2423)
            at android.content.res.Resources.loadDrawable(Resources.java:2330)
            at android.content.res.Resources.getDrawable(Resources.java:758)
            at android.graphics.drawable.AnimationDrawable.inflate(AnimationDrawable.java:319)
            at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1095)
            at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1017)
            at android.content.res.Resources.loadDrawableForCookie(Resources.java:2418)
            at android.content.res.Resources.loadDrawable(Resources.java:2330)
            at android.content.res.Resources.getDrawable(Resources.java:758)
            at android.content.Context.getDrawable(Context.java:402)
            at android.view.View.setBackgroundResource(View.java:16106)
            at com.vinay.vshotelapplication.VSHotelApplicationMainActivity.onCreate(VSHotelApplicationMainActivity.java:53)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-22 23:37:37.774    1845-1845/com.vinay.vshotelapplication I/Process﹕ Sending signal. PID: 1845 SIG: 9
02-22 23:39:58.136    2323-2323/com.vinay.vshotelapplication I/Process﹕ Sending signal. PID: 2323 SIG: 9

A: We need the code to see the exact Error Sorce, but i am guessing you have a really high Resolution pictures on your code. Had an equivalent error with a 5000*1419 picture, and reducing the resolution to 500*142, so 1/100 of the memory got free again.


text: Q: How to relate tables in mysql database I am building a mock question and answer site using mysql as my database. I have 3 tables. Questions, answers, and comments. My question is, how do I relate the comments table to the other two tables, as comments can exist for both.


text:
Q: In ASPxGridView from Devexpress, can I specify the colors in color edit column? I'm using ASPxGridView from Devexpress and I need color edit column but I need a specific colors in it, not all the colors.
Can I specify which colors I need to show in this color edit column?
If not, which control I have to use to get what I want? any suggestions?
Thanx

A: According to this:
http://www.devexpress.com/Support/Center/p/S33198.aspx
ASPxColorEdit doesn't support custom colors.
You could try something like this:
1.Take GridViewDataTextColumn and set its EditItemTemplate to your custom template (must implement System.Web.UI.ITemplate)
2.In your custom template use some other color picker component (farbtastic, jPicker, colorpicker)
3.Use chosen picker component to set GridViewDataTextColumn value in order to save it.


text:
Q: Click on bottom tab to prompt a modal using React Native Anyone know how to prompt a modal when press on the bottom tab? In React Native

A: You can add event listener for tabPress and trigger the modal from the event listener. Like this:
const [showModal, setShowModal] = React.useState(false);

React.useEffect(() => {
  const unsubscribe = navigation.addListener('tabPress', (e) => {
    // Prevent default behavior
    e.preventDefault();
    setShowModal(true);
  });

  return unsubscribe;
}, [navigation]);

and in your return part:
<Modal
  visible={showModal}
  onRequestClose={() => {
    setShowModal(false);
  }}
>
  {/* Your code */}
</Modal>

the e.preventDefault() is optional, if you want to prevent tabPress to navigate to another screen then to that, otherwise don't use it.