text:
Q: In UWP, what is the equivalent of DependencyType property of DependencyProperty Class of WPF? After migrating a WPF class library to a UWP class library, the following code is throwing an error. The PropertyType property of DependencyProperty class worked in WPF. I tried to get help from Dependency properties overview of similar class in UWP and this online article but got a bit confused.
What I'm missing here and how can I make it work?
Code snippet [error occurs at first line of the method]:
using Windows.UI.Xaml;
using System.Reflection;
using Windows.UI.Xaml.Documents;
using System.ComponentModel;
....

private static void SetPropertyValue(XmlElement xamlElement, DependencyProperty property, string stringValue)
{
    TypeConverter typeConverter TypeDescriptor.GetConverter(property.PropertyType);
    try
    {
        object convertedValue = typeConverter.ConvertFromInvariantString(stringValue);

        if (convertedValue != null)
        {
            xamlElement.SetAttribute(property.Name, stringValue);
        }
    }
    catch(Exception)
    {
    }
}

Error:

'DependencyProperty' does not contain a definition for 'PropertyType' and no accessible extension method 'PropertyType' accepting a first argument of type 'DependencyProperty' could be found (are you missing a using directive or an assembly reference?)

Snapshot of "ALL" the packages installed:

A: Following is a simple example of how you can use DependencyProperty in UWP .
XAML
<Page x:Name="loginPage"
... >

<TextBlock Text="{Binding welcomeText,ElementName=loginPage}"></TextBlock>

C#
using Windows.UI.Xaml;
...
public string welcomeText
{
     get { return (string)GetValue(welcomeTextProperty); }
     set { SetValue(welcomeTextProperty, value); }
}

// Using a DependencyProperty as the backing store for welcomeText.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty welcomeTextProperty =
        DependencyProperty.Register("welcomeText", typeof(string), typeof(LoginPage), null);

In the above example we are binding the dependency property welcomeText which we define in the code behind (C#) to a TextBlock.
Please note, ElementName=loginPage is the page name that we define in the XAML.
Hope this helps.

EDIT 1:
From what I can understand from your code you are trying to get the PropertyType value in order to convert it to a different type.
For this requirement you can do something like this:
In the following example we have a custom value converter which converts Length of a string to Visibility, in other words, return Visibility based on the length of string it receives for conversion, while also checking if the type of value provided is of the type string.
XAML
<Page x:Name="loginPage"
 xmlns:converters="using:projectName.converters"
... >
<Page.Resources>
    <converters:LengthToVisibilityConverter x:Key="lengthToVisibilityKey"></converters:LengthToVisibilityConverter>
</Page.Resources>
...
<TextBlock x:Name="flyoutTxt" Text="{Binding welcomeText,ElementName=loginPage}"></TextBlock>
<TextBlock Text="Has some text" Visibility="{Binding Path=Text,ElementName=flyoutTxt,Converter={StaticResource lengthToVisibilityKey}}"></TextBlock>

Here, the second TextBlock's visibility is based on the length of text of flyoutTxt.
C#
Custom Converter class to convert Length to Visibility :
class LengthToVisibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {   //checking if type of "value" is String and its length
        if(value != null && value.GetType() == typeof(string) &&
           value.ToString().Length > 0)
        {
            return Visibility.Visible;
        }
        else
        {
            return Visibility.Collapsed;
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Please note, there are no changes required in the property dependency defined above.


text:
Q: By design, why was the value parameter of Html.RadioButton made as a type of object? By design, why was  the value parameter of Html.RadioButton made as a type of object rather than string?
string RadioButton(this HtmlHelper htmlHelper, string name, object value);

A: That's because a radio button could have any value and when the helper decides whether it should be checked or not it looks for a corresponding value in the model state.
For example:
<%= Html.RadioButton("foo", 123) %>

and inside the controller you could pass integer value:
ViewData["foo"] = 123;

and the helper will automatically select the radio button. If you have a complex object it would use the Convert.ToString method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: im getting this "bundle.js:102 GET https://api.unsplash.com/photos?client_id=undefined 401" import { useState, useEffect } from "react"

export default function GetImages() {
   const [images, setImages] = useState([])

   useEffect(() => {
    const fetchImages = async () => {
        const response = await fetch(`https://api.unsplash.com/photos?client_id=${process.env.REACT_APP_UNSPLASH_API_KEY}`)
        const data = await response.json()
        setImages(data)
    }

    fetchImages()
   }, [])
    return (
        <>
            <h1>{images.length}t</h1>
        </>
    )
}

got this error :

"bundle.js:102 GET https://api.unsplash.com/photos?client_id=undefined 401

I have saved id in env file.
could someone correct me


text:
Q: Problems with the variable Webdriver driver when I use PageObjects I want to use: Login_Page Login = PageFactory.initElements(driver, Login_Page.class); in a unique way in all steps.
When I use it for each step I have no problems, but on the contrary Java shows me the error: " Value driver is always 'null'".
I would also like to replace Thread.sleep (2000); for a better solution.
Here is my Code:
package stepdefs;

import Pages.Login_Page;
import cucumber.api.java.pt.Dado;
import cucumber.api.java.pt.Entao;
import cucumber.api.java.pt.Quando;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;

import java.util.concurrent.TimeUnit;

public class StepDefinitions {

      WebDriver driver;
      Login_Page Login = PageFactory.initElements(driver, Login_Page.class);

      @Dado("^que que estou na pagina principal do Gmail\\.$")
    public void que_que_estou_na_pagina_principal_do_Gmail () throws Exception
    {
        System.setProperty("webdriver.chrome.driver", "C:\\browsers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.navigate().to("https://www.gmail.com");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Quando("^forneco as credenciais validas\\.$")
    public void forneco_as_credenciais_validas () throws Exception {
      // Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
        Login.setEmail("rbkamontana@gmail.com");
        Login.ClickOnNextButton();
        Thread.sleep(2000);
        Login.setSenha("automation10");
        Thread.sleep(3000);
        Login.ClickOnEnterButton();
        driver.manage().window().maximize();
        Thread.sleep(3000);
    }

    @Entao("^posso ver que estou logado\\.$")
    public void posso_ver_que_estou_logado () throws Exception {
        driver.findElement(By.xpath("//*[@id=\"gb\"]/div[2]/div[3]/div[1]/div[2]/div/a/span")).click();
        String stringAtual = driver.findElement(By.xpath("//*[@id=\"gb\"]/div[2]/div[4]/div[1]/div[2]/div[1]")).getText();
        String StringEsperada = "Rebeka Montana";
        Assert.assertTrue(stringAtual.contains(StringEsperada));
        //driver.quit();
    }
}

A: Instead of Thread.sleep you can use selenium WebDriverWait function by a Locator.
Ref:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html
void waitForElement(By Locator){
    WebDriverWait myWait = new WebDriverWait(myDriver, 20);
    myWait.until(ExpectedConditions.visibilityOfElementLocated(Locator));
}

Try initiating this inside of a constructor instead:
 public StepDefinitions(){
 driver = new ChromeDriver();
 Login  = PageFactory.initElements(driver, Login_Page.class);
 }

A: An instance method is initializing the driver field at runtime, which explains why things work inside the step definition method. The solution is deceptively simple: create a getter method for the page model:
public class StepDefinitions {
    WebDriver driver;
    Login_Page login;

    private Login_Page getLoginPage() {
        if (login == null) {
            login = PageFactory.initElements(driver, Login_Page.class);
        }

        return login;
    }

    @Quando("^forneco as credenciais validas\\.$")
    public void forneco_as_credenciais_validas () throws Exception {
        Login_Page login = getLoginPage();

        login.setEmail("rbkamontana@gmail.com");
        login.ClickOnNextButton();
        Thread.sleep(2000);
        login.setSenha("automation10");
        Thread.sleep(3000);
        login.ClickOnEnterButton();
        driver.manage().window().maximize();
        Thread.sleep(3000);
    }


text:
Q: nhibernate to linq 3.2 generate error sql on || operator now i'm using nhibernate 3.2 as the orm,when i write code like this:
PostReaderBll postReaderBll=new PostReaderBll();
    var query = from p in postReaderBll.Query()
                where (p.Post.Flag == (int)PostType.Post && p.Post.MailState == (int)MailState.Normal) || (p.ReceiveUser == LoginUser.UserIdentity && p.Post.Flag == (int)PostType.Mail && p.Post.MailState == (int)APSP.Form.MailState.Normal)
                select p;

i get this sql:
SELECT   TOP ( 10 /* @p0 */ ) ID1_70_,
                 IsRead2_70_,
                 ReceiveU3_70_,
                 ReadDate4_70_,
                 Flag5_70_,
                 Label6_70_,
                 PostID7_70_   FROM     (select postreader0_.[ID]     as ID1_70_,
             postreader0_.[IsRead]              as IsRead2_70_,
             postreader0_.[ReceiveUser]         as ReceiveU3_70_,
             postreader0_.[ReadDate]            as ReadDate4_70_,
             postreader0_.[Flag]                as Flag5_70_,
             postreader0_.[Label]               as Label6_70_,
             postreader0_.[PostID]              as PostID7_70_,      ROW_NUMBER()
               OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row
      from   PostReader postreader0_
             inner join Post post1_
               on postreader0_.[PostID] = post1_.[ID]
      where  post1_.[Flag] = 1 /* @p1 */
             and post1_.[MailState] = 0 /* @p2 */
              or postreader0_.[ReceiveUser] = 'admin' /* @p3 */
                 and post1_.[Flag] = 0 /* @p4 */
                 and post1_.[MailState] = 0 /* @p5 */) as query   WHERE   query.__hibernate_sort_row > 0 /* @p6 */  ORDER BY query.__hibernate_sort_row

but i need the where  like this:
( post1_.[Flag] = 1 /* @p1 */
             and post1_.[MailState] = 0 /* @p2 */)
              or (postreader0_.[ReceiveUser] = 'admin' /* @p3 */
                 and post1_.[Flag] = 0 /* @p4 */
                 and post1_.[MailState] = 0 /* @p5 */)

A: It is the same because, OR operators are always evaluated after AND operators.
Reference documentation for OR operator:

Combines two conditions. When more than one logical operator is used
  in a statement, OR operators are evaluated after AND operators.
  However, you can change the order of evaluation by using parentheses.

http://msdn.microsoft.com/en-us/library/ms188361.aspx


text:
Q: Unittest for decorator with self arguments I have a retry decorator that acts based on raised exceptions:
def retry(times, exceptions):
    def decorator(func):
        def wrapped_func(self):
            attempt = 0
            while attempt < times:
                try:
                    return func(self)
                except exceptions:
                    self.logger.info(
                        "Error, retry in process.. attempt {} of {}".format(
                            attempt, times
                        )
                    )
                    attempt += 1
            return func(self)
        return wrapped_func
    return decorator

And will be used in a class function like:
@retry(times=10, exceptions=(ValueError,))
def function_that_fails(self):
    raise ValueError

I'm trying to test this function like:
class sample_class:
    def __init__(self, logger):
        self._logger = logger
        self._count = 0

    @property
    def count(self):
        return self._count

    @property
    def logger(self):
        return self._logger

    @retry(times=10, exceptions=(ValueError,))
    def sample_func(self):
        self._count += 1
        raise ValueError

class TestUtils(TestCase):
    def setUp(self):
        self._logger = Mock()
        self._sample_class = sample_class(self._logger)
        self._count = 0

    def test_retry_function(self):
        with self.assertRaises(ValueError):
            self._sample_class.sample_func()
        self.assertEqual(self._sample_class.count, 10)

    def test_retry_function_2(self):
        @retry(times=10, exceptions=(ValueError,))
        def sample_func():
            self._count += 1
            raise ValueError
        with self.assertRaises(ValueError):
            sample_func()
        self.assertEqual(self._count, 10)

The first test works but the dummy class is something that I would like to avoid, the second one I receive the error:
E   TypeError: wrapped_func() missing 1 required positional argument: 'self'

And it's expected due to the self argument inside the retry function, I tried multiple options with no success, what I'm doing wrong?

A: You could simply use a Mock object for the self parameter instead of creating an entire class:
from unittest.mock import Mock

def test_retry_function_2(self):
    @retry(times=10, exceptions=(ValueError,))
    def sample_func(mock_arg):
        mock_arg._count += 1
        raise ValueError
    mock = Mock(_count=0)
    with self.assertRaises(ValueError):
        sample_func(mock)
    self.assertEqual(mock._count, 10)

Simpler yet, you could use a Mock as the decorated function, and use the built-in call_count in place of a _count that you have to increment yourself:
def test_retry_function_3(self):
    mock = Mock(side_effect=ValueError)
    with self.assertRaises(ValueError):
        retry(10, ValueError)(mock)(Mock())
    self.assertEqual(mock.call_count, 11)

It's even easy to verify that your decorator calls logger.info on each retry:
def test_retry_function_4(self):
    mock_func = Mock(side_effect=ValueError)
    mock_self = Mock()
    with self.assertRaises(ValueError):
        retry(10, ValueError)(mock_func)(mock_self)
    self.assertEqual(mock_func.call_count, 11)
    self.assertEqual(mock_self.logger.info.call_count, 10)


text:
Q: in tcl script, exec make check RUNTESTFLAGS="compile.exp --target_board=atmega128-sim" doesn't work I am trying to run the gcc testsuite using a driver script in tcl.
When  i write
if {[catch {exec make check RUNTESTFLAGS="compile.exp --target_board=atmega128-sim"} errmsg ]} {
    puts "Test finished with failures\n $errmsg"
} else {
    puts "Test finished"
}

This gives error as
Test finished with failures
make: unrecognized option `--target_board=atmega128-sim"'
Usage: make [options] [target] ...
......
But if I remove the compile.exp from the RUNTESTFLAGS, it works fine.
if {[catch {exec make check RUNTESTFLAGS="--target_board=atmega128-sim"} errmsg ]} {

.....

Is it because of the double quotes present in argument RUNTESTFLAGS?
I need to run make check with different RUNTESTFLAGS.
Please suggest a way to achieve this.
Thanks in advance !!

A: First off, the core of this question is about:
exec make check RUNTESTFLAGS="compile.exp --target_board=atmega128-sim"

Everything else is just (correct) wrapping. The issue is that you are using Bourne shell syntax above, not Tcl syntax, so the above ends up with RUNTESTFLAGS set to "compile.exp (with the quote) and the rest is sent as another argument to make. Not what you want! (Tcl only lets a double-quoted string start at the front of a word; bash is more lenient.) A correct version would be:
exec make check "RUNTESTFLAGS=compile.exp --target_board=atmega128-sim"

But it's easier and much clearer to split that up, like this:
set runTestFlags "compile.exp --target_board=atmega128-sim"
exec make check RUNTESTFLAGS=$runTestFlags


text:
Q: Help define referential integrity in Zend Framework 1.8.3 using Data Mapper model I am unable to define referential integrity relationship using Zend Frameworks table relationships as documented in the manual.
I have exhausted every possible configuration (so it seems), and now am facing the prospect of developing the application without being able to use cascading deletions, which  is undesirable.
Can anyone see what is wrong or offer any suggestions?
My project is setup using the new ZF 1.8.3 recommended method, with datamappers, and I wonder if this is a reason why I am unable to replicate the behavior as described in the reference guide. Does anyone have any experience of this problem?
Here are the relevant parts of the classes:
application/models/UsersMapper.php
class Default_Model_UsersMapper {
    public function deleteUser($id, Default_Model_Users $users){

    $usersTable = new Default_Model_DbTable_Users();
    $usersRowset = $usersTable->find( $id );
    $userToDelete = $usersRowset->current();
    $userToDelete->delete();

}

application/models/DbTable/Users.php
class Default_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
/**
 * @var string Name of the database table
 */
protected $_name = 'users';

/**
 * @desc  reference map
 *
 */
 protected $_referenceMap = array(
    'Comment' => array(
    'columns'       =>  array('user_id'),
        'refTableClass' =>  'Comment',
        'refColumns'    =>  array('id'),
        'onDelete'      =>  self::CASCADE
    )
);

}

application/models/CommentMapper.php
… and the related table defined by the class:
Comment.php
class Default_Model_DbTable_Comment extends Zend_Db_Table_Abstract
{
/**
 * @var string Name of the database table
 */
protected $_name = 'comment';

    /**
 * @desc Defining referential integrity here since we are using MyISAM
 * Dependent tables are referred via the class name.
 */
protected $_dependentTables = array('Users');
}

A: Thanks for spotting the mistake in the class definitions.
My problem getting Zend Framework to provide a DRI layer has become narrowed and can now be summarized as such.
Using these class definitions I am able to delete the user but not the related comment through my local UserController  "public/users/delete/userId/22"
    class Default_Model_DbTable_Comment extends Zend_Db_Table_Abstract
    {
        /**
         * @var string Name of the database table
         */
        protected $_name = 'comment';

        /**
         * @desc  reference map
         *
         * Rows in the comment table are to be automatically deleted if the row in the
     * User table to which they refer is deleted
     *
     */
     protected $_referenceMap = array(
        'User' => array(
            'columns'       => 'user_id',   // the foreign key(s)
            'refTableClass' => 'Default_Model_DbTable_Users',
            'refColumns'    =>  'id',
            'onDelete'      =>  self::CASCADE,
        )
    );

}
class Default_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    /**
     * @var string Name of the database table
     */
    protected $_name = 'users';

     /**
     * @desc Defining referential integrity here since we are using MyISAM
     * Dependent tables are referred via the class name.
     */
    protected $_dependentTables = 'Default_Model_DbTable_Comment';

}

A: Ohhhh, I see it now. Your classes are named Default_Model_DbTable_Xxx, yet you refer to them as Xxx in your classes. Do the changes tharkun suggested and change your classnames to be valid:
e.g.
protected $_dependentTables = array('Comment');

and
'refTableClass' =>      'User',

becomes
protected $_dependentTables = array('Default_Model_DbTable_Comment');

and
'refTableClass' => 'Default_Model_DbTable_User'


text:
Q: Determine if $f=g$ almost everywhere. Determine the set of real values where the given function $f$ does not equal the given function $g$. Then use Definition 1.2.3 to prove $f=g$ almost everywhere.
Definition 1.2.3: The functions $f$ and $g$ are said to be equal almost everywhere when $f(x)=g(x)$ for all $x$ in the functions domains, except possible for a set $x$ values that has measure zero.
The two functions are
$f(x)=\begin{cases}
1 & x\in(0,1) \\
0 & x\notin (0,1)
\end{cases}$
and $g(x)=\begin{cases}
1 & x\in[0,1] \\
0 & x\neq[0,1]
\end{cases}$
I see that $f(1)\neq g(1) $ and $f(0)\neq g(0)$.
So is the set of real values where $f\neq g$ $\{0,1\}$?
And how to I show that $f=g$ almost everywhere using the definition?
This is what I have for determining measure zero:
Let $\epsilon >0$ be given and let $S=\{0,1\}$. Then we can cover $S$ with the open intervals $I_1 = (-\frac{\epsilon}{4},\frac{\epsilon}{4})$ and $I_2 = (\frac{1-\epsilon}{4}, \frac{1+\epsilon}{4})$.
$m(I_1)=0$ and $m(I_2)= \frac{\epsilon}{2}$.
Then $\sum_{n=1}^{2} m(I_n) = 0+\frac{\epsilon}{2} = \frac{\epsilon}{2} < \epsilon$

A: If your measure is Lebesgue measure $\lambda$, then $\lambda(\{0,1\})=0$ and the functions agree on the rest of the points, so you found your zero measure set. (I think you refer to Lebesgue measure as you are  using open interval to compute the measure of your set, allegedly using the Lebesgue outer measure representation of measurable sets).
Of course on different measure spaces this might not be true. Let $(\mathbb R, \{\emptyset,\mathbb R,\{1\}, \mathbb R\backslash \{1\}\}, \delta_1)$ be your measure space, where $\delta_1(A)=1$ if $1\in A$ and $0$ otherwise. Then for every zero measure set $A$ in your $\sigma$-algebra (only $\mathbb R\backslash \{1\}$ and $\emptyset$), there exist a point $\mathbb R\backslash A$ where the two functions differ.


text:
Q: How to remove specific ID based on specific condition (e.g., different value in variable)? I have 8 observations per subject ID. All subjects were asked to complete 8 tasks (i.e., 8 observations) in the same session, i.e., each ID should have an identical session time. However, in my dataset, for ID #5, 2 observations had the same session time, and 6 observations had the same session time. Therefore, I would like to exclude ID#5 from this example dataset. I have multiple IDs in my extended dataset. I would appreciate if someone could provide an example code to remove IDs with different session times.
Example dataset:
data work;
input id SessionTime v1 v2 v3;
datalines;
1   18.2    2   3   6
1   18.2    3   7   8
1   18.2    4   6   12
1   18.2    6   8   10
1   18.2    8   9   22
1   18.2    9   10  25
1   18.2    10  12  30
1   18.2    12  17  4
2   16.7    3   7   6
2   16.7    4   11  10
2   16.7    5   10  8
2   16.7    7   12  20
2   16.7    9   13  23
2   16.7    10  14  28
2   16.7    11  16  2
2   16.7    13  21  4
3   18.2    4   11  8
3   18.2    5   15  6
3   18.2    6   14  18
3   18.2    8   16  21
3   18.2    10  17  26
3   18.2    11  18  0
3   18.2    12  20  2
3   18.2    14  25  6
4   19.3    5   15  4
4   19.3    6   19  16
4   19.3    7   18  19
4   19.3    9   20  24
4   19.3    11  21  7
4   19.3    12  22  0
4   19.3    13  24  4
4   19.3    15  29  2
5   20.3    6   19  14
5   20.3    7   23  17
5   28.4    8   22  22
5   28.4    10  24  5
5   28.4    12  25  5
5   28.4    13  26  2
5   28.4    14  28  0
5   28.4    16  33  12
;
run;

Thanks

A: Proc SQL by default performs automatic remerging when you select columns that are not in a group.  This feature can be leveraged to filter your data using a having clause.
Example:
Select the ids that have exactly 8 rows and only 1 session.
proc sql;
  create table want as
  select * from have
  group by id
  having count (*) = 8 and count (distinct sessiontime) = 1
  ;

A: If you just calculate how many observations there are per group.
proc sql;
create table want as select *,count(*) as nobs
  from have group by id,sessiontime
;

It will then be easy to exclude the groups that do not have 8 observations.
proc means data=want;
  where nobs=8 ;
run;


text:
Q: Class Not Found when extends a Class of Subdirectory Controller in ZendFramework I've the next structure
-application
--controllers
---Sub
----DemoController.php
---IndexController.php
-models
-views
-Boostrap.php
Well, in my Sub/DemoController.php I've the next:
<?php
class Sub_DemoController extends Zend_Controller_Action
{
    public function indexAction()
    {
        echo 'hello demo';
    }
}

And my IndexController.php like this:
<?php
class IndexController extends Sub_DemoController
{
}

When I run my web throw the next error: Class 'Sub_DemoController' not found ...
I try with initialize class with Application_Sub_DemoController, but return the same result.
I don't want use modules, I know how uses modules in Zend Framewoork but I don't looking for it.
Any ideas?

A: You need to add resourceType to your resource autoloader add this to you bootstrap file:
$this->getResourceLoader()
     ->addResourceType('sub', 'controllers/Sub', 'Sub');

More: http://framework.zend.com/manual/1.12/en/zend.loader.autoloader-resource.html

A: Please have a look at Zend framework (1.7.5): how to change controller directory
I think you didn't set the controller directory properly or your autoloader does not work.


text:
Q: Wi-Fi network created but not allowing connection to the Internet I am able to create the Wi-Fi signal through my MacBook Pro, though it doesn't connect to internet when I use it in other devices.
I am using OS X Yosemite and I tried to use the Wi-Fi created from my Mac in my Lenovo tablet and Samsung smartphone.
I called Apple service and they say they cannot help for I am not using Apple tablet and Apple smartphone.

A: The first thing to try is to enable Internet Sharing from System Preferences -> Sharing.

Now choose the right source and destination, connect your device to WiFi shared network and try to navigate.


text:
Q: Django-CMS Custom plugin and placeholders I'm really new to Django-CMS, I had a look at the docs but I can;'t find what I need so I could be probably doing it wrong.
Anyway I'm creating a custom plugin, I have the model with 3 placeholders inside:
models.py
class Tile(CMSPlugin):
   text = PlaceholderField('text', related_name='tile_text')
   img = PlaceholderField('img', related_name='tile_img')
   link = PlaceholderField('link', related_name='tile_link')

then I have 3 different Plugins using the model:
cms_plugins.py
from cms.plugin_base import CMSPluginBase
from cms.models.pluginmodel import CMSPlugin
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _

from tiles_plugin.models import Tile

class BigTilePlugin(CMSPluginBase):
    model = Tile
    name = _('Big Tile Plugin')
    render_template = 'tiles_plugin/big_tile.html'
    allow_children = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        return context

class MedTilePlugin(CMSPluginBase):
    model = Tile
    name = _('Medium Tile Plugin')
    render_template = 'tiles_plugin/med_tile.html'
    allow_children = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        return context

class SmallTilePlugin(CMSPluginBase):
    model = Tile
    name = _('Small Tile Plugin')
    render_template = 'tiles_plugin/small_tile.html'
    allow_children = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        return context

plugin_pool.register_plugin(BigTilePlugin)
plugin_pool.register_plugin(MedTilePlugin)
plugin_pool.register_plugin(SmallTilePlugin)

and then I have the templates:
big_tile.html
{% load cms_tags %}

        {% render_placeholder instance.text %}

        {% render_placeholder instance.link %}

        {% render_placeholder instance.img %}

And here it comes the problem, when I create the plugin and i insert inside the text/picture/link plugins, these are not populated so basically everything is empty, it's like the javascript is not populating it (for sure it's not the javascript) but I think I'm missing the relationship with the child_plugins.
Can anyone help me out?
Thanks
EDIT
This made it work properly:
    {% for plugin in instance.child_plugin_instances %}
        {% render_plugin plugin %}
    {% endfor %}

Thanks to @mfcovington

A: It looks like almost everything is right. However, to get text, for example, you need to use instance.tile.text instead of instance.text.
So, your template should look something like this:
{% load cms_tags %}

        {% render_placeholder instance.tile.text %}

        {% render_placeholder instance.tile.link %}

        {% render_placeholder instance.tile.img %}

Alternatively, when you set the context, you could set context['tile']:
class BigTilePlugin(CMSPluginBase):
    ...
    def render(self, context, instance, placeholder):
        context['tile'] = instance.tile
        return context

This would allow you to use tile.text, etc. instead of instance.tile.text, etc. in your template.
EDIT:
In case you are interested, besides your model info, there are lots of other things contained within instance. For example, in one of my cms_plugins.py files I added print(dir(instance)) within a CMSPlugin for a model called carousel and got the following output to my terminal (it will, of course differ from yours, but most things will be in common):
['DoesNotExist', 'Meta', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_manager', '_carousel_cache', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_ordering', '_check_swappable', '_check_unique_together', '_db_connection', '_default_manager', '_deferred', '_do_insert', '_do_update', '_get_FIELD_display', '_get_basepath', '_get_children_path_interval', '_get_database_connection', '_get_database_cursor', '_get_lastpos_in_path', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_parent_path_from_path', '_get_path', '_get_pk_val', '_get_serializable_model', '_get_unique_checks', '_inc_path', '_inst', '_int2str', '_meta', '_perform_date_checks', '_perform_unique_checks', '_placeholder_cache', '_prepare_pos_var', '_prepare_pos_var_for_add_sibling', '_prepare_pos_var_for_move', '_process_foreign_keys', '_render_meta', '_save_parents', '_save_table', '_set_pk_val', '_state', '_str2int', '_valid_pos_for_add_sibling', '_valid_pos_for_move', '_valid_pos_for_sorted_add_sibling', '_valid_pos_for_sorted_move', 'add_child', 'add_root', 'add_sibling', 'add_url', 'alias_reference', 'aliaspluginmodel', 'alphabet', 'carousel', 'carousel_id', 'carouselplugin', 'changed_date', 'check', 'child_plugin_instances', 'clean', 'clean_fields', 'cmsplugin_ptr', 'cmsplugin_ptr_id', 'cmsplugin_set', 'column', 'copy_plugin', 'copy_relations', 'copy_url', 'creation_date', 'date_error_message', 'delete', 'delete_url', 'depth', 'dump_bulk', 'edit_url', 'file', 'find_problems', 'fix_tree', 'flash', 'full_clean', 'gap', 'get_ancestors', 'get_annotated_list', 'get_breadcrumb', 'get_breadcrumb_json', 'get_children', 'get_children_count', 'get_database_vendor', 'get_depth', 'get_descendant_count', 'get_descendants', 'get_descendants_group_count', 'get_first_child', 'get_first_root_node', 'get_first_sibling', 'get_foreign_keys', 'get_instance_icon_alt', 'get_instance_icon_src', 'get_last_child', 'get_last_root_node', 'get_last_sibling', 'get_media_path', 'get_next_by_changed_date', 'get_next_by_creation_date', 'get_next_sibling', 'get_parent', 'get_plugin_class', 'get_plugin_class_instance', 'get_plugin_instance', 'get_plugin_name', 'get_position_in_placeholder', 'get_prev_sibling', 'get_previous_by_changed_date', 'get_previous_by_creation_date', 'get_root', 'get_root_nodes', 'get_short_description', 'get_siblings', 'get_sorted_pos_queryset', 'get_translatable_content', 'get_tree', 'googlemap', 'has_change_permission', 'id', 'inheritpageplaceholder', 'is_child_of', 'is_descendant_of', 'is_leaf', 'is_root', 'is_sibling_of', 'language', 'link', 'load_bulk', 'move', 'move_url', 'multicolumns', 'node_order_by', 'notify_on_autoadd', 'notify_on_autoadd_children', 'num_children', 'numchild', 'numconv_obj', 'numconv_obj_', 'objects', 'page', 'parent', 'parent_id', 'path', 'picture', 'pk', 'placeholder', 'placeholder_id', 'placeholderreference', 'plugin_type', 'position', 'post_copy', 'prepare_database_save', 'reload', 'render_plugin', 'save', 'save_base', 'serializable_value', 'set_base_attr', 'set_translatable_content', 'shinyapppluginmodel', 'steplen', 'teaser', 'text', 'translatable_content_excluded_fields', 'unique_error_message', 'validate_unique', 'video']


text:
Q: Why is this statement with bitwise operators the same as this if statement? I was reading this question Why is it faster to process a sorted array than an unsorted array? and the best answer provided by
Mysticial. The answer does a great job of explaining what is happening and why and also says this:

So what can be done?
If the compiler isn't able to optimize the branch into a conditional
  move, you can try some hacks if you are willing to sacrifice
  readability for performance.
Replace:

 if (data[c] >= 128)
     sum += data[c];

with:

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

This eliminates the branch and replaces it with some bitwise
  operations.

What exactly is this code doing and why is it equivalent?

A: It first converts the comparison to subtraction with 128.
Then the sign of the result (whether subtracting went below 128) is expanded to either all zeroes or all ones, which is anded to the value being added, zeroing it out if the result of the subtraction was negative.


text:
Q: Facebook widget (by Milap Patel) how to translate the text? im using the facebook widget for wordpress by: http://wordpress.org/extend/plugins/facebook-pagelike-widget/
on my blog, but I would like to translate or change the text that currently says "Find us on Facebook". Is that posible?
Ive search through the plugin folder and its files but im not experienced enough or its just not there. please help if posible.

A: In the plugin folder you can edit the file named fb.js on line 7:
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId="+appid;

Change en_US to the locale you want. The full list of available Facebook locales can be found here: https://www.facebook.com/translations/FacebookLocales.xml
The problem with doing this will be the locale will switch back to en_US if you install an update to the plugin. I would get your own embed code from Facebook (https://developers.facebook.com/docs/reference/plugins/like-box/) and paste it into your theme or a HTML widget for your sidebar.


text:
Q: Comparing the performance of two teams measuring many variables once Which statistical tools are best suited for this problem:
Team A goes and measures 3 magnitudes in 200 locations (let's imagine the volume of a room, the insulation coefficient and the average temperature outside the room).  For each room they calculate the energy this room will consume to keep the desired temperature for a week.
So after the measurement campaign they have measured these 3 magnitudes in 200 different rooms (each room is only measured once).  So the data looks like:
 (Room_volume, r_coefficient, T, estimated_energy)

Team A is assumed to be very good at getting their results. Now team B measures the same 200 rooms, and calculates all the estimated energies for each room.
How should we measure the performance of team B vs team A (where A is assumed to be accurate)?
Forgetting the physics, as it's just an illustrative example, how do you compare the accuracy of a measurement campaign measuring 3 values from which a 4th one can be calculated deterministically?  Note that none of these values are distributed in any special way among the 200 samples (they don't look gaussian)
I started looking at the distribution of errors, so:
 {Estimated_energy_Ai - Estimated_energy_Bi} with i = 1..200

And seeing how many results are within a standard deviation.  What other tools are appropriate?

A: If you are 100% sure your data is non-normal, then you can perform a T-test to say if the two results are significantly different.
if your data sets have equal sample and variance
try using scipy.stats.ttest_rel
http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.stats.ttest_rel.html


text:
Q: How can I exclude files from Visual Studio, but still deploy them upon publishing? We are experiencing bad slowdowns in Visual Studio 2019 that appears partly due to a large folder of content (~12,000 files) that we have in our wwwroot folder. This content rarely changes, but it ends up getting searched when we do "Find in files...", etc. which we don't need, and ends up slowing down normal operations such as adding/renaming classes.
Is there any way to keep the content in source control, exclude it from Visual Studio, yet still have it get deployed when we publish?
I haven't been able to figure out if this is possibly editing the csproj file using the settings such as DefaultItemExcludes, or various options on the ItemGroup element.

A: Here is what we have done to (hopefully) resolve this issue for us:

*

*Added the following line to our WebApp.csproj file within the PropertyGroup:
<ProjectGroup>
    <DefaultItemExcludes>$(DefaultItemExcludes);wwwroot\hugecontentfolder\**</DefaultItemExcludes>
</ProjectGroup>

*The huge content folder stays where it is in source control, this simplifies things as we need those files there to be served locally for development

*We updated our Azure DevOps pipelines with new tasks to copy the contents of that folder from source control into the build artifact staging directory

*Updated the Dotnet Publish Azure Devops task to no longer zip it's output

*Another new Azure DevOps task to Archive the build artifact staging directory (which now has the non-zipped dotnet publish output, as well as the huge content folder output in the correct location) into a zip file for publishing.


text:
Q: What is a zero argument constructor in Dart flutter What is a zero-argument constructor in Dart flutter?
while creating a bloc in flutter I am receiving the following error
  The superclass 'Bloc<QuoteEvent, QuoteState>' doesn't have a zero argument constructor.
Try declaring a zero argument constructor in 'Bloc<QuoteEvent, QuoteState>', or explicitly invoking a different constructor in 'Bloc<QuoteEvent, QuoteState>'.

kindly guide how to fix it. thanks
below is code
import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';

import 'package:random_quote/repositories/repositories.dart';
import 'package:random_quote/models/models.dart';
import 'package:random_quote/bloc/bloc.dart';

class QuoteBloc extends Bloc<QuoteEvent, QuoteState> {
  final QuoteRepository repository;

  QuoteBloc({@required this.repository}) : assert(repository != null);

  @override
  QuoteState get initialState => QuoteEmpty();

  @override
  Stream<QuoteState> mapEventToState(QuoteEvent event) async* {
    if (event is FetchQuote) {
      yield QuoteLoading();
      try {
        final Quote quote = await repository.fetchQuote();
        yield QuoteLoaded(quote: quote);
      } catch (_) {
        yield QuoteError();
      }
    }
  }
}

A: initialState property was removed from flutter_bloc since v5.0.0. Here is migration guide.
You should use super() constructor instead:
class QuoteBloc extends Bloc<QuoteEvent, QuoteState> {
  final QuoteRepository repository;

  QuoteBloc({@required this.repository}) :
    assert(this.repository != null),
    super(QuoteEmpty());

  ...

A: A zero-argument constructor is literally a constructor that can be invoked with zero arguments.  This includes constructors that take only optional arguments.
If you have a derived class that does not explicitly invoke its base class constructor, the derived class's constructors will implicitly invoke the default (unnamed) constructor in the base class with zero arguments.  If you need to call a named constructor in the base class or if you need to pass arguments, you will need to invoke the base class constructor explicitly.
In your case, QuoteBloc derives from Bloc<QuoteEvent, QuoteState>, but the QuoteBloc constructor does not explicitly invoke any constructor from Bloc, which apparently does not provide a default, zero-argument constructor.

A: SomeClass();//this is zero argument constructor
SomeClass2(String argument1);//this is one argument constructor
SomeClass3(String argument1,String argument2);//this is 2 argument constructor


text:
Q: determine how a linux process was invoked Is there a way in linux, to determine how a process was invoked?
I know, that ps displays the startup parameters, but I'm interested how the process start was executed.
Was it a init.d script, a cron job or manual invocation via cli.
Right now I am looking through all configs/commands manually, is there an easy way I am overlooking?
(I also know, that the presence of systemd etc. is distro related which helps to priorize a little bit.)

A: In most cases, for a process of pid 1234, you can get valuable information about it thru /proc/1234/ (see proc(5) for details)
See also credentials(7) and Advanced Linux Programming and Linux From Scratch
For exemple, try ps $$ then cat /proc/$$/status then cat /proc/$$/maps then cat /proc/$$/comm in your terminal (running probably the GNU bash shell, or zsh)
Consider writing your C program doing appropriate syscalls(2) (with perhaps opendir(3) and readdir(3)...) to query that information from /proc/ ....
Remember to read errno(3). A lot of functions (like open(2), read(2), getpwnam(3) ....) can fail.
Download, then study for inspiration the source code of the GNU bash shell (or even of the Linux kernel), it is free software.


text:
Q: Should all Combinations be included in a truth table? I have been Learning about the IC-7490 Decade Counter which has 4 reset pins meaning 16 combinations, but the truth table can be compressed into just 4 Rows as I have done here:
Is this fine or should I mention all the other combinations? What is recommended?

A: Not as long as the information is unambiguous.
However, in your case, the R0(1) and R0(2) do not matter at all. If you remove them from the table you will get the same formula at the end when working out the table to the formula.
If you would put the entire table, you will also get the same formula. So you just made already some assumptions (for the X). Your table is halfway making the formula already, which is no problem at all. It saves you some time not to put all 16 combinations.
You better can start with the entire table if you cannot trivially make the assumptions you made (e.g. the X-es which can be either 0 or 1).


text:
Q: Rendering a partial view with ajax Currently I have a main view called getRolesByYear.cshtml. In this view I have three buttons, each for an year. When I click a button(or on page load) I invoke a method, which takes an int 'year' for a parameter and calls an ajax with the year parameter. This ajax calls an action method (getRolesByYear, the one for the main view). The Action method makes a query to a database, a result of which is a list of ViewModel objects. In the return statement I return a PartialView like this : return PartialView("_yearlyRoles",list);. Sadly, after all this, instead of getting a list of the desired objects in my frontend, all i get is an error from  the error part of the ajax call. I am generally a novice and I am very stuck with this.
Here is the main view getRolesByYear.cshtml:
    @{
    ViewBag.Title = "getRolesByYear";
}

    @DateTime.Now.Year
    @DateTime.Now.AddYears(-1).Year
    @DateTime.Now.AddYears(-2).Year

The partial view :
@model IEnumerable<eksp.Models.RoleViewModel>

@foreach (var item in Model)
{

item.Role.RoleName

 item.Role.RoleDescription

Focus start : item.Role.FocusStart

Focus end : item.Role.FocusStart

}

The Action Method :
[HttpPost]
    public ActionResult getRolesByYear(int year)
    {
        string currentUserId = User.Identity.GetUserId();

        var list = db.WorkRoles.
            Join(db.WorkRolesUsersDetails,
            o => o.WorkRoleId, od => od.WorkRoleId,
            (o, od) => new
            {
                WorkRoleId = o.WorkRoleId,
                RoleName = o.RoleName,
                RoleDescription = o.RoleDescription,
                CompanyId = o.CompanyId,
                WRUDId = od.WRUDId,
                UserDetailsId = od.UserDetailsId,
                FocusStart = od.FocusStart,
                FocusEnd = od.FocusEnd
            }).ToList()
            .Select(item => new RoleViewModel(
               item.WorkRoleId,
                item.RoleName,
                item.RoleDescription,
                item.CompanyId,
                item.WRUDId,
                item.UserDetailsId,
                item.FocusStart,
                item.FocusEnd)).ToList();

        //RoleViewModel rv = list;

        if (Request.IsAjaxRequest())
        {
            return PartialView("_yearlyRoles", list);
        }
        else
        {
            return View(list);
        }
    }

A: Given the reported error message, you need to alter your ajax call. By setting "data" parameter to "json" you're telling ajax to expect JSON-formatted data back in the response, but a partial view is HTML, so change your ajax call to reflect this:
$.ajax({
    type: "POST",
    url: '@Url.Action("getRolesByYear", "WorkRoles")/' + year,
    dataType: "html", //set the correct data type for the response
    success: successFunc,
    error: errorFunc
});

As an aside, you can improve your error handling on the client side quite straightforwardly by changing errorFunc to something like this, using the parameters that are provided to the callback by $.ajax:
function errorFunc(jQXHR, textStatus, errorThrown) {
    alert("An error occurred while trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}

For less instrusive reporting and/or easier debugging, you could change the alert to console.log. To get more detail you could also log the entire jQXHR object:
console.log(JSON.stringify(jQXHR));


text:
Q: How can I get my public IPV4 address from NAT internal network with python guys
I just want to look up my public ipv4 address from NAT internal network, I know lots of webpages offering that function, only if you visit them by opening webpages with a browser. The thing I figure out is to extract the IP address information from the webpage with python, I had used python's lib called 'requests', but every time the code response without IP information I anticipate when I visit those webpages which can show my public address correctly in a browser. I guess it is probably because those pages used a code-proof visiting strategy. So is there any way that I can use to get my public IP address with python code, just something like restful service?

A: public_ip = requests.get('https://ifconfig.me').text

The simplest way to get your public IP is to get it from a REST service, like ifconfig.me, using requests (which you mentioned in your question and needs to be installed with pip). requests.get() sends an HTTP GET request to the REST API and returns a Response object that has a text attribute which contains the content of the response, in this case your public IP address.


text:
Q: Google map with transparency I have already worked before with map skins.  In a new project, I would like to display the map transparently on the top of a picture (just maintaining the country + region lines.)
You can see it in the attached example.


text:
Q: Sum of distances of a variable point from two fixed points. Given that $A\equiv(4,2)$ and $B\equiv(2,4)$, find a point $P$ on the line $3x+2y+10=0$ such that $PA+PB$ is minimum.

My attempt:
In $\triangle PAB$,
$$PA+PB\ge AB$$ Hence, the minimum value should be $AB=2\sqrt 2$. But in the solution point $P$ is given as $\displaystyle(-\frac{14}{5}, -\frac{4}{5})$ from which $PA+PB$ comes out to be $10\sqrt 2$.
Where am I going wrong? Help is requested!

A: This is an instance of Heron's problem and this is a proof without words:

A: If $A(4,2), B(2,4)$ are on the same side of the line not on the same line $L=3x+2y+10=0.$
Let the image of $A$ about $L$ be $A'$, then $A'P=AP$ then $AP+BP=A'P+BP$ is minimum
when $A',P,B$ are collinear and $PA;+PB=A'B$
Image $A'(x',y')$ is obtained as
$$\frac{x'-4}{3}=\frac{y'-2}{2}=-2\frac{12+4+10}{9+4}\implies x'=-8, y'=-6$$
The equation of $A'B$ is $x-y=-2$ and the required point $P$ is thr intersection of this line with $L$, we get $P(-14/5,-4/5)$ and $AP+BP \ge A'B=10\sqrt{2}$

A: Let $A'$ be symmetric to $A$ respect to $l:3x+2y+10=0$.
Thus, $BA'\cap l=\{P\}$.
I got, since $AA'\perp l,$ we obtain: $$AA'\cap L=\{(-2,-2)\},$$ $$A'(-8,-6),$$  the equation of $BA'$ it's $y=x+2$ and $$P\left(-\frac{14}{5},-\frac{4}{5}\right).$$

A: If you draw the graph, you will understand Michael's argument. To find the coordinate of $A^\prime$ quickly, you can use the formula for the distance from a point $(a,b)$ to line $Ax+By+C=0$ as follows:
$$d=\frac{|Aa+Bb+C|}{\sqrt{A^2+B^2}}.$$
Suppose the coordinate of $A^\prime$ is $(a, b)$, then
$$\frac{-(3a+2b+10)}{\sqrt{3^2+2^2}}=\frac{3(4)+2(2)+10}{\sqrt{3^2+2^2}}.$$
The reason of adding a negative sign to the left-hand side is because $A^\prime$ lies under the line $3x+2y+10=0$.
To solve $a$ and $b$, you need to add another equation from the fact that $AA^\prime$ is perpendicular to the line $3x+2y+10=0$.
$$\frac{b-2}{a-4}\cdot \frac{-3}{2}=-1.$$


text:
Q: Samba Share + Gradle = Java IO Exception I am using a new Mac OS X Server (OS X 10.11) with OpenDirectory and a samba share for remote homes setup.
Using Android Studio in this setup lead me to some issues with gradle. Gradle tries to lock files in the cache directory, which throws a java IOException. I could concentrate the problem to this demo code:
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockTest {

    public static void main(String[] args) throws Exception {
        RandomAccessFile file = null;
        FileLock fileLock = null;
        try
        {
            file = new RandomAccessFile(args[0], "rw");
            FileChannel fileChannel = file.getChannel();

            fileLock = fileChannel.tryLock();
            if (fileLock != null){
                System.out.println("File is locked");
            }
        } finally{
            if (fileLock != null){
                fileLock.release();
            }
        }
    }
}

Compiling and running this with the filename as the first argument shows the issue: A local file could be locked (whatever this means) but a file on a samba share throws this exception:
Exception in thread "main" java.io.IOException: Operation not supported
    at sun.nio.ch.FileDispatcherImpl.lock0(Native Method)
    at sun.nio.ch.FileDispatcherImpl.lock(FileDispatcherImpl.java:90)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1114)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1155)
    at FileLockTest.main(FileLockTest.java:15)

Now to my question: Is there any way to enable the file lock feature for a samba share with mac OS X server? Am I missing some tricky setup with the samba server?
This really makes using Android Studio (/gradle) impossible with an OpenDirectory setup..


text:
Q: Why does C == return true for equal strings? if( "string1" == "string2" )

Why does this work in C? It returns true when strings are equal? How? For example, it doesn't work in Java because the pointers are compared.

A: The C99 Rationale says on string literals (emphasis mine):

"This specification allows implementations to share copies of strings with identical text, to place string literals in read-only memory, and to perform certain optimizations".

It is allowed but non-required so the result could be different with a different implementation or with the same implementation if the program is slightly different.

A: I think comparing string using 'if( "string1" == "string2" )' is comparing pointers to string literals in C. You could refer to the following post:- C String -- Using Equality Operator == for comparing two strings for equality
int main() {

    if( "string1" == "string1" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    if( "string1" == "string2" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    char* s1 = "string1";
    char* s2 = "string2";

    printf("%s = %p %s = %p\n", s1, s1, s2, s2);
    return(0);
}

There are two if blocks in the above main function. One of them if comparing "string1" with itself which will result in TRUE. The second is comparing "string1" and "string2" which will result in FALSE. If you assign pointers to the string literals and print their addresses you will be able to see why in the first if block you get TRUE value and in the second if block you get the FALSE value. Following is the output:-
GAGUPTA2-M-40UT:Desktop gagupta2$ ./a.out
Strings are equal
Strings are not equal
string1 = 0x105f6ef50 string2 = 0x105f6ef82


text:
Q: How can reduce package size of the Google API PHP Client by using composer.json extra configuration? I am using the google-api-php-client in the WP plugin and the PHP composer downloading the complete git repo with almost 200 libraries so the size of the plugin is increasing due to that.
is there a way to get only the desired single package like sheet, drive, etc from this repo by using the PHP composer?
I have tested the following configuration but it is not working.
{
    "require": {
        "google/apiclient": "^2.12.1"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube"
        ]
    }
}


text:
Q: #define across a whole program Is it possible (and if so is it a good idea) to have a preprocessor directive, particularly #define to apply across a whole application, or at least multiple files?
I'm trying to manipulate an array in multiple parts of a program, so I have to make sure the memory allocated to it is still in scope.
To do this I've decided I want to declare the array inside my main object, which wont be deleted until the app is quit. The problem is I don't know at compile time how large my array needs to be, so I want to use #define MAX_ARRAY_SIZE 20.
This is fine, but I'd like to only need to change the max size in one place. Is there a good (and safe) way to do this or should I suck it up and put the #define in all the files that need it?

A: create a global header-file and use header-guard. After inclusion of this global header in each of your headerfiles / *.c / *.cpp - files you will have the macro available to your local code. I would include the global header in your implementation-files IF you dont want to use the macro in your headers ... which is what i also recommend.
example :
global.h:
#ifndef GLOBAL_H
#define GLOBAL_H
#define MYCONSTANT 0xFF
#endif

child-files:
#ifndef GLOBAL_H
#include "global.h"
#endif

also dont forget to use
#pragma once

if your compiler supports it

A: If you use gcc/g++ or compatible tools you can add it as a compiler directive, for example in your makefile.
g++ ... -DMAX_ARRAY_SIZE=20 ...

This is a common way to #define across the whole build and it makes the change very isolated, which is nice.

A: It is fine to have a #define across multiple files.  You could do this with a header file that is shared.  However, it doesn't sound like that will solve your problem.
If you don't know the size of your array at compile time, this will not help--since #define will only work at compile time.
You could simply have the size of the array as another variable and dynamically allocate your array using new and delete it using delete[].  Or simply use std:vector.

A: This is often handled by the build toolchain, rather than in the code.  It's surprisingly difficult to apply a #define to a whole program, especially when that program is large.
If you're using cmake to create the makefiles, you can do cmake ... -DMAX_ARRAY_SIZE=20.  Under linux using gcc, this ultimately ends up becoming g++ ... -DMAX_ARRAY_SIZE=20, which you can also do if your building from hand rather than using makefiles.
On another note, this is not a great use for macros IMO.  Macros skirt around the C++ type system, are very difficult to debug & maintain, and should usually be avoided unless you have no other choice.  There are times when you have no other choice -- but this isn't one of them.  instead of a macro, use a real variable:
static const size_t MaxArraySize = 20;

This should be in a header included everywhere you want to use it.  There will be only one place where this declaration exists.

A: Yep! declare it as a MACRO or just as a gobal variable in a header file.
Make sure to include this header file where you use/ modify.
if you are also looking to modify it then global variable is simplest way to handle it.
It is also possible to be done using MACRO
just use:
undef MAX_ARRAY_SIZE
define MAX_ARRAY_SIZE 100

A: You have several options here. Classic approach is to to move your #define to a header file and include it from any relevant source file.
A better approach might be this:
template <class T, int maxSize = 20>
class myClass
{
    T myArr[maxSize];
    ...
};

int main()
{
    myClass<int> x;
    return 0;
}

This way there is no need for all the logistics of the macro approach.


text:
Q: Simultaneously Play & Save Movie So right now my AVPlayer plays videos from remote URLs (video file sizes are 200-300KB) with the following code,
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:someURL options:nil];
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
        cell.player = [AVPlayer playerWithPlayerItem:playerItem];

        AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:cell.player];
        cell.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

        layer.frame = someFrame;
        [cell.layer addSublayer: layer];

So far, I've only seen examples where videos are played just from the remote URL or they are downloaded first, and then played from the local URL.
I'd like to start playing the video from the URL, and while it is playing, I'd like to save it locally to the cache. How do I do this?


text:
Q: Compute $\text{Hom}_{\text{continuous} }(\hat{\mathbb Z}, (\mathbb C_p)^\ast)$ I'm trying to compute $\text{Hom}_\text{continuous}(\hat{\mathbb Z}, (\mathbb C_p)^\ast)$. By $\hat{\mathbb Z}$ I mean the profinite completion of $\mathbb Z$ and by $(\mathbb C_p)^\ast$ I mean the invertible elements in $\mathbb C_p$.
I tried using the decomposition $\mathbb C_p ^\ast \cong p^\mathbb Q \times U(1)$.
$U(1)$ are the elements in $\mathbb C_p $ with absolute value $1$.
I'm not sure if that helps and I'm not even sure how to compute $\text{Hom}_\text{continuous}(\hat{\mathbb Z}, p^\mathbb Q)$. Could anyone help?

A: Note that $\hat{\mathbb{Z}}$ is the direct product of $\mathbb{Z}_p$ and $\mathbb{Z}^p$, where $\mathbb{Z}^p$ is again the infinite direct product $\prod_{l \neq p}\mathbb{Z}_l$. Therefore, one has a natural isomorphism $\operatorname{Hom}_{cont}(\hat{\mathbb{Z}}, \mathbb{C}_p^\times) \simeq\operatorname{Hom}_{cont}(\mathbb{Z}_p, \mathbb{C}_p^\times)
\times \operatorname{Hom}_{cont}(\mathbb{Z}^p, \mathbb{C}_p^\times)$.
After this step, the problem decomposes into two parts.
For any real number $r$, we denote by $B(r)$ the subgroup $\{z \in \mathbb{C}_p^\times: |z - 1|_p<r\}$ of $\mathbb{C}_p^\times$.

For $\operatorname{Hom}_{cont}(\mathbb{Z}^p, \mathbb{C}_p^\times)$:
Let $\chi:\mathbb{Z}^p \rightarrow \mathbb{C}_p^\times$ be a continuous character. We consider the image $H$ of $\chi$.
Since $\mathbb{Z}^p$ is compact, $H$ must be a compact subgroup of $\mathbb{C}_p^\times$.
Since $H\cap B(p^{-1})$ is an open subgroup of $H$, we see that the index $[H:H\cap B(p^{-1})]$ is finite. This means that there exists an integer $M$ such that $H^M \subseteq B(p^{-1})$.
However, since the multiplication by $p$ map is an automorphism on $\mathbb{Z}^p$, we also have $H \subseteq H^p$, and therefore $H^M \subseteq H^{Mp} \subseteq B(p^{-p})$ (note that we used the fact $B(p^{-1})^p\subseteq B(p^{-p})$, which can be proved using the $p$-adic logarithm and exponential maps).
This procedure can be iterated and will give: $H^M \subset H^{Mp^k} \subseteq B(p^{-p^k})$ for all $k$. Letting $k$ tend to infinity, we see that $H^M$ must be equal to $\{1\}$.
Therefore, $\chi$ is a finite character and hence factor through $\mathbb{Z}/M\mathbb{Z}$ for some $M$ prime to $p$.

For $\operatorname{Hom}_{cont}(\mathbb{Z}_p, \mathbb{C}_p^\times)$:
Let $\chi:\mathbb{Z}_p \rightarrow \mathbb{C}_p^\times$ be a continuous character. By continuity, it is totally determined by its value at $1$. We write $a$ for the value of $\chi(1)$.
Apparantly, $a$ cannot be an arbitrary element of $\mathbb{C}_p^\times$. There is a restriction: since $\chi$ is continuous, the limit $\lim_{k \rightarrow \infty}\chi(p^k)$ should be equal to $\chi(0)$, which is $1$.
Hence $a$ must be a unit in $\mathbb{C}_p^\times$. Moreover, its image in the residual field must be equal to $1$. So $a$ is in the ball $B(1)$.
Conversely, for any element $a$ of $B(1)$, it is easy to see that there is a continuous character $\chi_a:\mathbb{Z}_p\rightarrow\mathbb{C}_p^\times$ which maps $1$ to $a$.
The map $a \mapsto \chi_a$ is then an isomorphism from $B(1)$ to $\operatorname{Hom}_{cont}(\mathbb{Z}_p, \mathbb{C}_p^\times)$.


text:
Q: Why won't this answer to project euler number 4 work properly? numbers = []
palindromes = []
for i in range (100,999):
    for j in range(100,999):
        number = i * j
        test = str(number)
        if test == test[::-1]:
            palindromes.append(number)

print(palindromes[-1])

This code gives back palindromes. However it gives back 580085, which is far from 906609 which is correct. Is there something in the code that makes it quit early?

A: Your list does contain all the palindromes in that range, but not necessarily in a sorted order; the biggest one is somewhere in the middle. Use max to retrieve it.
print(max(palindromes))


text:
Q: How does a charged field's coupling to the electromagnetic field translate to a worldline coupling? Suppose we're interested in (minimally) coupling a heavy scalar particle to the electromagnetic field. In quantum field theory, we describe the particle as an excitation of a complex scalar field $\phi$. Including the simplest possible coupling leads to the theory of scalar QED, with Lagrangian
$$\mathcal{L} = - \frac14 F_{\mu\nu} F^{\mu\nu} + |D_\mu \phi|^2 - m^2 |\phi|^2.$$
By expanding out the kinetic term, we see that there are vertices where a $\phi$ emits a photon, and where a $\phi$ emits two photons. The latter is required by gauge invariance.
On the other hand, if the particle is localized, we could also describe it as a worldline supplying a classical current. For a trajectory $y^\mu(t)$, the current is
$$J^\mu(x) = e \int d \tau \, \frac{dy^\mu}{d\tau} \, \delta(x - y(\tau))$$
and the action is
$$S = - \int dx \, \frac14 F_{\mu\nu} F^{\mu\nu} + \int dx \, J^\mu A_\mu + m \int d \tau.$$
Everything is gauge invariant, since $J^\mu$ is.
Both of these pictures are common, but I'm confused how to translate between them. On the quantum field side, we know that $\phi$ must be a complex scalar, and that it must have a two-photon coupling to ensure gauge invariance. But on the worldline side these facts aren't manifest at all! This doesn't make sense, because in both cases it should be possible to calculate, the probability of producing two hard photons when the particle is accelerated. The results should match, but since the worldline picture is "missing" the two-photon coupling, I don't see how it can.
More specifically, it's clear that the amplitude to produce one hard photon matches between the two formalisms -- what's puzzling to me is that it seems like this implies the amplitude to produce two hard photons in the worldline formalism should match the corresponding amplitude in the field theory formalism, without the two photon vertex.
What's going on?

A: I think the best way to see where the four-point interaction disappears is to follow the derivation of the worldline formalism. Christian Schneider's PhD thesis has a good walkthrough for scalars and spinors in section 4.2; the majority of this answer paraphrases it.
Starting with the scalar QED Lagrangian you write down at the beginning of the question, you get the path integral
$$\mathcal{Z} = \int \mathcal{D} \phi \mathcal{D} \phi^* \mathcal{D}A \, \mathrm{e}^{iS[\phi, \phi^*, A]}$$
where $S$ is the action from the scalar QED lagrangian. The next step is to rewrite the lagrangian in a Gaussian form: by essentially completing the square we find
$$S \supset \phi^* (D^2 + m^2) \phi.$$
The next trick is to Wick rotate to Euclidean space (changing $D^2 \to -D^2$ and getting rid of the oscillatory integral), so we can integrate out the matter field to give
$$\mathcal{Z}_\mathrm{E} = \int \mathcal{D} A \det (-D^2 + m^2) \mathrm{e}^{- \frac{1}{4}\int F_{\mu \nu} F^{\mu \nu}}. $$
This is where the four-point interaction appears to vanish: we have integrated out over all the scalar field loops and hidden the interactions in the functional determinant. What follows is a series of integral tricks to write the functional determinant as an integral over all worldlines. We eventually get
$$\mathcal{Z}_\mathrm{E} = \mathcal{N} \int_0^\infty \frac{\mathrm{d}T}{T} \int \mathcal{D} x \int \mathrm{D} A \, \mathrm{e}^{-\frac{1}{4} \int F_{\mu \nu} F^{\mu \nu}}\,\mathrm{e}^{-\int_0^T \mathcal{L}_\mathrm{eff}[x, A] \, \mathrm{d} \tau},$$
where $\mathcal{L}_\mathrm{eff}$ is the worldline effective action, and $T$ is a parameter introduced that can be thought of as the worldline length. The effects of the four-point interaction are hidden in the $x$ and and $T$ integrals; if you sum them to all orders you'll get the same result as the standard QFT one.
As noted on p6 of this paper, the fact that the worldline method integrates over diagrams including the scalar interactions is one of its strengths; it can greatly simplify certain calculations.

A: For what it is worth, the seagull term in scalar QED
$$\begin{align} \exp&\left(i\Gamma_{\text{1-loop}}[\phi_{\rm cl}\!=\!0; A_{\rm bg}]\right)\cr
~=~&\int \!{\cal D}\phi~\exp\left[i\int\!d^dx\left\{-\left|\left(\frac{1}{i}\partial_{\mu} - qA_{{\rm bg},\mu} \right) \phi\right|^2 - m^2 |\phi|^2\right\}\right] \end{align}$$
has a formal analog in the Hamiltonian worldline (WL) formalism
$$\begin{align}&\int_{\mathbb{R}_+} dT \int \!\frac{{\cal D}x{\cal D}p{\cal D}e}{\text{ Vol(Gauge)}}~\cr
&\exp\left[i\int_{\tau_i}^{\tau_f}\!d\tau \left\{p_{\mu}\dot{x}^{\mu} - \frac{e}{2}\left((p - qA_{\rm bg})^2+m^2 \right) \right\}\right]\delta[\text{Gauge-fixing}]. \end{align}$$
For more information, see Refs. 1+2.
References:

*

*F. Bastianelli, Constrained hamiltonian systems and relativistic particles, 2017 lecture notes; chapters 2 + 3 + 4.

*C. Schubert, Perturbative Quantum Field Theory in the String-Inspired Formalism, arXiv:hep-th/0101036; sections 3.2 + 4.3.1.
--
Notation & Conventions: Minkowski signature $(-,+,+,+)$.


text:
Q: Scripting installation of a virtual package provider on Debian/Ubuntu First, what's the simplest way to get a list of (real) packages that provide a particular virtual package? 'aptitude show' seems to include it in the output for a virtual package, but 'apt-cache show' does not. However, aptitude is not always installed, and grep'ing for "Provided by:" in a script would be fragile due to localization.
# aptitude show java-sdk
No current or candidate version found for java-sdk
Package: java-sdk
State: not a real package
Provided by: default-jdk, gcj-4.4-jdk, gcj-4.5-jdk, gcj-jdk, openjdk-6-jdk, sun-java6-jdk

# apt-cache show java-sdk
N: Can't select versions from package 'java-sdk' as it is purely virtual
N: No packages found

Second, is there any reasonable way to rank the providers such that I'm likely to choose the latest or "most preferred" one? In the 'java-sdk' case, a script should obviously just use 'default-jdk' to begin with; however, if someone hadn't thought to create that, I could imagine sorting by a combination of Priority, Component/Section, and Version. (Obviously, this would mainly be useful for virtual packages providing a standard API; automatically picking a provider for 'mail-reader' would be silly.)
To be concrete, I'm trying to automate the installation of Cloudera Hadoop using Chef. 'hadoop' is a virtual package, where the corresponding real package is currently 'hadoop-0.20':
# aptitude show hadoop
No current or candidate version found for hadoop
Package: hadoop
State: not a real package
Provided by: hadoop-0.20

When there's more than one provider (e.g. hadoop-0.22), I basically want to automatically pick the latest version if 'hadoop-X.YY' is present. (Or better yet, get the Version for each from apt somehow, rather than trying to parse the names.) I know I could achieve this with some scripting, but it wouldn't surprise me if a more elegant way already existed.
Update: 'apt-cache showpkg' includes "Reverse Provides", which further seems to include full version information. This helps, but any idea how to get only this section?
# apt-cache showpkg hadoop
Package: hadoop
Versions:

Reverse Depends:
  sqoop,hadoop
  hadoop-pig,hadoop
  hadoop-hive,hadoop
Dependencies:
Provides:
Reverse Provides:
hadoop-0.20 0.20.2+923.21-1~maverick-cdh3

A: If you install the grep-dctrl package, you can use grep-available:
grep-available -F Provides -s Package <virtual-package-name>

I don't have hadoop packages available in my debian sources.list so i'll use mail-transport-agent as an example:
$ grep-available -F Provides -s Package  mail-transport-agent
Package: xmail
Package: exim4-daemon-light
Package: exim4-daemon-heavy
Package: esmtp-run
Package: postfix
[...most deleted...]

if you want version numbers too:
$ grep-available -F Provides -s Package,Version  mail-transport-agent
Package: xmail
Version: 1.27-1.1+b1

Package: exim4-daemon-light
Version: 4.76-2

Package: exim4-daemon-heavy
Version: 4.76-2

Package: esmtp-run
Version: 1.2-6
[...]

Note the convenient, easily parsed paragraph mode for each package in this second example.
There are numerous other options, including omitting the field names ("Package:", "Version:", etc).  See the man page or --help for more details.

A: Your "most preferred" package is handled by alternatives. The command update-alternatives can give you information on the alternative packages and their priority.
update-alternatives --query editor will display all of the editor entries and their priority, in a machine-parseable format.
There is also a utility called whiff that accepts input and returns the first usable entry.


text:
Q: UIBarButtonItem not clickable in UIToolBar I have a UIPickerView and I am adding a UIToolBar with 2 UIBarButtonItems to it.
var toolBar = UIToolbar()
toolBar.frame.origin.y = -40
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()

var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")

toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true

pickerView.addSubview(toolBar)
pickerView.bringSubviewToFront(toolBar)
view.bringSubviewToFront(toolBar)

The problem is, that when I try to click on the the UIBarButtonItem, it doesn't fire, it doesn't even recognize it, it just clicks the cell beneath it.

A: Can you try this codes.
    var textField = UITextField(frame: CGRectMake(20, 50, view.width - 40, 30))
    textField.backgroundColor = UIColor.redColor()
    view.addSubview(textField)

    var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.width, 300))
    pickerView.backgroundColor = UIColor.whiteColor()
    pickerView.showsSelectionIndicator = true

    var toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
    var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")

    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    textField.inputView = pickerView
    textField.inputAccessoryView = toolBar

A: I believe that you need to raise the picker and toolbar using the standard UIResponder mechanism or cheat by using a hidden UITextField to get the same result.
See my updated answer to your original question:
Add buttons to UIPickerView - Swift 1.2


text:
Q: Developing Networking Security Applications & System utilities in Java I come from a C/Linux background and don't have much background in Java. I generally develop system administrator utilities like :

*

*disk cleanup

*retrieve lost data / files

*repairing file systems

*disk de-fragmentation

I also develop Network monitoring security applications which help admins monitor :
- their networks,
- scan incoming & outgoing data packets,
- remotely block ports / USBs
- monitor emails with attachments etc
Right now we write code in C for Linux which has to be ported to windows but such a problem will not exist in Java.
My questions are :

*

*Is Java the right language for writing these applications & utilities (as mentioned above)?

*I understand Java will provide Libraries and classes to access system resources / network / sockets but will Java abstraction be a hindrance at some point (which would restrict the flexibility which C/C++ provide )?

*If for example I want to write a utility to repair a file system / or retrieve data for Windows & Unix ...will I be using same API for both OS or there are different API for different OS?
I am not concerned about the speed / execution trade off since none of my applications have to make real time decisions as in the gaming industry.

A: Java is the right language if you want portability. You can do almost everything you can do with C/C++ and you can utilize patterns and libraries that help you create great maintainable designs. In case there is something very low level you cannot do with Java, you always can create your own native code that is loaded with Java Native Interface. Thus the only non-portable code you will have will be these native-code libraries.

A:
Right now we write code in C for Linux which has to be ported to
  windows but such a problem will not exist in Java.

Java can abstract away only so much since in the end, low level stuff always boils down to making system calls, which are different between OSes.
As long as you're working with pure java logic, or simple operating system utilities, you'll be golden. You want to open a TCP socket and connect to google.com? No problem. You want to open a file in a known location, read some lines, process them, and write the results to a different file? No problem, Java has you covered.
But, if you want to do more low-level stuff with Java, you'll run into trouble pretty soon. You want to open a raw socket and send a TCP packet? You can't, windows doesn't allow that. You want to get a file's creation time on Linux? You can't, Linux doesn't keep that information. Java's BasicFileAttributes.creationTime() will return a file's modification time on Linux. You want to get a nanosecond resolution timestamp? Well, you can, but only on some OSes. Or say you want to get the computer's hostname without resorting to a network lookup (which depends on a network being actually available), well, get ready for some hacking (this is my own answer by the way).
Now, to your more specific questions:

Is Java the right language for writing these applications & utilities    (as mentioned above)?

I frankly don't know. I never tried defragmenting or restoring a file programmatically from Java. But since it involves some very low level filesystem operations, I suggest you do some serious reading before moving to Java. Check whether the APIs you need exist in the language itself or in some good libraries.

I understand Java will provide Libraries and classes to access system
  resources / network / sockets but will Java abstraction be a hindrance
  at some point (which would restrict the flexibility which C/C++
  provide )?

Yes. For instance, it's impossible to open a raw socket using pure Java. And if I recall correctly, it's also impossible to set some socket options.

If for example I want to write a utility to repair a file system / or
  retrieve data for Windows & Unix ...will I be using same API for both
  OS or there are different API for different OS?

I never tried repairing a file system in Java, so I can't tell you about the APIs involved. But I find it hard to believe you'll find a pure Java api for doing low level stuff with the file system. You'll probably have to write your own native code (and run it through JNI) or use someone else's library (which probably uses JNI, like the raw socket library I mentioned earlier).


text:
Q: Why is a table re-rendering moving table data outside of the table? I have a JSF file that has an html table in it. The table is surrounded by <a4j:outputPanel></a4j:outputPanel> tags.
The table set up is like this:

Inside the first 	 of the first row there are 2 div elements. When I was using the page I clicked an <a4j:commandButton> that rerendered the page and I noticed that the second and third  in the first row were moving to their own row below the first. I checked the source code and the 2 divs that were in the first  were no longer in the table at all and were moved to before the
 tag and there were now only 2  elements in the first
. To test it more I made another <a4j:commandButton> that does nothing except rerender the <a4j:outputPanel> that the table is in and it was still happening. I was able to fix it but putting an empty table row before the first. This is a workaround but I would like to know why it was happening in the first place. Anyone know?
I am using a tomcat 6 server if it makes a difference.


text:
Q: serving files using django - is this a security vulnerability I'm using the following code to serve uploaded files from a login secured view in a django app.
Do you think that there is a security vulnerability in this code? I'm a bit concerned about that the user could place arbitrary strings in the url after the upload/ and this is directly mapped to the local filesystem.
Actually I don't think that it is a vulnerability issue, since the access to the filesystem is restricted to the files in the folder defined with the UPLOAD_LOCATION setting.
UPLOAD_LOCATION = is set to a not publicly available folder on the webserver

url(r'^upload/(?P<file_url>[/,.,\s,_,\-,\w]+)', 'project_name.views.serve_upload_files', name='project_detail'),

@login_required
def serve_upload_files(request, file_url):
    import os.path
    import mimetypes
    mimetypes.init()

    try:
        file_path = settings.UPLOAD_LOCATION + '/' + file_url
        fsock = open(file_path,"r")
        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)
        print "file size is: " + str(file_size)
        mime_type_guess = mimetypes.guess_type(file_name)
        if mime_type_guess is not None:
            response = HttpResponse(fsock, mimetype=mime_type_guess[0])
        response['Content-Disposition'] = 'attachment; filename=' + file_name
        #response.write(file)
    except IOError:
        response = HttpResponseNotFound()
    return response

EDIT: Updated the source according Ignacio Vazquez-Abrams comments:
 import os.path
 import mimetypes

  @login_required
  def serve_upload_files(request, file_url):
    mimetypes.init()
    try:
        file_path = os.path.join(settings.UPLOAD_LOCATION, file_url)
        #collapse possibly available up-level references
        file_path = os.path.normpath(file_path)
        #check if file path still begins with settings.UPLOAD_LOCATION, otherwise the user tampered around with up-level references in the url
        #for example this input: http://127.0.0.1:8000/upload/..\test_upload.txt results having the user access to a folder one-level higher than the upload folder
        #AND check if the common_prefix ends with a dir separator, Because although '/foo/barbaz' starts with '/foo/bar'
        common_prefix = os.path.commonprefix([settings.UPLOAD_LOCATION, file_path])
        if common_prefix == settings.UPLOAD_LOCATION and common_prefix.endswith(os.sep):
            fsock = open(file_path,"r")
            file_name = os.path.basename(file_path)
            mime_type_guess = mimetypes.guess_type(file_name)
            if mime_type_guess is not None:
                response = HttpResponse(fsock, mimetype=mime_type_guess[0])
                response['Content-Disposition'] = 'attachment; filename=' + file_name
            else:
                response = HttpResponseNotFound()
        else:
            print "wrong directory"
            response = HttpResponseNotFound()
    except IOError:
        response = HttpResponseNotFound()
    return response

A: A few tips:

*

*Use os.path.join() to join the path together.

*Use os.path.normpath() to get the actual path with no ".." references.

*Use os.path.commonprefix() against UPLOAD_LOCATION and the generated path, and verify that the result starts with UPLOAD_LOCATION.

*Make sure that UPLOAD_LOCATION ends with a dir separator.

TL;DR: Use os.path.


text:
Q: MongoDB scalability concern on large multi-update operation I'm using MongoDB Node.js native driver and doing an update operation with multi option enabled:
productCollection.update(
  {'categories.id': category.id},
  {'$set': {
    'categories.$.name': category.name,
    //...and so on
  }},
  {multi: true}
);

I expect the collection to substantially grow in the future, so the updates will affect millions of records. Response time is not an issue in this case, what I'm concerned about is the future scalability of the operation, specially peak memory usage and affecting the performance of other operations in the database.
I'm not sure how MongoDB handles situations like this, would it be better to implement some sort of "batching" by retrieving groups of records into the application (with pagination using skip/limit or _id/limit) and then do bulk updates for each "batch", even if it takes more time?


text:
Q: SQL timeout - DB not indexed I'am currently having a slow performance problem with a SQL inner join on two tables with 10 000 000 rows. (about 10-15 minutes response)
The DB is not indexed.
Is indexing the only solution available for me?

A: If you're querying on a field that is not indexed, then it's going to do a table scan over the entire table (10 million rows.)
If you're doing a like = '%blah%' that's going to be slow as well.
It might help if you actually posted your query (or one similar) so that we could give you more info.

A: These are the options available to you

*

*Change your query to not have a join. This is easy if the data you want is only one one table.

*Add an index to the correct table.

*Change your schema to not require a join. This might require moving data around, hierarchical data, or a materialized view, or some other de normalization process.


text:
Q: Testing load document functionality with JMeter I am testing a service that has "load document" functionality. I need to send a unique document with every request. In the HTTP request sampler config menu I see that I can send a document along with my request. However, I don't have a clue as to how I am going to send a different document with every request. Is there a way to get JMeter to either slightly modify a document, generate a specified document, or even perhaps select a series of externally generated documents for submission with a request?

A: You may use CSV Data Set Config under While Controller to read and send pre-created test documents names in cycle.
This will look like:

*

*create collection of different test-documents to send with your request;
OPTIONALLY: store path to folder with created documents as jmeter variable - to use in script;

*create list of test-documents;
you can do this in BeanShell Sampler with code as shown below;

*add While Controller to send test-documents in cycle;
CSV Data Set Config to While Controller as child - to read test-documents names from list.

Detailed:

${__javaScript("${testFile}"!="<EOF>",)} - to read list till the end of file

BeanShell Sampler code to generate test-files list:
import java.text.*;
import java.io.*;
import java.util.*;

String [] params = Parameters.split(",");

String contentList = params[0];
String testDataDir = params[1];

File dir = new File(System.getProperty("user.dir") + File.separator + testDataDir);
BufferedWriter out = null;

try {

    if (!dir.exists()) {
        throw new Exception ("Directory " + dir.getName() + " not found.");
    }

    File contentFile = new File(System.getProperty("user.dir") + File.separator + contentList);

    if (contentFile.exists()) {
        contentFile.delete();
    }

    FileWriter fw = new FileWriter(contentFile, true);
    out = new BufferedWriter(fw);

    System.out.println("\n--------------------------------------------------------------------------------------");
    System.out.println("CONTENT LIST:\n");

    if ((dir.exists()) && (dir.listFiles() != null) && (out != null)) {
        for (File f : dir.listFiles()) {
            if (contentFile.length() == 0) {
                out.write(f.getName());
            } else {
                out.write("\n" + f.getName());
            }

            out.flush();

            System.out.println("Content " + f.getName() + " added to " + contentFile.getName() + ".");
        }
    }

    System.out.println("--------------------------------------------------------------------------------------\n");
}
catch (Exception ex) {
    IsSuccess = false;
    log.error(ex.getMessage());
    System.err.println(ex.getMessage());
}
catch (Throwable thex) {
    System.err.println(thex.getMessage());
}
finally {
    out.close();
}


text:
Q: how to parse string object without double quote in front in json i have an array in my angular applicaton for eg:
searchTerm : any[]

I have a textbox with a value {'state':'tn'} and want to push this to the searchTerm array. Currently i add this item to a service and then array as:
  private onItemAdded(event): void {
    const filter = JSON.parse('"' + event['value'] + '"');
    this.dataService.addFilter(filter);
  }

But it is storing as "{'state':'tn'}"
How can i parse this without double quotes in the front?
console.log('ADDED FILTER', event['value']);

here the value is printed as {'state':'value'}
but when assign to variable as below, it adds double quotes
let filter = event['value'];

Thanks

A: why you are using parse?, it is for converting from JSON to object, instead use stringify which will parse your object to JSON(string)

const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);


text:
Q: Javascript not working in Codeigniter I'm having trouble with document.write in codeigniter.
Here is my test code:
<script type="text/javascript">
document.write("Hello World!");
</script>

In a standard html or php document it works fine and writes Hello World! on the browser screen. So that eliminates browser oddities and doctypes etc and javascript is definitely not disabled.
However, if I put the same script in a vanilla codeigniter view, nothing appears on the screen.
Anyone got a clue what's wrong?

A: Always giving the asker the benefit of the doubt, I installed a fresh copy of CI live with your code, one in <head>, one in <body>, and had absolutely no problem.
I'm afraid you aren't giving enough details or have an unrelated error. Maybe you turned javascript off.


text:
Q: Some need help on SQL statement Assume the following table:
Select *
from TestTable;

  Name      value
   B          3
   C          1
   A          2

I want to output as follows:
  Name      value
   A          1
   B          2
   C          3

Notice that in the result Names are matched to their corresponding ordinal values from the value column.
Anyone help, how can I write the SQL statement?

A: select
    Name, Value
from
    -- Order the Name table
    (select row_number() over (order by name) as id, Name from TestTable) as n
    inner join
    -- Order the Value table
    (select row_number() over (order by value) as id, Value from TestTable) as v
    on n.id = v.id -- Combine two table by the ordered id

A: SELECT A.Name, B.Value FROM (
SELECT ROW_NUMBER() OVER(ORDER BY Name) as N, Name FROM Tab ) as A
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Value) as N, Value FROM Tab) as B on B.N = A.N

A: WITH
 test1 AS
(SELECT ROW_NUMBER() over(order by Name)as id , Name  FROM Testing ),
 test2 AS
(SELECT ROW_NUMBER() over(order by value)as id , value  FROM Testing )
SELECT Name,Value
FROM   test1
       JOIN test2
          ON test1.id=test2.id


text:
Q: Postgres function NULL value for row that references NEW I have a trigger setup to fire after a row is updated or inserted for table A. There is also a table B that references table A, but also has another column which I want to analyze, a boolean (so this function would only be usable on an UPDATE).
When I try to access the column:
SELECT col1 FROM B WHERE B.aID = NEW.ID;

This column col1 is always NULL.
Why is this? How can I get the boolean value upon an update?

A: Most probably you are running into a naming conflict. Parameter names (IN and OUT parameters) are visible in the function body (almost) anywhere and take precedence over unqualified column names. Did you declare col1 as variable in the function?
To avoid the conflict, table-qualify the column name:
SELECT b.col1 FROM tableb b WHERE b.aID = NEW.ID;

This is good practice in any case.
It is also good practice to prefix variable names, so they wouldn't normally conflict with table columns. Like: _col1.


text:
Q: Можно ли сделать исполняемый файл приложения, написанного на java с расширением не jar, а exe? Я создал приложение на языке java, но проблема в том, что после создания исполняемого jar файла, я могу его запустить только со специальным программным обеспечением, соответственно если кто-то попытается его запустить с другого компьютера, у него ничего не выйдет.
Как сделать исполняемый файл с расширением exe?

A: Для того, чтобы преобразовать jar в exe, нужно скачать Launch4j, установить путь к начальному файлу и конечному результату (с нужным расширением)

Нажать на вкладку JRE, в пункте Min JRE version написать 1.6.0_22
После чего нажать на шестерёнку, вбить имя доп файла и нажать save

A: Если вы используете IntelliJ тогда в Project Structure -> Artifacts  -> выберите Native Bundle: All

далее выберите во вкладке Build -> Build Artifact -> имя приложения -> Build

*.exe файл вы найдете тут:

USER\IdeaProjects\projectname\out\artifacts\projectname\bundles\projectname -> там будет находится ваш .exe файл.


text:
Q: Set pidgin settings to another folder As default on Windows 7 Pidgin sets its message logs and account settings to the folder
%AppData%\.purple

How do I move that folder to another location on my drive D:/ ?
I thought about using a symbolic link, but I'm not sure if that works on different drives too. Maybe there is an easier solution by changing some registry settings?

A: Right click the link for pidgin (the one in the start menu and desktop),
click Properties and in the Target: line change.
"C:\Program Files\Pidgin\pidgin.exe"

to
"C:\Program Files\Pidgin\pidgin.exe" --config="D:\SomeDir\.pidgin"

A: You can also set the PURPLEHOME environment variable to set a new location for the folder.
See: https://developer.pidgin.im/wiki/Using%20Pidgin#Whereismy.purpledirectory


text:
Q: Suppress points in exam class How do I globally suppress the display of points (for questions and for parts) in exam class?
I like to have the points display on the question sheet, but not on the answer (questions+solutions) sheet.
I tried \nopointsinmargin but that did not work. It only shifted the displayed points to another location.
A minimum working example:
\documentclass[answers]{exam}
%\documentclass{exam}
%\pointsinrightmargin
\nopointsinrightmargin
\begin{document}
\begin{questions}
    \question[5]
        How long is a piece of string?
        \begin{parts}
            \part[2] Define "piece".
            \begin{solution}
                A piece is \dots
            \end{solution}
            \part[3] Define string.
            \begin{solution}
                A string is \dots
            \end{solution}
    \end{parts}
    \droppoints
\end{questions}
\end{document}

A: You could add
\ifprintanswers\pointformat{}\fi

to the preamble. The \pointformat macro is used to define the formatting of the printed points, by leaving it empty nothing is printed. \ifprintanswers means that \pointformat{} is only used if the answers option is added to the class options.
Complete code, using an example from the manual.
\documentclass[
% answers
]{exam}
\ifprintanswers\pointformat{}\fi
\begin{document}
\begin{questions}
\question[7] Who was the fifth Beatle? \answerline[Murray the K]
\question[5] What is the answer to the ultimate question of life, the
universe, and everything? \answerline[42]
\end{questions}
\end{document}

Without answers option:

With answers: