text:
Q: How to fix "A lambda expression with a statement body cannot be converted to an expression tree" for sql for execution? I have to sort this table of "Report's" on data within a nested table. I.e. each Report item has a number of Net's associated with it and each Net has a status attribute that I need to sort the list of Reports on. Here is an example of what I've been able to get so far, however I am having trouble being able to write this in a way that will be acceptable for IOrderedQueryable because I need this to still be translated into SQL and executed through that rather than where I am writing the code:
var orderedReports = reports.OrderBy((r) =>
{
    switch (r.Nets.Any(n => n.Status.Contains("New")) ? "New" :
            r.Nets.Any(n => n.Status.Contains("Updated")) ? "Updated" :
            r.Nets.Any(n => n.Status.Contains("Ignored")) ? "Ignored" : "None" )
    {
        case "New": return 1;
        case "Updated": return 2;
        case "Ignored": return 3;
        case "None": return 4;
        default: return 5;
    }
}).ThenBy(r => r.ReportID);

I realize that many reports can have similar or even matching number of statuses so after the initial sort, I then sort by the ID of that report. I basically want all the reports that have at least one "New" status first, then the others to follow as described above. I also want to reiterate that I need to make sure this stays in IOrderedQueryable because this needs to be executed in SQL when making the query to the database.

A: Looks like the switch statement has no SQL equivelant and it's expecting to run this in Linq to Objects.
It appears that a conditional operator has a direct conversion:
https://www.codeproject.com/Articles/38264/How-to-Create-T-SQL-CASE-Statements-With-LINQ-To-S
I highly recommend testing in LinqPad because it can produce the SQL equivalents to help you with debugging.


text:
Q: Checkbox on "change" function does not work in Safari browser at first click I have this function:
function CompareProduct(product_id) {
    $(document).ready(function() {
        $('#' + product_id).on('change', function() {
            if ($(this).is(':checked')) {
                CheckboxCompare.Add(product_id);
                $('#' + product_id).attr("disabled", true);
            } else if (!$(this).is(':checked')) {
                compare_product_remove(product_id);
                $('#' + product_id).attr("disabled", true);
                $('.compare-product_' + product_id).fadeOut();
            }
        });
    });
}

Edited... HTML:
{% for product in products %}
    <input class="compare-checkbox" autocomplete="off" type="checkbox" name="{{ product.product_id }}" value="1" id="{{ product.product_id }}" data-toggle="tooltip" title="{{ button_compare }}" onclick="CompareProduct('{{ product.product_id }}');" />
 {% endfor %}

Which working fine on Chrome, Mozilla, but does not work on Safari.
On Safari browser, when click first time just  a checbox become selected... when I click second time checkbox deselecting and function works. And when I click again function also working.
   So first click of the checkbox on Safari does not work.
How to solve this problem?
EDITED:
I find solution for my issue... on Safari browser also working fine:
function CompareProduct(product_id) {
var checkbox = document.getElementById(product_id);
        if (checkbox.checked == true) {
            CheckboxCompare.Add(product_id);
        } else if (checkbox.checked != true){
            compare_product_remove(product_id);
        }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: htaccess domain access without file endings I want domain.de/test.php to appear without the .php.
I tried this, but its not working. Is there a conflict maybe?
This is my full .htaccess now. Do I have an error somewhere or conflict?
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

# FORCE HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://bm-translations.de/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

#remove the need for .php extention
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

<IfModule mod_filter.c>
<IfModule mod_deflate.c>
## Enable gzip compression ##
# compress text, HTML, JavaScript, CSS, and XML
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Remove browser bugs
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
## END Enable gzip compression ##
</IfModule>
</IfModule>

AddType font/woff .woff
ExpiresByType font/woff "access plus 1 year"
AddOutputFilterByType DEFLATE font/woff

AddType image/svg+xml .svg
AddOutputFilterByType DEFLATE image/svg+xml

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 3 month"
ExpiresByType image/jpg "access 3 month"
ExpiresByType image/jpeg "access 3 month"
ExpiresByType image/gif "access 3 month"
ExpiresByType image/png "access 3 month"
ExpiresByType image/svg+xml "access 3 month"
ExpiresByType text/css "access 3 month"
ExpiresByType text/html "access 3 month"
ExpiresByType application/pdf "access 3 month"
ExpiresByType text/x-javascript "access 3 month"
ExpiresByType application/javascript "access plus 3 month"
ExpiresByType application/x-shockwave-flash "access 3 month"
ExpiresByType image/x-icon "access 3 year"
ExpiresDefault "access 3 month"
</IfModule>
## EXPIRES CACHING ##

I tried to put the part with file-extension on top and at the bottom, but everywhere its not working.

A: You may use these rules in site root .htaccess:
RewriteEngine On

# remove www and redirect http to https
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

# internally add .php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

A: Solution was to add RewriteBase /
RewriteEngine on
RewriteBase /
# FORCE HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://bm-translations.de/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

#remove the need for .php extention
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]


text:
Q: Unit testing classes with mocked repository dependecies I have a service class with several methods. Service has some dependencies on repositories. I am using Moq to mock the repository. I have a problem with the proper unit testing one of the methods. I will give you an example:
public interface IRepository<T>
{
    IEnumerable<T> FindAll();
    IEnumerable<T> FindByQuery(Predicate<T> predicate);
    //many other methods for retreiving T's
}

public class MyService
{
    private readonly IRepository<Category> _repo;

    public MyService(IRepository<Category> repo)
    {
        _repo = repo;
    }

    public List<Category> FindActiveCategories()
    {
        return _repo.FindAll().Where(x => x.Active).ToList();
    }
}

Now, I wrote a unit test:
public FindActiveCategories_WhenCalled_ShouldReturnActiveCategories() {
   var moq = new Mock<IRepository<Category>>();
   var list = new List<Category>
   {
       new Category {Active = true},
       new Category {Active = false}
   };
   moq.Setup(x => x.FindAll()).Returns(list);
   var service = new MyService(moq.Object);
   var result = service.FindActiveCategories();

   Assert.IsTrue(result.All(x=>x.Active));
}

And the test of course passed. But than I realized that I retreived all the Categories in my service method using FindAll - it was an obvious thing to correct, because I didn't want to load several thousands of categories to memory just to pull out only few of them. So I changed the implementation of FindActiveCategories method to this:
public List<Category> FindActiveCategories()
{
    return _repo.FindByQuery(x => x.Active).ToList();
}

And my test failed this time. The problems is obvious - the test depended on the implementation details. I knew that the FindActiveCategories method uses FindAll method of the repository, so I wrote a setup for this method. After changing the implementation I have to change the implementation of the test method - this seems to be a problem. Of course I could've setup all the Find... methods but there are plenty of them in the repository and one can choose many of them, this also doesn't seem right approach for me. Not to mention TDD - if I was trying to write the test first, I wouldn't know what and how to mock the repository interface. My question is: what is a correct way to handle this kind of dependencies to be able to write implementation independent unit tests.

A: Despite the title of this question, the actual question here seems to be "should I need to change my test if my code implementation changes?"
The answer to that is that if the implementation is entirely contained within your code under test then 'no'. For example, if I have a method to multiply two values and I implement it the obvious way, I can write tests to prove that it works. Now if I change the implementation to do the calculation using a for loop and accumulating a total within the loop, all of my tests should pass with no changes.
The problem is that most of the code we write isn't like that: it depends on other things. If the code under test depends on other things we have two choices: do an integration test, or mock the dependency.

*

*The integration test supplies the class under test with the real dependencies that it would be using when actually in use. This is the most valuable testing, since it is completely realistic. The answer here would also be 'no need to change the test if you change the implementation'. However, this is often impractical, since it exponentially increases the cost of writing and maintaining the tests.

*Mocking requires you to specify how the dependency should behave, so by definition, your test must know what the code under test is going to use, and how. Therefore if you change the implementation, you should reasonably expect to have to change the test, so the answer would be 'yes'.

However, consider this point. The parts of your test which do not relate to mocking should not need to change. You aren't using the Arrange Act Assert pattern (which can help make tests more readable, particularly when mocking); but the Act and Assert parts, which would be the last two lines of your test, should not need to change. Maybe that will allow you to believe you're still doing TDD.
But don't lose sleep over it: there are other things which would benefit from your attention more. For example, change the implementation of your method to...
public List<Category> FindActiveCategories()
{
    return new List<Category>();
}

... then the test will pass, even though the code won't do what you want (because the All in the assert returns true for an empty list).
Hope this was useful.

A: The following will work for the change made above.
[TestClass]
public class MyServiceShould {
    [TestMethod]
    public void FindActiveCategories_WhenCalled_ShouldReturnActiveCategories() {
        //Arrange
        var moq = new Mock<IRepository<Category>>();
        var list = new List<Category> {
            new Category {Active = true},
            new Category {Active = false}
        };
        moq
            .Setup(x => x.FindByQuery(It.IsAny<Predicate<Category>>()))
            .Returns((Predicate<Category> predicate) => list.Where(x => predicate(x)));
        var service = new MyService(moq.Object);

        //Act
        var result = service.FindActiveCategories();

        //Assert
        Assert.IsTrue(result.All(x => x.Active));
    }
}

The mock takes the passed predicate and applies it to the fake collection in order to allow the test to be exercised to completion.
Reference Moq Quickstart to get a better understanding of how to use the mocking framework.


text:
Q: Extending a list of list in Haskell Is there anyway that I can extend a list of list in Haskell?
I'm trying to write a function that generates [1,2,2,3,3,3,4,4,4,4.....] which is basically a 1 one, 2 twos, 3 threes etc.
My Attempt:

nnss :: [Integer]
nnss = [nPrint x x | x <- [1,2..]]

The problem with my attempt is that nPrint x x returns a list of integers, for example, nPrint 2 2 would return [2, 2]. Is there anyway I can "expand" the list from [1,2,3...] to [1,2,2,3,3,3...] ?

A: The function signature we're looking for is [[a]] -> [a] and if we check hoogle we see that concat is what we're looking for.
And in this case though, the list comprehension is unnecessary since we're just iterating over each item, so we really want to just do a map. So since combining map and concat is so common we can just write
concatMap (\x -> nPrint x x) [1..]

You can ignore this if you're new to haskell but since the list monad is defined with concatMap we could also write
[1..] >>= \x -> nPrint x x

A: You can also write it without using maps and list concatenations (just prepend in constant time):
nnss :: [Integer]
nnss = genRepeated 1 1

genRepeated :: Integer -> Integer -> [Integer]
genRepeated x 0 = genRepeated (x+1) (x+1)
genRepeated x y = x : genRepeated x (y-1)

Than
take 22 nnss == [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7]

Other fast possibility is:
nnss :: [Integer]
nnss = flatten [take x $ repeat x | x <- [1..]]

flatten :: [[a]] -> [a]
flatten [] = []
flatten ([]:xs) = flatten xs
flatten ((x:xs):ys) = x : flatten (xs:ys)

A: Just add concat:
nnss :: [Integer]
nnss = concat [nPrint x x | x <- [1,2..]]


text:
Q: Internationalization Flutter by intl I've learned flutter. I built an internationalized app using the intl
dependency (follow this)

*

*I run 1st command well (no error message):

flutter packages pub run intl_translation:extract_to_arb --output-dir=lib/l10n lib/main.dart

3 files were generated:

*I need to create intl_{locale}.arb file before run next command.

*Next command:

flutter packages pub run intl_translation:generate_from_arb
--output-dir=lib/l10n --no-use-deferred-loading
lib/main.dart lib/l10n/intl_*.arb

It always returns a message although the corresponding message (messages_en.dart) file is generated:
No @@locale or _locale field found in intl_en, assuming 'en' based on the file name.
No @@locale or _locale field found in intl_messages, assuming 'messages' based on the file name.

How can I run the 2nd command without the messages, because I think they are unexpected messages ?

A: 1.
flutter packages pub run intl_translation:generate_from_arb \ --output-dir=lib/l10n --no-use-deferred-loading \ lib/main.dart lib/l10n/intl_*.arb

should be changed to:
flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/l10n ****lib/DemoLocalizations.dart****

(where ****lib/DemoLocalizations.dart**** should be update to the file where you created this file from the steps you created.
2.
you will have the strings generated. these need to copied to intl*.arb
3.
then you should run:
flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/l10n    --no-use-deferred-loading ****lib/DemoLocalizations.dart**** lib/l10n/intl_*.arb

A: You should write in each file the following. Then flutter will automatically identify the language.
{
  "@@locale": "en",
  "title": "Flutter Example App",
  "@title": {
    "type": "text",
    "placeholders": {}
  }
}

A: Between the steps you mentioned 1. and 2. you should copy the new strings to intl*.arb.


text:
Q: Best way to reorganize dict in a specific string in Python I have a dict.
some_dict = {'cars': 'Audi', 'price': '50k', 'year': '2016'}.

And I want a string:
cars=Audi, price=50k, year=2016

And I wonder, what is the best way of doing it?
There is always some option like this:
response = ''
   for key, value in some_dict.items():
        response += (str(key) + '=' + str(value) + ', ')
   response[-1]='.' # for replacing comma to a point

But it does not seem to be an excellent decision..
I am convinced there is a better way.

A: some_dict = {'cars': 'Audi', 'price': '50k', 'year': '2016'}
', '.join('='.join(i) for i in some_dict.items())

Output:
'cars=Audi, price=50k, year=2016'

A: A better single line and clean way would be:
print ", ".join(map(lambda x:"=".join(x), some_dict.items()))

First we join all the key, value pairs with "=" sign to get a list of strings where keys and values are joined by "=" and then we again .join() this list with ", ".
To add more syntactic sugar as suggested by @juanpa.arrivillaga, you can simply use:
print ", ".join(map("=".join, some_dict.items()))


text:
Q: using flask, send_file a second time to get changed file with same path and name - caching problem? On our flask website we implemented a "Download" button. This button invokes a function in flask which is providing the user with an zipped file via send_file(). The first time everything works fine. After clicking the button the second time, the user receives the exact same file again. Seems fine, but in the time the button is clicked again, the file that flask should send is changed and the old one is not existing anymore.
I tried to understand why this is happening with the PyCharm Debugger and noticed, that after pressing the download button a second time, the download routine is not even evoked anymore. So I think there is some kind of caching going on in the background. I even deleted the file to be send from the file system and then pressed the Download button a second time... I got the original file back.
Maybe you guys experienced something similar and can help me with your knowledge. Thank you in advance.
The download code:
@app.route('/download/<expID>')
def download(expID):

 experiment = dbc.getExperiment(int(expID))

# only execute, if owner of experiment calls it AND experiment is NOT running or in queue
 if experiment.getOwner() == cas.username and experiment.getStatus() != 1 and experiment.getStatus() != 2:
    ownerPath = dbc.getUser(experiment.getOwner()).getPath()
    fileName = cas.username + "_" + expID

    # remove old zip (if existing)
    try:
        os.remove(experiment.getPath() + "/" + fileName + ".zip")
    except FileNotFoundError:
        pass

    # create zip in owner folder to work around recursion problem
    make_archive(ownerPath + "/" + fileName, 'zip', root_dir=experiment.getPath(), base_dir=None)

    # move from owner folder to owner/experiment folder
    shutil.move(ownerPath + "/" + fileName + ".zip", experiment.getPath() + "/" + fileName + ".zip");

    # trigger download
    return send_file(
        experiment.getPath()+"/"+fileName + ".zip", as_attachment=True)
 return redirect('/dashboard')

the button:
<form action="/download/{{experiments[i][0]}}">
                <input type="submit" id="download" value="download" />
            </form>

A: I found a solution in the documentation of send_file.
Flask indeed caches files that you send via send_file and does not access the function you called previously for a certain amount of time. To limit this behavior you can use the cache_timeout argument. For me it looks like this:
return send_file(
            experiment.getPath()+"/"+fileName + ".zip", as_attachment=True, cache_timeout=0)


text:
Q: Normal force of ball sliding on concave surface Imagine a ball is sliding along a surface shaped like $y=x^2$. Like ,
but please ignore the fact that the center of the ball is on the surface instead of the edge.
When the ball is stationary, I can calculate the normal force fairly easily. $F_\text{net}$
in the direction normal to the surface is 0. The normal force is normal to the surface, so it is the force that is exactly strong enough to cancel the normal component of the force of gravity.
The normal force comes out to $<\frac{-a}{(1 + a^2)}, \frac{1}{(1 + a^2)}>$, where $a=f_{\text{surface}}'(x)$ (or in this specific case: $a=2x$)
I initially expected this to be true even after the ball begins sliding down the surface, but I found that it was not. Intuitively, I understand that a velocity with a non-zero component in the normal direction affects the strength of the normal force. This seems like the same mechanism by which the normal force is able to stop a falling object as it hits the ground, for example.
In the falling ball example, the relationship between velocity and normal force seems a bit sticky mathematically. Assuming neither the ground nor the object compress, the normal force would have to be infinite initially, right? It would only be infinite for an infinitesimal amount of time (so the integral would still be finite). However, in that case, the $v(t)$ curve is discontinuous, while it seems like $v(t)$ would be continuous for a ball sliding on $y=x^2$, so hopefully the relationship is less obnoxious in the continuous case.
Is there a mathematical formulation of this relation between normal force and velocity? Can I add a velocity parameter to my equation for $F_\text{net}(x)$ (making it $F_\text{net}(x, v)$) to take this relationship into account?
Note: I also see a conservation of energy solution that sidesteps the normal force issue altogether, but I'd like to understand the forces aspect.

A: When a particle follows a path then at any instant there is tangential vector $\vec{e}$ and a normal vector $\vec{n}$ allowing for the velocity to be defined as $$\vec{v} = v \vec{e}$$ and the acceleration $$ \vec{a} = \dot{v} \vec{e} + \frac{v^2}{\rho} \vec{n} $$ where $\rho$ is the radius of curvature of the path.
For a path defined by a function $f(x)$ with derivatives $f'(x)$ and $f''(x)$ the radius of curvature is
$$ \rho(x) = \frac{\left(1+{f'(x)}^2\right)^\frac{3}{2}}{f''(x)} $$
and the direction vectors are
$$ \begin{aligned}
 \vec{e}(x) &= \begin{pmatrix}
\frac{1}{\sqrt{1+{f'(x)}^2}} \\
\frac{f'(x)}{\sqrt{1+{f'(x)}^2}}
 \end{pmatrix} & \vec{n}(x) &= \begin{pmatrix}
- \frac{f'(x)}{\sqrt{1+{f'(x)}^2}} \\
\frac{1}{\sqrt{1+{f'(x)}^2}}
 \end{pmatrix} \end{aligned} $$
The last part for you, is the fact that gravity only affects the tangential acceleration $\dot{v} = \vec{g} \cdot \vec{e}$ (with $\cdot$ the vector dot product)
$$ \dot{v} = -\frac{g f'(x)}{\sqrt{1+{f'(x)}^2}} $$
with total acceleration
$$ \vec{a} = \dot{v} \vec{e} + \frac{v^2}{\rho} \vec{n}
\\\vec{a} = \begin{pmatrix} - \frac{g f'}{1+f'^2} - \frac{v^2 f' f''}{\left(1+f'^2\right)^2} \\
- \frac{g f'^2}{1+f'^2} + \frac{v^2 f''}{\left(1+f'^2\right)^2} \end{pmatrix} $$
The total force applied is $\vec{F} = m \vec{a}$ and the reaction force is the component normal to motion or $$\boxed{R = \vec{n} \cdot \vec{F} = \frac{m v^2}{\rho} = \frac{m v^2 f''}{\left( 1 + f'^2 \right)^\frac{3}{2}}}$$

note: this area of study is called differential geometry (Frenet formulas). Look it up.

A: All you need is Newtons law and the fact that the force from the surface is the normal force since you have no friction. Then draw a diagram and see that $N_x/N_y=df/dx=v_y/v_x$. Then solve $F=d\vec{p}/dt=m\vec{g}+\vec{N}$.
If you need $\vec{v}$ aswell use energy conservation and initial condition.
Post solution. ;)


text:
Q: Php look through json array modify a special value and return the array So I have a JSON array with some content in the array. each item has product id and price, my aim is to loop through this array, and modify the product price and return array with modified product price.
here is the json array snippet in result/
"variation_combination_price" => array:4 [▼
0 => array:10 [▼
  "id" => 1
  "product_id" => 1364
  "cost_price" => 600
  "promo_price" => 900
  "price" => 900
  "combination_array" => array:2 [▼
    0 => array:8 [▶]
    1 => array:8 [▶]
  ]
  "combination_array_string" => "{"1":"3","2":"4"}"
  "quantity" => 10000
  "status" => 1
  "DOCUMENTATION" => array:2 [▶]
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]

So the result above is the original response. As you can see we have 4 items there, the aim is to loop though them, modify the price and return same 4 items.
  foreach ($product_data['variation_combination_price'] as
  $variation_combination_price){

        $variation_combination_price['price'] = 666;

        $product_data['variation_combination_price'] =
$variation_combination_price;

    }

    dd($product_data['variation_combination_price']);

My result should come with the same array where price is modified.
"variation_combination_price" => array:4 [▼
0 => array:10 [▼
  "id" => 1
  "product_id" => 1364
  "cost_price" => 600
  "promo_price" => 900
  "price" => 666
  "combination_array" => array:2 [▼
    0 => array:8 [▶]
    1 => array:8 [▶]
  ]
  "combination_array_string" => "{"1":"3","2":"4"}"
  "quantity" => 10000
  "status" => 1
  "DOCUMENTATION" => array:2 [▶]
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]

A: You are not looping by reference.
Whatever changes you do in the loop will not change the value of the array.
In order to do so you need to add a &
foreach ($product_data['variation_combination_price'] as &$variation_combination_price){
    $variation_combination_price['price'] = 666;
}

Just remember to unset the variable after the loop also.
unset($variation_combination_price);

To make sure you don't change the array data after the loop is done.


text:
Q: Fetching data with multiprocessing I have a function posting to a server (AWS Lambda) to perform OCR of an base64 image:
def image_to_text(image64):
    url = base_url + 'text-to-image'
    data = json.dumps({'image64': image64})
    r = requests.post(url, data)
    r.raise_for_status()
    return r.json()['text'].encode('utf-8')

The function works: image_to_text('some long string') will return a proper response.
Problem: Using image_to_text in parallel (multi-process) makes the application halt (without warnings or errors) at r = request.post(url, data)
Example:
import multiprocessing as mp
from multiprocessing import cpu_count

p = mp.Pool(cpu_count())
p.map(image_to_text, ('A long string',
                      'Another long string'))
p.terminate()

Question: Why is my application halting and how can I use multiprocessing to fetch data with requests?

A: Your application probably is not halting but it's slowing down significantly due to the large amount of data you are transferring through the Pool. What you perceive as a "halt" is actually big IPC overhead.
From the multiprocessing programming guidelines.

Avoid shared state
As far as possible one should try to avoid shifting large amounts of data between processes.

The Pool relies on an internal pipe to transfer the data to the workers which will execute your image_to_text function. This pipe becomes a bottleneck if the amount of data which needs to be delivered is huge. In your case, you are sending the data back and forth doubling the amount of bytes which need to be serialized and shipped.
I'd recommend you to dump the data to temporary files and send to image_to_text the file names only. The image_to_text will open and read the data from the files autonomously. You will notice your logic becoming significantly faster and more robust as well.


text:
Q: Bulk insert task fails, BUT actually succeeds? I made a simple bulk task to load data from a 3-4 kb csv (.txt) file. All the data is loaded correctly and yet SSIS shows that its failed. I don't get it. Why ?
The so-called error is -
[Bulk Insert Task] Error: An error occurred with the following error message: "Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (My_ID).".
I am using SSIS 2008 and SQL server 2008 for this one.

A: Did you set your setting to continue on failure in the SSIS package ?? are you sure you have got all the rows in you table after this error occurred ? because it seems like your text file had some column names and you didnt set the FIRSTROW = 2 in your bulk insert statement.


text:
Q: 2 Instances on Heroku Free Tier? I have an app with a postgres add on deployed on Heroku free tier. When opening up my integrated Datadog infrastructure list, I expected to see 2 hosts - 1 for the api and one for the db. Instead, I see 3. What is the third?
$heroku info
=== myappname
Addons:         heroku-postgresql:hobby-dev
Auto Cert Mgmt: false
Dynos:          web: 1, run: 1
Git URL:        https://git.heroku.com/myappname.git
Owner:          name@gmail.com
Region:         us
Repo Size:      937 KB
Slug Size:      123 MB
Stack:          heroku-20
Web URL:        https://myappname.herokuapp.com/

Not sure what the web and run refers to here.
heroku regions --common --json outputs an array of length 2. The machines have 2 different ids. One in Europe, one in the US.
Clicking into the hosts in datadog, I see 2 with info that says dynotype:run and one that says dynotype:web

A: I had started a 1 off background process (heroku CLI) which is the third machine
Steps to reproduce:

*

*heroku ps

*Use the run.wxyz to match with the datadog infrastructure list info

https://devcenter.heroku.com/articles/dynos
I'm still not entirely sure the other node is my db, but that would likely make the most sense.


text:
Q: Python selenium while loop passing despite condition being met I created a while loop that should look a the titles of the chrome pages and if they all contain the string 404 the pages refresh and the loop starts again. And if any of the pages does not contain the string 404 then the while loop condition is false and my code just continues.
However the while loop is being passed while I know that the condition is true and all the webpages titles contain the string 404 in them
# Open first window and Maximize Window
driver.get(web_link_00)
driver.maximize_window()
web_title_00 = driver.title
print('First Window: ' + web_title_00)
# Open a new window, Switch to the new window
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get(web_link_15)
web_title_15 = driver.title
print('Second Window: ' + web_title_15)
# Open a new window, Switch to the new window
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[2])
driver.get(web_link_20)
web_title_20 = driver.title
print('Third Window: ' + web_title_20)

# Checking if listing is live with While Loop
while '404' in (web_title_00, web_title_15, web_title_20):
    print("listing Not Live Yet")
    driver.switch_to.window(driver.window_handles[0])
    driver.refresh()
    driver.switch_to.window(driver.window_handles[1])
    driver.refresh()
    driver.switch_to.window(driver.window_handles[2])
    driver.refresh()

Note:
When I change the while loop to check one condition it executes properly example below
However now its just checking for one condition rather than 3
# Checking if listing is live with While Loop
# Before: while '404' in (web_title_00, web_title_15, web_title_20):
while '404' in web_title_00:
    print("listing Not Live Yet")
    driver.switch_to.window(driver.window_handles[0])
    driver.refresh()
    driver.switch_to.window(driver.window_handles[1])
    driver.refresh()
    driver.switch_to.window(driver.window_handles[2])
    driver.refresh()

A: this condition if '404' in (.., .., ..): is for exact match like
a = "good title"
b = "404" # change to "bad 404" and it will not work

if '404' in (a,b):
  print('error found")

To match contains you need loop to check it one by one, or use any() for list comprehension
while any('404' in t for t in [web_title_00, web_title_15, web_title_20]):
    print("listing Not Live Yet")


text:
Q: links in codeigniter I'm experimenting with codeigniter but don't really understand how links work.
for example, I have a link like this:
localhost/ci/welcome/cat/7
My base url is localhost/ci, so by clicking on this link I would expect the method "cat" of controller "welcome" to be called.
This method is very simple:
   function cat()
    {
        echo "just a test.";
    }

Pretty basic - I would expect to see the text on screen, but I just see a 404 -page not found error.
What could be the problem?

A: http://localhost/ci/index.php/welcome/cat/7

A: Have you configured mod_rewrite (or URL rewriting in general) properly for CodeIgniter? It's not supported out of the box.
They have some instructions in their wiki.

A: I had problems with the rewrite rule suggested in the user guide.  I was also getting 404s.  I had to remove the slash before index.php in the rule.
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

As Veeti says, also remember to enable mod_rewrite for Apache.


text:
Q: Javascript Connect 4 game, checking a winner I am trying to make a Connect 4 game using Javascript.
So I began trying to search the horizontal for 4 in a row and made up this:
for (var y = 0; y < Column - 1; y++)
  for (var x = 0; x < Row - 1; x++)
    if (myArray1[y][x] == 1){
           Win1++;
           if (Win1 == 4){
              alert("Won");
              }
        } else {Win1 = 0}

I got it working when only checking 1 row, but when I added a second for loop to also check the columns it stopped working.
My intention is to run this (And code for checking vertical and diagonal) everytime I place down a piece.

A: As pointed out by @LuanNico in the comments, you need to reset your counter variable Win1 before each row or column.
If your Column and Row variables hold the number of columns and rows, you might also have a one-off error by stopping your loop iteration one row or column too early.
I recommend to fix and reorganize your code a little bit as follows:

function checkColums(board, columns, rows) {
  for (var y = 0; y < columns; y++) {
    var consecutive = 0;
    for (var x = 0; x < rows; x++) {
      if (board[y][x] == 1) {
        consecutive++;
        if (consecutive == 4) {
          return true;
        }
      }
    }
  }
  return false;
}

function checkRows(board, columns, rows) {
  for (var x = 0; x < rows; x++) {
    var consecutive = 0;
    for (var y = 0; y < columns; y++) {
      if (board[y][x] == 1) {
        consecutive++;
        if (consecutive == 4) {
          return true;
        }
      }
    }
  }
  return false;
}

// Example:
var board = [
  [1, 0, 1, 0],
  [0, 1, 1, 0],
  [1, 0, 1, 1],
  [1, 1, 1, 0]
];

console.log(checkColums(board, 4, 4)); // false
console.log(checkRows(board, 4, 4));   //  true


text:
Q: How to create a message with markup but without a text in telegram? I have such replying keyboard:
keyboard = [
        [
            InlineKeyboardButton("Play with a bot", callback_data=str(ONE)),
            InlineKeyboardButton("Results", callback_data=str(TWO)),
        ]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text(None, reply_markup=reply_markup)

It gives me such a result:

How can I get rid of the first "null" string?

A: You're passing None as the Title, resulting in null, you should pass a message as it's required for the send_message and reply_text method:

text (str) – Text of the message to be sent. Max 4096 characters after entities parsing. Also found as telegram.constants.MAX_MESSAGE_LENGTH.

So, since you're required to add some text, pass it as the a extra argument to the function:
keyboard = [
    [
        InlineKeyboardButton("Play with a bot", callback_data='a'),
        InlineKeyboardButton("Results", callback_data='b'),
    ]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('How can I help?', reply_markup=reply_markup)

As described in my comment, sending a separate message also requires some text

A: You cannot send an inline keyboard without text or any type of media supported by Telegram (photos, videos, audios etc). If instead you only want to update the inline keyboard without changing the message content, use the editMessageReplyMarkup method. This will update the inline keyboard leaving the original message intact.


text:
Q: Close Camera after x Seconds in Ionic 2 Application I am developing a cross platform application using Ionic 2 / Cordova. Where the cordova-plugin-camera plug in is being used.
The problem is that I have to close the camera from the application after x seconds.
A whole lot of reading and search has not produced any results.
Can somebody point me in the right direction?


text:
Q: I want to perform multiple user login action using selenium in set up method I am not using testng.xml I am using maven pom.xml only Here is my code which I have tried only for one type of user login
@BeforeMethod
    public void setUp(){

        log.info("Setting up test");
        prop = new Properties();
        prop.load(new FileInputStream(new File(loginFile)));

        verificationErrors = new StringBuffer();
log.info("Running Firefox Driver");

        System.setProperty("webdriver.gecko.driver", GECKO_DRIVER_PATH);
 driver.manage().deleteAllCookies();
        baseUrl = getSeleniumTarget();
        driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(80, TimeUnit.SECONDS);
        driver.manage().window().setPosition(new Point(0, 0));
        driver.manage().window().maximize();

        WebDriverThreadLocal.setWebDriver(driver);

        login("manageuser");
}

protected void login(String username) {
        LoginPage page = PageFactory.initElements(driver, LoginPage.class);

        log.info("Loging in");
        driver.get(baseUrl + prop.getProperty("login.customerportal"));
        page.setUsername(prop.getProperty(username + ".username"));
        page.setPassword(prop.getProperty(username + ".password"));
        page.clickLoginButton();

if I want to use multiple type of user  login in set up method  is it possible and if yes how?
If I want to use employee login in set up method how can I do it?

A: You need to instantiate multiple WebDriver instances and repeat all the configuration code for each one. Hence, invoking login steps for different drivers you will simulate multiple user logins.
You might have a List<WebDriver> drivers instead of WebDriver driver where you define your drivers.
You also can have something like login(WebDriver driver, String username) and do something like:
for(WebDriver driver: drivers){
    login(driver, userNameThatYouHaveTakenFromSomewhere)
}


text:
Q: Create new column to data frame import pandas as pd
import numpy as np

train = pd.read_csv("train.csv")

train["DayOfWeek_Monday"] = train.apply(lambda row: row["DayOfWeek"]=="Monday")

What I want is to add new columns of 'DayOfWeek_Monday','DayOfWeek_Tuesday' and etc using existing column 'DayOfWeek'. How do I add new columns?

A: Use get_dummies with DataFrame.reindex for correct ordering and last DataFrame.join to original:
df = pd.DataFrame({'DayOfWeek':['Sunday','Monday','Wednesday','Thursday', 'Sunday']})

c = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df1 = pd.get_dummies(df['DayOfWeek'], dtype=bool).reindex(c, axis=1, fill_value=False)
df = df.join(df1.add_prefix('DayOfWeek_'))
print (df)
  DayOfWeek  DayOfWeek_Monday  DayOfWeek_Tuesday  DayOfWeek_Wednesday  \
0     Sunday             False              False                False
1     Monday              True              False                False
2  Wednesday             False              False                 True
3   Thursday             False              False                False
4     Sunday             False              False                False

   DayOfWeek_Thursday  DayOfWeek_Friday  DayOfWeek_Saturday  DayOfWeek_Sunday
0               False             False               False              True
1               False             False               False             False
2               False             False               False             False
3                True             False               False             False
4               False             False               False              True


text:
Q: Django How to redirect to 404 page if url patterns don't match I am developing a blog with django,I want to redirect users to 404 page in case url patterns do not match. I know how to redirect to the 404 page when search queries to the database do not match i want to be able to do this when a url do not match any define in urlpatterns. How can i achieve this with django.

A: You can make the changes to setting.py file of you project directory and debug=false then it will render default 404 page
Note Use this in the production or you can use handler404


text:
Q: Java: How to grab the next new "box"? I am very new to OOP. I'm finally slowly grasping the concept of it. But I am stuck on how to grab the next new "box" of type Question from my Quiz class. I don't even know how to explain it and am probably missing proper terminology. But here is my code.
I have two classes: Question and Quiz
public class Question{

   String question;
   public Question(String placeQuestion){
   question = placeQuestion;
   }
}

public class Quiz{
private ArrayList<Question> questions = new ArrayList<Question>();

   public void setQuestion(String q){
   Question setQ = new Question(q);
   questions.add(setQ);
   //each time here I create a "box" of Question class that has a String question in it
   }
   public Question getNextQuestion(){
   //here I want to get the next "box" Question class with the String question
   //in it. How do I track the current question "box" and go to the next one?
   }
}

So how do I go to the next Question class "box" in the quiz class? For example, I have 20 questions. I want getNextQuestion to return the Question "box" of question 2 if I'm at 1. Or actually how do I even know I am at question 1 "box"

A: Something like this:
public class Question {
    String question;
    public Question(String placeQuestion) {
        question = q;
    }
}

public class Quiz {
    private ArrayList<Question> questions = new ArrayList<Question>();
    private int qindex=0;

    public void setQuestion(String q){
        Question setQ = new Question(q);
        questions.add(setQ);
        //each time here I create a "box" of Question class that has a String question in it
    }
    public Question getNextQuestion(){
        Question q = questions.get(qindex);
        qindex++;
        return q;
    }
}

Mind you, you need to do more work than this - for example checking the length of the ArrayList before you call questions[qindex].


text:
Q: LogicApps editor and Visual Studio 2019 how? With Vs2017 and LogicApp tools I was able to see my logic apps locally in design view within visual studio. I use Vs2019 and I don't have the option "open in visual Studio" any more, only option available from the cloud explorer is open in the portal.

A: Looks like its missing for me as well. I even went a step ahead and downloaded the Azure Logic Apps Tools for Visual Studio 2019 which has only 74 installs at the moment and i still can't see Open in Visual Studio Designer

A: I was facing the same issue with VS 2019 Enterprise.
I saw that it was missing the extension "Azure Logic Apps Tools For Visual Studio 2019". Ideally it should have come with Azure Development workload.
I installed that extension and it worked for me.
Thanks!
Visual Studio 2019 Logic Apps Tools Extension Screenshot

A: Visual Studio 2019 just went GA yesterday, 02 APR 19.
It can take all of the SDKs some time to catch up.
In the mean time, Visual Studio 2017 is still fully supported and can be run side by side Visual Studio 2019.

A: you could find the description in the official doc: Quickstart: Create automated tasks, processes, and workflows with Azure Logic Apps - Visual Studio.
In there you could get the newest extension for VS 2019, and you could see an Important note with blue background:

For Visual Studio 2019, Cloud Explorer can open the Logic App Designer
  in the Azure portal, but can't yet open the embedded Logic App
  Designer.

Due to the function development is not yet perfect, so for now you could only create new logic app and the Logic Apps in Azure cannot be opened.


text:
Q: fast-csv adds unwanted quotation mark to number I'm trying to write to csv with fast-csv in nodejs but somehow quotation marks appear in the csv which cause some problems.

 await csv.write([
['Header1', 'Header2'], [firstnamestring, arrayofnumbers1], [secondnamestring,
arrayofnumbers2]
], {headers:true}).pipe('test.csv')

actual outcome:
Header1, Header2
Name, "1,2,2"

Name, "3,3,4"

Desired outcome:
Header1, Header2
Name, 1,2,2
Name, 3,3,4

I logged the array of numbers right before and no quotation marks appear. I'm not sure where they come from.
Thanks!


text:
Q: How to call a function which has a same name with a parameter I am new to react. I wanna call a function from other .js file which has the same name with the parameter in the dashboard function. But it shows TypeError: getCurrentProfile is not a function. Any tips and helps are much appreciated in advance!
for example:
import { getCurrentProfile } from '../actions/profile';

const Dashboard = ({
getCurrentProfile,
auth: { user }

}) => {
useEffect(() => {
    getCurrentProfile();
}, []);
return(
    <Fragment>

 DAshboard

Welcome {user && user.name}

    </Fragment>
    );
};

error:
TypeError: getCurrentProfile is not a function

A: You'll need to make it so that there's no name collision. You could rename the import, or rename the destructured prop, or don't destructure the props at all.
Actually, it doesn't look like the getCurrentProfile prop is used at all, so you could just remove it from the parameter list:
const Dashboard = ({
    auth: { user }
}) => {
    useEffect(getCurrentProfile, []);
    return (
        <Fragment>

 DAshboard

Welcome {user && user.name}

        </Fragment>
    );
};

If you actually are using the getCurrentProfile prop somewhere, then you could do
const Dashboard = (props) => {
    const { user } = props.auth;
    useEffect(getCurrentProfile, []);

A: You can use "as" in your import.
import { getCurrentProfile as Alias } from '../actions/profile';

and than use that Alias name in your hook
useEffect(() => {
    Alias();
}, []);


text:
Q: If I sleep in one bed, then in a separate bed and then remove it, what will happen to my spawn? As the title suggests, if I have one bed set up in my base, then go adventuring and bring a bed with me, will my spawn change back to the original bed location each time I pick up the bed I just slept in?

A: Your spawn point will reset to the default location - what it was when you first created the world, and will get the following message when you die:


text:
Q: Two way mutual SSL authentication https://www.naschenweng.info/2018/02/01/java-mutual-ssl-authentication-2-way-ssl-authentication/
I tried implementing the "SSLMutualAuthTest" code in the above link. But it has a function 'PrivateKeyStrategy()' which is currently deprecated in the java version-8. I am not able to find a alternate function for it.

A: Use org.apache.http.ssl.PrivateKeyStrategy instead. It seems the interface has moved from the httpclient library to httpcore library.


text:
Q: Cannot remove the State of Defer Object  var defer8 = $.Deferred();
    function get_outlet_data()
    {
        db.transaction(populateDBOutlet);
        retrieve_Data_outlet(localStorage.username);
     defer8.resolve();
    }

$.when(defer8).then(function() {
 });

Here i used defer object to wait until the function get_outlet_data run.But i need to remove the state of defer8 inside the When function

A: var get_outlet_data = function () {
    var deferred = $.Deferred();
    db.transaction(populateDBOutlet);
    retrieve_Data_outlet(localStorage.username);
    deferred.resolve(); // Note: the lines above are probably asynchronous, so you want to resolve the promise when they are done
    return deferred.promise();
};

$.when(get_outlet_data()).then(function () {
    // No need to remove the state, because the deferred will be re-created on a second call
});

What I did was move the deferred object inside the function, so it is re-created every time you call the function. Therefore there should be no need to 'reset the state' (which I think is not possible anyway)
Edit: Just so you know, there's an error in your code: $.when does not accept a deferred object, it accepts a promise. So the correct way to use it is $.when(deferred.promise(), ...) and not $.when(deferred, ...)


text:
Q: Python 3.6 for loop is only printing one string per line, why? I am making a small Morse Code translator, and everything works fine; nonetheless, the output is not shown properly.
CIPHER = {'E': "⦾", "A": '⦿', 'R': '⦾⦿', 'I': '⦿⦾', 'O': '⦿⦿',
        'T': '⦾⦾⦿', 'N': '⦾⦿⦾', 'S': '⦾⦿⦿', 'L': '⦿⦾⦾',
        'C': '⦿⦾⦿', 'U': '⦿⦿⦾', 'D': '⦿⦿⦿',
        'P': '⦾⦾⦾⦿', 'M': '⦾⦾⦿⦾', 'H': '⦾⦾⦿⦿',
        'G': '⦾⦿⦾⦾', 'B': '⦾⦿⦾⦿', 'F': '⦾⦿⦿⦾',
        'Y': '⦾⦿⦿⦿', 'W': '⦿⦾⦾⦾', 'K': '⦿⦾⦾⦿',
        'V': '⦿⦾⦿⦾', 'X': '⦿⦾⦿⦿', 'Z': '⦿⦿⦾⦾',
        'J': '⦿⦿⦾⦿', 'Q': '⦿⦿⦿⦾',
        '1': '⦾⦾⦾⦾⦿', '2': '⦾⦾⦾⦿⦿', '3': '⦾⦾⦿⦿⦿',
        '4': '⦾⦿⦿⦿⦿', '5': '⦿⦿⦿⦿⦿', '6': '⦿⦾⦾⦾⦾',
        '7': '⦿⦿⦾⦾⦾', '8': '⦿⦿⦿⦾⦾', '9': '⦿⦿⦿⦿⦾',
        '0': '⦿⦿⦿⦿⦿'
        }
def main():
    msg = input("Type your message below:\n\n")
    for char in msg:
        if char == ' ':
            print (' '*7,)
        elif char not in 'abcdefghijklmnopqrstuvwxyz1234567890':
            print ('')
        else:
            print (CIPHER[char.upper()])

I would expect the output for "Hello, World!" to be something like this:
⦾⦿⦾⦾⦿⦾⦾⦿⦿       ⦿⦿⦾⦿⦿⦾⦾⦿⦿⦿
However, the actual output looks much more like this:
⦾
⦿⦾⦾
⦿⦾⦾
⦿⦿

⦿⦿
⦾⦿
⦿⦾⦾
⦿⦿⦿

I tried removing and placing commas randomly. Then, I tried removing the '\n' statements on the input, but nothing changed with respect to the output. I tried to use the .splitlines as shown here (For loop outputting one character per line), but it stopped printing completely! Then, I googled it and did not found anything close to this problem, so I started to read more material on Python strings. I found a website (https://automatetheboringstuff.com/chapter6/) that has a good amount of material about Python strings, but I could not find anything that could solve my problem there.
I would greatly appreciate your help!

A: You seem to be accustomed to Python2 convention of using comma at the end of print arguments to prevent automatically adding newline. This is no longer working in Python3. You should use keyword argument end='' instead, like this: print (' '*7, end='')

A: Use
print(sth, end='')

to print without breaking line.


text:
Q: Hypernym for injured and dead I'm working on some project that deals with natural disasters. I need to find the most proper word that can be used to refer to someone who either was injured or died in a disaster.
Can I use casualty? Or maybe involved is better?

A: Perhaps victim is the word you are searching for:-

*

*a person who suffers from a destructive or injurious action or agency: a victim of an automobile accident.


text:
Q: Laravel serve without affecting the other apps I have installed Laravel 5 and I know there's no way to run
'php artisan serve' anymore.
Laravel project is in a subfolder: www.site.com/laravelProject.
Can I run this command (in my laravel project folder) from CLI:
php -S localhost/project:8000 -t public/

without affecting the other folders from live (from localhost) ?
I mean, this command will still let the other folders running and being accessed with their url?
Will still the other folders work?
Thx :)
Edit:
'php artisan serve' actually works.
But there's a problem:
user@server# php artisan serve
Laravel development server started: <http://127.0.0.1:8000>

I actually have it on remote server, not locally. How can I fix it?

A: As stated by the answer you get when running php artisan serve, this command only starts a development server.
For production, you have to setup a Virtual Host pointing to your Laravel application.
An example Virtual Host for Apache would look like this:
<VirtualHost *:80>
    DocumentRoot "/Users/myName/Projects/laravel/public"
    ServerName myLaravel.dev
    <Directory "/Users/myName/Projects/laravel/public">
            AllowOverride All
            Options FollowSymLinks +Indexes
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>


text:
Q: How to display git branch in PS1 with other output? I got to display just the branch name in the PS1 if I am in a git repo
linux PS1 - display branch name only inside a git repo, but I am not able to get it integrated with my earlier PS1, which is
 PS1="[\D{%F} \@] \u /\W $ "

this displays, datetime + username
 [2015-08-20 11:38 PM] mtk

I tried
PS1="[\D{%F} \@] \u /\W $(__git_ps1) $ "

but, i get error
__git_ps1: command not found
<empty PS1>

Any way to get git branch name along with earlier details that my PS1 used to output?
EDIT:
I also tried
 PS1="[\D{%F} \@] \u /\W '$(__git_ps1)' $ "

but, this gives empty quotes always, even inside a git repo.
The question is different from that one. I was to display time and date + git branch (if its inside a repo).

A: PS1="[\D{%F} \@] \u /\W \$(__git_ps1) $ "

or
PS1='[\D{%F} \@] \u /\W $(__git_ps1) $ '

You must escape the $ in order to be executed each time, not only once. You can do so by using single quotes or escaping it with a \.


text:
Q: Necesito concatenar en una sola fila Necesito que solo se muestre una sola fila, para que donde dice código se junten
esto es el código que tengo
select
ev.ID,ev.Origen,
stuff(servicios.codigo,1,1,'')as codigo,
ev.Estatus,ev.Situacion,
ev.FechaEmision,
incidencia911.incidente,
incidenciaP.Tipo as CtPolicia, incidenciaP.Descripcion as CdPolicia,
incidenciaM.Tipo as CtModK, incidenciaM.Descripcion as CdModk,
ev.EventoDireccion,ev.Direccion,ev.DireccionEntreCalles,ev.DireccionNumero,ev.DireccionNumeroInt,ev.Colonia,ev.Municipio,
ev.MapaLatitudUTM,ev.MapaLongitudUTM,ev.Distrito,ev.cuadrante,ev.Telefono,ev.Nombre,ev.ApellidoPaterno,ev.ApellidoMaterno,ev.Sexo,ev.Edad
from Evento as ev
left join Evento_servicios as servicioID on servicioID.evento_id = ev.ID
left join ops_servicio as servicios on servicios.id = servicioID.servicio_id
left join EventoModuloK as emk on emk.IDEvento = ev.ID
left join EventoDetenido as evd on ev.ID = evd.IDEvento
left join Incidencia as incidencia911 on incidencia911.id = ev.incidencia_id
left join IncidenciaPECUU as incidenciaP on ev.incidenciapecuu_id = incidenciaP.ID
left join IncidenciaPECUU as incidenciaM on emk.incidenciapecuu_id = incidenciaM.ID
where ev.ID = 403285

Me sale así

ID               Código
----------      -------------
1               es
1               pm
1               v

Necesito que lo que esta en código me salga en una sola fila
Intente usar el stuff me me muestra lo mismo


text:
Q: PHP cURL error 58 Need some help understanding the ubiquitous cURL 58 error, which is due to, in this case, including a PEM file with the cURL request.
 Error 58: unable to set private key file

My code can successfully open the .pem file (see fopen() call) but cURL complains that it cannot set the private key file. Trying to better understand if this something on the client end (me) or something being returned from the host. Pretty sure it's on my end but not sure what.
Thanks
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiURL);
$fh = fopen($this->certPath,'a+');

if($fh){
         echo "File opened!";
         fclose($fh);
       } else {
         echo "File not opened";
}

    curl_setopt($ch, CURLOPT_SSLCERT, $this->certPath);
    curl_setopt($ch, CURLOPT_POSTFIELDS, trim($SOAPrequest));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    if (curl_error($ch)) {
        printf("Error %s: %s", curl_errno($ch), curl_error($ch));
    }
    curl_close ($ch);

    return $result;
}

The key:
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
[...]
-----END CERTIFICATE-----

A: Your file does not contain any private key, only public key.
I think you probably have no reason to use CURLOPT_SSLCERT at all.


text:
Q: Set limit on callproc method in psycopg2 I'm using psycopg2 to manipulate a postgreSQL database.
I'm using the callproc method a lot because it is very convenient to directly pass procedure responses to new procedure calls.
However, I need to get the first line of the response of a procedure call returning a huge number of rows.
The classical way to do so is something like:
cursor.callproc(<proc-path>, <proc-parameters>)
data = cursor.fetchone()

But as there is a huge quantity of data which are retrieved, this takes 7 seconds.
When I simply call:
cursor.execute("select * from <proc-path>(<proc-parameters-as-a-string>) limit 1")
cursor.fetchone() # more or less equivalent to cursor.fetchall() here

The result just comes in the blink of an eye. However this implies converting parameters manually to something understandable as a string by the database, which is not convenient.
Is there a way using callproc or something equivalent to limit the server response to N elements only?


text:
Q: Azure WebJob process multiple service bus queues that are set in configuration I am currently working on a solution where a webjob monitors a service bus queue. This works great but it needs to be easily adaptable to manage any number of queues just be changing a list of queues in the config.
Currently I can see that I can do this:
    public static void ProcessQueueMessage1([ServiceBusTrigger("queue1")] BrokeredMessage message, TextWriter log)
    {

    }

And for another queue I would need to add another method:
    public static void ProcessQueueMessage2([ServiceBusTrigger("queue2")] BrokeredMessage message, TextWriter log)
    {

    }

Obviously, I don't want to add a new method every time I need to watch a new queue.
How would I go about using a WebJob to monitor any queue who's name is in my config? I mean a list of queue names not just one in config.
For example, I know I can use a QueueNameResolver to do the following:
    public static void ProcessQueueMessage([ServiceBusTrigger("%nameInCofig%")] BrokeredMessage message, TextWriter log)
    {}

But I really want to process a list of queue names with only one WebJob ProcessQueueMessage method.
I have been searching for ages and am nearly at the point of using a WorkerRole instead.
Any help would be great.

A: I'm also curious why you've got multiple queues being handled by the same method - there might be a better design pattern and approach for this...but...
You could accomplish this by not using the trigger attribute and instead start up the web job host and use some code that iterates over the queues specified in your config file, wiring up a queue client with the same OnMessage action for each one.  Something like this:
.
.
.
var factory = MessagingFactory.CreateFromConnectionString("");
foreach (var queue in queues)
{
    var client = _factory.CreateQueueClient(queue);
    client.OnMessage(OnMessageReceived, options);
}
.
.
.

public void OnMessageReceived(BrokeredMessage message)
{
     // do your work
}

There are a number of additional options on the QueueClient and OnMessage call for how messages should be handled, but this approach might work.


text:
Q: Loop inside the gridview on devexpress I am new on devexpress,so I have a simple question here.what is the equal of the this code on devexpres gridview.
here is the my code
for (int i = 0; i <gridView1.RowCount; i++)
{
    string Name = gridView1.Rows[i].["ColumName"].toString();
}

I looked at the a method something gridView1.Rows[i] but ,not available.

A: Take a look at the documentation for Traversing Rows in the DevExpress support center. Looks like this would work:
for (int i = 0; i < gridView1.VisibleRowCount; i++)
{
    DataRow row = gridView1.GetDataRow(i);
    string name = row["ColumnName"].ToString();
}

A: You can loop through like this
for (int i = 0; i < gridView1.VisibleRowCount; i++)
{
int currentRowHandle = gridView1.GetVisibleRowHandle(i);
string value = grid.GetCellValue(rowHandle,grid.Columns["Column Name"]);
}


text:
Q: Coloring ordered list items above 10+ When using this method to color numbers of ordered list items:
  ol {
    padding-left:0;
    >li {
      list-style-type: none;
      counter-increment: list;
      position: relative;
      padding-left: 30px;
      &:before {
        content: counter(list) ".";
        position: absolute;
        left: 5px;
      }
    }
  }

When reaching double digits you get this issue when number gets too close to the text: http://d.pr/i/IDh8r7
Anyway make it so it doesnt happen and not just adding more padding?

A: You can do that like this instead, where you align it from the right

ol {
  padding-left: 0;
}

ol>li {
  list-style-type: none;
  counter-increment: list;
  position: relative;
  padding-left: 30px;
}

ol>li:before {
  content: counter(list) ".";
  position: absolute;
  /* right: calc(100% - 25px);              this is the same as "left: 5px"  */
  right: calc(100% - 20px);             /*  this will probably look better   */
}

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

A: How about some text-align: right on the numbers ? I know it's not necessarily what you asked for, but it would be much more visually pleasing.


text:
Q: PHP - DateTime::createFromFormat() returns null I have this code...
class log{
    private $dateTime;
    private $message;

    function log($dt, $message){
        $this->dateTime = DateTime::createFromFormat('d/m/Y H:i:s', substr($dt, 0, -1));
        $this->message = $message;
    }
    function get_dateTime(){
        return $this->dateTime->format('d/m/Y H:i:s');
    }
    function get_message(){
        return $this->message;
    }
}

In parameter $dt has format 17/05/2019 03:15:42:. I get it by reading a text file.
I read the file and create the class object:
while (($line = fgets($handle)) !== false && $line !="\n") { //format example : 30/04/2019 07:59:14: File creation.
   $date = strtok($line, " ");
   $hour = strtok(" ");
   $message = strtok("");

   $log = new log($date." ".$hour,$message);
   echo $log->get_dateTime()."
";
}

The result is: Fatal error: Call to a member function format() on a non-object in...
If I pass the parameter "manually" it works fine.
$log2 = new log('30/04/2019 07:59:14:',"test");
echo $log2->get_dateTime()."
";

If I use code
echo $date; Correct date is returned. Same if I make echo $hour;
How is this possible?

A: Problems seems to be the file encoing. When checking line section in hexadecimal it seems to use 3 byte more than when passing text manually.
file seccion in HEX: ef bb bf 33 30 2f 30 34 2f 32 30 31 39 20 30 37 3a 35 39 3a 31 34 3a
same text in HEX passed manually: 33 30 2f 30 34 2f 32 30 31 39 20 30 37 3a 35 39 3a 31 34 3a
Also string size is different (string(23) and string(20)) checking it with var_dump function.
File is in UTF8 encoding. https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8


text:
Q: select group_concat vs group_concat on left join I'm analyzing a few queries and have noticed some interesting results when trying to extract multiple fields from different tables based on a user_id. Consider the following tables:
+------------------------+------------------+------+-----+---------+----------------+
| Field                  | Type             | Null | Key | Default | Extra          |
+------------------------+------------------+------+-----+---------+----------------+
| subscription_id        | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id                | int(11) unsigned | YES  | MUL | NULL    |                |
| expires                | int(11) unsigned | YES  | MUL | NULL    |                |
| created                | int(11) unsigned | YES  | MUL | NULL    |                |
| modified               | int(11)          | YES  |     | NULL    |                |
+------------------------+------------------+------+-----+---------+----------------+

I want to GROUP_CONCAT all of a user's subscriptions when fetching users. Currently this method works for one field:
SELECT u.id,
(
    SELECT GROUP_CONCAT(s.subscription_id)
    FROM subscriptions s
    WHERE s.user_id = u.id
) AS subscription_ids
FROM users u
LIMIT 10

And I can add all of the fields with different SELECT GROUP_CONCATs. However this method is very slow with any real number of rows due to MySQL joining the subscriptions table for every field. Is there a way that I can GROUP_CONCAT all of the fields at once when listing users?
I've tried a LEFT JOIN method:
SELECT
    u.id AS user_id,
    GROUP_CONCAT(s.subscription_id) AS subscription_ids
FROM users u
LEFT JOIN subscriptions s
    ON s.user_id = u.id
LIMIT 10

However, that appears to concatenate all of the subscription_ids. I'm a bit stumped why the LEFT JOIN would do that. But I'm surprised there doesn't appear to be an easy way to concatenate a list of fields from a different table.

A: The GROUP_CONCAT is an aggregate function and therefore needs to be applied with GROUP BY clause.
SELECT
    u.id AS user_id, GROUP_CONCAT(s.subscription_id) AS subscription_ids
FROM
    users u
    LEFT JOIN subscriptions s ON s.user_id = u.id
GROUP BY
    u.id
LIMIT 10


text:
Q: What does ?. and ?? operator in javascript do? I recently noticed usage like this in a java script code base what does it do. I was unable to find any relevant documentation regarding that. Though intuitively operators seem to checking whether property is present. Is there any official documentation regarding this.
Ex:
args?.propertyName !== 'someValue'
const value = props.someProp ?? props.defaultProp;

A: They are for optionals:
val ?? other is called nullish coalescing operator and is equivalent to val == null ? other : val
and optionalThing?.property is refered as optional chaining and is the same as optionalThing == null ? null : optionalThing.property
This optional chaining expressions result in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing ( allows you to do things like optionalThing?.optionalProperty?.anotherOptionalProperty?.property ).

A: The ?. is called the optional chaining operator (TC39 Stage 4), it is used when you are not sure whether a nested property exists or not. If you try to use the . operator to access a property which is undefined you get a TypeError.
For example:
const obj = {foo: {} };

//This is safe, results in undefined
console.log(obj?.foo?.bar?.baz);

//This results in Uncaught TypeError: Cannot read property 'baz' of undefined
console.log(obj.foo.bar.baz);

Where as the ?? is called the null coalescing operator (TC39 Stage 3). When you are using falsy values like an empty string "" or a 0 with a || operator the operand on the right hand side of the || is returned as the falsy value is ignored.
The ?? comes handy when you don't want that and actually you want to consider the falsy values. If the value on the left is a null or undefined only then the value on the right of the ?? is taken:
For example:
const empString = "";
const defaultValue = empString || "A default value";
//Outputs A default value as "" empty string is falsy
console.log(defaultValue);

const actualValue = empString ?? "A default value";
//Does not print the default value as the empString is neither null or undefined
console.log(actualValue);

Same for other falsy values like 0, false, in disagreement with the || operator which will output the 'default string:
console.log(false ?? 'default') //false

console.log(0 ?? 'default') // 0

Only for undefined and null this will output the default value provided in agreement with the || operator:
console.log(undefined ?? 'default') //default

console.log(null ?? 'default') //default


text:
Q: How to Submit Permission(read_stream, publish_actions) for Review on Facebook I want to get a user's wall post (photo or video) shared from Facebook pages. I am using graph.facebook.com/USER_ID/feed option to get this data via read_stream permission. Is there any other option available for the required task?
I have to post status on user's wall through my app whenever required. I am using publish_actions option.
The problem is that these permissions need review from Facebook.
I'm working on the website and App review required Privacy Policy URL. Is this possible to submit for review based on local host site address?
What should I write in Privacy Policy URL and Terms of Service URL options??? Because my website is in development phase and I need user's account data for further work.

A: About read_stream:

This permission is granted to apps building a Facebook-branded client
  on platforms where Facebook is not already available. For example,
  Android and iOS apps will not be approved for this permission. In
  addition, Web, Desktop, in-car and TV apps will not be granted this
  permission.

Source: https://developers.facebook.com/docs/facebook-login/permissions/v2.2#reference-read_stream
You may try to use /me/statuses with the user_status permission instead.
Obviously, you cannot send anything in that only runs on localhost, you should have a working prototype showing how exactly you are using the permissions. Also, you are not allowed to autopost anything to the user wall just because he authorized publish_actions. Every single entry has to get approved by the user and every single entry must be 100% user generated.


text:
Q: Как открыть APK файл в Android Studio? Как открыть APK файл в Android Studio?
A: Никак. APK файл - это обычный ZIP архив, содержащий скомпилированный код. Android Studio не открывает APK файлы.
A: Простой способ: использовать онлайн-инструмент http://www.javadecompilers.com/apk , загрузить apk и получить исходный код.
Процедура для декодирования .apk файлов, шаг за шагом:
Шаг 1:
Создайте новую папку и скопируйте файл .apk, который вы хотите декодировать.
Теперь переименуйте расширение этого .apk-файла в .zip (например, переименуйте с filename.apk в filename.zip) и сохраните его. Теперь вы можете получить доступ к файлам classes.dex и т. Д. На этом этапе вы можете видеть чертежи, но не файлы xml и java, поэтому продолжайте.

Шаг 2:
Теперь извлеките этот .zip-файл в ту же папку (или NEW FOLDER).
Загрузите dex2jar и извлеките его в ту же папку (или NEW FOLDER).
Переместите файл classes.dex в папку dex2jar.
Теперь откройте командную строку и смените каталог на эту папку (или NEW FOLDER). Затем напишите d2j-dex2jar classes.dex (для терминала mac или ubuntu write ./d2j-dex2jar.sh classes.dex) и нажмите enter. Теперь у вас есть файл classes.dex.dex2jar в той же папке.
Загрузите java decompiler , дважды щелкните по jd-gui, щелкните по открытому файлу и откройте classes.dex .dex2jar из этой папки: теперь вы получаете файлы классов.
Сохраните все эти файлы классов (в jd-gui, щелкните File -> Save All Sources) по имени src. На этом этапе вы получаете источник java, но файлы .xml по-прежнему не читаются, поэтому продолжайте.

Шаг 3:
Теперь откройте еще одну новую папку
Вставьте файл .apk, который вы хотите декодировать
Загрузите последнюю версию apktool И окно установки apktool (обе могут быть загружены из одной и той же ссылки ) и поместите их в ту же папку
Откройте командное окно
Теперь запустите команду, например apktool if framework-res.apk и следующую
apktool d myApp.apk (где myApp.apk обозначает имя файла, которое вы хотите декодировать)

теперь вы получаете папку с файлами в этой папке и можете легко прочитать XML-файлы apk.
Шаг 4:
Это не какой-либо шаг, просто скопируйте содержимое обеих папок (в данном случае и новую папку) в один файл
и наслаждайтесь источником код ...

A: откройте меню Build | Analyze APK и затем выберите нужный файл.


text:
Q: Meteor+ Blaze : If else block in spacebars template not executing for the second time The objective is to show buttons dynamically on click event. On click of edit button, save and cancel buttons are displayed. On click of cancel button, the edit button should be displayed back which is not working. I am using session in helper.
template.html

    <title>ifelse</title>

Welcome to Meteor!

    {{> hello}}

<template name="hello">
    {{isEdit}}

    {{#if isEdit}}

            <button class="button">Save</button>
            <button class="cancelEditLogic button">Cancel</button>

        {{else}}
        <button class="editDishButtonLogic button">Edit</button>
    {{/if}}
</template>

template.js
if (Meteor.isClient) {

    Template.hello.events({
        "click .editDishButtonLogic": function(event, template) {
            console.log("edit true");

            Session.set("isEditSession", "true");
        }

    });

    Template.hello.events({
        "click .cancelEditLogic": function(event, template) {
            console.log("edit false");
            Session.set("isEditSession", "false");
        }
    });

    Template.hello.helpers({
        isEdit: function() {
            console.log("edit helper : " + Session.get("isEditSession"));
            return Session.get("isEditSession");
        }
    });
}

The project is also deployed @ http://ifelse.meteor.com for reference.

A: Resolved:
Changed the below line:
Session.set("isEditSession", "false");
to so:
Session.set("isEditSession", false);
false is a boolean here - notice that false is not in quotes anymore. Thanks to benjick who answered it here @ https://forums.meteor.com/t/if-else-block-in-spacebars-template-not-executing-for-the-second-time/8388/2


text:
Q: "background-size: cover" not working correctly. I've done this almost a million times but it's been a while and I cannot get it to work for some reason.
My HTML file consists of nothing but an empty body tag. Here's my css:
body{
    height: 100%;
    width: 100%;
    -webkit-font-smoothing: antialiased;
    background-image: image-url("background.jpg");
    background-size: cover;
    background-repeat: no-repeat;
}

The width stretches/shrinks to fit the window perfectly, but the height refuses to. Here's what happens when I shrink the browser window:

What am I doing wrong?

A: Use
html,
body {
  height: 100%;
}

The body does not cover the rest of your page.


text:
Q: How to run Jacoco for Android using Gradle? I am trying to run Jacoco with Gradle for a sample Android App. I know that both Android and Java plugin cannot be included, so I believe that pre-instrumentation should be done for android code, before running tests to generate jacoco.exec file. However, I am getting TargetInvocationException, caused by java.lang.StackOverflowError while running my gradle build file. The error is:

FATAL ERROR in native method: processing of -javaagent failed

Here is my build.gradle:
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.8.+'
    }
}
apply plugin: 'android'
apply plugin: 'jacoco'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            res.srcDirs = ['res']
            java.srcDir file('src')
        }
    }
}

    sourceSets {
        unitTest {
            java.srcDir file('unitTest/src')
        }
    }

    configurations {
        unitTestCompile.extendsFrom runtime
        unitTestRuntime.extendsFrom unitTestCompile
        codeCoverage
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        unitTestCompile files("$project.buildDir/classes/release")
        unitTestCompile 'junit:junit:4.11'
        unitTestCompile 'org.robolectric:robolectric:2.2'
        unitTestCompile 'com.google.android:android:4.0.1.2'
        codeCoverage 'org.jacoco:org.jacoco.agent:0.6.5.201403032054:runtime@jar'
    }

    tasks.whenTaskAdded { task ->
        if(task.name == 'unitTest'){
            task.jvmArgs "-javaagent:${configurations.codeCoverage.asPath}=destfile=${project.buildDir.path}/coverage-results/jacoco.exec,sessionid=HSServ,append=false",
                    '-Djacoco=true',
                    '-Xms128m',
                    '-Xmx512m',
                    '-XX:MaxPermSize=128m'
        }

    }
    task unitTest(type:Test, dependsOn: assemble){
        description = "run unit tests"
        testClassesDir = project.sourceSets.unitTest.output.classesDir
        classpath = project.sourceSets.unitTest.runtimeClasspath

        afterTest { desc, result ->
            println "Executing test ${desc.name} [${desc.className}] with result: ${result.resultType}"
        }
    }

build.dependsOn unitTest

What's wrong here?

A: Try out the new gradle plugin 0.10 which supports tests with Jacoco.
dependencies {
    classpath 'com.android.tools.build:gradle:0.10.+'
}

From the tools.android.com page:
Test code coverage support with Jacoco. Enable in the tested Build Type with testCoverageEnabled = true. HTML and XML Report generated in build/reports/coverage. Configure version of Jacoco with:
android {
  jacoco {
    version = '0.6.2.201302030002'
  }
}

Known issue: This is not compatible with using Dagger.


text:
Q: JavaScript: search user input in number of arrays I am working with D3js library. On the web page, there is a search box which user can input their parameter. I receive arrays of data via Ajax post to my database. Following is the code:
..........
var aa;
var bb;
$(function(){
$.ajax({
    type: "POST",
    url: "http://localhost:7474/db/data/transaction/commit",
    accepts: {json: "application/json"},
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify(query), //query is somewhere above the code
    //pass a callback to success to do something with the data
    success: function (data) {
        aa = data.results[0].data;
        aa.forEach(function (entry) {
             passVar(entry.row[0].name)
        });}}
    );
});

function passVar(smth){
    bb =[smth];
    console.log (bb);
    //Should search the user input..........
    }
//if the user input matches, filter function should run.........
function filterData() {
    var value = d3.select("#constraint")[0][0].value;

    inputValue = value;

    ............
}

As the result of console.log(bb)I receive the following on console:
["Direct Digital Control System"]
["Fire Protection"]
["HVAC Cooling- Waterside"]
["HVAC Heating- Waterside"]
["HVAC System"]
["HVAC-01"]
["HVAC-02"]

What I want to do:
If the user input match with one of the results in var bb, then program should run function filterdata() {....for querying. If not, don't do anything.
How should I write the code to make the search and run the other function? Thanks for the any help/suggestion.

A: You can loop through the array and find whether the user input is equals to the current index value of the array. if equals you can call your function and break the loop since no need to loop further more.
for(int i=0; i<bb.length; i++){

    if(bb[i] == userInput){

        filterdata();

        break;

    }

}


text:
Q: Custom Number Pad For iPad App I'm creating an in-house app for iPad running on iOS 8 (not for app store) and one of the requirements is a custom keyboard that replicates the iPad unlock/PIN code entry number pad.
I based my custom number pad on this project: https://github.com/lnafziger/Numberpad
In my project I have added a new UIView to the UIViewController so that I can replicate the dots that appear when a 4-digit PIN code is typed as below:

My problem is that I cannot get the targeting of the numbers correct when I tap them.  My goal is that when I tap the numbers 0 to 9 that the first tap will put that number into the first text box and the second into the second etc.  But I cannot get the taps on the number pad to register in any of the 4 available UITextFields.
[EDIT]
Here is that part of the code so far:
#pragma mark - KEYPAD IBACTIONS

// A number (0-9) was just pressed on the number pad
// Note that this would work just as well with letters or any other character and is not limited to numbers.
- (IBAction)numberpadNumberPressed:(UIButton *)sender {
    if (self.targetTextInput) {
        NSString *numberPressed  = sender.titleLabel.text;
        if ([numberPressed length] > 0) {
            UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
            if (selectedTextRange) {
                [self textInput:self.targetTextInput replaceTextAtTextRange:selectedTextRange withString:numberPressed];
            }
        }
    }
}

// The delete button was just pressed on the number pad
- (IBAction)numberpadDeletePressed:(UIButton *)sender {
    if (self.targetTextInput) {
        UITextRange *selectedTextRange = self.targetTextInput.selectedTextRange;
        if (selectedTextRange) {
            // Calculate the selected text to delete
            UITextPosition  *startPosition  = [self.targetTextInput positionFromPosition:selectedTextRange.start offset:-1];
            if (!startPosition) {
                return;
            }
            UITextPosition  *endPosition    = selectedTextRange.end;
            if (!endPosition) {
                return;
            }
            UITextRange     *rangeToDelete  = [self.targetTextInput textRangeFromPosition:startPosition
                                                                               toPosition:endPosition];

            [self textInput:self.targetTextInput replaceTextAtTextRange:rangeToDelete withString:@""];
        }
    }
}

// The clear button was just pressed on the number pad
- (IBAction)numberpadClearPressed:(UIButton *)sender {
    if (self.targetTextInput) {
        UITextRange *allTextRange = [self.targetTextInput textRangeFromPosition:self.targetTextInput.beginningOfDocument
                                                                     toPosition:self.targetTextInput.endOfDocument];

        [self textInput:self.targetTextInput replaceTextAtTextRange:allTextRange withString:@""];
    }
}

// The done button was just pressed on the number pad
- (IBAction)numberpadDonePressed:(UIButton *)sender {
    if (self.targetTextInput) {
        [self.targetTextInput resignFirstResponder];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    return YES;
}

// Replace the text of the textInput in textRange with string if the delegate approves
- (void)textInput:(id <UITextInput>)textInput replaceTextAtTextRange:(UITextRange *)textRange withString:(NSString *)string {
    if (textInput) {
        if (textRange) {
            // Calculate the NSRange for the textInput text in the UITextRange textRange:
            int startPos                    = [textInput offsetFromPosition:textInput.beginningOfDocument
                                                                 toPosition:textRange.start];
            int length                      = [textInput offsetFromPosition:textRange.start
                                                                 toPosition:textRange.end];
            NSRange selectedRange           = NSMakeRange(startPos, length);

            if ([self textInput:textInput shouldChangeCharactersInRange:selectedRange withString:string]) {
                // Make the replacement:
                [textInput replaceRange:textRange withText:string];
            }
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *passcode = [textField text];
    passcode = [passcode stringByReplacingCharactersInRange:range withString:string];

    switch ([passcode length]) {
        case 0:
            self.txtBulletField0.text = nil;
            self.txtBulletField1.text = nil;
            self.txtBulletField2.text = nil;
            self.txtBulletField3.text = nil;
            break;
        case 1:
            self.txtBulletField0.text = @"*";
            self.txtBulletField1.text = nil;
            self.txtBulletField2.text = nil;
            self.txtBulletField3.text = nil;
            break;
        case 2:
            self.txtBulletField0.text = @"*";
            self.txtBulletField1.text = @"*";
            self.txtBulletField2.text = nil;
            self.txtBulletField3.text = nil;
            break;
        case 3:
            self.txtBulletField0.text = @"*";
            self.txtBulletField1.text = @"*";
            self.txtBulletField2.text = @"*";
            self.txtBulletField3.text = nil;
            break;
        case 4:
            self.txtBulletField0.text = @"*";
            self.txtBulletField1.text = @"*";
            self.txtBulletField2.text = @"*";
            self.txtBulletField3.text = @"*";

            // Notify delegate a little later so we have a chance to show the 4th bullet
            [self performSelector:@selector(notifyDelegate:) withObject:passcode afterDelay:0];

            return NO;

            break;
        default:
            break;
    }

In the original project the number pad targeted one UITextField and put all the number taps into there.  Now I want to have it automatically move between my 4 UITextFields (one UITextField should only accept 1 character and then move to the next UITextField).  The numberpadNumberPressed method does not seem to trigger updating the text fields at all.
[END EDIT]
How would I do this?

A: This could be so simple.
Just keep the numbers that have been tapped in one mutable string variable. When a key is pressed, add the next number. If the delete key is pressed delete the last number, if any. That should be easy. E.g.
if (pinString.length < 4) {
   [pinString appendString:sender.titleLabel.text]
}

and
if (pinString.length) {
   [pinString deleteCharactersInRange:NSMakeRange(pinString.length-1,1)];
}

You are not editing the numbers in the text fields, so you should use labels instead. In the following, I assume you have given them the tags 101, 102, 103 and 104.
Then just do something like this:
for (UILabel *label in theFourTextLabels) {
   label.text = label.tag - 100 > pinString.length ? "" : "*";
}


text:
Q: How to obtain man page contents in Python? im running linux and i want to import some man pages to my application.
i came up with this:
p = subprocess.Popen(('man %s' % manTopic,), shell = True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
if stdout:

but its no good, man is displaying only first page and blocks my applicationon
How can i obtain man page with Python?

A: You can grab the whole output of a command with check_output. Furthermore, using a shell is not necessary and might even make your application vulnerable to a shell injection attack and is strongly discouraged.
import subprocess

pagename = 'man'
manpage = subprocess.check_output(['man', pagename])

Note that using man will give you output formatted for a terminal. If you want to have it formatted differently, you'll have to

*

*call man -w <name> to get the location of the manpage,

*probably decompress the manual page,

*feed it to groff using the -T option to select the type of output you want.

When calling groff, don't forget to load the correct macro's.
On FreeBSD I tend use groff -Tlatin1 -mandoc <file> to get text output.

A: Try:
p = subprocess.Popen(('man -P cat %s' % manTopic,), shell = True)
stdout, stderr = p.communicate()
if stdout:

instead --
the "-P" option overrides the pager program used by the "man" command.