Q: mysql query using the wrong indexes I have some optimization problems with some of my queries in a mysql database. After I build my application I am trying to optimize using mysqltuner and explain, to find non indexed queries. This is a query that is running often and reports that is not using the index :
SELECT  count(*) AS rangedandselling
    FROM
      ( SELECT  DISTINCT `store_formats`.`Store Name`
            FROM  (`eds_sales`
                    JOIN  `store_formats`
                      ON (`eds_sales`.`Store Nbr` = `store_formats`.`Store Nbr`)
                  )
            WHERE  `eds_sales`.`Prime Item Nbr` = '4'
              AND  `eds_sales`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME)
                                          AND CAST('2016-07-21' AS DATETIME)
              AND  `store_formats`.`Format Name` IN ('format1','format2')
              AND  `store_formats`.`Store Name` IN (
                SELECT  DISTINCT `store_formats`.`Store Name`
                    FROM  (`eds_stock`
                            JOIN  `store_formats`
                              ON (`eds_stock`.`Store Nbr` = `store_formats`.`Store Nbr`)
                          )
                    WHERE  `eds_stock`.`Prime Item Nbr` = '4'
                      AND  `eds_stock`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME)
                                                  AND CAST('2016-07-21' AS DATETIME)
                      AND  `store_formats`.`Format Name` IN ('format1','format2')
                      AND  `eds_stock`.`Curr Traited Store/Item Comb.` = '1' )
      ) t

This is the explain output : https://tools.mariadb.org/ea/pyb3h
Although I have indexed the columns involved in the joins and lookups, it looks like it is picking another index. this other index is called uniqness, and is composed of 6 different columns in the source columns that I use for inserts (the combination of those columns is the only thing that makes a row unique, hence the name I gave.). I then made sure I have indexes for the other columns and I can see them in the explain. I am not sure why this happens, can someone help?
Any ideas on optimizing this query?
Here is the explain for those that the link above does not work :
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+---+---+---+---+---+---+---+---+---+---+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 167048 |  |
| 2 | DERIVED | eds_sales | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 4 | const | 23864 | Using where; Using index; Using temporary |
| 2 | DERIVED | store_formats | ref | Store Nbr,Store Name,Format Name | Store Nbr | 5 | equidata.eds_sales.Store Nbr | 1 | Using where |
| 2 | DERIVED | <subquery3> | eq_ref | distinct_key | distinct_key | 84 | func | 1 | Distinct |
| 3 | MATERIALIZED | store_formats | ALL | Store Nbr,Store Name,Format Name | NULL | NULL | NULL | 634 | Using where; Distinct |
| 3 | MATERIALIZED | eds_stock | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 8 | const,equidata.store_formats.Store Nbr | 7 | Using where; Distinct |
+---+---+---+---+---+---+---+---+---+---+

I am also posting the related tables structure :
--
-- Table structure for table `eds_sales`
--
CREATE TABLE `eds_sales` (
  `id` int(12) NOT NULL,
  `Prime Item Nbr` int(12) NOT NULL,
  `Prime Item Desc` varchar(255) NOT NULL,
  `Prime Size Desc` varchar(255) NOT NULL,
  `Variety` varchar(255) NOT NULL,
  `WHPK Qty` int(5) NOT NULL,
  `SUPPK Qty` int(5) NOT NULL,
  `Depot Nbr` int(5) NOT NULL,
  `Depot Name` varchar(255) NOT NULL,
  `Store Nbr` int(5) NOT NULL,
  `Store Name` varchar(255) NOT NULL,
  `EPOS Quantity` int(5) NOT NULL,
  `EPOS Sales` float(4,2) NOT NULL,
  `Date` date NOT NULL,
  `Client` varchar(255) NOT NULL,
  `Retailer` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `eds_sales`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Prime Item Desc`,`Prime Size Desc`,`Variety`,`WHPK Qty`,`SUPPK Qty`,`Depot Nbr`,`Depot Name`,`Store Nbr`,`Store Name`,`Date`,`Client`) USING BTREE,
  ADD KEY `Prime Item Nbr` (`Prime Item Nbr`),
  ADD KEY `Store Nbr` (`Store Nbr`);

Table structure for table eds_stock
CREATE TABLE `eds_stock` (
  `Prime Item Nbr` int(12) NOT NULL,
  `Prime Item Desc` varchar(255) NOT NULL,
  `Prime Size Desc` varchar(255) NOT NULL,
  `Variety` varchar(255) NOT NULL,
  `Curr Valid Store/Item Comb.` int(12) NOT NULL,
  `Curr Traited Store/Item Comb.` int(12) NOT NULL,
  `Store Nbr` int(12) NOT NULL,
  `Store Name` varchar(255) NOT NULL,
  `Curr Str On Hand Qty` int(12) NOT NULL,
  `Curr Str In Transit Qty` int(12) NOT NULL,
  `Curr Str On Order Qty` int(12) NOT NULL,
  `Curr Str In Depot Qty` int(12) NOT NULL,
  `Curr Instock %` int(12) NOT NULL,
  `Max Shelf Qty` int(12) NOT NULL,
  `On Hand Qty` int(12) NOT NULL,
  `Date` date NOT NULL,
  `Client` varchar(255) NOT NULL,
  `Retailer` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `eds_stock`
  ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Store Nbr`,`Date`,`Client`,`Retailer`),
  ADD KEY `Prime Item Nbr` (`Prime Item Nbr`),
  ADD KEY `Store Nbr` (`Store Nbr`),
  ADD KEY `Curr Valid Store/Item Comb.` (`Curr Valid Store/Item Comb.`);

Table structure for table store_formats
CREATE TABLE `store_formats` (
  `id` int(12) NOT NULL,
  `Store Nbr` int(4) DEFAULT NULL,
  `Store Name` varchar(27) DEFAULT NULL,
  `City` varchar(19) DEFAULT NULL,
  `Post Code` varchar(9) DEFAULT NULL,
  `Region #` int(2) DEFAULT NULL,
  `Region Name` varchar(10) DEFAULT NULL,
  `Distr #` int(3) DEFAULT NULL,
  `Dist Name` varchar(26) DEFAULT NULL,
  `Square Footage` varchar(7) DEFAULT NULL,
  `Format` int(1) DEFAULT NULL,
  `Format Name` varchar(23) DEFAULT NULL,
  `Store Type` varchar(20) DEFAULT NULL,
  `TV Region` varchar(12) DEFAULT NULL,
  `Pharmacy` varchar(3) DEFAULT NULL,
  `Optician` varchar(3) DEFAULT NULL,
  `Home Shopping` varchar(3) DEFAULT NULL,
  `Retailer` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `store_formats`
  ADD PRIMARY KEY (`id`),
  ADD KEY `Store Nbr` (`Store Nbr`),
  ADD KEY `Store Name` (`Store Name`),
  ADD KEY `Format Name` (`Format Name`);

A: CAST('2016-07-14' AS DATETIME) -- the CAST is not needed; '2016-07-14' works fine.  (Especially since you are comparing against a DATE.)
IN ( SELECT ... ) is inefficient.  Change to a JOIN.
On eds_stock, instead of
INDEX(`Prime Item Nbr`)

have these two:
INDEX(`Prime Item Nbr`, `Date`)
INDEX(`Prime Item Nbr`, `Curr Traited Store/Item Comb.`, `Date`)

INT is always a 4-byte number, even if you say int(2).  Consider switching to TINYINT UNSIGNED (and other sizes of INT).
float(4,2) -- Do not use (m,n); it causes an extra rounding and my cause undesired truncation.  Either use DECIMAL(4,2) (for money), or plain FLOAT.
Bug??  Did you really want 8 days, not just a week in
AND `Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME)

I like this pattern:
AND `Date` >= '2016-07-14'
AND `Date`  < '2016-07-14' + INTERVAL 1 WEEK

Instead of two selects
SELECT  count(*) AS rangedandselling
    FROM ( SELECT  DISTINCT `store_formats`.`Store Name` ...

One select will probably work (and be faster):
SELECT COUNT(DISTINCT `store_formats`.`Store Name`) AS rangedandselling ...

Once you have cleaned up most of that, we can get back to your question about 'wrong index', if there is still an issue.  (Please start a new Question if you need further help.)


Q: Django: Form submission in ajax style without csrf token I am new to django. Suppose I have a form and I would like to submit a file to the server in ajax.
I notice that the server has HTTP 403 error when I don't specify the csrf token in the post statement (correct behaviour), but somehow the file can still be able to upload to the server...
Here is my sample code:
models.py (include model and form):
from django.db import models
from django.forms import ModelForm

# Create your models here.
class Dummy(models.Model):
    myfile = models.FileField(upload_to='temp')

class DummyForm(ModelForm):
    class Meta:
        model = Dummy
        fields = ['myfile',]

views.py:
# Create your views here.
class TestFormView(View):
def get(self, request):
    form = DummyForm()

    context = { 'form' : form }
    print form
    return render(request, 'testform.html', context)

def post(self, request):
    print request.FILES
    form = DummyForm(request.POST, request.FILES)
    print form.is_valid()
    print form.errors
    print form.is_bound
    if form.is_valid():
        form.save()

    print Dummy.objects.all().count()
    return render(request, 'testform.html')

testform.html:
<form id="myForm" action="testform/" method="post" enctype="multipart/form-data">
{% csrf_token %}
 <input id="id_myfile" type="file" size="60" name="myfile">
 <input type="submit" value="Ajax File Upload">
</form>

0%

Of course if I put the csrf token in the $post function, I get HTTP 200.
My concern is that will this create security hole because it looks like anyone can upload files to the server?
Thanks!


Q: Making Mac shortcuts (e.g. Cmd-C) work on linux Is there a way to map Cmd+C to Copy in linux? (instead of Ctrl+C)
Would be nice if I could also have the emacs style ones, like Ctrl+B to move left by one character.

A:
Is there a way, on Linux/X, to map certain key combos to other key combos?

In the tradition of all open source projects, there's not a way, there are several.  At the lowest level you've got kernel keybindings, which is probably not what you want.  At the X server level you've got xkb with its myriad utilities.  And then it seems that every window manager - gnome, kde, xfce or other - also has a keymapping utility.   xkb seems to have lots of utils and such around it, and is likely more complete than any random window manager's keymapping utils, so I'd look at that first.

A: KDE 3 is probably the most flexible here; there's a pre-defined keyboard shortcut scheme named "Mac Scheme".  You can set it through KControl Control Center > Regional & Accessibility > Keyboard Shortcuts or kcmshell keys and it will have effect on almost all KDE applications immediately.  You might miss some of those Emacs-like "Ctrl-*" shortcuts that OS X has, but that aside, it works well (as long as your X modifiers are mapped correctly).  And if it's not to your liking, it's easily customizable.
You can also set Control Center > Desktop > Behavior to enable a Mac OS-like menubar; all KDE applications will then share a menubar at the top of the screen instead of being individually attached to each window.

A: Update 02/03/2020
Kinto has now been rewritten in C for Ubuntu/Debian systems using x11. It also uses json config files, making it easier to manage and extend to other applications than just terminals. The app no longer maps to Super in the Terminal apps, it will now properly map to Ctrl+Shift to create the exact same feel as having a Cmd key.
Please checkout the latest release.
https://github.com/rbreaves/kinto
The main change to allow for the Super = Ctrl+Shift change is in this symbols file.
default partial xkb_symbols "mac_levelssym" {
    key <LWIN> {
      repeat= no,
      type= "ONE_LEVEL",
      symbols[Group1]= [ Hyper_L ],
      actions[group1]=[ SetMods(modifiers=Shift+Control) ]
    };
    key <RWIN> {
      repeat= no,
      type= "ONE_LEVEL",
      symbols[Group1]= [ Hyper_R ],
      actions[group1]=[ SetMods(modifiers=Shift+Control) ]
    };
};

Pjz's answer is correct in saying that an xkb solution would be ideal, sadly few have taken that route, most likely due to the difficulty of learning xkb and it seems many have gone the route of using Xmodmap files which is being deprecated while we are on our way to Wayland.
This answer may be several years too late, but here it is any ways.
Kinto is a tool I recently created that will address this problem and does so by using xkb and by listening to what app you are currently using, as it also changes the keymap while using terminals so the mac like experience can be consistent.
https://github.com/rbreaves/kinto
https://medium.com/@benreaves/kinto-a-mac-inspired-keyboard-mapping-for-linux-58f731817c0
Here's a Gist as well, if you just want to see what is at the heart of it all, it will not alternate your keymap when needed though. The Gist also does not include custom xkb keymap files that setup macOS style cursors/word-wise manipulations that use Cmd and the arrow keys.
https://gist.github.com/rbreaves/f4cf8a991eaeea893999964f5e83eebb
Edit: Posting the contents of the gist as well. I cannot realistically post the contents of Kinto.
# permanent apple keyboard keyswap
echo "options hid_apple swap_opt_cmd=1" | sudo tee -a /etc/modprobe.d/hid_apple.conf
update-initramfs -u -k all

# Temporary & instant apple keyboard keyswap
echo '1' | sudo tee -a /sys/module/hid_apple/parameters/swap_opt_cmd

# Windows and Mac keyboards - GUI (Physical Alt is Ctrl, Physical Super is Alt, Physical Ctrl is Super)
setxkbmap -option;setxkbmap -option altwin:ctrl_alt_win

# Windows and Mac keyboards - Terminal Apps (Physical Alt is Super, Physical Super is Alt, Physical Ctrl is Ctrl)
setxkbmap -option;setxkbmap -option altwin:swap_alt_win

#
# If you want a systemd service and bash script to help toggle between
# GUI and Terminal applications then look at project Kinto.
# https://github.com/rbreaves/kinto
#
# Note: The above may not work for Chromebooks running Linux, please look
# at project Kinto for that.
#
# If anyone would like to contribute to the project then please do!
#

A: You'll get almost all of the way there if you switch Cmd and Ctrl

A: xmodmap -e "keycode 63 = Control_L"
That way Cmd will be Control. No other keys will be swapped
Edited: I forgot the "-e"


Q: TBB error when compiling I have the following piece of code that i am trying to execute
#include <iostream>
#include <cstring>
#include "tbb/tbb.h"

using namespace std;
using namespace tbb;

class Accumulate{
    float& arr;
    float* src;

    public:
    Accumulate(float& _arr, float* _src)
    :arr(_arr), src(_src){}
    void operator() (int i) const{
        arr += src[i];
    }

};

int main(int argc, const char * argv[]) {
    float arr[4] = {1,3,9,27};
    float sum = 0;
    parallel_for(0, 4, Accumulate(sum, arr));
    cout<< sum << endl;
}

I am trying to make use of parllel_for to calculate the sum and this requires the tbb library. I downloaded the source tbb directory and pasted it in my xcode project directory.
When i try to compile the above code, i seem to get the following error
'tbb/internal/_flow_graph_types_impl.h' file not found
I am not sure what i am missing, please advise

A: I can see this file in TBB repo: https://github.com/01org/tbb/blob/tbb_2017/include/tbb/internal/_flow_graph_types_impl.h
Please make sure that your installation of TBB is not damaged.
Off-topic advice, there is a data-race in your program on sum and you can use lambda instead of explicit functor:
int main(int argc, const char * argv[]) {
    float arr[4] = {1,3,9,27};
    atomic<float> sum = 0; // fixing data-race. Still, it's not recommended way
    parallel_for(0, 4, [&](int i){
        sum += arr[i];
    });
    cout<< sum << endl;
}

See also tbb::parallel_reduce in order to make this code correct, clean, and efficient.


Q: UIViewControllers not receiving orientation notifications I've spent the last hour or so trying to work out why not all my UIViewControllers are receiving orientation change notifications.
I've got a subclassed UIViewController attached to the window, that internally creates a few other UIViewControllers to manage smaller portions of the screen which are re-used elsewhere in the application I'm building.
The problem is, only the UIViewController attached to the window is receiving the orientation change notifications.
The other UIViewControllers aren't firing their - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration methods.
I'm assuming it's expected behaviour, and I can't seem to find anything mentioning it in the docs.
Is there a way to make sure all active UIViewControllers are getting orientation changes? Or does the parent view controller have to tell it's children when changes are occurring?
Cheers.

A: Are all your view controllers returning YES to shouldAutorotateToInterfaceOrientation: ? If so, I suggest to pass the interface orientation messages from the parent to the children viewControllers, as you suggested.
I have been doing so before and had no problems with that approach so far.


Q: applying a class to a div I have a css which has some attribute as follows:
.ts{
    background-image: url("images/xyz/pb.gif");
    background-repeat: no-repeat;
    padding:0,0,0,20px;
    display:none;
}

.ts.visible{
    display: inline;
}

Now i want to apply the this style to a div in my html page.How cna i do it.I dont know css

A: Yep, what they said. Also, if you want to assign more than one class, use a space to separate them, like so:
.
Edit:
Also, use spaces to separate the "padding" values, like this: padding: 0 0 0 20px;, or just use padding-left: 20px;.

A: You can use it like this:
...

But I strongly recommend you take a look at css here, it's not that hard.

A: Just give that
 a class attribute, like this:

If you want it to have both classes, use a space between like this:

A: You'd simply do:

Contents of div

That said, I very much suspect that's not the answer you're looking for. :-)


Q: Storing similar objects in a database I am developing an a house renting/selling application, it will allow users to post rental and houses on sale. My concern is the two objects have some similar and different attributes,for example here is a house on rent can have the following attributes `
public class RentalHouse extends Property{

private int numOfBedrooms;
private int payMonthsInAdvance;
private double securityDeposit;
private double rentals;
private String dayOfVacancy;

}

Whilst a house on sale can have the following attributes
public class SaleHouse extends Property{

private int numOfBedrooms;
private double price;

}

public class Property {

private long id;
private String title;
private String description;
private ArrayList<String> images;
private String province;
private String area;

}

Now here is my question; is it good design to have 2 tables for one for rental houses the other for houses on sale? and what would you advice?


Q: What partition key to choose in cosmos db with little data and one customer per database? We’re developing a personnel management system based on blazor and Cosmos DB serverless. There will be one customer per database and around 30 “docTypes”. The biggest categories by number and data volume are "users" and "employees". When we query we get all data of users and employee at once. So it can be several thousand. The other doctypes are much smaller an less frequently queried.
The volume of data per customer will not exceed 5 GByte. The most frequent queries are to 3 docTypes.
Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key?
thanks

A: Based on the information you supplied it sound like docType is a good property to use as partition key, since it can be used to avoid cross partition queries. Especially since you state this will be often be used in your queries. With the max size you stated it will also be unlikely to cause you issues as a single partition can contain up to 20GB of data.
One thing to watch out for is Hot Partitioning. You state that your users partition might be a lot bigger than others. That can result into one partition doing all of the lifting while the others sit mostly idle which results and causing inefficiëncy of your total throughput.
On the other side it won't really matter for your use case. Since none of the databases will exceed that 5GB you'll always stay within a single partition, but it's always good though to think about it beforehand; As situations may change and you end up with a database that does split into partitions.
Lastly I would never use a single partition for all data. It has no benefits. If you have no properties that could serve as partition key then id is the better choice (so a logical partition per document). It won't hit storage limitations and evenly distributes throughput between partitions.

A: I would highly recommend you first take a look at this segment of the Data Modelling & Partitioning presentation by Thomas Weiss, Cosmos DB program manager. In my view it's one of the best resources to understand how to think about partitioning.
Do agree with David Makogon that you didn't provide enough data. For instance, we know there are 30 doc types per single database - given cosmosdb database uses containers, I actually expect each docType to have its own container - contrary to what you wrote:

Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key?

Which suggests you want to use a single container for all your data. I wouldn't keep users and employees as documents in the same container. They are separate domains and deserve their own container.
See Azure docs page on Partition Strategy and subsequent paragraph about access patterns. The recommendation is to:

Choose a partition key that enables access patterns to be evenly spread across logical partitions.

In the access patterns section, the good practice mentioned is to separate data into hot, medium and cold data and place it into their own containers. One caveat is, that according to this page the max number of containers per database with shared throughput is 25.
If that is not possible, and all data has to end up in a single container, then docType seems to be the right partition key, because your queries will get data by docType if I understood correctly.
As 404 wrote, you want to avoid Hot Partitioning i.e. jamming most of documents in a container into a single or a few logical partitions. Therefore you want to choose a partition key based on most frequent operations.


Q: MethodNotAllowedHttpException laravel 4.2 error here is my ContactController.php:
public function destroy($id){
    $contact = Contact::find($id);
    $contact->delete();
    return Redirect::to('http://localhost:8000/contactsview');
}

Here is my rountes.php
Route::delete('/contactsview/destroy/{id}', array('uses'=>'ContactController@destroy'));

Here is my index.blade.php:
{{ Form::open(array('url'=>'/contactsview/delete/'.$contact->id, 'method'=>'DELETE', 'style'=>'display:inline;')) }}
<!-- {{ Form::hidden('id', $contact->id) }} -->
{{ Form::submit('Delete') }}
{{ Form::close() }}

What did I do wrong?

A: Try the form with this instead, passing in the $contact->id as a param rather than directly in the URL:
{{ Form::open(array('method' => 'DELETE', 'action' => array('ContactController@destroy', $contact->id )) }}


Q: java Opencv unsatisfiedLinkError, native Library is loaded I am trying to run some program on opencv, but I am getting this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError:
org.opencv.objdetect.CascadeClassifier.CascadeClassifier_0(Ljava/lang/String;)J

I have already loaded the library, libopencv_java310.so by using this code:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

I have also added the path to the native library.
I have searched a lot on the internet, but the only reason this error comes, is due to native library is not loaded. What could be the other reason of getting this error.
Can anyone help....!  Any help will be appreciated.

A: you might move your System.loadLibrary(Core.NATIVE_LIBRARY_NAME); to a static block so the dll gets loaded before any instruction of opencv .


Q: xmlns required for bean component of spring-servlet.xml for spring security application How to determine what xmlns are required for beans component of my spring-servlet.xml(spring configuration file) for spring security application?
Is this is the correct code?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

...

</beans>

A: I got my answer in the spring framework reference and that is mention below:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
...
</beans>

In general it should be like this. for reference Spring Security 3.0 Reference


Q: Embed a Mobile Emulator on a Website? I'm basically wondering if it was possible to create a functionality similar to this site: http://www.howtogomo.com/en/#gomo-meter
I want to add some kind of feature on my website that will allow visitors to check to see how their websites looked on a mobile device like an iPhone or Android phone.

A: You could fire up the android emulator from the android sdk , then using android debugging bridge fire up the following command
adb shell
am start -a android.intent.action.VIEW -d http://stackoverflow.com
then follow the following blog
http://android.amberfog.com/?p=168 , to take screen shot .

A: No. It looks like this site renders the website on the server side, and then sends down an image of this to your browser.
If you are interested only in Android and iPhone (and similar smartphones with browsers based on webkit) then you could try a similar approach to http://iphonetester.com. This uses a frame embedded to simulate the size (in pixels) of an iPhone. Note, that even though these browsers may be based on webkit, it doesn't mean their implementation is the same - see http://www.quirksmode.org/webkit.html for variance across different webkit based browsers.
This won't work if you want to stray to other non webkit based browsers.


Q: Creating artificial data out of data that only contains sentences I am trying to create artificial data. However my current data only contains sentences.
Two example rows that I have are the following:

Your order is on its way with tracking {imaginary tracking code}. Visit {imaginary random link} for more information.

The package has been shipped out with tracking {imaginary tracking code}. Visit {imaginary random link} for more information.

Now what I want to do is basically take these sentences and create thousands of them but with randomized tracking codes. I thought about splitting the sentences at two at the tracking code but couldn't figure out a way to split them at the specific tracking code. Like most tracking codes they contains numbers but also sometimes letters(usually at the front).
My current method which is bad would be to split the sentence into words. then check each word if it contains numbers. If it does contain a number that is the tracking code and now I have my way of creating artificial version of that sentence by taking everything before the tracking code inserting my artificial tracking code and everything after the tracking code. Repeating this for every row in the dataset and then randomizing the dataset.
So my question is, is there a more optimal way?

A: I suggest that you use regex to identify the codes to replace with random codes.
This example is deliberately simplified, I have used static codes and not randomly generated one and the regex pattern needs to be defined and refined.
import re
sentences = ('Your order is on its way with tracking 1234567890. Visit 98765432 for more information.',
'The package has been shipped out with tracking 1245789865. Visit 65659865 for more information.')

code1='9999999999'
code2='11111111'

for x in sentences:
  y = re.findall(r'(\D*)\d+(\D*)\d+(\D*)' ,x)
  if y[0][2]:
    z = y[0][0] + code1 + y[0][1] + code2 + y[0][2]
    print(z)

output
Your order is on its way with tracking 9999999999. Visit 11111111 for more information.
The package has been shipped out with tracking 9999999999. Visit 11111111 for more information.


Q: Java Firestore query snapshot returning string rather than boolean I am trying to map my query results from firestore back to a class in my java application.
I have saved this as a Boolean on the web console, see the image:

And then on the app I use the following function to map this to my class:
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        List<uk.wefix.FirestoreModels.Job> mJobsList = new ArrayList<>();
        if(task.isSuccessful()){
            for(QueryDocumentSnapshot document : task.getResult()) {
                uk.wefix.FirestoreModels.Job job = document.toObject(uk.wefix.FirestoreModels.Job.class);
                mJobsList.add(job);
            }
            mjobsAdaptor.clear();
            mjobsAdaptor.addAll(mJobsList);
        } else {
            Log.d("JobsFragment", "Error getting documents: ", task.getException());
        }
    }
});

And the class it maps to:
public class Job {

    public String first_name;
    public String second_name;
    public String phone_number;
    public Boolean complete;

    public Job() {}

    public Job(String first_name, String second_name, String phone_number, Boolean complete) {
        this.first_name = first_name;
        this.second_name = second_name;
        this.phone_number = phone_number;
        this.complete = complete;
    }

    /**
     * @return String
     */
    public String getFirst_name(){
        return first_name;
    }

    /**
     * @return String
     */
    public String getSecond_name(){
        return second_name;
    }

    /**
     * @return String
     */
    public String getPhone_number(){
        return phone_number;
    }

    /**
     * @return Boolean
     */
    public Boolean getComplete(){
        return complete;
    }
}

It seems like Firestore is returning a String instead of a Boolean which means I get the following error out:
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.String to boolean (found in field 'complete')

Obviously I could just do something like this in the Job class, but that seems a bit hacky and I am not sure if this is just a bug or if I am doing something wrong.
Potential 'hacky' solution
/**
 * @return Boolean
 */
public Boolean getComplete(){
    if(complete.equals("true")){
        return true;
    }else{
        return false;
    }
}

Query:
CollectionReference jobs = db.collection("jobs");
Query query = jobs.whereEqualTo("technician_id", 10).whereEqualTo("date", "2018-12-12");


Q: Program or script to see hex triplets in their actual color I've got a theme file that looks like following:
PRIMARY1_COLOR=#7CACDF
PRIMARY2_COLOR=#A5C6E9
PRIMARY3_COLOR=#E2EDF8
SECONDARY1_COLOR=#7CACDF
SECONDARY2_COLOR=#A5C6E9
SECONDARY3_COLOR=#B9D3EE

Is there any tool which allows editing such file while displaying actual colors?

A: You can use Geany. It has "Color chooser" button - select your hex code and click on it and you will see the color and will be able to change it.

A: You can create an HTML file with your favorite text editor and simply load it up your browser. Try this:

PRIMARY1

PRIMARY2

...

You can even automatically generate this with some clever find & replace or Excel formulas.


Q: Duplicate code but make the copied slower I build the shooting game by C# and Unity.
I use GameController and GameStatus to show the score and time.
At first scene, I have no problem. It can run smoothly.
But the second scene, I copy scene from first and make new GameController for second scene.
It's work but running game slower.
I try to make new project by using same code, but it's slow even it's my first scene.
I don't know cause of this happen.
Below is my code, it's work.
using UnityEngine;
using System.Collections;

public class MyGameController2 : MonoBehaviour

    private Gun gun;

    public GUISkin mySkin2;

    private GameStatus gameStatus;

    public float countDownTime2;
    private float scoreTime2;
    private float menuTime2;
    // Use this for initialization
    void Start () {
        countDownTime2 = 60.0f;
        scoreTime2 = countDownTime2+3;
        menuTime2 = countDownTime2+5;
        gameStatus = (GameStatus)GetComponent(typeof(GameStatus));
    }
        // Update is called once per frame
    void Update () {
        countDownTime2 -= Time.deltaTime;
        if(gameStatus.score >= 300){Application.LoadLevel("MainScene2");}
        if(countDownTime2 <= 0.0f)
        {gameStatus.isGameOver = true;
        countDownTime2 = 0.0f;
        gameStatus.score +=0;
        }
        scoreTime2 -= Time.deltaTime;
        menuTime2 -= Time.deltaTime;

    }

    void OnGUI()
    {
        float sw = Screen.width;
        float sh = Screen.height;
        GUI.skin = mySkin2;
        int mScore = gameStatus.score;
        if(countDownTime2 > 0.0f){
        GUI.Label (new Rect(50,0,sw/2,sh/2), "Score : " + mScore.ToString(),"scoreStyle");
        GUI.Label (new Rect(400,0,0,0), "Time : " + countDownTime2.ToString("000") ,"timeStyle");
        }
        if(gameStatus.isGameOver)
        {GUI.Label (new Rect(120,100,sw/2,sh/4),"Game Over","messageStyle");}

        if (scoreTime2 <= 0.0f)
        {
        GUI.Label (new Rect(130,50,0,0), "Your Score is " + mScore.ToString(),"scoreStyle2");
        }

        if(menuTime2 <= 0.0f){
        // Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
        if(GUI.Button(new Rect(100,220,80,20), "Retry")) {
            Application.LoadLevel("MainScene");}

        if(GUI.Button(new Rect(300,220,80,20), "Menu")) {
            Application.LoadLevel("TitleScene");}
        }
    }
}


Q: EF5 Code First Many to Many with Migrations I have done this before, but for some reason cannot get it to work in EF5.
Usually it just automatically picks up when I have many to many relationships like this one...
public class Beer
{
    public int Id { get; set; }
    public virtual ICollection<Restaurant> Restaurants { get; set; }
}

public class Restaurant
{
    public int Id { get; set; }
    public virtual ICollection<Beer> Beers { get; set; }
}

I am wanting a RestaurantsBeers table or whatever with just RestaurantId and BeerId.
When I create it using the normal Code First way by just running the application it works.

Using migrations though, it won't create that table.

I ran Enable-Migrations then Add-Migration FirstDb and finally Update-Database... No dice...
Also tried this...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Beer>()
            .HasMany(b => b.Restaurants)
            .WithMany(a => a.Beers)
            .Map(m => m.MapLeftKey("BeerId")
                          .MapRightKey("RestaurantId")
                          .ToTable("BeersRestaurants"));
    }

A: Migrations to create a new M2M relationship are not supported yet in EF5.0RC per my experience trying to track down the same issue.  Thus why it will work on standard DB creation but doesn't work with Migration features.  You can export the create SQL from the standard code first database initialization and run it manually on the migration for now.
This should be resolved when EF5.0 goes RTM but for now we have to wait it out.


Q: Select multiple checkboxes using angularjs but unable to get selected one I am trying to get the list of selected checkboxes using angularjs. But unable to get selected.
HTML code Here

        <input type="checkbox" id="product_{{x.id}}"  class="form-control" ng-model="x.Selected">

        {{ x.category_name }}

script code:
.controller('categorieCtrl', function($scope, $http) {
   $scope.result = [{
            id: 1,
            category_name: 'Apple',
            Selected: false
        }, {
            id: 2,
            category_name: 'Mango',
            Selected: false
        }, {
            id: 3,
            category_name: 'Orange',
            Selected: false
        }];

 $scope.myFunc = function () {
     debugger;
     var message = "";
            for (var i = 0; i < 3; i++) {
                if ($scope.result[i].Selected) {
                    var id = $scope.result[i].id;
                    var categoryName =  $scope.result[i].category_name;
                    message += "Value: " + id + " Text: " + categoryName + "\n";
                }
            }
        alert(message);
    };
});

In the above code i am not getting selected items. Please let me know how can i get selected items using angularjs.

A:
  I've created a plunkr with your code here and it is working fine. I suppose you are not calling myFunc() correctly.
And also instead of using
for (var i = 0; i < 3; i++) {
  if ($scope.result[i].Selected) {
      ...
  }
}

You can make use of angular.forEach which will give you the object directly
angular.forEach(($scope.result, function(result, index){
  if (result.selected){
     ...
 });


Q: Flash light not detected I am trying to write an app which turns on flash light when a button is pressed. The problem is the app is not detecting flash light on my phone. I have searched alot on internet. Sure others have faced the problem, I have also applied those solutions but they don't seem to work. I don't know what is causing this problem. Posting the code here:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting_point);

    if(! getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) // checking if flash light is available inn android phone
    {
        Toast.makeText(StartingPoint.this, "Sorry this app can't work without flash light", Toast.LENGTH_LONG).show();
        finish();
    }

    cam = Camera.open();

    param = cam.getParameters();

}

@Override
public void onClick (View v)
{
      if(!flashOn)
        {
            i=0;

            flashOn=true;

            param.setFlashMode(Parameters.FLASH_MODE_TORCH);
            cam.setParameters(param);
            cam.startPreview();
        }
        else{
                i=0;

                flashOn=false;

                param.setFlashMode(Parameters.FLASH_MODE_OFF);
                cam.setParameters(param);
                cam.stopPreview();
            }

}
I have added these permissions in Android Manifest as well.
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />

Regards

A: I have an app that checks the flashlight feature and it works fine. Here is the code I used for checking if the user has the light:
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
    new AlertDialog.Builder(this)
    .setTitle("Sorry")
    .setMessage("It appears that your device is incompatible with this app. Sorry for the inconvenience.")
    .setNeutralButton("Close", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            finish();
        }
    }).show();
    return;
}

Now to actually make the light work, I made a toggle button and wrote the following code:
private boolean isLightOn = false;
private Camera camera;
private ToggleButton button;
public Vibrator v;

if (camera == null) {
    camera = Camera.open();
}

final Parameters p = camera.getParameters();

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        if (isLightOn) {

        Toast.makeText(context, "Light off!", Toast.LENGTH_SHORT).show();
        v.vibrate(40);
        p.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(p);
        camera.stopPreview();
        isLightOn = false;

        } else {

            Toast.makeText(context, "Light on!", Toast.LENGTH_SHORT).show();
        v.vibrate(40);
        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(p);
        camera.startPreview();
        isLightOn = true;

        }

    }
});

And finally, here are the only permissions I used:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

Note: All of the above code is in the onCreate method of my activity.
Hope this helps solve your problem!

A: I think you aren't setting your params again:
I used this to check if there is a flashlight:
public static Boolean hasFlashLight(Context context){
    return context.getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

and to turn it off and on:
Parameters params = mCamera.getParameters();
if (!isFlashlightOn) {
    params.setFlashMode(Parameters.FLASH_MODE_OFF);
} else {
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
mCamera.setParameters(params);

Let me know if it works for you too.

A: I had the same problem. Use this
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
  //Flash ok
  Parameters params = mCamera.getParameters();
  params.setFlashMode(Parameters.FLASH_MODE_TORCH);
} else {
  //Flash not supported
}

to determinate if your device has flash.

A: Some cameras need surface holder, otherwise they block the flash.
SurfaceView preview = (SurfaceView) findViewById(...);
SurfaceHolder holder = preview.getHolder();
holder.addCallback(this);
Camera camera = Camera.open();
camera.setPreviewDisplay(holder);


Q: Kafka 0.10.1.0 Test Server: Request METADATA failed I'm getting basic errors after setting up a super simple single-instance Kafka VM. This is for tiny volume development testing.
This is using the latest Confluent Platform 3.1.1 which includes the almost latest Kafka 0.10.1.0.
FYI, a slightly newer bug patch Kafka 0.10.1.1 is out, but the next post 3.1.1 Confluent Platform binary that includes that isn't available quite yet.
I configure /etc/kafka/server.properties with (I'm using a static local IP for dev testing simplicity):
listeners=PLAINTEXT://192.168.50.20:9092
advertised.listeners=PLAINTEXT://192.168.50.20:9092

(is that right?)
Simple console admin commands are generating errors. This leads me to believe that there is something wrong with the basic setup/configuration.
~$ /usr/bin/kafka-consumer-groups --new-consumer --bootstrap-server localhost:9092 --list
Error while executing consumer group command Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null))
java.lang.RuntimeException: Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null))
    at kafka.admin.AdminClient.sendAnyNode(AdminClient.scala:67)
    at kafka.admin.AdminClient.findAllBrokers(AdminClient.scala:87)
    at kafka.admin.AdminClient.listAllGroups(AdminClient.scala:96)
    at kafka.admin.AdminClient.listAllGroupsFlattened(AdminClient.scala:117)
    at kafka.admin.AdminClient.listAllConsumerGroupsFlattened(AdminClient.scala:121)
    at kafka.admin.ConsumerGroupCommand$KafkaConsumerGroupService.list(ConsumerGroupCommand.scala:304)
    at kafka.admin.ConsumerGroupCommand$.main(ConsumerGroupCommand.scala:66)
    at kafka.admin.ConsumerGroupCommand.main(ConsumerGroupCommand.scala)

EDIT: The problem, thanks to Gondola_Ride, was that I specified the IP in listeners in server.properties. I could connect via that IP, but not via localhost. The solution was to use host 0.0.0.0 which is Kafka's convention for binding to all local TCP interfaces:
listeners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://192.168.50.20:9092

A: Try adding an entry in the /etc/hosts on the host where you are running this command for this host 192.168.50.20 and see if it works
Something like
127.0.0.1       localhost.localdomain localhost
OR
192.168.50.20  hostname hostname-alias
Then try using it in the command
OR
Try using ip address directly in the command instead of localhost


Q: Google maps api and geolocation, Javascript and Html Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
     var map;
  var infowindow;

  function initialize() {

    if (navigator.geolocation)
   {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
    function showPosition(position)
    {

    var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );

    map = new google.maps.Map(document.getElementById('map'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlon,
      zoom: 15,
      disableDefaultUI: true
    });

    var request = {
      location: latlon,
      radius: 555,
      types: ['bar']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
     }
    }
   }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      alert(place.name);
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);

Working code
 var map;
  var infowindow;

  function initialize() {
    var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);

    map = new google.maps.Map(document.getElementById('map'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlon,
      zoom: 15,
      disableDefaultUI: true
    });

    var request = {
      location: latlon,
      radius: 555,
      types: ['bar']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      alert(place.name);
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);

Any help if appreciated :)

A: Replace your line:
var latlon = new google.maps.LatLng
      (position.coords.latitude + "," + position.coords.longitude);

with
var latlon = new google.maps.LatLng
      (position.coords.latitude, position.coords.longitude);

The problem is in concatenating two values into one where constructor expects two parameters.


Q: Try/Catch with while loop can't work Problem

*

*Method asks user for an integer value.

*Pass the value into a loop to ensure it is a positive number.

*Add a in.nextline to ensure the value don't overrun into next line of code. -

*Return integer value.
private static int getIntFromUser(String aa) {

int aaa = 0;
 while (true && aaa <= 0) {
     try {
         System.out.println(aa + ": ");
         aaa = in.nextInt();
             if (aaa <= 0) {
                 System.out.println("Please enter a positive number.");
             }
         } catch (Exception e) {
         System.out.println("Please enter an integer: ");

 in.next();
         }
 }
 in.next();
 return aaa;
}

Question
Try/Catch with while loop can't work ?

A: Tested it myself, it returns aaa properly (after removing in.next() at the bottom of the method and replacing it with in.nextLine()). When you do a return call, you need to send it somewhere. Such as System.out or to a variable like int x = getUserFromInput("test: ");
public class Tester {

    private static Scanner in = new Scanner(System.in);

    private static int getIntFromUser(String aa) {

        int aaa = 0;
        while (true && aaa <= 0) {
            try {
                System.out.println(aa + ": ");
                aaa = in.nextInt();
                if (aaa <= 0) {
                    System.out.println("Please enter a positive number.");
                }
            } catch (Exception e) {
                System.out.println("Please enter an integer: ");
                in.next();
            }
        }
        in.nextLine();
        return aaa;
    }

    public static void main(String[] a) {
        System.out.println(getIntFromUser("test123"));
    }
}

Output


Q: ActiveRecord STI delete doesn't work correctly I want to store two models using active record, but delete doesn't work as expected.

*

*Evaluation has id, name and description

*and SqlEvaluation has additional two columns of query_string and database.

I want to use those two tables, and eval_typ_id is used to distinguish which subclass should be used: 1 for SqlEvaluation.
create table eval (
eval_id int,
eval_name varchar,
eval_desc varchar,
eval_typ_id int
);

create table sql_eval (
eval_id int
query_str varchar
database varchar
);

After some research, I used the following code, it works well except "delete", which didn't delete the row in sql_eval. I cannot figure out where is wrong?
require 'rubygems'
require 'active_record'
require 'logger'

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(:adapter => "ibm_db",
                                        :username => "edwdq",
                                        :password => "edw%2dqr",
                                        :database => "EDWV2",
                                        :schema => "EDWDQ" )

class Eval < ActiveRecord::Base
  set_table_name "eval"
  set_primary_key :eval_id

  TYPE_MAP = { 1 => 'SqlEval' }

  class << self
    def find_sti_class(type)
      puts "#{type}"
      super(TYPE_MAP[type.to_i])
    end

    def sti_name
      TYPE_MAP.invert[self.name]
    end
  end

  set_inheritance_column :eval_typ_id
end

class SqlEval < Eval
  has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id, :foreign_key=>:eval_id, :include=>true, :dependent=>:delete
  default_scope :conditions => { :eval_typ_id => 1 }
end

class SqlEvalDetails < ActiveRecord::Base
  belongs_to :sql_eval, :class_name=>'SqlEval',
    :conditions => { :eval_type_id => 1 }
  set_table_name "sql_eval"
  set_primary_key :eval_id
end

se = SqlEval.find(:last)

require 'pp'

pp se
pp se.details

# Eval.delete(se.eval_id)
se.delete

A: Sorry for messing the code. It is first time to post for me. Here is the code.
require 'rubygems'
require 'active_record'
require 'logger'

ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(:adapter => "ibm_db",
                                    :username => "edwdq",
                                    :password => "edw%2dqr",
                                    :database => "EDWV2",
                                    :schema => "EDWDQ" )

class Eval < ActiveRecord::Base
  set_table_name "eval"
  set_primary_key :eval_id

  TYPE_MAP = { 1 => 'SqlEval' }

  class << self
    def find_sti_class(type)
      puts "#{type}"
      super(TYPE_MAP[type.to_i])
    end

    def sti_name
      TYPE_MAP.invert[self.name]
    end
  end

  set_inheritance_column :eval_typ_id
end

class SqlEval < Eval
  has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id,     :foreign_key=>:eval_id, :include=>true, :dependent=>:delete
  default_scope :conditions => { :eval_typ_id => 1 }
end

class SqlEvalDetails < ActiveRecord::Base
  belongs_to :sql_eval, :class_name=>'SqlEval',
    :conditions => { :eval_type_id => 1 }
  set_table_name "sql_eval"
  set_primary_key :eval_id
end

se = SqlEval.find(:last)
e = Eval.where(:eval_id => 26)

require 'pp'

pp se
pp e
pp se.details

# Eval.delete(se.eval_id)
se.delete


Q: ASP.NET RSS feed error in link tag in item node? Issue with Razor in Umbraco RSS Feed Having an issue with creating an rss feed against a blog in umbraco using razor.  The code below works but as soon as I try and add any value into the link tag under the item node I get an xml error, below is the code.
<rss version="2.0">
    <channel>
        <title>@landing.uBlogsyRssTitle</title>
        <description>@landing.uBlogsyRssDescription</description>
        <copyright>@landing.uBlogsyRssCopyright</copyright>
        @*<image>@landing.uBlogsyRssImage</image>*@
        <link>@Request.Url.Host@landing.Url</link>
        <lastBuildDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</lastBuildDate>
        <pubDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate>
        @foreach (var p in posts)
        {
        <item>
            <title>@p.GetProperty("uBlogsyContentTitle").Value</title>
            <link></link>
            <author>@p.GetProperty("uBlogsyPostAuthor").Value</author>
            <description>@p.GetProperty("uBlogsyContentBody").Value.StripHtml().Trim()</description>
            <guid>@p.Url</guid>
            <pubDate>@p.GetProperty("uBlogsyPostDate").Value.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate>
        </item>
        }
</channel>
</rss>

A: This is my answer to another post with the same problem solved:
Since MVC4 Razor verifies that what you are trying to write is valid HTML. If you fail to do so, Razor fails.
Your code tried to write incorrect HTML:
If you look at the documentation of link tag in w3schools you can read the same thing expressed in different ways:

*

*"The  element is an empty element, it contains attributes only."

*"In HTML the  tag has no end tag."

What this mean is that link is a singleton tag, so you must write this tag as a self-closing tag, like this:
<link atrib1='value1' attrib2='value2' />
So you can't do what you was trying to do: use an opening and a closing tag with contents inside.
That's why Razor fails to generate this your <xml> doc.
But there is one way you can deceive Razor: don't let it know that you're writing a tag, like so:
@Html.Raw("<link>")--your link's content--@Html.Raw("</link>")
Remember that Razor is for writing HTML so writing XML with it can become somewhat tricky.


Q: Multiple framebuffers and textures not working on intel drivers I'm writing an application using PyOpengl and PySide. My main machine is installed with ubuntu and an nvidia card (proprietary drivers), the premise is just to tell that the application is working properly in this setting.
I'm testing this application on a machine with an intel hd 3000 and Ubuntu 12.10, the drivers are the default intel drivers. Everything is working so far except for the application of multiple post-processing filters.
The process works like that:
render the scene and output a color texture (texture0) using a framebuffer object (called fb0).
render the first postprocessing effect by binding the textures produced in the previous step. The processed color output is saved in another texture (extratexture1) by using another framebuffer (fb1).
render another postprocessing effect by using the new color texture (extratexture2 and fb2).
render the result on the screen.
What I obtain is a white screen (my background color perhaps).
If I remove the last step and render the extratexture1, I obtain the correct result. If I remove the second step only and render the extratexture2 I obtain the correct result. Therefore the problem should not be in the texture initialization code.
It's like that this driver doesn't support more than 2 framebuffers (+ default one) at a time. Or probably failing to reset some important state.
Was anybody able to code a similar thing on an intel video card? I'm running out of ideas of what the problem can be.
I add some example code to troubleshoot any error:
Initialization of framebuffers and textures, at initialization time. The texture are regenerated at each resize.
   self.fb0, self.fb2, self.fb1 = glGenFramebuffers(3)
   # Creation of texture0

   glDrawBuffers(1, np.array([GL_COLOR_ATTACHMENT0], dtype='uint32'))

   # Creation of extratexture1
   # Creation of extratexture2

Creation of each texture:
def create_color_texture(fb, width, height):
    # Simple wrapper for glGenTexture and glTexImage2D
    texture = Texture(GL_TEXTURE_2D, width, height, GL_RGB, GL_RGB,
                      GL_UNSIGNED_BYTE)

    # Set some parameters
    texture.set_parameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    texture.set_parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    glBindFramebuffer(GL_FRAMEBUFFER, fb)
    glViewport(0, 0, width, height)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           texture.id, 0)
    return texture

Code that draws the texture to screen:
def render(self, fb, textures):
    # We need to render to a quad
    glBindFramebuffer(GL_FRAMEBUFFER, fb)
    glViewport(0, 0, self.widget.width(), self.widget.height())
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glUseProgram(self.quad_program)

    qd_id = glGetUniformLocation(self.quad_program, "rendered_texture")
    # Setting up the texture
    glActiveTexture(GL_TEXTURE0)
    textures['color'].bind()
    # Set our "rendered_texture" sampler to user Texture Unit 0
    glUniform1i(qd_id, 0)

    # Set resolution
    glUniform2f(glGetUniformLocation(self.quad_program, 'resolution'), self.widget.width(), self.widget.height())
    # Set gamma value
    glUniform1f(glGetUniformLocation(self.quad_program, 'gamma'), self.gamma)

    # Let's render a quad
    quad_data = np.array([-1.0, -1.0, 0.0,
                          1.0, -1.0, 0.0,
                          -1.0,  1.0, 0.0,
                          -1.0,  1.0, 0.0,
                          1.0, -1.0, 0.0,
                          1.0,  1.0, 0.0],
                         dtype='float32')

    vboquad = vbo.VBO(quad_data)
    vboquad.bind()

    glVertexPointer(3, GL_FLOAT, 0, None)
    glEnableClientState(GL_VERTEX_ARRAY)

    # draw "count" points from the VBO
    glDrawArrays(GL_TRIANGLES, 0, 6)

    vboquad.unbind()
    glDisableClientState(GL_VERTEX_ARRAY)


Q: Ruby TCPSocket Server - Can I tell to what host a client was connecting? I have a ruby server based on TCPSocket (non-HTTP).
I have 2 different domains, both pointing with an A-Record to my servers IP Address (the same one). So, there are clients connecting to one of those domains.
Is it possible to tell which domain a client was connecting to?
I saw that this is possible in other protocols, but I'm not sure if this is based on manually added headers or really extracted from the basic tcp/ip connection. E.g. in PHP there is $_SERVER["HTTP_HOST"] which shows to which domain a client was connecting.

A: At the TCP socket level, the only things that are known are the source and destination IP addresses (and ports) of the connection.  How the IP address was resolved via DNS is not possible to know at this layer.  Even though HTTP works on top of TCP, HTTP servers have to look at the HTTP headers from the client to know which domain they are making a request to. (That's how the HTTP_HOST value gets filled in.)
One possible solution is to configure your server to have an additional IP address. This can be by assigning an additional IP address to the NIC or adding an additional NIC.  Then have each domain use a different IP address.  Otherwise, this is not possible and you may want to consider your application protocol on top of TCP to convey this information.


Q: NumPy linear equations I was wondering to check for an algorithm that would solve set of three linear equations in two variables which change in every equation adjacently for example

*

*a + b = 0

*a + c = 0

*b + c = 1

I am open to all suggestions

A: Use the np.linalg.solve library:
https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
import numpy as np
a = np.array([[1,1,0], [1,0,1], [0,1,1]])
b = np.array([0,0,1])
x = np.linalg.solve(a, b)

A: alternative to the answer
import numpy as np
A = np.array([[1, 1, 0], [1, 0, 1], [0, 1, 1]])
B = np.array([0, 0, 1])
X = np.linalg.inv(A).dot(B)

print(X)


Q: Extract elements of lists in an RDD What I want to achieve
I'm working with Spark and Scala. I have two Pair RDDs.
rdd1 : RDD[(String, List[String])]
rdd2 : RDD[(String, List[String])]

Both RDDs are joined on their first value.
val joinedRdd = rdd1.join(rdd2)

So the resulting RDD is of type RDD[(String, (List[String], List[String]))]. I want to map this RDD and extract the elements of both lists, so that the resulting RDD contains just these elements of the two lists.

Example
rdd1 (id, List(a, b))
rdd2 (id, List(d, e, f))
wantedResult (a, b, d, e, f)

Naive approach
My naive approach would be to adress each element directly with (i), like below:
val rdd = rdd1.join(rdd2)
    .map({ case (id, lists) =>
        (lists._1(0), lists._1(1), lists._2(0), lists._2(2), lists._2(3)) })

/* results in RDD[(String, String, String, String, String)] */

Is there a way to get the elements of each list, without adressing each individually? Something like "lists._1.extractAll". Is there a way to use flatMap to achieve what I'm trying to achieve?

A: You can simply concatenate the two lists with the ++ operator:
val res: RDD[List[String]] = rdd1.join(rdd2)
  .map { case (_, (list1, list2)) => list1 ++ list2 }

Probably a better approach that would avoid to carry List[String] around that may be very big would be to explode the RDD into smaller (key value) pairs, concatenate them and then do a groupByKey:
val flatten1: RDD[(String, String)] = rdd1.flatMapValues(identity)
val flatten2: RDD[(String, String)] = rdd2.flatMapValues(identity)
val res: RDD[Iterable[String]] = (flatten1 ++ flatten2).groupByKey.values


Q: Delete all text in a file between two strings without importing any modules Due to restrictions I can't use any import modules like re, sys or os etc.
Anything that I have to import at the beginning is out. This has made my life hell.
Here is what I've got so far:
#I CANT USE ANY IMPORT MODULES DUE TO RESTRICTIONS ON THE MACHINE THIS RUNS ON :(
#
# These Are the Variables for our file path and the start and ending points of what I want to delete.
#----------------------------------------------------------------------------------------------------
DelStart = "//StartBB"
DelEnd = "//EndBB"
FilePath = "C:\\Users\\kenne_000\\Desktop\\New folder\\test.sqf"
#----------------------------------------------------------------------------------------------------
#Opens the FilePath in Read set this command to f
f = open(FilePath).read()

#Sets value of out to create file in Write mode called "Filepath".out
Out = open(FilePath + '.out', 'w')

#assigns fL as open FilePath and split it up line by line for indexing
fL = f.split('/n')

#Assings LN as index our file and find the lines DelStart and DelEnd
LN = fL.index(DelStart,DelEnd)

#This Gives an error
#>>> LN = fL.index(DelStart,DelEnd)
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#TypeError: slice indices must be integers or None or have an __index__ method

#text is replacing everything between our start and endpoints with nothing ""
# STILL NEED THIS SECTION NO CLUE HOW TO DO THIS

#Writes our new file Minus our designated start and end points
out.write(text)

#Closes Our New File
out.close()

#Ends Script
Script.close()

I was able to create a script that wrote all of the text and inserted the markers, which are individual for each set of text that gets inserted, but I no longer have any clue what to do when it comes to removing the section between the markers.

A: While the code in your self-answer looks like it ought to work, it's not particularly elegant:

*

*You should really be using a with block to work with files.

*Your variable line is misnamed: it doesn't contain a line at all, but the entire contents of your input file.

*Your script reads in the entire file at once, which may be problematic for large files in terms of memory use.

Here's an alternative:
def excise(filename, start, end):
    with open(filename) as infile, open(filename + ".out", "w") as outfile:
        for line in infile:
            if line.strip() == start:
                break
            outfile.write(line)
        for line in infile:
            if line.strip() == end:
                break
        for line in infile:
            outfile.write(line)

This function uses with open(...) (scroll down to the paragraph starting "It is good practice to use the with keyword ...") to ensure that files will be properly closed even if you hit an error of some kind, as well as reading and writing one line at a time to conserve memory.
If you have a file example.txt with the following content:
one
two
three
//StartBB
four
five
six
//EndBB
seven
eight
nine

... then calling excise() as follows ...
excise("example.txt", "//StartBB", "//EndBB")

... will do what you want:
example.txt.out
one
two
three
seven
eight
nine

A: CREDITS FOR THIS ANSWER GOES TO lazy1 and his comment solution:

fL is a list of lines. and fL.index will fine a line not part of it.
  Do you need to delete for every line or for the whole file? In any
  case, use string index to find start and end then slice away.
  Something like: i = line.find(DelStart) j = line.find(DelEnd) print
  line[:i] + line[j+len(DelEnd):]

# These Are the Variables for our file path and the start and ending points of what I want to delete.
#----------------------------------------------------------------------------------------------------
DelStart = "//StartBB" #Replace This With Proper Start Que
DelEnd = "//EndBB" #Replace this with the proper End Que
FilePath = "FILEPATH GOES HERE"
#----------------------------------------------------------------------------------------------------
#Sets Line to open our filepath and read it
line = open(FilePath).read()

#i finds our start place j finds our ending place
i = line.find(DelStart)
j = line.find(DelEnd)

#sets text as finding start and end and deleting them + everything inbetween
text = line[:i] + line[j+len(DelEnd):]

#Creates our out file and writes it with our filter removed
out = open(FilePath + '.out', 'w')
out.write(text)

#Closes Our New File
out.close()

#Ends Script
Script.close()

A: This uses only built-in string functions:
    string = "This is the string"
    stringA = "This"
    stringB = " string"
    stringC = stringA + stringB
    stringD = stringC.replace(string, stringC)

A: A rewrite of the important part of @KennethDWhite 's answer, as a function. I would simply have posted it as a comment to his answer, but that would not format correctly.
# ToDo: this also deletes the delimiters. Perhaps add a parameeter to indicuate
#       whether to do so,or just to delete the text between them?
def DeleteStringBetween(string, startDelimiter, endDelimiter):
    startPos = string.find(startDelimiter)
    endPos   = string.find(endDelimiter)

    # If either delimiter was not found, return the string unchanged.
    if (startPos == -1) or (endPos == -1):
        return string

    return string[:startPos] + string[endPos + len(endDelimiter):]


Q: Image fill is not working properly This is my html code

My image 1.jpg size is 150px x 150px and i have mentioned in the css as
.feature-image{
    width:150px;
    height:150px;
    display:block;
    position:relative;
    overflow:hidden;
}

.feature-image img{
    position:absolute;
    top:-50;
    left:0;
    width:100%;
}

I know that when i give different image size (for eg: 300x200 or 600x350 etc) the image will fill inside that 150x150 and not stretches.
But actually its not working properly. Please help whether there is any mistake in this code?

A: Ok. Let me explain how this work.
First things first. Your CSS has a bug.
top:-50;

This wont do anything. It has to be something like
top:-50px;

But my question is why do you want negative margins? it will only hide you image by 50 pixels on the top side.
Ok, now coming to the real issue. You say you have no problems when your Image is 150X150 pixels. Thats because the parent
 is 150x150. But if you have a different image size like 300x200 you have a problem.
This happens because in your CSS you have only mentioned width: 100% for the image.From here on its plain math.
The width=300 & height =200
Since you have mentioned width:100% the image automatically gets adjusted to the new width
300(original width)/150(new width)=2

So taking the same factor of 2
200(original height)/2=100(new height)

Hence you rendered image will have height of 100px.
if you want the rendered image to have same height of div just add this line to img CSS
height: 100%;

Working fiddle

A: from the code you have pasted, it's working properly. Are you able to link to the site where this is live and not working? Cache issue?
See jsfiddle: http://jsfiddle.net/FNQZn/
.feature-image {
    width:150px;
    height:150px;
    display:block;
    position:relative;
    overflow:hidden;
}
.feature-image img {
    position:absolute;
    top:-50;
    left:0;
    width:100%;
}


Q: mongodb query different array have different condition I have the following datas.
[{
    "_id" : ObjectId("abc123"),
    "device_id": "A001",
    "A_status": "VALID",
    "B_status": "VALID"
},
{
    "_id" : ObjectId("abc223"),
    "device_id": "A003",
    "A_status": "EXPIRED",
    "B_status": "VALID"
},
{
    "_id" : ObjectId("abc323"),
    "device_id": "B001",
    "A_status": "EXPIRED",
    "B_status": "VALID"
},
{
    "_id" : ObjectId("abc423"),
    "device_id": "B002",
    "A_status": "VALID",
    "B_status": "EXPIRED"
},]

I have two different device_id list:
a_list = ["A001", "A003", ...]
b_list = ["B001", "B002", ...]
a_list need match A_status is VALID, b_list need match A_status is VALID.
I want to find deive_id in a_list and A_status is VALID, deive_id in b_list and B_status is VALID,
so I will get following correct data
{
    "_id" : ObjectId("abc123"),
    "device_id": "A001",
    "A_status": "VALID",
    "B_status": "VALID"
},
{
    "_id" : ObjectId("abc323"),
    "device_id": "B001",
    "A_status": "EXPIRED",
    "B_status": "VALID"
}

How do I execute once query and get the answer?
Or have to separate queries for different conditions?

A: You can use Regex to get different data from MongoDB. To get model AXXX and A_status is VALID you can use this query.
{
    device_model: { $regex :/^A/},
    A_status: 'VALID'
}

To get BXXX and B_status is VALID you can use:
{
    device_model: { $regex :/^B/},
    B_status: 'VALID'
}

It may be useful to take a look into mongo regex documentation.

A: Use $or
db.collection.find({
  $or: [
    {
      A_status: "VALID",
      device_model: {
        $in: [
          "A001",
          "A003"
        ]
      }
    },
    {
      B_status: "VALID",
      device_model: {
        $in: [
          "B001",
          "B002"
        ]
      }
    }
  ]
})

mongoplayground


Q: Why DOM changes are not visible in the function that changes DOM? I have the JS/jQuery code:
function swapElements(parent, i) {
     var a = parent.eq(i);
     var b = parent.eq(i + 1);

     var atemp = a.clone();
     var btemp = b.clone();

     a.replaceWith(btemp);
     b.replaceWith(atemp);

     debugOutput(); // instead of some actions
 }
 swapElements(parent, i);

But the debugOutput function sees old unchanged version DOM.
I have tried to use MutationObserver and setTimeout to call debugOutput but got nothing.
However if I manually check the DOM from another function:
$("button").click(function () {
    debugOutput();
});

then debugOutput see new changed DOM immediately.
Why this is happening? How can I work with changed DOM directly after replaceWith in swapElements?
Thank you for any help.


Q: Recursive function that return result from 'if' statement instead of 'else' statement I'm pretty new in Python and I'm trying to write a simple recursive function:
def bugged_recursion(inp_value,list_index=0):
    '''Define a recursive function that tag lists according to one parameter.
    '''
    #check if a criterion is true at position 0 in the list
    if list_index == 0:
        if inp_value[list_index] == 'valid':
            status = 'valid inp_value'
        #if the criterion is false call the function at the next index
        else:
            status = 'invalid inp'
            list_index +=1
            bugged_recursion(inp_value,list_index=list_index)
    #check if a criterion is true at position 1 in the list
    else:
        if inp_value[list_index] == 'valid':
            status = 'index {} is a valid inp_value'.format(list_index)
        else:
            status = 'index is never a valid inp_value'
    print(status)
    #return the input and its status
    return (inp_value,status)

if __name__ == '__main__':
    inp_value = ['invalid','invalid']
    bugged_recursion(inp_value)

I don't understand why this function return the status from the if statement, instead of returning the status contained in the last else statement.
For me, the strangest is that it prints the right status at some point but won't return it.
I'm unable to understand why... I'm really curious about how I could perform this task using a recursive function.

A: Wow wow, how tortured this is.
def bugged_recursion(inp_value, list_index=0):
    # i don't get why you compare list_index here
    if list_index == 0:
        # you'll get an IndexError if list_index > len(inp_value)
        if inp_value[list_index] == 'valid':
            status = 'valid inp_value'
        else:
            status = 'invalid inp'
            # there is only one place where you increment list_index
            # i suppose there is something wrong here
            list_index +=1
            # you forgot to return here
            return bugged_recursion(inp_value, list_index=list_index)
    else:
        if inp_value[list_index] == 'valid':
            status = 'index {} is a valid inp_value'.format(list_index)
        else:
            status = 'index is never a valid inp_value'
    return (inp_value,status)

That aside, people usually tend to avoid recursion as much as possible (for example on Dive into Python).
Does this cover your needs?
def no_recursion(inp_value):
    for i, val in enumerate(inp_value):
        # you probably have a good reason to test the index
        if i == 0:
            if val == 'valid':
                yield 'valid inp_value: %s' % val
            else:
                yield 'invalid inp: %s' % val
        else:
            yield 'index %s is %s valid inp_value' % (
                i,
                'a' if val == 'valid' else 'never'
            )

print tuple(no_recursion(inp_value))

Gives: ('invalid inp: invalid', 'index 1 is never valid inp_value')


Q: Align x-axis tick locations of additional subplot with x-axis tick locations of FacetGrid object I want to add a second x-axis to my FacetGrid object. I managed to create a second x-axis by adding a second subplot to my figure that is below the first axis following the suggestions of this post. The ticks of my second x-axis should match with the horizontal locations of the ticks of the upper x-axis. However, in contrast to the post mentioned before, when using seaborn.catplot, the x-axis ticks of the FacetGrid figure do not exactly match with the beginning and end of the x-axis. Instead, seaborn.catplot 'compresses' the x-axis ticks, so that the first and last tick do not align horizontally with the start and end of the x-axis. As a result, one cannot simply set the x-axis ticks of the added subplot using get_xticks and set_xticks.
Here's a code example:
import numpy as np
import pandas as pd
import seaborn as sns

# simulate data
rng = np.random.RandomState(42)
measure_names = np.tile(np.repeat(['Train BAC','Test BAC'],10),4)
model_numbers = np.repeat([0,1,2,3],20)
measure_values = np.concatenate((rng.uniform(low=0.6,high=1,size=40),
                                rng.uniform(low=0.5,high=0.8,size=40)
                                ))
folds=np.tile([1,2,3,4,5,6,7,8,9,10],8)

plot_df = pd.DataFrame({'model_number':model_numbers,
                        'measure_name':measure_names,
                        'measure_value':measure_values,
                        'outer_fold':folds})

# plot data as pointplot
g = sns.catplot(x='model_number',
                y='measure_value',
                hue='measure_name',
                kind='point',
                seed=rng,
                data=plot_df)

ax2 = g.axes[0,0].twiny()

# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")

# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes",-0.30))

# set title
ax2.set_xlabel('Title of the second axis')

# get ticks of FacetGrid ax
xtickslocs = g.axes[0,0].get_xticks()

# set ticks of ax2 to first ax
ax2.set_xticks(xtickslocs)

which produces:

A: Simply match the limits of the x-axis
ax2.set_xlim(g.axes[0,0].get_xlim())


Q: How to setup and use Android Emulator (shipped in Android Studio) in a corporate environment (no internet access or admin rights)? I'm trying to use Emulator on a PC which has no internet connection and I'm not local admin. I've downloaded Android Studio (no install zip) on another PC and extracted contents, but it says "No SDK folder found".
Then I manually downloaded sdk tools zip and tried to update SDK folder with no luck. It says this folder does not include Android SDK.
Then I got my local admin guy to install Studio on the PC. But when I start Studio, I get the same "No SDK folder" error. I guess this is because setup installed SDK folder under local admin AppData folder. I cannot see his folder and couldn't contact him so far.
What should I do?

A: I got the admin guy to copy SDK folder from his directory under C:\Users\adminguy\AppData to somewhere I can read. Now it works ok.


Q: Why calling a function from shorthand function pointers array initialization doesn't compile? I have the following code in my project:
printf("Please select one of the tests: ");
int n;
scanf("%d", &n);
(void (* [])()) {test1, test2, test3, test4}[n - 1]();

For me, this code compiles and works as indented. But my professor said that this doesn't compile for her.
I write code compliant with the C23 standard and my compiler is Apple Clang v13.0.0. But about my professor, all I know is that she uses the MSVC compiler; I have no information on either the compiler version or the standard she marks the code with.
I tried changing the C standard to C99 and it still worked, so I think this has to be a compiler issue. I don't have a Windows machine to play around with MSVC and test whether the problem is the anonymous array initialization, the subscript operator immediately after it, the call operator after the entire thing, or something else entirely.
Now, of course I know that I can declare an array of function pointers first, and then assign every element, or just use a switch for this purpose. I also know that this is a kind of "clever code" that may not be welcome in actual projects maintained by more people, but this is my code, created for educational purposes only. Also, my professor likes this kind of "clever tricks" as extreme examples of what can you do with the language. What I do like to know is what could be the reason this code does not compile with MSVC. Is that syntax some compiler-specific language extension or is it just Microsoft which, as always, is not keeping up with support for all language features?

A: Your teacher is probably compiling your code as C++.
With dummy functions added, if this code is placed in a .c file and compiled with MSVC 2015, it compiles fine.  If the file has a .cpp extension, it generates the following errors:
x1.cpp(13): error C3260: ')': skipping unexpected token(s) before lambda body
x1.cpp(13): error C2143: syntax error: missing ';' before '}'
x1.cpp(13): warning C4550: expression evaluates to a function which is missing an argument list
x1.cpp(13): error C2676: binary '[': 'main::<lambda_8caaf9f5b122025ad6cda2ca258a66a7>' does not define this operator or a conversion to a type acceptable to the predefined operator
x1.cpp(13): error C2143: syntax error: missing ')' before ';'
x1.cpp(13): error C2059: syntax error: ';'

So it thinks your compound literal is a lambda function.  Compound literals are a C-only construct, so unless your C++ compiler supports them as an extension it won't work.
Have your teacher compile your code as C by putting it in a file with a .c extension.
Alternately, don't use a compound literal.  Create the array first, then index it and call the function.
void (*f[])() = {test1, test2, test3, test4};
f[n - 1]();


Q: Has there different JDKs or JVMs on each Java platforms? I am confused about java platforms.From the page Differences between Java EE and Java SE , java has four platforms. Has there any special things between them ? Are they use different JDKs or JREs ?
For clear my question , when I download JDK , I think I can create not only java desktop applications (with swing or javafx) but also web applications.If so ,why java says it has different platforms. If yes , it should has different jdk or jvm for each specific platform. As I think , different platforms mean I need to download different version of JDK. For instance , I need to download JDK for JavaEE platform which contains API for JavaEE.

A: It depends (like often).
The JDK is a development kit for Java SE including FX. So you can develop desktop applications but also web applications depending on the type of integration you prefer. The Java EE SDK contains also the Glassfish server, examples and tutorials but they are not really needed. The ME is a special minimized versions for embedded device development including special tools for that.
I am developing web application for years with a Java SE JDK only. As I normally use Spring Boot with an embedded container or install a Tomcat on demand, this works perfectly and the Java EE SDK is not needed.


Q: How to adjust the y-axis of bar plot in R using only the barplot function Using this example:
 x<-mtcars;
 barplot(x$mpg);

you get a graph that is a lot of barplots from (0 - 30).
My question is how can you adjust it so that the y axis is (10-30) with a split at the bottom indicating that there was data below the cut off?
Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?

A: This is not recommended. It is generally considered bad practice to chop off the bottoms of bars. However, if you look at ?barplot, it has a ylim argument which can be combined with xpd = FALSE (which turns on "clipping") to chop off the bottom of the bars.
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)

Also note that you should be careful here. I followed your question and used 0 and 30 as the y-bounds, but the maximum mpg is 33.9, so I also clipped the top of the 4 bars that have values > 30.
The only way I know of to make a "split" in an axis is using plotrix. So, based on

Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?

the answer is "no, this is not possible" in the sense that I think you mean. plotrix certainly does it, and it uses base R functions, so you could do it however they do it, but then you might as well use plotrix.
You can plot on top of your barplot, perhaps a horizontal dashed line (like below) could help indicate that you're breaking the commonly accepted rules of what barplots should be:
abline(h = 10.2, col = "white", lwd = 2, lty = 2)

The resulting image is below:

Edit: You could use segments to spoof an axis break, something like this:
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
xbase = -1.5
xoff = 0.5
ybase = c(10.3, 10.7)
yoff = 0
segments(x0 = xbase - xoff, x1 = xbase + xoff,
         y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2)
abline(h = mean(ybase), lwd = 2, lty = 2, col = "white")

As-is, this is pretty fragile, the xbase was adjusted by hand as it will depend on the range of your data. You could switch the barplot to xaxs = "i" and set xbase = 0 for more predictability, but why not just use plotrix which has already done all this work for you?!
ggplot In comments you said you don't like the look of ggplot. This is easily customized, e.g.:
library(ggplot2)
ggplot(x, aes(y = mpg, x = id)) +
    geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) +
    theme_classic()


Q: enter line to an object Hello in R how could I write a function which takes as an input a number at which aline should be entered into an existing object
matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)

Each vector should now be entered into the matrix into the matrix at row 3 (so it should be the new co row 3 .  The other rows would just be a pushed so the old row 3 is row 4 then

A: Here's a function I wrote for that a while back.  I've been using it.
#Christopher Barry, 28/01/2015

insertRows <- function(DF, mtx, row){
  if(is.vector(mtx)){
    mtx <- matrix(mtx, 1, length(mtx), byrow=T)
  }
  nrow0 <- nrow(DF)
  nrows <- nrow(mtx)
  ncols <- ncol(DF) #should be same as for mtx
  if(is.matrix(DF)){DF <- rbind(DF, matrix(0, nrows, ncols))}
  if(nrow0 >= row){
    DF[seq(row+nrows,nrow0+nrows),] <- DF[seq(row,nrow0),]
    DF[row:(row+nrows-1),] <- mtx
  }else{
    DF[seq(nrow0+1,nrow0+nrows),] <- mtx
  }
  return (DF)
}

Edited to work for matrices and data frames.

A: One way of doing this can be :
aa<- matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)
rbind(aa[1:2,],x,aa[3:5,])

A similar solution ot this, actually:
R: Insert a vector as a row in data.frame


Q: Checkbox form validator Angularjs2 I need to validate something like this. In the following form, SignUp button should be enabled only if user checked the checkbox. If user uncheck the checkbox the button should get disabled.
Following way enabled the button when user check the checkbox for the first time. But then if user uncheck the checkbox again the button remain enabled which actually should be disabled. All help appreciated. Thanks!
<form id="login-form" action="" method="post" role="form"  #loginForm='ngForm'>

                        <input type="text" required maxlength="12" minlength="12" required [(ngModel)]="user.ssn" name="ssn" #name="ngModel" tabindex="1" class="form-control input-box" placeholder=""
                            value="" autocomplete="off">

                        <input type="checkbox" id="chkTerm" ngModel name="cb" #cb="ngModel" required  />

                                <button class="btn" (click)='clicked()' class="btn waves-effect waves-light" [disabled]="!loginForm.form.valid" [ngStyle]="{'background-color': '#57e5a1'}" type="submit" name="action">SignUp</button>

                </form>


Q: SELECT query with ResultSet arguments in JAVA The server code of my Oracle database contains two files (classes) namely: Main.javaand DBManager.java. DBManager.java contains SQLPRocessing and SQLProcess methods (functions) that perform executeUpdate and executeQuery operations with the query statement, respectively. The SQL queries for dumping and fetching the data are written at the Main.java class. My database contains two tables T1and T2. My code has two queries for inserting the data as:
public void SQLProcessing(String ID, String X, String Y, String XE, String YE){
    db.SQLProcess("INSERT INTO T1 VALUES("+Double.parseDouble(ID)+ "," +Double.parseDouble(X)+ "," +Double.parseDouble(Y)+")");
    db.SQLProcessing("INSERT INTO T2 VALUES("+Double.parseDouble(ID)+ "," +Double.parseDouble(XE)+ "," +Double.parseDouble(YE)+")");
}

Similarly, for getting the data back from the database, I use single SELECT query as:
public ResultSet SQLProcess(String msg1, String msg2, String msg3, String msg4, String msg5){
    ResultSet rs = db.SQLProcess("SELECT * FROM T1, T2 WHERE T1.ID = T2.ID");
    return rs;
}

While executing the code, I get an error:
Exception in thread "Thread-1" java.lang.NullPointerException at Main.sendTo(Main.java:132) at Main$ServerReceiver.run(Main.java:79)

The line 132 of Main.java contains while(rs.next()) and line 79 contains sendTo(socket.getInetAddress()); . However, when I see the database, data is sent and stored in the database. So, I think the problem is with the SELECT query. I tried many possible SELECT queries from different threads, I could not solve the problem. Is my guess correct? Could anybody provide the real SELECT query for my case? Or is the error is triggered from another source?
The problem is with the cursor. It is null and I added an if statement as:
if(rs!=null) {
        while(rs.next()){//code}

Then it does not generate any error. However, the client device does not get any data from the server. How can I fix it?

A: Have you checked if (T1.ID = T2.ID) there are IDs which equal each other? Otherwise your queryresponse is empty because your where case declines a result.
Sometimes there is a extra column at first place. So maybe your data is not inserted correctly?

A: Using Double or Float for id purposes is an issue here, I suppose, as precision is always in issue.
Simply, when you save a floating point number, like 7.2 it may be represented as 7.199999 or 7.199998 or 7.2000001 etc, thus ids won't be equal.
For id I suggest using integer or something like UUID.


Q: I have a JTextArea that needs bottom margin I have a JTextArea with margins that work for the top, left, and right but not for the bottom. When the caret gets to the bottom, it just keeps going.
Here is my code:
    frame = new JFrame("");
    Container contentPane = frame.getContentPane();
    contentPane.add(textArea);

    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    textArea.setLineWrap(true);
    textArea.setMargin(new Insets(10, 50, 50, 560));


Q: How to edit Sublime Text build settings? I want to enable -std=gnu++11 in Sublime Text 3's C++ Single File build on Ubuntu 12.04.
I have already upgraded the tool chain to the latest g++ and do not want to see the following error on every build:

error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

I browsed to /home/myuname/.config/sublime-text-3 but cannot find any file to edit.
How can I edit the build settings?

A: edited
My original answer works, but there's a much better way of doing this, by creating your own build system. This use case is exactly why the feature is there.
Go to Tools → Build System → New Build System… (all the way at the bottom) and enter the contents below. Save as C++ 11 Single File.sublime-build, and it will now be accessible in the build system menu. Select it, hit CtrlB to build, and then hit CtrlShiftB to run the resulting program. Or you can use a Build and Run option and call it by hitting CtrlB, then selecting that option.
{
    "cmd": ["g++", "-std=gnu++11", "${file}", "-o", "${file_path}/${file_base_name}"],
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "cmd": ["${file_path}/${file_base_name}"]
        },
        {
            "name": "Build and Run",
            "cmd": ["g++ -std=gnu++11 ${file} -o ${file_path}/${file_base_name} && ${file_path}/${file_base_name}"],
            "shell": true
        }
    ]
}

If you need to edit it in the future, the file is in the User folder of Packages. The Packages directory is the one opened when selecting Preferences → Browse Packages…:

*

*Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages

*OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages

*Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages

*Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages InstallationFolder\Sublime Text\Data\Packages
The exact path depends on version and whether or not you upgraded from Sublime Text 3.

A: In my case, the problem is that in Windows, ST3 was calling py instead of python which was the default. If you change python in "cmd": ["python", "-u", "$file"] for your local python interpreter, the new system should work.

{
        "cmd": ["python3", "-u", "$file"],
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python",

        "env": {"PYTHONIOENCODING": "utf-8"},

        "windows": {
            "cmd": ["python", "-u", "$file"],
        },

        "variants":
        [
            {
                "name": "Syntax Check",
                "cmd": ["python3", "-m", "py_compile", "$file"],

                "windows": {
                    "cmd": ["py", "-m", "py_compile", "$file"],
                }
            }
        ]
    }


Q: Regex match of a string with numbers and uppercase letters failing I am trying to match lasko17A565 in the list below but the regex fails?specifically I am trying to look for the string present in variable train in the front followed by any combination of numbers and uppercase letters, can anyone provide guidance why it fails?
import re
xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
found_new_SDK = False
for SDK in xbsfindupdates_output_list:
    if re.match(r'%s[0-9A-Z]'%train,SDK):
        found_new_SDK = True
print found_new_SDK

CURRENT OUTPUT:-
False

EXPECTED OUTPUT:-
True

A: I suspect that the error is in how you are building the regex pattern to be used here.  I suggest concatenating the input list together by space to form a single input string, and then using the following regex pattern with re.findall:
\b(lasko[A-Z0-9]+)\b

The word boundaries are appropriate here, because the train value should be bounded on the left by a tab, and on the right by a space.
xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b(' + train + r'[A-Z0-9]+)\b'
matches = re.findall(pattern, inp)
print(matches)

This prints:
['lasko17A565']

Edit:
If you just want to find out if there is a match, then try:
xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b' + train + r'[A-Z0-9]+\b'
if re.search(pattern, inp):
    print("MATCH")
else:
    print("NO MATCH")

A: Try this:
for SDK in xbsfindupdates_output_list:
print(SDK,re.search("%s[0-9A-Z]+"%train,SDK))
if re.match("%s[0-9A-Z]+"%train,SDK.strip()):
    print("FOUND")
    found_new_SDK = True
print (found_new_SDK)

re.match is returning True iff both strings are same. Try re.search, which would search in string the required pattern

A: Match objects are always true, and None is returned if there is no match. Just test for trueness. So instead of match, i used re.search here:
xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
    train = 'lasko'
    found_new_SDK = False
    for SDK in xbsfindupdates_output_list:
          if re.search(r'\b' + train + r'[\d\S]+', SDK):
               found_new_SDK = True
    print found_new_SDK

O/p:
True


Q: NodeGit how to get last commit id of another branch? I have two branches checked out of my system Master and Dev.
My Working directory is Master from Master I want to push/merge file to dev after knowing the difference.
For say in Master I am working abc.txt file and I want to check the difference between the file present in dev with master.
How can I do it?
Getting this error

error while pushing == Error: no reference found for shorthand 'dev'
  (node:93479) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: no reference found for shorthand
  'dev'

Code
differenceCommit(fileName,branchName) {
        return new Promise(function (resolve,reject) {
            let repo,
                changes;
            open("./master")
                .then(function (repoResult) {
                    repo = repoResult;
                    return repo;
                })
                .then(function (commitId) {
                    return repo.getBranchCommit("dev");
                })
                ///Difference Before Push
                .then(function (commit) {
                    return commit.getDiffWithOptions("dev");
                })
                .then(function (diffList) {
                    console.log("************************");
                });
    }

A: Add origin/ to the name of the branch:
differenceCommit(fileName,branchName) {
        return new Promise(function (resolve,reject) {
            let repo,
                changes;
            open("./master")
                .then(function (repoResult) {
                    repo = repoResult;
                    return repo;
                })
                .then(function (commitId) {
                    return repo.getBranchCommit("origin/dev");
                })
                ///Difference Before Push
                .then(function (commit) {
                    return commit.getDiffWithOptions("origin/dev");
                })
                .then(function (diffList) {
                    console.log("************************");
                });
    }