text:
Q: GWT code is not rendered correctly when first time opened in IE I have my GWT application with TabLayoutPanel and when I load it in Chrome, everything is fine. But when I first load it in ie9 I don't get the full page: several labels and images on the first tab didn't load. But when I create the second tab and then open the first one, everything is fine. I found some questions about this on this site that the code is correct. The problem must be in  first time uploading css. I compared the code in Chrome and IE(first load and after creating the second tab in TabLayoutPanel) and here are the results
Chrome

   <link rel="stylesheet" href="http://127.0.0.1:8888/myproject/Upload.css">

IE (first load)

   <link rel="stylesheet" href="http://127.0.0.1:8888/myproject/Upload.css">

   ...

   ...

IE (after creating the second tab in TabLayoutPanel)

<link rel="stylesheet" href="http://127.0.0.1:8888/myproject/Upload.css">

   ...

   ...

Help me please. What should I do? I need that the page loaded correctly in the first loading.
Java Code
    public void onModuleLoad() {
       startAuthApplication();
}
    private void startAuthApplication() {
         AppController appController = new AppController();
         appController.go(RootLayoutPanel.get());
    }
/********************************************************************/
            public class AppController{
                public void go(final HasWidgets container) {
                    SystemPresenter systemPresenter = new SystemPresenter(AppFactory.getSystemView());
                    systemPresenter.go(container);
                }
            }
/********************************************************************/
        public class SystemPresenter{
        private final SystemView systemView;

            public SystemPresenter(SystemView systemView) {
                this.systemView = systemView;
            }

            public void go(HasWidgets container) {
                container.clear();
                container.add(systemView.asWidget());
            }
        }
/********************************************************************/
    public class AppFactory {
        private static SystemView systemView;
        private static TabPanelViewImpl tabPanelView;

        public static SystemView getSystemView() {
            if (systemView == null) {
                systemView = new SystemViewImpl();
            }
            return systemView;
        }

        public static TabPanelViewImpl getTabPanelView() {
            if (tabPanelView == null) {
                tabPanelView = new TabPanelViewImpl();
            }
            return tabPanelView;
        }
    }
/********************************************************************/
    public class SystemViewImpl extends Composite implements SystemView {

        interface Binder extends UiBinder<DockLayoutPanel, SystemViewImpl> {
        }

        private static Binder binder = GWT.create(Binder.class);

        @UiField(provided = true)
        TabPanelViewImpl tabPanelView;

        public SystemViewImpl() {
            tabPanelView = AppFactory.getTabPanelView();
            initWidget(binder.createAndBindUi(this));
        }
    }
/********************************************************************/
public class TabPanelViewImpl extends Composite implements TabPanelView,
        DocListEditDraftEventHandlers {

    interface TabPanelViewImplBinder extends
            UiBinder<TabLayoutPanel, TabPanelViewImpl> {
    }

    private static TabPanelViewImplBinder binder = GWT
            .create(TabPanelViewImplBinder.class);
    private TabPanelPresenter presenter;

    @UiField(provided = true)
    TabLayoutPanel tabPanel;

    private DocListTableView docListTableView;

    public TabPanelViewImpl() {
        super();
        tabPanel = new TabLayoutPanel(30, Unit.PX);
        docListTableView = AppFactory.getDocListTableView();
        tabPanel.add(docListTableView, "List of Docs");
        initWidget(binder.createAndBindUi(this));
    }
/********************************************************************/
public class DocListTableView extends Composite {

    interface DocListTableViewUiBinder extends
    UiBinder<Widget, DocListTableView> {
    }

    private static DocListTableViewUiBinder uiBinder = GWT
            .create(DocListTableViewUiBinder.class);

    private final DocListTableConstants constants = GWT
            .create(DocListTableConstants.class);

    private final Resources resources = GWT.create(Resources.class);

    private final DocListTableResources resource = GWT
            .create(DocListTableResources.class);

    @UiField(provided = true)
    CellTable<DocList> cellTable;

    @UiField
    Label emptyLabel;
    @UiField(provided = true)
    Label userLabel;

    public DocListTableView() {
        userLabel = new Label("User: "
                + AppFactory.getUserInfo().getUserName());
        initWidget(uiBinder.createAndBindUi(this));
    }
/********************************************************************/

DocListTableView.ui.xml
<ui:with field="res"
        type="com.myproject.client.resources.DocListTableConstants" />
<g:DockLayoutPanel unit='EM'>
        <g:north size='5'>
            <g:HTMLPanel addStyleNames="{docListStyle.center}">
                <g:HorizontalPanel width="100%">
                    <g:cell horizontalAlignment="ALIGN_LEFT">
                        <g:Label addStyleNames="{docListStyle.label}" ui:field="userLabel" />
                    </g:cell>
                </g:HorizontalPanel>
                <g:HorizontalPanel width="100%">
                    <g:cell horizontalAlignment="ALIGN_CENTER">
                        <g:Label addStyleNames="{docListStyle.label} {docListStyle.centerLabel}"
                            text="{res.label}" />
                    </g:cell>
                </g:HorizontalPanel>
            </g:HTMLPanel>
        </g:north>
        <g:center>
            <g:HTMLPanel addStyleNames="{docListStyle.center1}">
                <g:HorizontalPanel width="100%">
                    <g:cell horizontalAlignment="ALIGN_CENTER">
                        <g:Label ui:field="emptyLabel" visible="false">Your document list is empty</g:Label>
                    </g:cell>
                </g:HorizontalPanel>

                            <ct:CellTable addStyleNames='{docListStyle.panel1}'
                                ui:field='cellTable' />

                            <my:DocListSimplePager ui:field='pager'
                                visible="false" />

            </g:HTMLPanel>
        </g:center>
        <g:south size='10'>
            <g:HTMLPanel addStyleNames="{docListStyle.center}">
                <g:Label addStyleNames="{docListStyle.label}               {docListStyle.centerLabel}"
                    text="{res.status}" />

                            <g:Image url="images/status/draft.png"></g:Image>

                                <ui:text from='{res.draft}' />

                            <g:Image url="images/status/accept.png"></g:Image>

                                <ui:text from='{res.accept}' />

                            <g:Image url="images/status/send.png"></g:Image>

                                <ui:text from='{res.send}' />

                            <g:Image url="images/status/get.png"></g:Image>

                                <ui:text from='{res.get}' />

            </g:HTMLPanel>
        </g:south>
    </g:DockLayoutPanel>

I know I posted a lot of code, but I hope it quite understanding. I add DocListTableView on the first tab of TabLayoutPanel and in DocListTableView.ui.xml file only celltable+pager display in first load. The other Labels and
 element doesn't show up.
Edit
Interface Resources and DocListTableResources I use in cellTable and they render correctly.
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;

public interface Resources extends ClientBundle {

    @Source("draft.png")
    ImageResource draft();

    @Source("edit.png")
    ImageResource edit();
...
}
import com.google.gwt.user.cellview.client.CellTable;

public interface DocListTableResources extends CellTable.Resources {
    public interface DocListTableStyle extends CellTable.Style {
    };

    @Override
    @Source({ "DocListTableStyle.css" })
    DocListTableStyle cellTableStyle();

}

Edit2
import com.google.gwt.i18n.client.ConstantsWithLookup;

public interface DocListTableConstants extends ConstantsWithLookup {
    public String label();

    public String status();

    public String draft();
...

A: If the tabs loads properly the second time you trigger it, there might some kind of race condition going on when the view is initially created and populated. In such cases, Scheduler.scheduleDeferred usually helps:

A deferred command is executed after the browser event loop returns.

Meaning, the code in the callback will be executed when the view is created and added to the DOM.
As to where this call is needed - I can only guess, you know your code best :) I'd start with:
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
    @Override
    public void execute() {
        tabPanel.add(docListTableView, "List of Docs");
    }
});

A: Thanks for all your help, but I found the error by myself.
In DocListTableView.ui.xml I use DockLayoutPanel and set it size in EM.
<g:DockLayoutPanel unit='EM'>

There is a problem with IE with using EM. So I tried to use PX and it worked!


text:
Q: Python: Cancel object creation during initialization I'm creating a list of objects, and if any have some undesirable data while they're being initialized, I'd like to immediately cancel their initialization, and move on to the next object. Is there a best practice for something like this in Python?
data = [good, bad]
theList = [myObject(some_data) for some_data in data]

# I'd like myObject to determine if it should create itself, after some data parsing.

Should I just return nothing from __new__ ? Or do I just need to separate out the data validation logic from myObject..? Or..?
Thanks!
Context: Given a folder path, I'm checking a bunch of stuff in sequence (is the basename formatted correctly, if so, does a certain file exist, if so, parse it...etc)

A: Like the other answer said, validate the data before creating objects. Somewhat like this:
def validate(data):
    if data_is_good: return True
    else: return False

data = [good, bad]
theList = [myObject(some_data) for some_data in data if validate(some_data)]

A: You can raise an exception inside the class' __init__. Note, however, that you can no longer use a list comprehension (which is no huge loss).

A: You should check / validate if you have correct data, prior to feeding the data to your object constructor. If data is invalid you should raise an error, eg raise ValueError or your own custom exception. Only when the data is valid should you can with creating the object. in addition you can also raise the exception from your class object's init method too.

A: You can use a generator. This will create the object whether or not the data is valid, but retain it based on a flag set during the init.
e.g.,
data = [good, bad]
theList = [obj for obj in (MyObject(some_data) for some_data in data) if obj.data_is_valid]

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP string parameter best practice I have a PHP function that internally builds an object graph using among other things one string parameter, then uses json_encode() to create a JSON string and then post the JSON string to a remote web service.
Like this:
function send($text)
{
    $payload = array(
        'text' => $text
        // Set additional properties here ...
    );

    $payload_json = json_encode($payload);

    // Post $payload_json to remote service with Curl ...
 }

From the manual of json_encode (http://php.net/manual/en/function.json-encode.php)

All string data must be UTF-8 encoded.

I see a couple of options:

*

*Attempt to validate that $text is in fact UTF-8 and throw an exception if it is not

*Attempt to detect the encoding in $text and convert it to UTF-8 if necessary

*Return false when $text is not UTF-8

*Communicate with my API users in documentation that $text must be UTF-8

*Check for error with json_last_error() and throw an exception if an error was encountered

What is the best practice?

A: You should always communicate to the users of the API what you're expecting.
If you expect UTF-8 encoded text, say so in your documentation.
Once it's in there, you should return a descriptive error such as "Invalid Encoding, for more information read the documentation: link" where link goes to the relevant page for the call that failed
This way, you're not responsible anymore, and the developers that use your API will know what is going wrong, and you don't have to worry about it in your API.
You're the developer, it's your API, and your API has it's own rules, if people want to use it, they need to follow the rules you set.


text:
Q: XML validation based on dtd The paragraph below is from this source http://en.wikipedia.org/wiki/Document_Type_Definition
"Note that any valid SGML or XML document that references an external subset in its DTD, or whose body contains references to parsed external entities declared in its DTD (including those declared within its internal subset), may only be partially parsed but cannot be fully validated by validating SGML or XML parsers in their standalone mode (this means that these validating parsers will not attempt to retrieve these external entities, and their replacement text will not be accessible)."
Can someone explain this to me in simpler terms?

A: Ok, i got it, it only means that if the document is a standalone one, it will only be partially parsed and not fully because external references will be ignored


text:
Q: Finding AWS security group duplicate entries Is it possible to find duplications in the security groups in AWS?
For example :
Security group 1 has :
   198.168.5.2/24 ,
   192.168.4.2/24 ,
   172.54.60.12/24
Security group 2 has :
192.168.4.2/24 ,
172.54.60.12/24 ,
52.43.56.98/32
As you can see there are two exact same IPs in both SGs. Can this be done through AWS Cli ?

A: Yes, you can use the ip-permission.cidr filter for this. From the documentation:

ip-permission.cidr - An IPv4 CIDR range that has been granted permission in a security group rule.

So you can use this to specify the CIDR range you want to check for, and it will list only the security groups containing a rule matching that CIDR range.
Example command:
aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values=172.54.60.12/24

Further reading:

*

*AWS Documentation - aws ecs describe-security-groups

*AWS Documentation - Using Shorthand Syntax with the AWS Command Line Interface


text:
Q: How do I detect duplicate files inside and across torrents? If I'm downloading a bunch of torrents, is there a way or a client that detects files already downloaded and stops downloading them?
Edit:
Clarifying from the comments. Yes this means finding duplicate files between different torrents and avoiding downloading them.
I know some clients allow you to select which files inside a torrent to download. Is it possible to get a checksum of individual files inside a torrent, before you download them? If so I could make a script or something.

A: It's not possible to determine if a file in a torrent also exist in another torrent from the data available in the .torrent files. There simply is no deduplication support in the standard BitTorrent protocol.
When a torrent is created, all files in it is concatenated together and then chunked up in pieces.
example:
Files  |---#1|#2|---#3|-----------------------#4|#5|------#6|-----#7|-------#8|
Pieces |--0|--1|--2|--3|--4|--5|--6|--7|--8|--9|-10|-11|-12|-13|-14|-15|-16|17|

*

*All pieces has the same length except the last one.

*A file has one or more pieces.

*A piece may contain (parts from) more than one file.

*It's very rare that internal file and piece boundaries align (except if padding files is used).

*A file in a multi-file torrent almost always has a piece shared with another file.

The problem is that it's not possible to create a file hash from the piece hashes.
(@jdwolf Even if file #1 and file #3 is identical, all their piece hashes will be different.)
There is a few torrent creator programs that optionaly can add file hashes, but afaik it's not used anywhere.


text:
Q: Add static navbar bootstrap I'm trying to learn some front-end development and I found an interesting thing [HERE][1]. I would like to keep the sliding effect whenever I move the cursor to left or right, but the navbar to be static/fixed.
  [1]: https://codepen.io/bradtraversy/pen/dJzzdB

A: something like this?
https://codepen.io/mikehavoc/pen/KQzgQG/

  Navbar
 <button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false"
aria-label="Toggle navigation">

  </button>

        Home (current)

        Features

         Pricing

         Disabled

The Designer

     Read More

The Programmer

     Read More

A: CSS to make fixed navbar
nav{
position:fixed !important;
width:100% !important
}

nav{
position:fixed !important;
width:100% !important
}
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      WebSiteName

Home

          Page 1

Page 1-1

Page 1-2

Page 1-3

Page 2

Page 3

 Sign Up

 Login

Collapsible Navbar

In this example, the navigation bar is hidden on small screens and replaced by a button in the top right corner (try to re-size this window).

Only when the button is clicked, the navigation bar will be displayed.

Fixed Navbar

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

Scroll this page to see the effect

with bootstrap use easily make fixed navvbar with class navbar-fixed-top
top specifies position of navbar
example


text:
Q: How can I replace the  element in many HTML files? My directory ~/foo contains many HTML files. Each one has a different unwanted title element. That is, each file contains the code
<title>something unwanted</title>

Many of these files also contain some span elements like this
#+Title:
correct title

I'd like to write a script that scans each HTML file and, for each file that contains a code-block of the second type, replaces the unwanted title with the correct title.
Once the title has been replaced, I'd like the script to remove the code in the second block.
For example, running the script on
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

    <title>foo.org</title>

#+Title: my desired title
#+Date: <2015-08-23 Sun>

* hello world

Vivamus id enim.

should result in
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

    <title>my desired title</title>

      #+Date: <2015-08-23 Sun>

      * hello world

      Vivamus id enim.

Any ideas what HTML parser would work well for this job?

A: The following is one way to do it Python.
import sys
from lxml import etree
from lxml.html import parse
doc = parse(sys.argv[1])
title = doc.find('//title')
span1 = doc.find('//span[@class="org-document-info-keyword"]')
span2 = doc.find('//span[@class="org-document-title"]')
title.text = span2.text.strip()
span1.getparent().remove(span1)
span2.getparent().remove(span2)
print etree.tostring(doc)

You can put that into a file called script.py and then to run it on an HTML source file foo.html and write the results to new-foo.html, do this:
python script.py foo.html > new-foo.html


text:
Q: Disable option in select I have this select:
<select>
    <option class="1">1st</option>
    <option class="2">other1</option>
    <option class="2">other2</option>
    <option class="1">2st</option>
    <option class="2">other1</option>
    <option class="2">other2</option>
</select>

How can I disable the options with class "1"?

A: <select>
<option class="1">1st</option>
<option class="2">other1</option>
<option class="2">other2</option>
<option class="1">2st</option>
<option class="2">other1</option>
<option class="2">other2</option>
</select>

<script>
$(function(){
    $('select').find('option.1').attr('disabled', 'disabled');
});
</script>

Note: Your class names are not following convention
Naming rules:

*

*Must begin with a letter A-Z or a-z

*Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"),
and underscores ("_")

*In HTML, all values are case-insensitive

A: Using jQuery, you can do the following (whereas c1 is a valid replacement for 1)

jQuery("option.c1").attr("disabled", "disabled");

This fetches all elements of tag option that have a class of c1 set and, for each matched tag, the attribute disabled is added with value disabled (this is common practice, as disabled does not really need an argument, but XML requires an argument for attributes).


text:
Q: UFW: Allow 2 external IPs + loopback, deny everything else I have a ubuntu server with IPv4 and IPv6 networking enabled. Currently, network config looks like this:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet static
    address 45.***.***.**1/24
    gateway 45.***.***.***

# This is an IPv6 interface
iface eth0 inet6 auto
    up   ip addr add 192.168.***.**1/17 dev eth0 label eth0:1
    down ip addr del 192.168.***.**1/17 dev eth0 label eth0:1

I want another server in the network, which has the IPs
45.***.***.**2  and
192.168.***.**2

to be able to access any port, in or out of this server on it's private IP. Traffic in or out from this server's public IP (45...) should be dropped. Loopback should of course remain untouched.
Currently there are no IP tables entries or ufw rules. I'd like to go with ufw for it's simplicity. How can I lock down this server as described above?


text:
Q: Как вывести http аргументы в bash скрипт на nginx Есть кусок конфига nginx
server {

location /lua {
 content_by_lua '
 os.execute("/opt/test/script.sh")';
}

дальше хочу из http строки сделать разбивку по компонентам.
URI=="http://127.0.0.1/lua?&arg1=123&arg2=456"

Как правильно написать скрипт, чтобы на выходе иметь значения arg1 и arg2 и можно было ими оперировать? Возможно надо как-то правильно отдаль аргументы из lua?
Я вижу это как-то примерно так:
script.sh
_______________________

URI=="http://127.0.0.1/lua?&arg1=123&arg2=456"

echo $arg1 >> /tmp/test
echo "$arg2" >> /tmp/test
_______________________

A: Тут примеры есть. GET параметры у nginx доступны из переменных $arg_{имя_параметра}. В вашем примере они будут $arg_arg1 и $arg_arg2. Что-то типа:
location /nginx_var {
    default_type 'text/plain';

    content_by_lua "os.execute('/opt/test/script.sh ' .. ngx.var['arg_arg1'] .. ' ' .. ngx.var['arg_arg2'])";
}

A: Решил проблему следующим образом:
часть конфига nginx
location /test {
          content_by_lua_file "/opt/test/script.lua";
     }
Часть конфига скрипта - для вытаскивания данных из http строки:
local arg1 = ngx.var.arg_arg1
local arg2 = ngx.var.arg_arg2
      os.execute("echo ".. arg1 .." >> /tmp/test")
      os.execute("echo ".. arg2 .." >> /tmp/test")


text:
Q: Does anybody knows how a query is read by php when I call it? I'm having a hard time trying to compare dates in php using symfony framework when one of the dates is comming from a sql, I try to compare both dates but the one I'm calling from postgresql just won't be read as a regular date and I can't debug it because for some reason when there's a var_dump(), an echo() or a print_r() on the code it just freezes
I've tried to use it as an array, as string and so on, but I just can't take the response in a way that I'm able to compare with the current date.
/**
 * @return boolean
 */
public function isClientExpired(Clients $client)
{
    $em = $this->getEntityManager();
    $name = $client->getName();
    $query = $em->getConnection()->prepare("

        SELECT MAX(av.expiring_date)
        FROM ms_evaluations ev, ms_users_roles usr, ms_users us,
        ms_clients cl
        WHERE us.name = '$name'
        AND us.id = cl.user_client
        AND ev.urid_avaliado = usr.id
        AND usr.user_id = us.id

      ");
    $query->execute();
    $date = $query->fetchAll();
    $today = date('Y/m/d');

    if ($date<$today) {
        return true;
    } else {
        return false;
    }
}

The function should return true if the client evaluation was expired and false if it wasn't, but instead it always returns false.
The fact that I can't debug the code makes it even harder because I'm unable to see how is that query or the date comming to me and consequently I'm not able to figure out how to treat the response for my code to work. Does anybody at least knows how that date is comming to me? when I execute it directly on postgree it retuns me something like:
|´´´´max´´´´|
|2019/23/08|
It's a single row and a single column response, at least on postgre
Thanks in advance folks

A: The result of fetchAll() as the documentation say, is an array:
https://www.php.net/manual/pdostatement.fetchall.php
You should get the first result of fetchAll() or use fetchColumn().
https://www.php.net/manual/pdostatement.fetchcolumn.php


text:
Q: How to override the systemd default LogLevel When I look at the file /etc/systemd/system.conf I can see the following:
[Manager]
#LogLevel=info
#LogTarget=journal-or-kmsg
#LogColor=yes
#LogLocation=no

But if I run systemctl show -pLogLevel the result is
LogLevel=notice

I tried to create a directory named /etc/systemd/system.conf.d and to add a my.conf file inside and then rebooted, but couldn't see any change.
Am I looking at the right config file?

A: The dropin system configuration is relatively recently introduced. I believe you are running an old version of systemd.
I have tested your case on systemd 226 and things are working as expected.
$>:Development$ systemctl show -pLogLevel
LogLevel=info
$>:Development$ cat /etc/systemd/system.conf | grep LogLevel
#LogLevel=info


text:
Q: How do I setup simple firebase ajax request? I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. When I load test.html in my browser, the console says -
XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
//text.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Firebase Test</title>

//firebase rules
{
    "rules": {
        ".read": true,
        ".write": true
    }
}

A: Firebase expects the body to be a JSON string, so you'll need to stringify it:
$(document).ready(function () {
   var param = {lastName: "Doe", firstName: "John"};

   $.ajax({
     url: 'https://jleiphonebook.firebaseio.com/.json',
     type: "POST",
     data: JSON.stringify(param),
     success: function () {
       alert("success");
     },
     error: function(error) {
       alert("error: "+error);
     }
   });
 });

This will accomplish the same by the way:
$.post('https://jleiphonebook.firebaseio.com/.json',
  JSON.stringify(param),
  function () {
    alert("success");
  }
);


text:
Q: Make UIView Height Dependent On Negative Space Between Two Objects I know how to do this in code, but I am desperately trying to get this to work via the interface builder.
I have a UIView's, and then 2 UIView's below it.
I have the top UIView and the Bottom UIView set with rigid constraints.
I want the middle UIView to resize based on the space between them. If you look at the image below you can see the white space. I would like to know what constraint(s) I could use so that the dark blue bar bases its height on the space between the upper and lower UIViews.
TL;DR How can I get the dark blue bar to have its height be the negative space between 2 views.

Thanks!

A: The dark blue bar should have the following constraints:

*

*vertical space to white view = 0

*vertical space to light blue view = 0

*leading space to superview = 0

*trailing space to superview = 0


text:
Q: Dynamically apply a common dependent gradle file? I have a gradle file (common-utils.gradle) with a bunch of useful functions common across various projects. I've got that file in Artifactory. Now, I want my project's build.gradle to pull down that common-utils.gradle file and "apply from: 'common-utils.gradle'" so I can then use those utility methods.
Is there a way to do that dynamically, so the first time I run "gradle test" it fetches this common file and applies it? Or do I have to have some sort of one time "init" task I run after I clone the repository to go fetch the file?

A: well the easiest way to apply a *.gradle file you already have in artifactory is to reference this remote file in the apply from method:
apply from:'http://yourartifactory/repo/path/to/1.0/common-utils.gradle'

one downside of this is, that gradle does not cache this file atm. It will resolve it with every single gradle invocation. There is an open issue listed for that in the gradle issue tracker. you can vote for caching at http://issues.gradle.org/browse/GRADLE-835
cheers,
René


text:
Q: Setting Select Parameter = "" If User Doesn't Provide Input From Search Page I'm trying to run a simple select statement, and then output the results to a GridView in ASP.NET/ C# WebForms.  The database I'm pulling from is a Microsoft SQL Server Database.
I'm trying to pass the variables received from user input from the search page to the results page through URL variables. I will then get them on the results page, and apply them to the query.  If the results page is loaded without going through the search page first, the query string, From will be undefined, and the results page will display everything in the dataset.
The problem I'm running into is with the LastName. Let's say LastName is optional in the search and may or may not be added. FirstName is required and the page cannot be submitted to the results page without it (for simplicity).  The results page however can be accessed without being submitted from the search page. In this case, we simply do a select * from the table and populate the gridview with the entire result set.
Code behind for results page:
string fromval = Request.QueryString["from"];
//checking to see if from is next, otherwise just run the regular select * query.  If from = next, URL Variables exist.  If URL Variables exist, we need to add them to the query.
if (fromval == "next")
{
    //set variables from URL, sent from text boxes found on the search page
    string sfName = Request.QueryString["pfName"];
    string slName = Request.QueryString["plname"];
}

dsResults.SelectParameters.Add("FirstName", sfName.ToString());
//we will never hit this code without providing first name, so we know it will always be there

if (slName != "")  //if last name was provided in the search box
{
    dsResults.SelectParameters.Add("LastName", slName.ToString());
    //if I provide a value for last name, this works fine
}
else
{
    //simply set the value of @LastName to "" so like will ignore it. 'WHERE LASTNAME Like ""' should allow every row.  Runs fine with LastName LIKE "" in SqlServer Mgt. Studio.
    dsResults.SelectParameters.Add("LastName", "");
}

dsResults.SelectCommand = "SELECT * FROM [exampleTable] WHERE FirstName LIKE '%' + @FirstName + '%' AND LastName LIKE '%' + @LastName + '%';"

//check for a postback
if (!Page.IsPostBack)
{
    //bind the gridview data
    gvResults.DataSource = dsResults;
    gvResults.DataBind();
}

If I provide a value for Last Name in the URL, it runs fine with no problem, and gives the expected results.  If I don't, the query pulls nothing as if it's completely ignored.
Results page code simplified as much as possible:
<asp:GridView ID="gvResults" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvResults_RowDataBound" CssClass="table table-bordered">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
    </Columns>
</asp:GridView>

<!-- If the query is not changed in the code behind (happens when URL Variables Exist) then it simply selects * from the example table. -->
<asp:SqlDataSource ID="dsResults" runat="server" ConnectionString="myConnectionString" SelectCommand="SELECT * FROM [exampleTable]"></asp:SqlDataSource>

Search page code simplified as much as possible:
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequireFN" runat="server" ErrorMessage="First Name is required." ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>

<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" text="Search" /></div>

Code behind for search page:
protected void btnSearch_Click(object sender, EventArgs e)
{
    Response.Redirect("ResultsPage.aspx?from=next&pfName=" + txtFirstName.Text + "&plName=" + txtLastName.Text);
}

I realize that this may not be the best way to go about this, and am open to other suggestions if you have any.
Thank you.

A: Change
SELECT *
FROM [exampleTable]
WHERE FirstName LIKE '%' + @FirstName + '%' AND LastName LIKE '%' + @LastName + '%';

To this, where you bypass the LastName test when it is an empty string.
SELECT *
FROM [exampleTable]
WHERE FirstName LIKE '%' + @FirstName + '%' AND (coalesce(@LastName,'') = '' OR LastName LIKE '%' + @LastName + '%');

As an aside I recommend changing
dsResults.SelectParameters.Add("LastName", slName.ToString());

To the following where you fully specify the datatype and length rather than allowing them to be automatically determined. Doing it this way will avoid hard to find bugs and potentially improve performance.
dsResults.SelectParameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 128) { Value = slName.ToString() });

Where you use the correct SqlDbType and length to match the column in your database.
You might also want to check that the LastName string provided isn't just a long series of spaces because that will also return no results to the user and could be confusing to them.

A: You may have missed NULLs and DBNULL.Value values.  This amplifies the previous answer a bit...
Please change:
if (fromval == "next")
{
    //set variables from URL, sent from text boxes found on the search page
    string sfName = Request.QueryString["pfName"];
    string slName = Request.QueryString["plname"];
}

to read:
if (fromval == "next")
{
    //set variables from URL, sent from text boxes found on the search page
    string sfName = Request.QueryString["pfName"];
    string slName = Request.QueryString["plname"];
}
if (!(sfName is string)) { sfName = ""; }
if (!(slName is string)) { slName = ""; }

And in case you have spaces as your whole string (unlikely from Request.QueryString), please change to:
dsResults.SelectParameters.Add("LastName", SqlDbType.NVarChar, 128). value = slName.ToString().Trim();

-- no condition needed so eliminate the test on slName.
Finally, change the SQL to read like this...
dsResults.SelectCommand = "SELECT * FROM [exampleTable] WHERE FirstName LIKE '%' + @FirstName + '%' AND (@LastName = '' OR LastName LIKE '%' + @LastName + '%');"


text:
Q: Fdisk outputting seemingly absurd CHS values Take the following fdisk input:
o # Create DOS/MBR partition table.
n # Create new partition.
    p # Partition type
    1 # Partition ID
    2048 # Starting sector
    +4M # Ending sector
t # Assign said partition to a FAT12 filesystem.
    1 # FAT12 filesystem.
a # Mark said partition as bootable.
w # Write partition table.

Now, let's take a look at the MBR, specifically of the partition entry (partition entry starts at 0x80 near the end of the first line).
000001b0: 0000 0000 0000 0000 4a2f 9087 0000 8020  ........J/.....
000001c0: 2100 01a2 2200 0008 0000 0020 0000 0000  !..."...... ....
000001d0: 0000 0000 0000 0000 0000 0000 0000 0000  ................
000001e0: 0000 0000 0000 0000 0000 0000 0000 0000  ................
000001f0: 0000 0000 0000 0000 0000 0000 0000 55aa  ..............U.

According to the layout of the MBR portion entries (given here and here), the values we can glean the CHS tuple from are 0x20, 0x21, 0x00.
0x20 is rather simple: it equates to the 32nd head.
0x21 contains both the starting sector and the starting cylinder. 0x21 -> 0b00100001, giving 33 as the sector, and the 8th and the 9th bits of the cylinder resulting in 0 (0b00).
Combining the cylinder bits of 0b00 (from the 0x21) and 0b00000000, we get 0b0000000000 as the cylinder. All in all, we end up with a starting head of 32, a starting sector of 33, and a starting cylinder of 0.
When I try and load this CHS via BIOS interrupts, it complains that the CHS is invalid (I can read other sectors just fine). I assume this is because the head is 32; after all, why would you have a 16-platter hard disk?
tl;dr
Fdisk outputs MBR with CHS values.
My question is if I'm misunderstanding how the CHS value is encoded into the partition entry or if this is a quirk of fdisk.

A: According to fdisk itself, the C/H/S values are indeed supposed to be:

Command (m for help): x

Expert command (m for help): p

Disk test.disk: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xd771f127

Device     Boot Start   End Sectors Id Type  Start-C/H/S End-C/H/S Attrs
test.disk1 *     2048 10239    8192  1 FAT12     0/32/33  0/162/34    80

fdisk doesn't try to match the actual disk geometry – this has long been impossible within the C/H/S limits, so all it does is compute some values that would give the correct result when converted back to LBA.
Code from util-linux include/pt-mbr.h:
static inline void
dos_partition_sync_chs(struct dos_partition *p,
                       unsigned long long int part_offset,
                       unsigned int geom_sectors,
                       unsigned int geom_heads)
{
        unsigned long long int start = part_offset + dos_partition_get_start(p);
        unsigned long long int stop = start + dos_partition_get_size(p) - 1;
        unsigned int spc = geom_heads * geom_sectors;

        if (start / spc > 1023)
                start = spc * 1024 - 1;
        if (stop / spc > 1023)
                stop = spc * 1024 - 1;

        p->bc = (start / spc) & 0xff;
        p->bh = (start / geom_sectors) % geom_heads;
        p->bs = ((start % geom_sectors + 1) & 0x3f) |
                (((start / spc) >> 2) & 0xc0);

        p->ec = (stop / spc) & 0xff;
        p->eh = (stop / geom_sectors) % geom_heads;
        p->es = ((stop % geom_sectors + 1) & 0x3f) |
                (((stop / spc) >> 2) & 0xc0);
}

Comment from util-linux libfdisk/src/dos.c:
 /*
  * Conversion from C/H/S to LBA is defined by formula:
  *   LBA = (c * N_heads + h) * N_sectors + (s - 1)
  * Let o to be:
  *   o = LBA - (s - 1)
  * Then formula can be expressed as:
  *   o = (c * N_heads + h) * N_sectors
  */

why would you have a 16-platter hard disk?

You pretend to have a 16-platter hard disk in order to represent more disk space than the C/H/S system could normally represent. With only 64ki cylinders × 255 sectors × 2 heads per platter, all you can reach is ~8 GB per platter and obviously disks have slightly outgrown that by now.
The OS or firmware doesn't control each head individually, it just passes the numbers to the disk via ATA commands and gets data back, so it doesn't really care whether the disk somehow has 255 heads or not. And neither does the disk itself, anymore – the first thing disks now do is use a formula to convert the C/H/S values to linear LBA addresses (assuming the disk was given C/H/S and not LBA to begin with).
So even before BIOSes and OSes switched to dealing directly with LBA, it was already common to use "absurd" C/H/S values in order to access more disk space that the format would normally allow.
All current operating systems just ignore the C/H/S fields in MBRs and deal with LBA exclusively, and apparently that's what "OnTrack Disk Manager" used to do in MS-DOS. (Also, as far as I know, SCSI disks never supported C/H/S to begin with, they were always LBA-only.) I'm somewhat sure that just about any BIOS you'll find these days has native support for LBA via "extended INT 13h" (as Google tells me).


text:
Q: Get command line current folder in ruby gem I'm writing a small ruby gem which should generate couple of files, so I'm using executables.
How can I (in my ruby code) get the current folder of the command line from which the gem was executed?
For example, when I run my tool in this path:
~/Projects/MyProject/ $ my-tool

How can I get the ~/Projects/MyProject/ in my ruby code?
Thank you

A: Dir.pwd or Dir.getwd should do. Please note they return full absolute path, with ~ expanded.
https://ruby-doc.org/core-2.5.0/Dir.html#method-c-pwd


text:
Q: How I can set global variable inside function lua webView = nil
func()
function func()
              webView = native.newWebView( 0, 0, display.contentWidth, display.contentHeight )
              webView:request( "https://api.twitter.com/oauth/authenticate?oauth_token="..twitter_request_token )
              webView:addEventListener( "urlRequest", webListener )

end
print(webView) -- webView = nil

How I can get webView outside func, which I change inside func. Help ne, please

A: There is (almost) nothing wrong with your example. You need to make sure to call func() after you define it, but other than that it should work. For example, this outputs something for me:
webView = nil
function func()
  webView = "something"
end
func()
print(webView)

Yes, you can use explicit reference _G.webView inside the function, but there is no need to do that in your case.
If you still have an issue, it's probably because your func() is not executed when you think it is. Try to print the value of webView after it's assigned inside the function.

A: You can just append _G in front of your variable in will work as global variable.
Everywhere you have to use your variable with _G.
For Ex:
_G.yourVaribalename=display.newText();

A: You dont' need to declare variables, they are automatically global unless specified as local. And you can't call func() before func is defined. So try this:
function func()
    webView = native.newWebView( 0, 0, display.contentWidth, display.contentHeight )
    webView:request( "https://api.twitter.com/oauth/authenticate?oauth_token="..twitter_request_token )
    webView:addEventListener( "urlRequest", webListener )
end
func()
print(webView) -- webView will not be nil

In the above, webView is global so it will exist globally as soon as created within func(), and will continue to exist after func() returns.


text:
Q: How to distinguish "to fold the paper up / down / back / over"?
fold [transitive] to bend something, especially paper or cloth, so that one
  part lies on top of another part   fold something First, fold the
  paper in half/in two.
The bird folded its wings.
a pile of neatly folded clothes
fold something up He folded the map up and put it in his pocket.
fold something down The blankets had been folded down.
fold something back Don't fold back pages to mark your place in a book.
fold something over Fold the dough over on top of itself.

Do we consider the meanings of "up", "down", "back" & "over" literally? (See the picture) or these adverbs can be used overlapped or interchangeably?

A: Yes, the words can be used literally as in your drawings. However, fold up can also mean to put away something that has been designed to fold to make it smaller for storage, such as a map or a deckchair.


text:
Q: Grep repeating patterns with a loop I have two files:
file1:
ABA
FFR
HHI
HAB

file2:
ABAABAABAABAABAABAABAABAABATRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABGTHFOOLLLHHHUUJCIICXXTKCIABAGGC

Each line in file1 is a pattern that is repeating in the beginning of the corresponding lines in file2. I would like to get the parts of each line from file2 that are not the repeating patterns from file1.
desired output:
TRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
DEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
GTHFOOLLLHHHUUJCIICXXTKCIABAGGC

I tried to use this loop:
while read -r line
do

grep -v "$line{1,}"   file2.txt

done < file1.txt

But I go this output:
ABAABAABAABAABAABAABAABAABATRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABGTHFOOLLLHHHUUJCIICXXTKCIABAGGC
ABAABAABAABAABAABAABAABAABATRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABGTHFOOLLLHHHUUJCIICXXTKCIABAGGC
ABAABAABAABAABAABAABAABAABATRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABGTHFOOLLLHHHUUJCIICXXTKCIABAGGC

A: With e.g. ABA in the variable, grep -v "$line{1,}" would give grep the pattern ABA{1,}, meaning it'd look for a single A, a single B and then at least one A. The last repetition doesn't matter, though, as there's nothing after that, so even a single ABA would match that.
Well, except that by default, grep uses basic regular expressions (BRE), where the counted repetition must be written with backslashes, as \{n,m\}. In extended regular expressions (ERE), {1,} would one or more repeats (and so would +); but in BRE, it's just four literal characters (and + also is a regular character).
But grep prints full lines that match, or with -v, don't match; it doesn't remove parts of the line. (Except with grep -o where it only prints the matching part, but I don't think that would work with -v.) Also, with that loop, grep would look at all the lines for each pattern, which is why you get the contents of file2 repeated multiple times.

We'd need a loop that reads one line from each input on each iteration. It could be done in shell, but it would be slow. Something like AWK would be better, e.g.:
$ awk '{getline pat < "file1"; sub("^(" pat ")*", ""); print}' file2
TRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
DEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
GTHFOOLLLHHHUUJCIICXXTKCIABAGGC

The AWK program implicitly loops over the lines of file2 (and other files given on the command line), and here, we explicitly read one line from file1 each iteration. Then "^(" pat ")*" constructs a pattern like ^(ABA)*, which is matched against the current line, and substituted with the empty string.
This would not remove any instances of the pattern from further in the line, and e.g. ABAABAFOOABABAR would turn into FOOABABAR. If you want to remove those too, change it to gsub("(" pat ")*", "");.

A: A solution using awk which will remove the repeated pattern from every line in file1 from the corresponding line in file2:
awk 'NR==FNR { pattern[NR]="^(" $0 ")*"; next } { sub(pattern[FNR], ""); print }' file1 file2

Explanation:

*

*NR==FNR condition that matches the first file only.

*pattern[NR]="^(" $0 ")*"; construct a pattern from the string and add it to an array using the current line number as the index. ABA -> ^\(ABA\)* = any number of repeated string ABA at the beginning of the line.

*next skip all further processing. This results in the following action being applied to the second (and following) file(s) only.

*sub(pattern[FNR], "") substitute the pattern for the current line number with an empty string

*print print the (modified) line

A possible solution using awk which will remove every pattern in file1 from every line in file2:
awk 'NR==FNR { pattern[count++]="^(" $0 ")*"; next } { for(i = 0; i < count; i++) sub(pattern[i], ""); print }' file1 file2

Explanation:

*

*NR==FNR condition that matches the first file only.

*pattern[count++]="^(" $0 ")*"; construct a pattern from the string and append it to an array. ABA -> ^(ABA)* = any number of repeated string ABA at the beginning of the line. count will be the number of lines after processing file1

*next skip all further processing. This results in the following action being applied to the second (and following) file(s) only.

*for(i = 0; i < count; i++) loop over all patterns

*sub(pattern[i], "") substitute the pattern by an empty string

*print print the (modified) line

A: Following your approach of a while read-bash-loop, sed could do the trick as follows:
#!/bin/bash
i=0
while read pat ; do
    ((i++))
    sed -n "${i}s/^\($pat\)\{1,\}//g;${i}p" file2
done < file1

I am a bit confused regarding your interpretation of "repreating pattern", where I assume it should be present at least twice, e.g. \{2,\} would feel more fitting to me.

A: $ paste file1 file2 | awk '{sub("^("$1")*","",$2); print $2}'
TRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
DEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
GTHFOOLLLHHHUUJCIICXXTKCIABAGGC

The above assumes neither file contains spaces and file1 doesn't contain regexp metacharacters.

A: There you go mate:
challenge.sh
#!/bin/bash
readarray -t searchStrs < file1.txt
linesInFile=$((${#searchStrs[@]} - 1))
line=0
while [ ${line} -le ${linesInFile} ]
do
        srchStr=$(echo ${searchStrs[$line]})
        result=$(grep -E "^${srchStr}" file2.txt | sed "s@${srchStr}@@g")
        line=$((${line} + 1))
        echo ${result}
done

./challenge.sh
TRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
DEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
GTHFOOLLLHHHUUJCIICXXTKCIABAGGC

cat file2.txt
ABAABAABAABAABAABAABAABAABATRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABGTHFOOLLLHHHUUJCIICXXTKCIABAGGC

A: This solution uses sed and nl instead of awk. It assumes that the character # is never part of the patterns in file1 and that no pattern starts with a tab character. It will replace the patterns from file1 only in the corresponding line of file2. (cat -n file1 can be used as an alternative to nl file1.)
It uses a single nl process and two sed processes independent from the number of lines in file1 and file2.
sed -f <(nl file1|sed 's/ *\([0-9]*\)\t\(.*\)/\1s#^\\(\2\\)*##/') file2

Step-by-step execution instead of explanation:
$ nl file1
     1  ABA
     2  FFR
     3  HHI
     4  HAB

$ nl file1|sed 's/ *\([0-9]*\)\t\(.*\)/\1s#^\\(\2\\)*##/'
1s#^\(ABA\)*##
2s#^\(FFR\)*##
3s#^\(HHI\)*##
4s#^\(HAB\)*##

$ sed -f <(nl file1|sed 's/ *\([0-9]*\)\t\(.*\)/\1s#^\\(\2\\)*##/') file2
TRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
DEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
GTHFOOLLLHHHUUJCIICXXTKCIABAGGC

To show that the script will only replace the corresponding pattern, I use an additional file3 which contains combinations of patterns at the beginning of the lines:
ABAABAABAABAABAABAABAABAABAHABHABHABTRCFUJIKHRTHVFHJJHVHJJKKHGCC
FFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFFRFHJKGHKKBVDTHJNJ
HHIHHIHHIHHIHHIFFRDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
HABHABHABHABHABHABHABHABABAABAGTHFOOLLLHHHUUJCIICXXTKCIABAGGC

$ sed -f <(nl file1|sed 's/ *\([0-9]*\)\t\(.*\)/\1s#^\\(\2\\)*##/') file3
HABHABHABTRCFUJIKHRTHVFHJJHVHJJKKHGCC
FHJKGHKKBVDTHJNJ
FFRDEDRJFKOLGCUOUUKJGLNJKKKKJKJKJGGHHBCFDII
ABAABAGTHFOOLLLHHHUUJCIICXXTKCIABAGGC


text:
Q: How to keep focus when AJAX updates dropdown I am using the following code which is calling a php page that grabs data from a DB table and updates a dropdown
<script type="text/javascript">
function refresh()
{
var req = new XMLHttpRequest();
Console.log("Grabbing Value");
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {
document.getElementById('monitor').innerHTML = req.responseText;
}
}
req.open("GET", 'test.php?lang=<?php echo $lng;?>', true);
req.send(null);
}
function init()
{
refresh()
var int=self.setInterval(function(){refresh()},3000);
}
</script>

This is working fine but my problem is, when I have an item in the drop down box selected and then this gets updated, the drop down box goes to the 1st item.
Is there any way for ajax to leave what I have highlighted and still update the dropdown box?


text:
Q: Set a class inside a dialog box Is it possible to open a class inside a dialog box in Android?
For example :
Dialog settingsDialog = new Dialog(this);
        settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        settingsDialog.setContentView(getLayoutInflater().
                                   inflate(R.layout.image_pager, null));
        settingsDialog.show();

is opening an image. How can I do the same for loading classes instead of xml layout?
Additional info:
This is my ImagePager class
public class ImagePopUp extends BaseActivity implements OnClickListener {

    private ViewPager pager;
    Button boutton_retour;
    public static String img;

    private DisplayImageOptions options;
    String url,image,title;
    ArrayList<Post> PostDetails = new ArrayList<Post>();

    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_diaporama_pager);

        showViewHolderExtra();

    }

    private class ImagePagerAdapter extends PagerAdapter {

        private String[] images;
        private LayoutInflater inflater;

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        ImagePagerAdapter(String[] images) {
            this.images = images;
            inflater = getLayoutInflater();
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public Object instantiateItem(View view, int position) {

            Dialog settingsDialog = new Dialog(ImagePopUp.this);
            settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            settingsDialog.setContentView(getLayoutInflater().inflate(R.layout.image_layout, null));
            settingsDialog.show();

            final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
            final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.im_pager);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loadinprogress);

            imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {

                public void onLoadingStarted() {
                    spinner.setVisibility(View.VISIBLE);

                }

                public void onLoadingFailed(FailReason failReason) {
                    String message = null;
                    switch (failReason) {
                        case IO_ERROR:
                            message = "Input/Output error";
                            break;
                        case OUT_OF_MEMORY:
                            message = "Out Of Memory error";
                            break;
                        case UNKNOWN:
                            message = "Unknown error";
                            break;
                    }

                    Toast.makeText(ImagePopUp.this, message, Toast.LENGTH_SHORT).show();

                    spinner.setVisibility(View.GONE);
                    imageView.setImageResource(android.R.drawable.ic_delete);
                }

                public void onLoadingComplete(Bitmap loadedImage) {
                    spinner.setVisibility(View.GONE);
                    Animation anim = AnimationUtils.loadAnimation(ImagePopUp.this, R.anim.fade_in);
                    imageView.setAnimation(anim);
                    anim.start();
                }

                public void onLoadingCancelled() {
                    // Do nothing
                }
            });

            ((ViewPager) view).addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }

    }

    public void showViewHolderExtra(){

        String[] seperated = img.split(";");

        Bundle bundle = getIntent().getExtras();
        int pagerPosition = bundle.getInt("POSITION", 0);

        System.out.println("image: "+ pagerPosition);

        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(new ImagePagerAdapter(seperated));
        pager.setCurrentItem(pagerPosition);

        options = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.ic_launcher)
            .cacheOnDisc()
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
            .build();
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch(v.getId()){

        case R.id.boutton_retour:
            finish();
        break;

        }
    }
}

I want this to appear in the dialog box on click.

A: You want the whole activity to load in a dialog box. There's a couple of ways. If the activity is just a ViewPager, you could just set the dialog's content to just that ViewPager:
    Dialog settingsDialog = new Dialog(this);
    settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    ViewPager mViewPager = new ViewPager(this);
    ImagePagerAdapter adapter = new ImagePagerAdapter(images);
    mViewPager.setAdapter(adapter);
    settingsDialog.setContentView(mViewPager);
    settingsDialog.show();

You could even load the whole activity with intents like normal, but then just have it look like a dialog, with a dialog theme or otherwise.
If you're made aware that .setContentView can take a resource id or a view, then it should become self-apparent what methods to employ. It would be just like onCreate.

A: The easiest way is just to set in your AndroidManifest:
 <activity
            android:name=".ImagePopUp"
            android:theme="@android:style/Theme.Dialog" >
        </activity>

If you need the dialog to have a custom size, you can use something like this at the beginning of your ImagePopUp class:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screen_width = dm.widthPixels;
int screen_height = dm.heightPixels;

getWindow().setLayout((screen_width *0.75), (int) (screen_height - 50));
getWindow().setGravity(Gravity.CENTER);

Then, open the class as usual, using an intent on click:
Intent intent = new Intent(YourActualClass.this, ImagePopUp.class);
startActivity(intent);

A: You can do this by using a custom view in your layout xml.
 settingsDialog.setContentView(getLayoutInflater().inflate(R.layout.image_pager, null));

layout/imagepaper.xml
<com.your.package.CustomLinearLayout
   xmlns: ...
   android:layout_width="" ... etc
   />

Then this is your 'class' for the dialog's layout
CustomLinearLayout.java
public class CustomLinearLayout extends LinearLayout {

     // Overridden constructors

     // onFinishInflate() etc

}

Another way to do this is with a 'DialogFragment'
shown here: http://blog.blundell-apps.com/tut-generic-fragment-dialog/
Your class extends DialogFragment:
 public class OneOptionDialogFragment<T> extends DialogFragment {

       // do stuff

 }

And to show the dialog (taken from above url):
 OneOptionDialogFragment<UserDetails> dialogFragment = OneOptionDialogFragment.newInstance(title, message, buttonText);
    dialogFragment.show(getSupportFragmentManager(), "DeleteFragTag");


text:
Q: WYSIWYG editor for Rails with Paperclip Integration I'm looking for a way of integrating a WYSIWYG editor into my rails app so it will use Paperclip for Image / File uploads.
What I want is this: User can use a WYSIWYG field to create some rich text. They can upload an image into this text but the image will be stored nicely in a DB (hopefully using something like Paperclip) instead of just being dumped in a folder on the server.
Can this be done? I've spent a fair while trawling the net for solutions to this problem. The closest I've come is a very handy looking plugin: http://github.com/galetahub/rails-ckeditor
However, the instructions are a bit vague and I got bogged down partway through the implementation.
I don't care what WYSIWYG editor I use, my requirements are very simple. I'm also not totally set on Paperclip so if there's another way (using attachment_fu) I'm happy to consider that too.
Edit:
I'm also happy if I can integrate a WYSIWYG editor with Paperclip and just store the images in the file system. It doesn't have to be uploaded to the DB. Any takers now?

A: This question was answered here:
WYSIWYG image uploads in Rails App
Thanks @Matchu


text:
Q: Digital ocean deployment -node.js app (Runs on ip, but not on domain) I am trying to deploy my node.js app on digitalocean. When i open it on ip like
107.170.16.24:3000 , it opens perfectly.
But, when i open it on domain like theconnect.io . I see
This site can't be reached

www.theconnect.io took too long to respond.

Ii checked nameservers and those look ok. Can someone tell me where is the error? Even if i know the error source, I may rectify it. But, right now i am confused , where should i look for error.
when i connect my ubuntu terminal and run "nodemon" command. It runs perfectly and shows me text like
root@nodejs-512mb-nyc2-01:~/poppop2# nodemon
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
in dir routes / index
moving to 404
onListening now
Db Connected

So, it looks everything is running fine as far app is concerned. Can someone tell me why it doesnt open when i type domain name theconnect.io

A: I just solved it. So, I will post my answer here. I changed port to 80 and it worked. Previously, it was 3000. Now, it works. Thanks


text:
Q: How do I forward-declare a constexpr object at namespace scope? On clang (trunk) I can forward declare an object that will later be defined with constexpr as follows:
// Fwd-declarations
struct S;
extern const S s;

// (... later) definitions
struct S {};
constexpr S s {};

Gcc 4.8 doesn't like this, telling me the forward-declaration and the definition differ in constexpr-ness. Is gcc speaking truth, or is this just a gcc bug?

A: I can't find any language in my copy of the C++11 standard that explicitly forbids constexpr-ness from mis-matching between a declaration and a definition, but I do see language explicitly forbidding constexpr from being used with extern (section 7.1.5), and I also see language requiring the initializer for a class-level static constexpr variable to be in the class.  Also, since the utility of constexpr is significantly reduced when the definition of the variable or its type is unavailable, I think it's likely the intent is that constexpr variables must be defined (or, for static class members, initialized) when they are declared.
As a work-around, perhaps you could provide an extern alias for the variable.  This would allow you to take its address, and that's the only thing I can think of that a forward-declaration would allow.  For example:
// .hpp file:
struct C;
extern C const &c;

// .cpp file:
struct C {
    constexpr C() { }
};
constexpr C cc;
C const &c = cc;

Side note:  I know that in C++14, they revisited/are revisiting constexpr, so it's possible that it works in Clang because it's implementing some draft spec of C++14.

A: The real answer is that gcc is plain wrong, clang is right. The code above should compile, and it will in gcc 4.9. Or so says this bug report.


text:
Q: await keyword doesn't wait in dart I'm using await keyword to wait for a method to complete and return something and then use switch statements to execute block of code based on the method returned value, but it doesn't await for it's value and when i try to print the value the output is null!
here is the code:
 PhoneNumVerification status = await accountRecoveryAdmin.verifyUserPhoneNumber(phoneNum);
 print(status); // prints null because it didn't wait for the method to complete
 switch (status) {
 // some code
 }

and here is the method:
enum PhoneNumVerification {
     failed,
     verified,
     wrongInput,
     smsVerificationNeeded
}

Future<PhoneNumVerification> verifyUserPhoneNumber(String phoneNum) async {
if (phoneNum.isEmpty ||
    !phoneNum.startsWith('01') ||
    phoneNum.length != 11) {
  return PhoneNumVerification.wrongInput;
}
try {
  await _auth.verifyPhoneNumber(
    phoneNumber: '+2$phoneNum',
    timeout: Duration(seconds: 30),
    verificationCompleted: (_) {
      return PhoneNumVerification.verified;
    },
    verificationFailed: (exception) {
      print(exception.message);
      return PhoneNumVerification.failed;
    },
    codeSent: (String verificationId, [int forceResendingToken]) {
      this.verificationId = verificationId;
      return PhoneNumVerification.smsVerificationNeeded;
    },
    codeAutoRetrievalTimeout: null,
  );
} catch (e) {
  print(e);
  return PhoneNumVerification.failed;
}
}

A: await accountRecoveryAdmin.verifyUserPhoneNumber(...) does wait.  The problem is that accountRecoveryAdmin.verifyUserPhoneNumber() didn't return a value.  If you run dartanalyzer on your code, it should report that not all paths through verifyUserPhoneNumber return a value.
Here's a simplified version of your code to make the problem more obvious:
Future<PhoneNumVerification> verifyUserPhoneNumber(String phoneNum) async {
  // ...

  try {
    await _auth.verifyPhoneNumber(
      // ...
    );
  } catch (e) {
    print(e);
    return PhoneNumVerification.failed;
  }
}

You can see the try block does not return a value.  It passed callbacks that have return statements, but that just specifies what those callbacks return; they are not what verifyUserPhoneNumber returns.
One way to fix it would be to make those callbacks set a variable in verifyUserPhoneNumber's scope, and later return that:
Future<PhoneNumVerification> verifyUserPhoneNumber(String phoneNum) async {
  // ...

  try {
    PhoneNumVerification result;
    await _auth.verifyPhoneNumber(
      // ...
      verificationCompleted: (_) {
        result = PhoneNumVerification.verified;
      },
      verificationFailed: (exception) {
        // ...
        result = PhoneNumVerification.failed;
      },
      codeSent: (String verificationId, [int forceResendingToken]) {
        // ...
        result = PhoneNumVerification.smsVerificationNeeded;
      },
      // ...
    );

    return result;
  } catch (e) {
    print(e);
    return PhoneNumVerification.failed;
  }
}

Edit:
It's not clear to me what the Future returned by FirebaseAuth.verifyPhoneNumber represents.  It could just signify that the request was sent, not that the verification completed.  If you want your function wait for verification to complete, you could do:
Future<PhoneNumVerification> verifyUserPhoneNumber(String phoneNum) async {
  // ...

  try {
    final verificationComplete = Completer<PhoneNumVerification>();
    await _auth.verifyPhoneNumber(
      // ...
      verificationCompleted: (_) {
        verificationComplete.complete(PhoneNumVerification.verified);
      },
      verificationFailed: (exception) {
        // ...
        verificationComplete(PhoneNumVerification.failed);
      },
      codeSent: (String verificationId, [int forceResendingToken]) {
        // ...
        verificationComplete(PhoneNumVerification.smsVerificationNeeded);
      },
      // ...
    );

    return await verificationComplete.future;
  } catch (e) {
    print(e);
    return PhoneNumVerification.failed;
  }
}


text:
Q: Finding the biggest diagonal element of a square matrix I'm trying to find the max. diagonal element of a square matrix (let's take a 2x2 matrix as an example; assume n = 2).
My logic is based on comparing [i][i] to [i + 1][i + 1] (the first element of a diagonal matrix compared to the next diagonal element).
Example input:
2
1 2 3 4
Example output:
First we print out the complete matrix:
1 2
3 4
Then we print out the diagonal elements only:
Diagonal elements: 1 4
Max. diagonal matrix element: 4206628 - this is where I'm not sure why it's messing up. The maximum diagonal element is supposed to be 4 in this case.
#include <stdio.h>

int main()
{

int i, j, n, max = 0;

scanf("%d", &n);

int MAT[n][n];

for (i = 0; i < n; i++){
    for (j = 0; j < n; j++){
        scanf("%d", &MAT[i][j]);
    }
}

 for (i = 0; i < n; i++){
    for (j = 0; j < n; j++){
        printf("%d\t", MAT[i][j]);
    }
    printf("\n");
}   printf("\n");

for (i = 0; i < n; i++){

    printf("%d\t", MAT[i][i]);
    printf("\n");

    if (MAT[i][i] > MAT[i + 1][i + 1]){
        max = MAT[i][i];
    }   else max = MAT[i + 1][i + 1];

}

printf("\nMax. diagonal matrix element: %d", max);

return 0;
}

A: The problem seems to be coming from else max = MAT[i + 1][i + 1]. Since MAT[i + 1][i + 1] is not always defined (imagine when i = 1, you go out of the array length), a random value is read from memory. The way I would solve this problem you be to change the condition where you change the max value.
if (MAT[i][i] > max) // replacing max when the current value is bigger
{
    max = MAT[i][i];
}
// else not necessary

Using this snippet would not work if the array was filled with negative number since max is initialized at 0.


text:
Q: Raw partition recovery without data loss I had a dynamic disk and in order to get back to MBR I have used this video but instead of getting back to NTFS, I now have a RAW filesystem. Using Testdisk, I am getting Can't open filesystem. Filesystem seems damaged. when I try to list files, any way to recover them.
PS: Some article suggest using a data recovery tool, the problem that it would change date created and modified of folders and probably which is not desirable in my case.
Steps taken:
In Disk Management, right click and convert to MBR disk, and go through with it.
Use Minitool PW to restore partitions, it worked but the data partition was RAW.
I tried TestDisk and Minitool and always got the mentioned error.
So I formatted the disk and tried to get my files back but instead, I've gotten filenames like File_0001.ext.
To the best of my knowledge, I haven't written anything on the drive so theoretically what was done could be reversed.


text:
Q: UIView doesn't sizeToFit if a method is called by its self I have created a method
- (UIView *) drawView:(NSMutableArray *) arrayToDisplay;
wich works perfectly if it is called by another method, e.G.
-(void) preperationsBeforeDrawView.
But inside of arrayToDisplay I have a loop which gets activated if it finds a special object.

- (UIView *) drawView:(NSMutableArray *) arrayToDisplay {

[UIView * overAllView = [[UIView alloc] initWithFrame:CGRectZero];

 while ([arrayToDisplay containsObject:myObject]) {

     NSMutableArray *subArray = [[arrayToDisplay subarrayWithRange:NSRange] mutableCopy];
     UIView *result = [self drawView:subArray];
     [overAllView addSubView:result];
}
/*

* All the others drawView things

* Create Labels & Views

* add them as subview

*/
[overAllView sizeToFit];
return overAllView;
}

So, if the while-Loop is calling [self drawView:subArray] the returned UIView doesn't sizeToFit, even if it has subViews which have (width, hight != 0). It doesn't show any effect no matter if I call sizeToFit inside drawView or after. But the returned UIView from the first called drawView works perfectly :/.
Can you please tell me where I made the mistake?


text:
Q: File Structure / Directory View in Drupal Is there a way to have some sort of file structure or Directory view in Drupal? I've been searching for a couple weeks but haven't found anything.
EDIT: I am wanting some sort of file organization for every webpage in the content view (admin level), I want to be able to have folders and subfolders, that would essentially look publicly like www.example.com/folder/another_folder/file.html

A: If you're looking for a file browser/manage for your user, one of the more popular ones is IMCE.

IMCE is an image/file uploader and browser that supports personal
  directories and quota.

Check out the related projects on the IMCE page to see other similar modules.


text:
Q: How to read content from a file and store it in a 2D array I am trying to read the contents from a text file and store them in an 2D array, however I have run into an error.
These are the contents of the file:
R1  R2  R3  R4  R5
1   J   S2  Q   S2  J
2   J   S2  Q   S2  J
3   J   S2  Q   S2  J
4   J   S2  Q   S2  J
5   J   Q   S5  Q   J
6   S3  Q   S5  Q   S3
7   S3  Q   S5  Q   S3
8   S3  Q   S5  Q   S3
9   S3  S1  S5  S1  S3
10  A   S1  S5  S1  A
11  A   S1  K   S1  A
12  A   S1  K   S1  A
13  A   S1  K   S1  A
14  A   S1  K   S1  A
15  S2  A   K   A   S2
16  S2  A   S3  A   S2
17  S2  A   S3  A   S2
18  S2  A   S3  A   S2
19  S2  A   S3  A   S2
20  Q   S5  S3  S5  Q
21  Q   S5  J   S5  Q
22  Q   S5  J   S5  Q
23  Q   S5  J   S5  Q
24  Q   S5  J   S5  Q
25  S4  K   S2  K   S4
26  S4  K   S2  K   S4
27  S4  K   S2  K   S4
28  S4  K   S2  K   S4
29  S4  K   S2  K   S4
30  K   S4  S2  S4  K
31  K   S4  A   S4  K
32  K   S4  A   S4  K
33  K   S4  A   S4  K
34  K   S4  A   S4  K
35  S1  S4  A   S4  S1
36  S1  A   S1  A   S1
37  S1  A   S1  A   S1
38  S1  A   S1  A   S1
39  S1  A   S1  A   S1
40  Q   S3  S1  S3  Q
41  Q   S3  Q   S3  Q
42  Q   S3  Q   S3  Q
43  Q   S3  Q   S3  Q
44  Q   J   Q   J   Q
45  S2  J   S4  J   S2
46  S2  J   S4  J   S2
47  S2  J   S4  J   S2
48  S2  S2  S4  S2  S2
49  S2  S2  A   S2  S2
50  J   S2  A   S2  J
51  J   S2  A   S2  J
52  J   Q   A   Q   J
53  J   Q   A   Q   J
54  J   Q   J   Q   J
55  S5  Q   J   Q   S5
56  S5  J   J   J   S5
57  S5  J   J   J   S5
58  S5  J   S1  J   S5
59  S5  J   S1  J   S5
60  A   S3  S1  S3  A
61  A   S3  S1  S3  A
62  A   S3  Q   S3  A
63  A   S3  Q   S3  A
64  A   K   Q   K   A
65  S1  K   Q   K   S1
66  S1  K   S4  K   S1
67  S1  K   S4  K   S1
68  S1  Q   S4  Q   S1
69  S1  Q   S4  Q   S1
70  K   Q   K   Q   K
71  K   Q   K   Q   K
72  K   J   K   J   K
73  K   J   K   J   K
74  K   J   K   J   K
75  S3  J   J   J   S3
76  S3  NA  J   NA  S3
77  S3  NA  J   NA  S3
78  S3  NA  J   NA  S3
I have tried to do it by splitting each line into a string array, however I have run into the previous error.
This is my current code:
package slots;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Slots {

public static void main(String[] args) throws FileNotFoundException
{
   Scanner sc = new Scanner(new BufferedReader(new FileReader("reels_template.txt")));

   String [][] arr = new String[78][6];

   while(sc.hasNextLine()) {
     for (int i=0; i<78; i++) {
         String[] line = sc.nextLine().trim().split(" ");
        for (int j=0; j<5; j++) {
            arr[i][j] = line[j];
        }
     }
  }

   for (int i = 0; i < 78; i++) {
       for ( int j = 0; j < 6; j++) {
           System.out.print(arr[i][j]);
       }
       System.out.println();
   }

}

}
This is the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at slots.Slots.main(Slots.java:19)
Java Result: 1

EDIT:
After making some changes based on Logan Wlv's remark, I have ran into the following problem. The code is able to read the file successfully, however it does not read the last element of each line. Updated code:
Scanner sc = new Scanner(new BufferedReader(new FileReader("reels_template.txt")));

   String [][] arr = new String[78][6];
   String[] line = {};

     for (int i=0; i<78; i++) {
         if (sc.hasNextLine()) {
         line = sc.nextLine().trim().split("\\s+");
         }
        for (int j=0; j<5; j++) {
            arr[i][j] = line[j] + " ";
        }
     }

Sample output:
# R1 R2 R3 R4 null
1 J S2 Q S2 null
2 J S2 Q S2 null
3 J S2 Q S2 null

A: The check for sc.hasNextLine() is at wrong place, try following way. Also remove while loop.
    for (int i=0; i<78; i++) {
        if(sc.hasNextLine()) {
            String[] line = sc.nextLine().trim().split(" ");
            for (int j=0; j<5; j++) {
                arr[i][j] = line[j];
            }
        } else {
            break;
        }
    }

A: Every-time you have to skip 6 words from the current cursor
while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String[] words = line.trim().split(" ");
            int k = 0;
            for (int i = 0; i < 78; i++) {
                for (int j = 0; j < 6; j++) {
                    arr[i][j] = words[i + j + k];

                }
                k += 5;
            }
        }


text:
Q: Check the width of all images and set new width if over a certain size I have a page with several images that have the same class ".bestsell-thumb" . How can I make all these images into an array, then get each ones width and if it's greater than 80px change it to 80px?
I tried this
var  bsThumb = $(".bestsell-thumb").each(function(){
             $(this).height();
});

just to get the heights, but I'm pretty sure I'm way off.
Thanks for any help.

A: $(".bestsell-thumb").width(function(i, w) {
    return w > 80 ? 80 : w;
});

They do of course have to be loaded before you can get anything!

A: Try
$(".bestsell-thumb").each(function(){
    if ($(this).width() > 80) {
        $(this).css("width", "80px");
    }
});

A: You can try:
$(".bestsell-thumb").each(function(){
    if($(this).width() > 80){
        $(this).width("80px");
    }
});

A: Use CSS instead of JavaScript:
.bestsell-thumb {
  max-width: 80px;
  height: auto; /* maintains proportions */
}

You can set max-height in the same style block, too -- just set width: auto as well.


text:
Q: Visual Studio Emulator cannot start whitout internet? Exit Code 10 I have a strange problem, the VS Emulator starts normally if the internet is active, but without, it gives me this error:

17/10/2015 18:56:12: [Informational] Installable profiles initialized. Devices: 17 Platforms: 2
  17/10/2015 18:56:15: [Informational] Waiting to launch device...
  17/10/2015 18:56:15: [Informational] Launching Device: 4.5" Lollipop (5.1.1) XHDPI Phone
  17/10/2015 18:56:15: [Informational] Validating emulator arguments...
  17/10/2015 18:56:15: [Informational] Determining if emulator is already running...
  17/10/2015 18:56:15: [Informational] Preparing virtual machine...
  17/10/2015 18:56:18: [Informational] Launching emulator...
  17/10/2015 18:57:30: [Critical] Could not launch 'VS Emulator 4.5" Lollipop (5.1.1) XHDPI Phone' device. Exit code 10.
  17/10/2015 18:57:30: [Critical] XDE Path: C:\Program Files (x86)\Microsoft XDE\10.0.10240.0\xde.exe
  17/10/2015 18:57:30: [Critical] XDE Arguments: /sku Android /displayName "VS Emulator 4.5\" Lollipop (5.1.1) XHDPI Phone" /memSize 1024 /diagonalSize 4.5 /video "720x1280" /vhd "C:\Users\Fabio\AppData\Local\Microsoft\VisualStudioEmulator\Android\Containers\Local\Devices\vhd\4.5_Lollipop_(5.1.1)_XHDPI_Phone\image.vhd" /name "VS Emulator 4.5-inch Lollipop (5.1.1) XHDPI Phone.fabio"
  17/10/2015 18:57:30: [Critical] XDE Exit Code: CouldntStartVm (10)

The emulator has not verified if the VM is in execution: this host is unknown
Anybody knows the solution? I don't have internet always.
Thanks.


text:
Q: Extending django-oscarapi API ROOT to custom API class I have a django oscar application and I use django-oscarapi for my custom APIs. Some things are missing from the oscarapi like category and promotions but I have been able to use django-restframework to create the category API but the challenge I am facing now is how to add it to the API-ROOT. This is my code for rendering categories
customapi serializer class
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'numchild', 'name', 'description', 'image', 'slug')

Views
class CategoryList(generics.ListAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class CategoryDetail(generics.RetrieveAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

customapi/urls.py
url(r'^caty/$', CategoryList.as_view(), name='category-list'),
url(r'^caty/(?P<category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$',
        CategoryDetail.as_view(), name='category'),

Thanks in advance

A: You have to override the root view of oscarapi.  There maybe a way to partially override the module, but I was unsuccessful at this.
module to override:
https://github.com/django-oscar/django-oscar-api/blob/master/oscarapi/views/root.py
In your project add a file yourApp/api/views/root.py and paste in the contents of the source file above.
You can then add end points by adding a tuple to the PUBLIC_APIS or ADMIN_APIS function.


text:
Q: WPF: ScrollViewer in grid I have a grid:
<Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="*"/>
</Grid.RowDefinitions>

The second row is with scrollviewer:
    <ScrollViewer VerticalScrollBarVisibility="Auto" MinHeight="400" Grid.Row="1">
            <ItemsControl ItemsSource="{Binding SelectedUserControls}"/>
    </ScrollViewer>

I want the second row to be with scroll if needed,
But the scroll is never visible, event if the items controls are bigger than the screen.
How can i get the scroll to appear when needed?

A: EDIT:
Try removing 'MinHeight=400' and I bet it works!!
You have a MinHeight on your ItemsControl of 400. So until you have enough items to take up all 400, you will not see your scrollbar. I'm guessing the container holding your grid (or the explicit height on your grid is less that 400), and you have enough items to be too big for that container, but not enough items to fill the MinHeight of your ItemsControl.
Original Answer: I just ran a test app with 30 items in it (enough to fill the MinHeight) and it seems to work fine:
<Window x:Class="TestApp11.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:l="clr-namespace:TestApp11"
  Title="Window1" Loaded="Window_Loaded" Height="600" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ScrollViewer VerticalScrollBarVisibility="Auto" MinHeight="400" Grid.Row="1">
            <ItemsControl>
                ...
                 <ListBoxItem Content="Item 30" />
                ...
            </ItemsControl>
        </ScrollViewer>
    </Grid>
</Window>

Does your container holding your grid have an explicit Height?

A: Change MinHeight to MaxHeight.


text: Q: Fundamental Theorem of Projective Geometry for Finite Fields I was trying to understand the proof that the automorphism group of a projective plane over a finite field $F_q$  (denoted $PG(2, q)$) is $P\Gamma L(3, q)$, ie. elements $PGL(3, q)$ composed with field automorphisms of $F_q$ acting coordinate-wise. It is clear that $P\Gamma L(3, q) \leqslant Aut(PG(2, q))$, and I read that the reverse inclusion is true due to the Fundamental Theorem of Projective Geometry. I have seen a proof of the Fundamental Theorem of Projective Geometry in Artin's "Geometric Algebra," but it uses some deeper concepts in Algebraic Geometry. I was wondering if there is a simpler proof for the finite field case?


text:
Q: Understanding the output of perspective transform in context to the destination points? I am trying to understand the output of warpPerspective and getPerspectiveTransform. So I took an image given as:

and tried to transform complete image (using the boundary coordinates) into
coordinates as explained by pts2 below. Here is what I did.
import cv2
import numpy as np

image = "b.jpg"

img = cv2.imread(image)

pts1 = np.float32([
        [0,0],
        [0, img.shape[1]],
        [img.shape[0],img.shape[1]],
        [img.shape[0],0]
])

pts2 = np.float32([
        [100,100],
        [100,300],
        [300,300],
        [300,5]
])

M = cv2.getPerspectiveTransform(pts1,pts2)

dst = cv2.warpPerspective(img,M,(400,400))

cv2.imwrite("test.png", dst)

The output of the above code looks as follows:

What does this output mean in terms of the destination coordinates :
pts2 = np.float32([
        [100,100],
        [100,300],
        [300,300],
        [300,5]
])

Why does the output appear the way it appears right now? I cannot map this in my mind when I see the pts2 and compare with pts1 which are simple boundary coordinates.


text:
Q: UTF8Encoding string to byte[] conversion unexpected behavior I have this piece of code:
byte[] bytes = ...

// Here my bytes.Lenght is 181 (for example)

var str = UTF8Encoding.UTF8.GetString(bytes);
bytes = UTF8Encoding.UTF8.GetBytes(str);

// Here my bytes.Lenght is 189

Why?
How can I convert correctly the string to byte[]?
Edit: An example
public class Person
{
    public string Name { get; set; }
    public uint Age { get; set; }
}

...

Person p = new Person { Name = "Mary", Age = 24 };

string str;
byte[] b1, b2;

using (var stream = new MemoryStream())
{
    new BinaryFormatter().Serialize(stream, p);
    b1 = stream.ToArray();
    str = UTF8Encoding.UTF8.GetString(b1);
}

b2 = UTF8Encoding.UTF8.GetBytes(str);

A: // Here my bytes.Lenght is 181 (for example)
// Here my bytes.Lenght is 189

That can happen.

How can I convert correctly the string to byte[] ?

A difference in size does not mean the conversion is invalid. The initial sequence might have been though.
If you want to preserve the size, use ASCII encoding.

After the expanding edit:
new BinaryFormatter().Serialize(stream, p);
b1 = stream.ToArray();
str = UTF8Encoding.UTF8.GetString(b1);
b2 = UTF8Encoding.UTF8.GetBytes(str);

You make the assumption that a BinaryFormatter will apply  UTF8 encoding to strings.
It probably does not. It will add extra data (markers and size fields) to the stream.
So your 2 conversion (Serialize and GetString ) are just not compatible.
Aside from a difference in size, when you display the result it will probably contain some 'strange' characters.

Second Edit:

When I deserialize the new byte array (b2) it trows an Exception

Right. What you actually need is Convert.ToBase64String(), not UTF8.GetString()
Base64 strings can be stored and transported as strings and then converted back to byte[] again.

A: If you want to serialize an arbitrary byte[] to and from a string, don't use UTF8 encoding, use Base64.

A: Don't try to convert binary data to string with  UTF8.GetString(or any encoding). Use Convert.ToBase64String and  Convert.FromBase64String instead


text:
Q: Domain Name does not resolve to site's DC I am facing a puzzle:
My company has several branches, each branch's subnets have been defined in their own respective site, and each branch has its own RODC.
However, when pinging to the domain name (let's say, "example.com"), instead of resolving to the site's RODC, it resolves to the one of the main DCs on the Head Office.
AFAIK, when a computer on a site tries to resolve the domain name itself (e.g., when trying to access \\example.com\netlogon), it should resolve to the site's domain controller.
So, why am I seeing this behavior here?
Additional info:

*

*The main DCs on Head Office are a mix of 2008 and 2008 R2

*The RODC on the branches are 2008 R2

Any suggestion will be helpful. TIA.

More Information:
The problem was that the WAN link between Head Office and Branches are very slow (bandwidth costs a fortune in my country). There are several large files that we replicate through \\example.com\netlogon, and because some branch computers resolve example.com into the IP address of the Head Office DC, they're pulling those files through the slow WAN link instead of accessing the replica on the branch RODCs.

A: In our DNS, all of the DCs are listed in the DNS as ourdomain.com.  I believe this is expected behavior.  If you are worried about how logins are being handled, then you are looking at the wrong DNS entries.  For a description of how clients find their site's DCs, take a look at the following article.
http://technet.microsoft.com/en-us/library/cc978016.aspx
If the issue is the DFS location of a local share, you might take a look at this thread:
http://www.activedir.org/ListArchives/tabid/55/forumid/1/postid/35786/view/topic/Default.aspx

A: As uSlacker mentioned, this may not actually adversely affect operation of Windows clients and certain functions such as ldap communication.  This is due to how the internal Windows dc locator process functions, which among other things, prioritizes selected domain controllers by site.
A straight dns lookup at the command prompt is just that - a DNS lookup.  If a domain controller has registered it's A record in the domain zone, it may be returned as a response to a DNS query.  You may want to inspect your DNS zone and confirm which domain controllers have registered an A record.
If a packet capture reveals that branch computers are using a domain controller in another site, it may be due to it is common to configure domain controllers in spoke sites (branch offices) to use DNS mnemonics, that instructs a domain controller which DNS records to avoid registering.  In large directories, it is actually quite common for spoke domain controllers to not register an A record in their DNS zone.   If the branch office location also does not have a site associated with it's subnet, that may explain an affinity for the main site domain controllers.
More information:
How to optimize the location of a domain controller that resides outside of a client's site
http://support.microsoft.com/kb/306602


text:
Q: Using streams to pipe data in node.js Setup: I am reading data from a database and emailing the dataset as a CSV file. The data get read in chunks of 500 rows, and I'm using ya-csv to write the records as a CSV to a stream. I then want to use mailgun-js to email the file as an attachment.
Option 1 (what I don't want to do):

*

*create temp file;

*create write stream to that file;

*write all CSV records;

*read all of it back into memory to attach to an email;

 Option 2 (what I want to do but don't quite know how to):

*

*create a writable stream;

*create a readable stream;

*somehow pipe the writes from (1) into (2);

*pass the writable stream to ya-csv;

*pass the readable stream to mailgun;

*fetch data and write to the write stream until there's no more data;

*end the write stream, thus ending the read stream and sending the email.

I've been reading https://github.com/substack/stream-handbook and https://nodejs.org/api/stream.html, and the problem is that I can't use writable.pipe(readable);.
I have tried using a Duplex stream (i.e. both the write and read streams are just Duplex streams) but this doesn't work as Duplex is an abstract class and I'd have to implement several of the linking parts.
Question: how do I use streams to link up this writing of CSV records to streaming an attachment to mailgun?

A: Don't overthink it, mailgun-js can take a stream as attachment, it can be as easy as:
var csv = require('csv');
var mailgun = require('mailgun-js');

// this will stream some csv
var file = myDbStream.pipe(csv.stringify());

var data = {
    from: 'Excited User <me@samples.mailgun.org>',
    to: 'serobnic@mail.ru',
    subject: 'Hello',
    text: 'Testing some Mailgun awesomness!',
    attachment: file // attach it to your message, mailgun should deal with it
};

mailgun.messages().send(data, function (error, body) {
    console.log(body);
});

I don't know what your Db is, maybe the driver already has a support for streams or you'll have to feed csv manually (can be done very easily with event-stream).
Edit
ya-csv seems to not be able to be piped easily, csv works better.


text:
Q: how to find out which native libraries to link in buiding Rust static library I want to creat a static library using Rust, and then use it in a C program. The library is expected to be self-contained (i.e. all its dependencies are self-contained).
At first, crate-type = ["staticlib"] was added in Cargo.toml. But this methods seemed to worked only in simple cases, where Rust code only contains basic functions and no external crates.
For a more complex Rust code, the above method may fail to build a self-contained library. In this case, the library can be built, but it cannot be used by C program.
I also have learnt that one can build a self-contained library by typing
RUSTFLAGS='-C target-feature=+crt-static' cargo build --release --target=x86_64-unknown-linux-gnu
However, the libaray failed to be built.
error: linking with `cc` failed: exit status: 1
|
 = note: LC_ALL="C" PATH="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

 /usr/bin/ld: /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2: error adding symbols: DSO missing from command line
 collect2: error: ld returned 1 exit status> note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified

  = note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
  = note: use the `-l` flag to specify native libraries to link
  = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)>

I have also read the building part of the official instruction, from which I understand the native libraries should be linked to Rust cargo build, looking like
RUSTFLAGS='-C target-feature=+crt-static -L /path/to/nativelibrary' cargo build --release --target=x86_64-unknown-linux-gnu
Supposing that my Rust code uses dozens of external crates, each of which may also has its own dependencies, I really don't know what to fill in /path/to/nativelibrary.
Questions:

*

*Is there a more automatic way to generate a completely self-contained library?

*If the way by setting/path/to/nativelibrary is unavoidable, how to find out which native libraries to link?


text:
Q: Python only writes one lot of data to file The script is a web scraper that takes emails from trust a trader - I need it to write to a text file as well as printing to the console. Here is the code, why is it only printing one "batch" of data from a url to the file?
from lxml import html
import requests
urls = ['http://www.trustatrader.com/search/?seed=&trade=1&where=Avon&page=1','http://www.trustatrader.com/search/?seed=&trade=1&where=Bedfordshire&page=1']
myfile = open('xyz.txt', 'a')
for url in urls:
    page = requests.get(url)
    tree = html.fromstring(page.text)
    emails = tree.xpath('//li[@class="email"]/a/@href')
    emails = [email.replace('mailto:','') for email in emails]
    emails = [email.replace(' ','') for email in emails]
    for email in emails:
        print str(email)+';'
        myfile.write("%s\n" % email)
myfile.close()